--
-- Table structure for table `user_talk_attend`
--

DROP TABLE IF EXISTS `user_talk_attend`;
CREATE TABLE `user_talk_attend` (
  `uid` int(11) NOT NULL,
  `tid` int(11) NOT NULL,
  `ID` int(11) NOT NULL auto_increment,
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

ALTER TABLE user_talk_attend ADD INDEX idx_talk (tid);

-- Add a unique constraint so that each user can only be attending each talk once

ALTER TABLE user_talk_attend ADD UNIQUE INDEX idx_unique_user_talk (uid, tid);

INSERT INTO patch_history SET patch_number = 43;

Patch script changed to "star" from "attend".

--
-- Table structure for table `user_talk_star`
--

DROP TABLE IF EXISTS `user_talk_star`;
CREATE TABLE `user_talk_star` (
  `uid` int(11) NOT NULL,
  `tid` int(11) NOT NULL,
  `ID` int(11) NOT NULL auto_increment,
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

ALTER TABLE user_talk_star ADD INDEX idx_talk (tid);

-- Add a unique constraint so that each user can only star each talk once

ALTER TABLE user_talk_star ADD UNIQUE INDEX idx_unique_user_talk (uid, tid);

INSERT INTO patch_history SET patch_number = 43;


BEGIN;

CREATE TYPE body_kind AS ENUM (
    'star_white',
    'star_yellow',
    'star_red',
    'planet_blue',
    'planet_grey',
    'planet_green',
    'planet_brown',
    'black_hole',
    'dust_cloud',
    'gas_cloud'
);

CREATE TABLE body (
   uid bytea not null primary key,
   universe_uid bytea not null,
   kind body_kind not null,
   geometry circle not null
);

COMMENT ON TABLE body IS
'The center and radius of stars, planets, dust clouds, and other static
environmental entities. This is written once during universe creation,
and not altered there-after.';

COMMENT ON COLUMN body.uid IS
'Every "*uid" column entry is a value of 16 high entropy bytes.';

COMMENT ON COLUMN body.universe_uid IS
'The universe to which this body belongs.';

COMMENT ON COLUMN body.geometry IS
'Every body is circular.';

COMMIT;

Rename "universe" to "galaxy" and create a galaxy table with referencial integrity for bodies.

BEGIN;

CREATE TABLE galaxy (
    uid bytea NOT NULL PRIMARY KEY,
    created timestamp WITHOUT TIME ZONE NOT NULL
);

COMMENT ON TABLE galaxy IS
'Each game takes place in a galaxy. Separate galaxies do not interact.';

COMMENT ON COLUMN galaxy.uid IS
'Every "*uid" column entry is a value of 16 high entropy bytes.';

COMMENT ON COLUMN galaxy.created IS
'Every timestamp is in UTC+0.';

CREATE TYPE body_kind AS ENUM (
    'star_white',
    'star_yellow',
    'star_red',
    'planet_blue',
    'planet_grey',
    'planet_green',
    'planet_brown',
    'black_hole',
    'dust_cloud',
    'gas_cloud'
);

CREATE TABLE body (
   uid bytea NOT NULL PRIMARY KEY,
   galaxy_uid bytea REFERENCES galaxy (uid),
   kind body_kind NOT NULL,
   geometry circle NOT NULL
);

COMMENT ON TABLE body IS
'The center and radius of stars, planets, dust clouds, and other static
environmental entities. This is written once during galaxy creation,
and not altered there-after.';

COMMENT ON COLUMN body.uid IS
'Every "*uid" column entry is a value of 16 high entropy bytes.';

COMMENT ON COLUMN body.galaxy_uid IS
'The galaxy to which this body belongs.';

COMMENT ON COLUMN body.geometry IS
'Every body is circular.';

COMMIT;


--#SET TERMINATOR @
SET CURRENT SCHEMA LOGGER @

/**
 * Function that returns the value of the given key from the configuration
 * table.
 *
 * IN KEY
 *  Identification of the key/value parameter of the configuration table.
 * RETURNS The associated value of the given key. NULL if there is not a key
 * with that value.
 */
ALTER MODULE LOGGER ADD
  FUNCTION GET_VALUE (
  IN KEY ANCHOR CONFIGURATION.KEY
  )
  RETURNS ANCHOR CONFIGURATION.VALUE
  LANGUAGE SQL
  PARAMETER CCSID UNICODE
  SPECIFIC F_GET_VAL
  DETERMINISTIC
  NO EXTERNAL ACTION
  READS SQL DATA
  SECURED
 BEGIN
  DECLARE RET ANCHOR CONFIGURATION.KEY;
  SELECT VALUE INTO RET
    FROM CONFIGURATION C
    WHERE C.KEY = KEY
    FETCH FIRST 1 ROW ONLY;
  RETURN RET;
 END @

-- Constant logInternals
ALTER MODULE LOGGER ADD
  VARIABLE LOG_INTERNALS ANCHOR CONFIGURATION.VALUE DEFAULT (
  GET_VALUE ('logInternals')
  ) @

Select fixed with variable, global constants

--#SET TERMINATOR @
SET CURRENT SCHEMA LOGGER @

/**
 * Function that returns the value of the given key from the configuration
 * table.
 *
 * IN KEY
 *  Identification of the key/value parameter of the configuration table.
 * RETURNS The associated value of the given key. NULL if there is not a key
 * with that value.
 */
ALTER MODULE LOGGER ADD
  FUNCTION GET_VALUE (
  IN GIVEN_KEY ANCHOR CONFIGURATION.KEY
  )
  RETURNS ANCHOR CONFIGURATION.VALUE
  LANGUAGE SQL
  PARAMETER CCSID UNICODE
  SPECIFIC F_GET_VAL
  NOT DETERMINISTIC
  NO EXTERNAL ACTION
  READS SQL DATA
  SECURED
 BEGIN
  DECLARE RET ANCHOR CONFIGURATION.KEY;
  SELECT C.VALUE INTO RET
    FROM CONFIGURATION C
    WHERE C.KEY = GIVEN_KEY;
  RETURN RET;
 END @

-- Constant logInternals
ALTER MODULE LOGGER ADD
  VARIABLE LOG_INTERNALS ANCHOR CONFIGURATION.KEY CONSTANT 'logInternals' @

ALTER MODULE LOGGER ADD
  VARIABLE VAL_TRUE ANCHOR CONFIGURATION.KEY CONSTANT 'true' @


SELECT
  ("http://zoomhub.net/" || content.hashId) AS URL,
  content.numViews AS Views,
  ROUND(image.width * image.height / 1e6, 1) AS Megapixels
FROM
  content, image
WHERE
  content.id = image.contentid AND
  content.state = 'completed:success' AND
  content.numViews >= 200
ORDER BY (image.width * image.height) DESC
LIMIT 100;

Migrate report from SQLite to PostgreSQL

SELECT
  ('http://zoomhub.net/' || content.hash_id) AS URL,
  content.num_views AS Views,
  ROUND(image.width * image.height / 1e6, 1) AS Megapixels
FROM
  content, image
WHERE
  content.id = image.content_id AND
  content.state = 'completed:success' AND
  content.num_views >= 200
ORDER BY (image.width * image.height) DESC
LIMIT 100;


-- hash index takes too long to create
CREATE INDEX posts_post_type_id_idx on Posts USING btree (PostTypeId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_score_idx on Posts USING btree (Score)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_creation_date_idx on Posts USING btree (CreationDate)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_owner_user_id_idx on Posts USING hash (OwnerUserId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_answer_count_idx on Posts USING btree (AnswerCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_comment_count_idx on Posts USING btree (CommentCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_favorite_count_idx on Posts USING btree (FavoriteCount)
       WITH (FILLFACTOR = 100);

-- Composite indexes (optional)
CREATE INDEX posts_id_post_type_id_idx on Posts USING btree (Id, PostTypeId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_id_parent_id_idx on Posts USING btree (Id, ParentId)
       WITH (FILLFACTOR = 100);

Add index to search for AcceptedAnswers for Posts faster.

-- hash index takes too long to create
CREATE INDEX posts_post_type_id_idx on Posts USING btree (PostTypeId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_score_idx on Posts USING btree (Score)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_creation_date_idx on Posts USING btree (CreationDate)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_owner_user_id_idx on Posts USING hash (OwnerUserId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_answer_count_idx on Posts USING btree (AnswerCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_comment_count_idx on Posts USING btree (CommentCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_favorite_count_idx on Posts USING btree (FavoriteCount)
       WITH (FILLFACTOR = 100);

-- Composite indexes (optional)
CREATE INDEX posts_id_post_type_id_idx on Posts USING btree (Id, PostTypeId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_id_parent_id_idx on Posts USING btree (Id, ParentId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_id_accepted_answers_id_idx on Posts USING btree (Id, AcceptedAnswerId)
       WITH (FILLFACTOR = 100);


create table test1711251 (pre integer not null primary key, size integer not null,
level smallint not null, kind smallint not null, prop char (32));

copy 3 records into test1711251 from stdin DELIMITERS ',', '\n', '"';
0, 2, 0, 6, "auctionG.xml"
1, 1, 1, 1, "foo"
2, 0, 2, 1, "bar"

select * from test1711251;

Remove significant white space for string field.

create table test1711251 (pre integer not null primary key, size integer not null,
level smallint not null, kind smallint not null, prop char (32));

copy 3 records into test1711251 from stdin DELIMITERS ',', '\n', '"';
0, 2, 0, 6,"auctionG.xml"
1, 1, 1, 1,"foo"
2, 0, 2, 1,"bar"

select * from test1711251;


ALTER TABLE spreadsheet
    ADD filepath VARCHAR(500)
;

ALTER TABLE spreadsheet
ADD CONSTRAINT uc_spreadsheet_filepath UNIQUE (filepath)
;

Index is too long on live server

ALTER TABLE spreadsheet
    ADD filepath VARCHAR(200)
;

ALTER TABLE spreadsheet
ADD CONSTRAINT uc_spreadsheet_filepath UNIQUE (filepath)
;


DROP TYPE IF EXISTS app;
CREATE TYPE app AS ENUM ('telegram', 'vk');

CREATE TABLE IF NOT EXISTS rooms (
  id SERIAL PRIMARY KEY,
  owner_id BIGINT NOT NULL,
  owner_app app NOT NULL,
  guest_id BIGINT,
  guest_app app,
  active BOOLEAN NOT NULL DEFAULT TRUE,
  created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW()
  CHECK (owner_id <> guest_id)
);

CREATE UNIQUE INDEX ON rooms (owner_id) WHERE active = 'true';

Add null check for guest_id and guest_app

DROP TYPE IF EXISTS app;
CREATE TYPE app AS ENUM ('telegram', 'vk');

CREATE TABLE IF NOT EXISTS rooms (
  id SERIAL PRIMARY KEY,
  owner_id BIGINT NOT NULL,
  owner_app app NOT NULL,
  guest_id BIGINT,
  guest_app app,
  active BOOLEAN NOT NULL DEFAULT TRUE,
  created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW()

  CHECK (owner_id <> guest_id OR owner_app <> guest_app)
  CHECK ((guest_id IS NOT NULL AND guest_app IS NOT NULL) OR (guest_id IS NULL AND guest_app IS NULL))
);

CREATE UNIQUE INDEX ON rooms (owner_id) WHERE active = 'true';


CREATE TABLE k3_result (
  pageURL text,
  pageRank int
);

COPY k3_result FROM '/results/q1_1.csv' WITH DELIMITER ',';
COPY k3_result FROM '/results/q1_2.csv' WITH DELIMITER ',';

Fix delimiter in sql script

CREATE TABLE k3_result (
  pageURL text,
  pageRank int
);

COPY k3_result FROM '/results/q1_1.csv' WITH DELIMITER '|';
COPY k3_result FROM '/results/q1_2.csv' WITH DELIMITER '|';


CREATE TABLE IF NOT EXISTS public.journal (
  ordering BIGSERIAL,
  persistence_id VARCHAR(255) NOT NULL,
  sequence_number BIGINT NOT NULL,
  deleted BOOLEAN DEFAULT FALSE NOT NULL,
  tags VARCHAR(255) DEFAULT NULL,
  message BYTEA NOT NULL,
  PRIMARY KEY(persistence_id, sequence_number)
);
CREATE UNIQUE INDEX IF NOT EXISTS journal_ordering_idx ON public.journal(ordering);

CREATE TABLE IF NOT EXISTS public.snapshot (
  persistence_id VARCHAR(255) NOT NULL,
  sequence_number BIGINT NOT NULL,
  created BIGINT NOT NULL,
  snapshot BYTEA NOT NULL,
  PRIMARY KEY(persistence_id, sequence_number)
);

CREATE TABLE IF NOT EXISTS "state" (
    "global_offset" BIGSERIAL,
    "persistence_id" VARCHAR(255) NOT NULL,
    "revision" BIGINT NOT NULL,
    "state_payload" BYTEA NOT NULL,
    "state_serial_id" INTEGER NOT NULL,
    "state_serial_manifest" VARCHAR(255),
    "tag" VARCHAR,
    "state_timestamp" BIGINT NOT NULL,
    PRIMARY KEY("persistence_id")
    );
CREATE INDEX CONCURRENTLY "state_tag_idx" on "state" ("tag");
CREATE INDEX CONCURRENTLY "state_global_offset_idx" on "state" ("global_offset");

Apply syntax improvement on the legacy DDL aswell

CREATE TABLE IF NOT EXISTS public.journal (
  ordering BIGSERIAL,
  persistence_id VARCHAR(255) NOT NULL,
  sequence_number BIGINT NOT NULL,
  deleted BOOLEAN DEFAULT FALSE NOT NULL,
  tags VARCHAR(255) DEFAULT NULL,
  message BYTEA NOT NULL,
  PRIMARY KEY(persistence_id, sequence_number)
);
CREATE UNIQUE INDEX IF NOT EXISTS journal_ordering_idx ON public.journal(ordering);

CREATE TABLE IF NOT EXISTS public.snapshot (
  persistence_id VARCHAR(255) NOT NULL,
  sequence_number BIGINT NOT NULL,
  created BIGINT NOT NULL,
  snapshot BYTEA NOT NULL,
  PRIMARY KEY(persistence_id, sequence_number)
);

CREATE TABLE IF NOT EXISTS public.state (
    global_offset BIGSERIAL,
    persistence_id VARCHAR(255) NOT NULL,
    revision BIGINT NOT NULL,
    state_payload BYTEA NOT NULL,
    state_serial_id INTEGER NOT NULL,
    state_serial_manifest VARCHAR(255),
    tag VARCHAR,
    state_timestamp BIGINT NOT NULL,
    PRIMARY KEY(persistence_id)
    );
CREATE INDEX CONCURRENTLY state_tag_idx on public.state (tag);
CREATE INDEX CONCURRENTLY state_global_offset_idx on public.state (global_offset);


-- tiki_myisam.sql is run after tiki.sql if MyISAM is being installed
CREATE FULLTEXT INDEX ft ON tiki_articles(`title`, `heading`, `body`);
CREATE FULLTEXT INDEX ft ON tiki_blog_posts(`data`, `title`);
CREATE FULLTEXT INDEX ft ON tiki_blogs(`title`, `description`);
CREATE FULLTEXT INDEX ft ON tiki_calendar_items(`name`,`description`);
CREATE FULLTEXT INDEX ft ON tiki_comments(title,data);
CREATE FULLTEXT INDEX ft ON tiki_directory_sites(name,description);
CREATE FULLTEXT INDEX ft ON tiki_faq_questions(question,answer);
CREATE FULLTEXT INDEX ft ON tiki_faqs(title,description);
CREATE FULLTEXT INDEX ft ON tiki_files(name,description,search_data,filename);
CREATE FULLTEXT INDEX ft ON tiki_galleries(name,description);
CREATE FULLTEXT INDEX ft ON tiki_images(name,description);
CREATE FULLTEXT INDEX ft ON tiki_pages(`pageName`,`description`,`data`);
CREATE FULLTEXT INDEX ft ON tiki_tracker_item_fields(value);

Add missing SVN id keyword

-- tiki_myisam.sql is run after tiki.sql if MyISAM is being installed
-- $Id$
CREATE FULLTEXT INDEX ft ON tiki_articles(`title`, `heading`, `body`);
CREATE FULLTEXT INDEX ft ON tiki_blog_posts(`data`, `title`);
CREATE FULLTEXT INDEX ft ON tiki_blogs(`title`, `description`);
CREATE FULLTEXT INDEX ft ON tiki_calendar_items(`name`,`description`);
CREATE FULLTEXT INDEX ft ON tiki_comments(title,data);
CREATE FULLTEXT INDEX ft ON tiki_directory_sites(name,description);
CREATE FULLTEXT INDEX ft ON tiki_faq_questions(question,answer);
CREATE FULLTEXT INDEX ft ON tiki_faqs(title,description);
CREATE FULLTEXT INDEX ft ON tiki_files(name,description,search_data,filename);
CREATE FULLTEXT INDEX ft ON tiki_galleries(name,description);
CREATE FULLTEXT INDEX ft ON tiki_images(name,description);
CREATE FULLTEXT INDEX ft ON tiki_pages(`pageName`,`description`,`data`);
CREATE FULLTEXT INDEX ft ON tiki_tracker_item_fields(value);


#This contains all the db schema changes that are going to be applied every time the server is deployed
delete from ofProperty where name='provider.lockout.className';
insert into ofProperty values ('provider.lockout.className', 'com.magnet.mmx.lockout.MmxLockoutProvider');

delete from ofProperty where name='xmpp.parser.buffer.size';
insert into ofProperty values ('xmpp.parser.buffer.size', '2097152');

delete from ofProperty where name='xmpp.routing.strict';
insert into ofProperty values('xmpp.routing.strict', 'true');

delete from ofProperty where name='xmpp.client.idle';
insert into ofProperty values('xmpp.client.idle', '-1');

delete from ofProperty where name='xmpp.client.idle.ping';
insert into ofProperty values('xmpp.client.idle.ping', 'false');

delete from ofProperty where name='route.all-resources';
insert into ofProperty values('route.all-resources', 'true');

delete from ofProperty where name='xmpp.proxy.enabled';
insert into ofProperty values('xmpp.proxy.enabled', 'false');

delete from ofProperty where name='xmpp.auth.anonymous';
insert into ofProperty values('xmpp.auth.anonymous', 'false');

delete from ofProperty where name='route.all-resources';
insert into ofProperty values('route.all-resources', 'true');

Remove the duplicated entry "route.all-resources".


CREATE table storage_type_temp (
    id NUMERIC, text varchar
);

INSERT INTO storage_type_temp VALUES
    (0, 'UNKNOWN'),
    (1, 'NFS'),
    (2, 'FCP'),
    (3, 'ISCSI'),
    (4, 'LOCALFS'),
    (6, 'POSIXFS'),
    (7, 'GLUSTERFS'),
    (8, 'GLANCE'),
    (9, 'CINDER');

CREATE table storage_domain_type_temp (
    id NUMERIC, text varchar
);

INSERT into storage_domain_type_temp VALUES
    (0, 'Master'),
    (1, 'Data'),
    (2, 'ISO'),
    (3, 'ImportExport'),
    (4, 'Image'),
    (5, 'Volume'),
    (6, 'Unknown');

Add documentation about tables values

CREATE table storage_type_temp (
    id NUMERIC, text varchar
);

----------------------------------------------------------------
-- All values defined in ovirt-engine project:
-- backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/businessentities/storage/StorageType.java
----------------------------------------------------------------
INSERT INTO storage_type_temp VALUES
    (0, 'UNKNOWN'),
    (1, 'NFS'),
    (2, 'FCP'),
    (3, 'ISCSI'),
    (4, 'LOCALFS'),
    (6, 'POSIXFS'),
    (7, 'GLUSTERFS'),
    (8, 'GLANCE'),
    (9, 'CINDER');

CREATE table storage_domain_type_temp (
    id NUMERIC, text varchar
);

----------------------------------------------------------------
-- All values defined in ovirt-engine project:
-- backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/businessentities/StorageDomainType.java
----------------------------------------------------------------
INSERT into storage_domain_type_temp VALUES
    (0, 'Master'),
    (1, 'Data'),
    (2, 'ISO'),
    (3, 'ImportExport'),
    (4, 'Image'),
    (5, 'Volume'),
    (6, 'Unknown');


DROP TABLE IF EXISTS oskari_users;
DROP TABLE IF EXISTS oskari_roles;

CREATE TABLE oskari_users (
  id serial NOT NULL,
  user_name character varying(25) NOT NULL,
  first_name character varying(128),
  last_name character varying(128),
  uuid character varying(64),
  CONSTRAINT oskari_users_pkey PRIMARY KEY (id),
  UNIQUE (user_name)
);

CREATE TABLE oskari_roles (
  id serial NOT NULL,
  name character varying(25) NOT NULL,
  is_guest boolean default FALSE,
  UNIQUE (name)
);

Add table to map oskari users to roles

DROP TABLE IF EXISTS oskari_role_oskari_user;
DROP TABLE IF EXISTS oskari_roles;
DROP TABLE IF EXISTS oskari_users;

CREATE TABLE oskari_users (
  id serial NOT NULL,
  user_name character varying(25) NOT NULL,
  first_name character varying(128),
  last_name character varying(128),
  uuid character varying(64),
  CONSTRAINT oskari_users_pkey PRIMARY KEY (id),
  UNIQUE (user_name)
);

CREATE TABLE oskari_roles (
  id serial NOT NULL,
  name character varying(25) NOT NULL,
  is_guest boolean default FALSE,
  CONSTRAINT oskari_roles_pkey PRIMARY KEY (id),
  UNIQUE (name)
);

CREATE TABLE oskari_role_oskari_user (
  id serial NOT NULL,
  user_name character varying(25) REFERENCES oskari_users(user_name),
  role_id integer REFERENCES oskari_roles(id),
  CONSTRAINT oskari_role_oskari_user_pkey PRIMARY KEY (id)
);


--
-- Database for  gas-api
--

-- --------------------------------------------------------

--
-- Table structure for table `newusers`
--

CREATE TABLE `newusers` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(35) NOT NULL,
  `lastname` varchar(35) NOT NULL,
  `username` varchar(36) NOT NULL,
  `studentnumber` int(9) NOT NULL,
  `email` varchar(255) NOT NULL,
  `IS_DELETED` tinyint(1) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `nominations`
--

CREATE TABLE `nominations` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nominee` varchar(255) NOT NULL,
  `nominator` varchar(255) NOT NULL,
  `position` varchar(255) NOT NULL,
  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `positions`
--

CREATE TABLE `positions` (
  `name` varchar(255) NOT NULL,
  `description` varchar(1000) NOT NULL,
  PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Update DB schema for audit table

--
-- Database for  gas-api
--

-- --------------------------------------------------------

--
-- Table structure for table `newusers`
--

CREATE TABLE `newusers` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(35) NOT NULL,
  `lastname` varchar(35) NOT NULL,
  `username` varchar(36) NOT NULL,
  `studentnumber` int(9) NOT NULL,
  `email` varchar(255) NOT NULL,
  `IS_DELETED` tinyint(1) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `nominations`
--

CREATE TABLE `nominations` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nominee` varchar(255) NOT NULL,
  `nominator` varchar(255) NOT NULL,
  `position` varchar(255) NOT NULL,
  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `positions`
--

CREATE TABLE `positions` (
  `name` varchar(255) NOT NULL,
  `description` varchar(1000) NOT NULL,
  PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `audit`
--

CREATE TABLE `audit` (
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `user` varchar(255) NOT NULL,
  `message` varchar(1000) NOT NULL,
  PRIMARY KEY (`timestamp`,`user`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


# We include a default installation of WordPress with this Vagrant setup.
# In order for that to respond properly, a default database should be
# available for it to use.
CREATE DATABASE IF NOT EXISTS `wordpress_default`;
GRANT ALL PRIVILEGES ON `wordpress_default`.* TO 'wp'@'localhost' IDENTIFIED BY 'wp';

# Create an external user with privileges on all databases in mysql so
# that a connection can be made from the local machine without an SSH tunnel
CREATE USER 'external'@'%' IDENTIFIED BY 'external';
GRANT ALL PRIVILEGES ON *.* TO 'external'@'%';

Create the external database user with a stored procedure

# We include a default installation of WordPress with this Vagrant setup.
# In order for that to respond properly, a default database should be
# available for it to use.
CREATE DATABASE IF NOT EXISTS `wordpress_default`;
GRANT ALL PRIVILEGES ON `wordpress_default`.* TO 'wp'@'localhost' IDENTIFIED BY 'wp';

# Create an external user with privileges on all databases in mysql so
# that a connection can be made from the local machine without an SSH tunnel
#
# We use a stored procedure for this because the mysql.user table is persistent after
# the first `vagrant up` and an error will be thrown if we try to create a
# user that already exists. So... a lot of lines of code to prevent red in our boot. :)
drop procedure if exists createExternalUser;
delimiter $$
create procedure createExternalUser(username varchar(50), pw varchar(50))
begin
IF (SELECT EXISTS(SELECT 1 FROM `mysql`.`user` WHERE `user` = 'external')) = 0 THEN
    begin
    set @sql = CONCAT('CREATE USER ', username, '@\'%\' IDENTIFIED BY \'external\'');
    prepare stmt from @sql;
    execute stmt;
    deallocate prepare stmt;
    end;
END IF;
end $$
delimiter ;

# Use the stored procedure to create our external user
call createExternalUser( 'external', 'external' );
GRANT ALL PRIVILEGES ON *.* TO 'external'@'%';


DROP FUNCTION IF EXISTS case_has_transactions_since_sync(text, text, timestamp with time zone);

CREATE FUNCTION case_has_transactions_since_sync(p_case_id text, p_sync_log_id text, sync_log_date timestamp with time zone)
  RETURNS boolean AS $$
    SELECT EXISTS(
      SELECT TRUE FROM form_processor_casetransaction AS transaction_table
        WHERE transaction_table.case_id = p_case_id
          AND transaction_table.server_date > sync_log_date
          AND transaction_table.sync_log_id IS DISTINCT FROM p_sync_log_id
    );
$$ LANGUAGE sql;

Make sql function PostgreSQL 9.1 compatible

DROP FUNCTION IF EXISTS case_has_transactions_since_sync(text, text, timestamp with time zone);

CREATE FUNCTION case_has_transactions_since_sync(p_case_id text, p_sync_log_id text, sync_log_date timestamp with time zone)
  RETURNS boolean AS $$
    SELECT EXISTS(
      SELECT TRUE FROM form_processor_casetransaction AS transaction_table
        WHERE transaction_table.case_id = $1
          AND transaction_table.server_date > $3
          AND transaction_table.sync_log_id IS DISTINCT FROM $2
    );
$$ LANGUAGE sql;


# jiveRoster: Change jid column to varchar
ALTER TABLE jiveRoster ALTER COLUMN jid jid varchar(1024) not null;

# jiveRoster: Add new index
ALTER TABLE jiveRoster ADD INDEX jiveRoster_jid_idx (jid);

UPDATE jiveVersion set version=14 where name = 'openfire';

Switch from ALTER COLUMN to CHANGE COLUMN.

# jiveRoster: Change jid column to varchar
ALTER TABLE jiveRoster CHANGE COLUMN jid jid varchar(1024) not null;

# jiveRoster: Add new index
ALTER TABLE jiveRoster ADD INDEX jiveRoster_jid_idx (jid);

UPDATE jiveVersion set version=14 where name = 'openfire';


-- hash index takes too long to create
CREATE INDEX posts_post_type_id_idx ON Posts USING btree (PostTypeId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_score_idx ON Posts USING btree (Score)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_creation_date_idx ON Posts USING btree (CreationDate)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_owner_user_id_idx ON Posts USING hash (OwnerUserId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_answer_count_idx ON Posts USING btree (AnswerCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_comment_count_idx ON Posts USING btree (CommentCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_favorite_count_idx ON Posts USING btree (FavoriteCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_viewcount_idx ON Posts USING btree (ViewCount)
       WITH (FILLFACTOR = 100);

Add an index on AcceptedAnswerId.

-- hash index takes too long to create
CREATE INDEX posts_post_type_id_idx ON Posts USING btree (PostTypeId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_score_idx ON Posts USING btree (Score)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_creation_date_idx ON Posts USING btree (CreationDate)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_owner_user_id_idx ON Posts USING hash (OwnerUserId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_answer_count_idx ON Posts USING btree (AnswerCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_comment_count_idx ON Posts USING btree (CommentCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_favorite_count_idx ON Posts USING btree (FavoriteCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_viewcount_idx ON Posts USING btree (ViewCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_accepted_answer_id_idx ON Posts USING btree (AcceptedAnswerId)
       WITH (FILLFACTOR = 100);


SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--

CREATE TABLE `issues` (
  `id` int(10) UNSIGNED NOT NULL,
  `title` varchar(128) NOT NULL,
  `description` text,
  `scene` varchar(256) NOT NULL,
  `state` int(11) NOT NULL,
  `category` int(11) NOT NULL,
  `position` varchar(48) NOT NULL,
  `cameraPosition` varchar(48) NOT NULL,
  `cameraOrientation` varchar(48) NOT NULL,
  `orthographicSize` float DEFAULT NULL,
  `reporter` varchar(64) NOT NULL,
  `assignee` varchar(64) DEFAULT NULL,
  `screenshot` varchar(64) DEFAULT NULL,
  `time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `archived` boolean NOT NULL DEFAULT FALSE
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--

ALTER TABLE `issues`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `issues`
  ADD INDEX (`archived`);

--

ALTER TABLE `issues`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;

Enlarge SQL fields to more comfortable sizes

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--

CREATE TABLE `issues` (
  `id` int(10) UNSIGNED NOT NULL,
  `title` varchar(256) NOT NULL,
  `description` text,
  `scene` varchar(256) NOT NULL,
  `state` int(11) NOT NULL,
  `category` int(11) NOT NULL,
  `position` varchar(64) NOT NULL,
  `cameraPosition` varchar(64) NOT NULL,
  `cameraOrientation` varchar(64) NOT NULL,
  `orthographicSize` float DEFAULT NULL,
  `reporter` varchar(128) NOT NULL,
  `assignee` varchar(128) DEFAULT NULL,
  `screenshot` varchar(64) DEFAULT NULL,
  `time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `archived` boolean NOT NULL DEFAULT FALSE
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--

ALTER TABLE `issues`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `issues`
  ADD INDEX (`archived`);

--

ALTER TABLE `issues`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;


-- phpMyAdmin SQL Dump
-- version 4.7.1
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Aug 23, 2017 at 08:05 AM
-- Server version: 10.1.23-MariaDB-9+deb9u1
-- PHP Version: 7.0.22-1~dotdeb+8.1

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";

--
-- Database: `codymaze`
--

-- --------------------------------------------------------

--
-- Table structure for table `moves`
--

CREATE TABLE `moves` (
  `telegram_id` int(11) NOT NULL,
  `reached_on` datetime DEFAULT NULL,
  `cell` char(2) CHARACTER SET ascii NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- --------------------------------------------------------

--
-- Table structure for table `user_status`
--

CREATE TABLE `user_status` (
  `telegram_id` int(11) NOT NULL,
  `completed` bit(1) NOT NULL DEFAULT b'0',
  `certificate_id` char(36) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `user_status`
--
ALTER TABLE `user_status`
  ADD PRIMARY KEY (`telegram_id`);
COMMIT;

Add certificate generation data on user table

-- phpMyAdmin SQL Dump
-- version 4.7.1
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Aug 23, 2017 at 03:54 PM
-- Server version: 10.1.23-MariaDB-9+deb9u1
-- PHP Version: 7.0.22-1~dotdeb+8.1

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";

--
-- Database: `codymaze`
--

-- --------------------------------------------------------

--
-- Table structure for table `moves`
--

CREATE TABLE `moves` (
  `telegram_id` int(11) NOT NULL,
  `reached_on` datetime DEFAULT NULL,
  `cell` char(2) CHARACTER SET ascii NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- --------------------------------------------------------

--
-- Table structure for table `user_status`
--

CREATE TABLE `user_status` (
  `telegram_id` int(11) NOT NULL,
  `completed` bit(1) NOT NULL DEFAULT b'0',
  `name` varchar(255) DEFAULT NULL,
  `email` varchar(1024) DEFAULT NULL,
  `certificate_id` char(36) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `user_status`
--
ALTER TABLE `user_status`
  ADD PRIMARY KEY (`telegram_id`);
COMMIT;


-- :name create-project :<! :1
-- :doc Create new project entry.
insert into projects (id, "user", name)
  values (:id, :user, :name)
  returning *;

-- :name update-project :<! :1
-- :doc Update a existing project entry.
update projects
  set name = :name, version = :version
  where id = :id AND
        "user" = :user AND
        deleted = false
  returning *;

-- :name delete-project :! :n
-- :doc Delete specified project
update projects
  set deleted = true, deleted_at = clock_timestamp()
  where id = :id AND "user" = :user AND deleted = false;

-- :name get-project-by-id :? :1
select p.*
  from projects as p
 where p.id = :id;

-- :name get-projects :? :*
-- :doc Get the project list with page counter (by user)
select pr.*, count(pg.id) as total_pages
  from projects as pr
  left outer join pages as pg
  on pg.project = pr.id
  where pr.user = :user AND
        pr.deleted = false
  group by pr.id
  order by pr.created_at desc;

Add new sql functions for work with project shares.

-- :name create-project :<! :1
-- :doc Create new project entry.
insert into projects (id, "user", name)
  values (:id, :user, :name)
  returning *;

-- :name update-project :<! :1
-- :doc Update a existing project entry.
update projects
  set name = :name, version = :version
  where id = :id AND
        "user" = :user AND
        deleted = false
  returning *;

-- :name delete-project :! :n
-- :doc Delete specified project
update projects
  set deleted = true, deleted_at = clock_timestamp()
  where id = :id AND "user" = :user AND deleted = false;

-- :name get-project-by-id :? :1
select p.*
  from projects as p
 where p.id = :id;

-- :name get-projects :? :*
-- :doc Get the project list with page counter (by user)
select pr.*, count(pg.id) as total_pages
  from projects as pr
  left outer join pages as pg
  on pg.project = pr.id
  where pr.user = :user AND
        pr.deleted = false
  group by pr.id
  order by pr.created_at desc;

-- :name get-project-by-share-token :? :*
select p.*
  from projects as p
  inner join project_shares as ps
          on (p.id = ps.project)
  where ps.token = :token;

-- :name get-share-tokens-for-project
select s.*
  from project_shares as s
 where s.project = :project
 order by s.created_at desc;


## Add clinical_significance to variation_feature (copied from variation)
ALTER TABLE variation_feature
ADD COLUMN clinical_significance
SET('drug-response','histocompatibility','non-pathogenic','other','pathogenic','probable-non-pathogenic','probable-pathogenic''unknown','untested') DEFAULT NULL;

UPDATE variation_feature vf, variation v
SET vf.clinical_significance = v.clinical_significance
WHERE v.variation_id = vf.variation_id;

#patch identifier
INSERT INTO meta (species_id, meta_key, meta_value) VALUES (NULL, 'patch', 'patch_73_74_c.sql|Add clinical_significance to variation_feature table');

Update the clinical_significance SET in variation and variation_feature

## Add clinical_significance to variation_feature (copied from variation)
ALTER TABLE variation
MODIFY COLUMN clinical_significance
SET('drug-response','histocompatibility','non-pathogenic','other','pathogenic','probable-non-pathogenic','probable-pathogenic','unknown','untested');

ALTER TABLE variation_feature
ADD COLUMN clinical_significance
SET('drug-response','histocompatibility','non-pathogenic','other','pathogenic','probable-non-pathogenic','probable-pathogenic','unknown','untested') DEFAULT NULL;

UPDATE variation_feature vf, variation v
SET vf.clinical_significance = v.clinical_significance
WHERE v.variation_id = vf.variation_id;

#patch identifier
INSERT INTO meta (species_id, meta_key, meta_value) VALUES (NULL, 'patch', 'patch_73_74_c.sql|Add clinical_significance to variation_feature table');


-- arguments: id:string; filename:string
SELECT file
FROM module_files as mf
LEFT JOIN files f on mf.fileid = f.fileid
WHERE mf.uuid = %(id)s AND mf.filename = %(filename)s;

Join on the module to allow the uuid matching condition.

-- arguments: id:string; filename:string
SELECT f.file
FROM module_files as mf
  LEFT JOIN files f on mf.fileid = f.fileid
  LEFT JOIN modules m on mf.module_ident = m.module_ident
WHERE m.uuid = %(id)s AND mf.filename = %(filename)s;


-- This is a naive, unoptimized way of checking two
-- JSON objects for equality. It uses python's json
-- module to load and re-dump the json object while
-- sorting its keys, and then calculates the object
-- hash from it.
--
CREATE OR REPLACE FUNCTION json_hash( a json ) RETURNS INTEGER AS $$
  import json
  return hash(json.dumps(json.loads(a), sort_keys=True, separators=(',', ':')))
$$ LANGUAGE plpythonu STRICT IMMUTABLE;

CREATE OR REPLACE FUNCTION json_eq( a json, b json ) RETURNS BOOLEAN AS $$
  SELECT json_hash(a) = json_hash(b);
$$ LANGUAGE SQL STRICT IMMUTABLE;

CREATE OPERATOR = (
  LEFTARG   = json,
  RIGHTARG  = json,
  PROCEDURE = json_eq
);

CREATE OPERATOR CLASS json_ops
DEFAULT FOR TYPE JSON USING hash AS
OPERATOR    1   =  (json, json),
FUNCTION    1   json_hash(json);

Use a 64-bit integer for the JSON hash, for 64bit machines

-- This is a naive, unoptimized way of checking two
-- JSON objects for equality. It uses python's json
-- module to load and re-dump the json object while
-- sorting its keys, and then calculates the object
-- hash from it.
--
CREATE OR REPLACE FUNCTION json_hash( a json ) RETURNS INT8 AS $$
  import json
  return hash(json.dumps(json.loads(a), sort_keys=True, separators=(',', ':')))
$$ LANGUAGE plpythonu STRICT IMMUTABLE;

CREATE OR REPLACE FUNCTION json_eq( a json, b json ) RETURNS BOOLEAN AS $$
  SELECT json_hash(a) = json_hash(b);
$$ LANGUAGE SQL STRICT IMMUTABLE;

CREATE OPERATOR = (
  LEFTARG   = json,
  RIGHTARG  = json,
  PROCEDURE = json_eq
);

CREATE OPERATOR CLASS json_ops
DEFAULT FOR TYPE JSON USING hash AS
OPERATOR    1   =  (json, json),
FUNCTION    1   json_hash(json);


CREATE TABLE `translations` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `domain` varchar(100) NOT NULL,
  `locale` varchar(5) NOT NULL,
  `singular` varchar(255) NOT NULL,
  `plural` varchar(255) DEFAULT NULL,
  `context` varchar(50) DEFAULT NULL,
  `value_0` varchar(255) DEFAULT NULL,
  `value_1` varchar(255) DEFAULT NULL,
  `value_2` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `domain_locale_singular` (`domain`,`locale`,`singular`),
  KEY `domain_locale` (`domain`,`locale`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Fix table name in SQL.

CREATE TABLE `i18n_messages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `domain` varchar(100) NOT NULL,
  `locale` varchar(5) NOT NULL,
  `singular` varchar(255) NOT NULL,
  `plural` varchar(255) DEFAULT NULL,
  `context` varchar(50) DEFAULT NULL,
  `value_0` varchar(255) DEFAULT NULL,
  `value_1` varchar(255) DEFAULT NULL,
  `value_2` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `domain_locale_singular` (`domain`,`locale`,`singular`),
  KEY `domain_locale` (`domain`,`locale`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE CoffeePeople (
  Id serial PRIMARY KEY,
  Name varchar(50) not null,
  Lat double precision,
  Lng double precision
);

CREATE TABLE CoffeeTokens (
  Id serial PRIMARY KEY,
  Person serial
);

CREATE TABLE CoffeeRequests (
  Id serial PRIMARY KEY,
  Host serial,
  Date timestamp with time zone not null,
  Label varchar(100),
  Lat double precision,
  Lng double precision
);

Add relations table for responses. Also mark required values not null.

CREATE TABLE CoffeePeople (
  Id serial PRIMARY KEY,
  Name varchar(50) not null,
  Lat double precision,
  Lng double precision
);

CREATE TABLE CoffeeTokens (
  Id serial PRIMARY KEY,
  Person serial not null
);

CREATE TABLE CoffeeRequests (
  Id serial PRIMARY KEY,
  Host serial not null,
  Date timestamp with time zone not null,
  Label varchar(100) not null,
  Lat double precision,
  Lng double precision
);

CREATE TABLE CoffeeResponses {
  Id serial PRIMARY KEY,
  Request serial not null,
  Person serial not null
}


ALTER TABLE SC_Classifieds_Classifieds
ADD (description	varchar(4000)	NULL,
  price		int 			NULL)
;

Fix the bad sql instruction for MSSQL

ALTER TABLE SC_Classifieds_Classifieds
ADD description	varchar(4000)	NULL, price int NULL
;


#Create db 'des' (Database-Exercise-System)
CREATE DATABASE IF NOT EXISTS des;

#Create 'argomenti' table
CREATE TABLE IF NOT EXISTS argomenti(
	id INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
    argomento varchar(255) NOT NULL
);

#Create 'soluzioni' table
CREATE TABLE IF NOT EXISTS soluzioni(
	id INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
    soluzione varchar(255) NOT NULL
);

#Create 'domandeALG' table
CREATE TABLE IF NOT EXISTS domandeALG(
	id INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
	testo varchar(255) NOT NULL,
	soluzione INT NOT NULL,
	argomento INT NOT NULL,
	FOREIGN KEY (soluzione) REFERENCES soluzioni(id),
	FOREIGN KEY (argomento) REFERENCES argomenti(id)
);

#Create 'domandeSQL' table
CREATE TABLE IF NOT EXISTS domandeSQL(
	id INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
	testo varchar(255) NOT NULL,
	soluzione INT NOT NULL,
	argomento INT NOT NULL,
	FOREIGN KEY (soluzione) REFERENCES soluzioni(id),
	FOREIGN KEY (argomento) REFERENCES argomenti(id)
);

Fix the query and test insert Argomenti.

#Create db 'des' (Database-Exercise-System)
CREATE DATABASE IF NOT EXISTS des;

#Create 'argomenti' table
CREATE TABLE IF NOT EXISTS des.argomenti(
	id INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
    argomento varchar(255) NOT NULL
);

#Create 'soluzioni' table
CREATE TABLE IF NOT EXISTS des.soluzioni(
	id INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
    soluzione varchar(255) NOT NULL
);

#Create 'domandeALG' table
CREATE TABLE IF NOT EXISTS des.domandeALG(
	id INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
	testo varchar(255) NOT NULL,
	soluzione INT NOT NULL,
	argomento INT NOT NULL,
	FOREIGN KEY (soluzione) REFERENCES soluzioni(id),
	FOREIGN KEY (argomento) REFERENCES argomenti(id)
);

#Create 'domandeSQL' table
CREATE TABLE IF NOT EXISTS des.domandeSQL(
	id INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
	testo varchar(255) NOT NULL,
	soluzione INT NOT NULL,
	argomento INT NOT NULL,
	FOREIGN KEY (soluzione) REFERENCES soluzioni(id),
	FOREIGN KEY (argomento) REFERENCES argomenti(id)
);

#Test population argomenti
INSERT INTO des.argomenti(argomento) VALUES ('Argomento1'),('Argomento2'),('Argomento3'),('Argomento4');


SET @start_date := '2012-08-10 01:37:00';
SET @end_date := '2012-08-13 12:33:00';

DROP VIEW IF EXISTS events;
CREATE VIEW events AS
SELECT  a.event_id as id,
        a.email,
        m.category,
        a.event_type,
        m.mailing_id,
        a.job_id,
        a.queue_id,
        i.name as instance,
        i.install_class,
        i.servername,
        a.result,
        a.dt_created,
        a.dt_received,
        a.dt_processed,
        a.is_test
FROM archive a
JOIN message m ON a.message_id=m.id
JOIN instance i ON m.instance_id=i.id;

BEGIN;

INSERT INTO weekend_events
	(email, category, event_type, mailing_id, job_id, queue_id, instance, install_class, servername, dt_created, dt_received, is_test)
SELECT
	email, category, event_type, mailing_id, job_id, queue_id, instance, install_class, servername, dt_created, dt_received, is_test
FROM events WHERE dt_processed > @start_date AND dt_processed < @end_date;

DELETE FROM archive WHERE dt_processed > @start_date AND dt_processed < @end_date;

COMMIT;

Move the event keeping the same event_id.

SET @start_date := '2012-08-10 01:37:00';
SET @end_date := '2012-08-13 12:33:00';

DROP VIEW IF EXISTS events;
CREATE VIEW events AS
SELECT  a.event_id as id,
        a.email,
        m.category,
        a.event_type,
        m.mailing_id,
        a.job_id,
        a.queue_id,
        i.name as instance,
        i.install_class,
        i.servername,
        a.result,
        a.dt_created,
        a.dt_received,
        a.dt_processed,
        a.is_test
FROM archive a
JOIN message m ON a.message_id=m.id
JOIN instance i ON m.instance_id=i.id;

BEGIN;

INSERT INTO weekend_events
	(event_id, email, category, event_type, mailing_id, job_id, queue_id, instance, install_class, servername, dt_created, dt_received, is_test)
SELECT
	event_id, email, category, event_type, mailing_id, job_id, queue_id, instance, install_class, servername, dt_created, dt_received, is_test
FROM events WHERE dt_processed > @start_date AND dt_processed < @end_date;

DELETE FROM archive WHERE dt_processed > @start_date AND dt_processed < @end_date;

COMMIT;


SELECT
    asn as asn,
    ip as cidr_ip,
    ip_start as start_ip,
    ip_end as end_ip,
    NET.IPV4_TO_INT64(NET.IP_FROM_STRING(ip_start)) AS start_ip_int,
    NET.IPV4_TO_INT64(NET.IP_FROM_STRING(ip_end)) AS end_ip_int
    FROM `k8s-infra-ii-sandbox.${GCP_BIGQUERY_DATASET_WITH_DATE}.pyasn_ip_asn_extended`
    WHERE regexp_contains(ip_start, r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}");

Remove hardcoded reference of GCP_PROJECT

SELECT
    asn as asn,
    ip as cidr_ip,
    ip_start as start_ip,
    ip_end as end_ip,
    NET.IPV4_TO_INT64(NET.IP_FROM_STRING(ip_start)) AS start_ip_int,
    NET.IPV4_TO_INT64(NET.IP_FROM_STRING(ip_end)) AS end_ip_int
    FROM `${GCP_PROJECT}.${GCP_BIGQUERY_DATASET_WITH_DATE}.pyasn_ip_asn_extended`
    WHERE regexp_contains(ip_start, r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}");


# --- !Ups
CREATE TABLE IF NOT EXISTS user_basemaps(
  id SERIAL NOT NULL PRIMARY KEY,
  created timestamp without time zone DEFAULT NOW(),
  modified timestamp without time zone DEFAULT NOW(),
  user_id INTEGER NOT NULL,
  url VARCHAR NOT NULL,
  name VARCHAR NOT NULL,
  overlay BOOLEAN DEFAULT FALSE,
  CONSTRAINT user_basemaps_user_id FOREIGN KEY (user_id)
    REFERENCES users(id) MATCH SIMPLE
    ON UPDATE CASCADE ON DELETE CASCADE
);;

SELECT create_index_if_not_exists('user_basemaps', 'user_basemaps_user', '(user_id)');;

-- copy existing user custom_basemap_url into new table
INSERT INTO user_basemaps (user_id, url, name)
SELECT id, custom_basemap_url, 'Custom'
FROM users WHERE custom_basemap_url IS NOT NULL;;

ALTER TABLE users
  DROP COLUMN custom_basemap_url;;

# --- !Downs

-- read add custom_basemap_url column
ALTER TABLE users
  ADD COLUMN custom_basemap_url VARCHAR;;

-- copy custom basemap urls back into old column
UPDATE users u SET custom_basemap_url = user_basemaps.url
FROM user_basemaps
WHERE u.id = user_basemaps.user_id AND user_basemaps.name = 'Custom' AND user_basemaps.url != '';;

-- Drop table user_basemaps
DROP TABLE user_basemaps;;

Check for empty urls when migration to custom basemaps

# --- !Ups
CREATE TABLE IF NOT EXISTS user_basemaps(
  id SERIAL NOT NULL PRIMARY KEY,
  created timestamp without time zone DEFAULT NOW(),
  modified timestamp without time zone DEFAULT NOW(),
  user_id INTEGER NOT NULL,
  url VARCHAR NOT NULL,
  name VARCHAR NOT NULL,
  overlay BOOLEAN DEFAULT FALSE,
  CONSTRAINT user_basemaps_user_id FOREIGN KEY (user_id)
    REFERENCES users(id) MATCH SIMPLE
    ON UPDATE CASCADE ON DELETE CASCADE
);;

SELECT create_index_if_not_exists('user_basemaps', 'user_basemaps_user', '(user_id)');;

-- copy existing user custom_basemap_url into new table
INSERT INTO user_basemaps (user_id, url, name)
SELECT id, custom_basemap_url, 'Custom'
FROM users WHERE custom_basemap_url IS NOT NULL AND custom_basemap_url != '';;

ALTER TABLE users
  DROP COLUMN custom_basemap_url;;

# --- !Downs

-- read add custom_basemap_url column
ALTER TABLE users
  ADD COLUMN custom_basemap_url VARCHAR;;

-- copy custom basemap urls back into old column
UPDATE users u SET custom_basemap_url = user_basemaps.url
FROM user_basemaps
WHERE u.id = user_basemaps.user_id AND user_basemaps.name = 'Custom' AND user_basemaps.url != '';;

-- Drop table user_basemaps
DROP TABLE user_basemaps;;


ALTER TABLE jam
ADD COLUMN jam_default_icon_url TEXT NULL AFTER jam_colors;

UPDATE jam
SET jam_default_icon_url = "logo.png";

INSERT INTO config
(config_lastedited, config_lasteditedby, config_key, config_value, config_category, config_description, config_type, config_options, config_editable, config_required, config_added_to_dictionary)
VALUES
(Now(), '1', 'DEFAULT_GAME_ICON_URL', 'logo.png', 'NEW_JAM_DEFAULTS', 'URL to the default entry icon for entries without a custom icon', 'TEXT', '[]', '1', '1', '1');

Fix user ID in migration 32

ALTER TABLE jam
ADD COLUMN jam_default_icon_url TEXT NULL AFTER jam_colors;

UPDATE jam
SET jam_default_icon_url = "logo.png";

INSERT INTO config
(config_lastedited, config_lasteditedby, config_key, config_value, config_category, config_description, config_type, config_options, config_editable, config_required, config_added_to_dictionary)
VALUES
(Now(), '-1', 'DEFAULT_GAME_ICON_URL', 'logo.png', 'NEW_JAM_DEFAULTS', 'URL to the default entry icon for entries without a custom icon', 'TEXT', '[]', '1', '1', '1');


CREATE TABLE IF NOT EXISTS `aircraft_owner` (
  `owner_id` int(11) NOT NULL AUTO_INCREMENT,
  `registration` varchar(20) NOT NULL,
  `base` varchar(255) DEFAULT NULL,
  `owner` varchar(255) NOT NULL,
  `date_first_reg` timestamp NULL DEFAULT NULL,
  `Source` varchar(255) NOT NULL,
  PRIMARY KEY (`owner_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `aircraft_owner` ADD INDEX(`registration`);
ALTER TABLE `aircraft_owner` ADD INDEX(`owner`);

Check if this make codacy happy

CREATE TABLE IF NOT EXISTS `aircraft_owner` (
  `owner_id` int(11) NOT NULL AUTO_INCREMENT,
  `registration` varchar(20) NOT NULL,
  `base` varchar(255) DEFAULT NULL,
  `owner` varchar(255) NOT NULL,
  `date_first_reg` timestamp NULL DEFAULT NULL,
  `Source` varchar(255) NOT NULL,
  PRIMARY KEY (`owner_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE aircraft_owner ADD INDEX(registration);
ALTER TABLE aircraft_owner ADD INDEX(owner);


CREATE DATABASE notes;

USE notes;

CREATE TABLE note_users (
    UserId CHAR(32) PRIMARY KEY,
    UserEmail VARCHAR(255),
    UserPassword VARCHAR(512),
    EmailConfirmation CHAR(32),
	Active TINYINT DEFAULT '0',
	JsonAuthentication VARCHAR(128)
);

CREATE TABLE user_preferences (
	PreferenceId INT(4) PRIMARY KEY AUTO_INCREMENT,
	UserId VARCHAR(60),
    TagColor VARCHAR(6) DEFAULT 'red',
	Pagination TINYINT DEFAULT '1',
	NoteOrder VARCHAR(15) DEFAULT 'oldest',
	SearchOptions VARCHAR(50) DEFAULT 'a:2:{i:0;s:4:"true";i:1;s:4:"true";}',
	FOREIGN KEY (UserId) REFERENCES note_users(UserId) ON DELETE CASCADE
);

CREATE TABLE note (
    NoteId INT(11) AUTO_INCREMENT PRIMARY KEY,
    NoteText VARCHAR(1024),
    NoteTags VARCHAR(1024),
	NoteTitle VARCHAR(256),
	NoteComplete TINYINT NULL DEFAULT '0',
	UserId VARCHAR(60),
	FOREIGN KEY (UserId) REFERENCES note_users(UserId) ON DELETE CASCADE
);

Change field size and default. Add datestamp for when the item was last edited

CREATE DATABASE notes;

USE notes;

CREATE TABLE note_users (
    UserId CHAR(32) PRIMARY KEY,
    UserEmail VARCHAR(255),
    UserPassword VARCHAR(512),
    EmailConfirmation CHAR(32),
	Active TINYINT DEFAULT '0',
	JsonAuthentication VARCHAR(128)
);

CREATE TABLE user_preferences (
	PreferenceId INT(4) PRIMARY KEY AUTO_INCREMENT,
	UserId VARCHAR(60),
    TagColor VARCHAR(6) DEFAULT 'red',
	Pagination TINYINT DEFAULT '1',
	NoteOrder VARCHAR(15) DEFAULT 'oldest',
	SearchOptions VARCHAR(80) DEFAULT 'a:3:{i:0;s:4:"true";i:1;s:4:"true";i:2;s:5:"false";}',
	FOREIGN KEY (UserId) REFERENCES note_users(UserId) ON DELETE CASCADE
);

CREATE TABLE note (
    NoteId INT(11) AUTO_INCREMENT PRIMARY KEY,
    NoteText VARCHAR(1024),
    NoteTags VARCHAR(1024),
	NoteTitle VARCHAR(256),
	NoteComplete TINYINT NULL DEFAULT '0',
	UserId VARCHAR(60),
	NoteLastEdited TIMESTAMP DEFAULT CURRENT_TIMESTAMP(),
	FOREIGN KEY (UserId) REFERENCES note_users(UserId) ON DELETE CASCADE
);


drop database if exists mo_development;
create database mo_development;
drop database if exists mo_test;
create database mo_test;
drop database if exists mo_tmp;
create database mo_tmp;
use mo_tmp;

drop procedure if exists createUser;
delimiter $$
create procedure createUser(username varchar(50), pw varchar(50))
begin
IF (SELECT EXISTS(SELECT 1 FROM `mysql`.`user` WHERE `user` = username)) = 0 THEN
    begin
    set @sql = CONCAT('CREATE USER ', username, '@\'localhost\' IDENTIFIED BY \'', pw, '\'');
    prepare stmt from @sql;
    execute stmt;
    deallocate prepare stmt;
    end;
END IF;
end $$
delimiter ;

call createUser('mo', 'mo');
use mo_test;
drop database mo_tmp;

grant all privileges on mo_development.* to 'mo'@'localhost' with grant option;
grant all privileges on mo_test.* to 'mo'@'localhost' with grant option;

Set db default collation & charset

drop database if exists mo_development;
create database mo_development
  DEFAULT CHARACTER SET utf8
  DEFAULT COLLATE utf8_general_ci;
drop database if exists mo_test;
create database mo_test
  DEFAULT CHARACTER SET utf8
  DEFAULT COLLATE utf8_general_ci;
drop database if exists mo_tmp;
create database mo_tmp;
use mo_tmp;

drop procedure if exists createUser;
delimiter $$
create procedure createUser(username varchar(50), pw varchar(50))
begin
IF (SELECT EXISTS(SELECT 1 FROM `mysql`.`user` WHERE `user` = username)) = 0 THEN
    begin
    set @sql = CONCAT('CREATE USER ', username, '@\'localhost\' IDENTIFIED BY \'', pw, '\'');
    prepare stmt from @sql;
    execute stmt;
    deallocate prepare stmt;
    end;
END IF;
end $$
delimiter ;

call createUser('mo', 'mo');
use mo_test;
drop database mo_tmp;

grant all privileges on mo_development.* to 'mo'@'localhost' with grant option;
grant all privileges on mo_test.* to 'mo'@'localhost' with grant option;


-- add the name column, which was missing before
alter table configurations
	add name varchar(250) null;

-- add the descriptions column
alter table configurations
	add description varchar(1000) null;

-- add the group name column wich was missing before
alter table configurations
	add groupName varchar(250) not null default('General');

-- add the display order column which was missing before.
alter table configurations
	add displayOrder int not null default(1);

-- add the value types column,
-- the possible values for this column include but not limited to ..
-- TEXT_AREA, TEXT, OPTION, BOOLEAN, NUMBER, DECIMAL, EMAIL, PASSWORD
alter table configurations
add value_type varchar(250) default('TEXT') not null;

-- Add the value options column
alter table configurations
  add value_options varchar(1000);

-- copy over the name from the keys column
update configurations set name = key;

-- convert the key column to an upper case text keys
update configurations set key = UPPER(key);

-- now let's clean out the required fields
alter table configurations
	alter column name set not null;

Fix wrong column names, '_' separated to camel case column names.

-- add the name column, which was missing before
alter table configurations
	add name varchar(250) null;

-- add the descriptions column
alter table configurations
	add description varchar(1000) null;

-- add the group name column wich was missing before
alter table configurations
	add groupName varchar(250) not null default('General');

-- add the display order column which was missing before.
alter table configurations
	add displayOrder int not null default(1);

-- add the value types column,
-- the possible values for this column include but not limited to ..
-- TEXT_AREA, TEXT, OPTION, BOOLEAN, NUMBER, DECIMAL, EMAIL, PASSWORD
alter table configurations
add valueType varchar(250) default('TEXT') not null;

-- Add the value options column
alter table configurations
  add valueOptions varchar(1000);

-- copy over the name from the keys column
update configurations set name = key;

-- convert the key column to an upper case text keys
update configurations set key = UPPER(key);

-- now let's clean out the required fields
alter table configurations
	alter column name set not null;


/*==LICENSE==
This file is part of Musec.
Copyright (C) 2013 Florian Meißner

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
==LICENSE==*/

\connect musec

SET client_encoding = 'UTF8';
SET standard_conforming_strings = off;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET escape_string_warning = off;

CREATE TABLE scores (
    id serial,
    username varchar(64) NOT NULL,
    scoredate timestamp DEFAULT now(),
    average decimal,
    score integer,
    played integer,
    bingo integer,
    streak integer,
    difficulty varchar(32)
);
ALTER TABLE scores OWNER TO musec;

Add primary key to scores table

/*==LICENSE==
This file is part of Musec.
Copyright (C) 2013 Florian Meißner

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
==LICENSE==*/

\connect musec

SET client_encoding = 'UTF8';
SET standard_conforming_strings = off;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET escape_string_warning = off;

CREATE TABLE scores (
    id serial PRIMARY KEY,
    username varchar(64) NOT NULL,
    scoredate timestamp DEFAULT now(),
    average decimal,
    score integer,
    played integer,
    bingo integer,
    streak integer,
    difficulty varchar(32)
);
ALTER TABLE scores OWNER TO musec;


BEGIN;

SELECT plan(2);

SELECT trend_directory.create_table_trend_store(
    'test1',
    'some_entity_type_name',
    '900',
    ARRAY[
        ('x', 'integer', 'some column with integer values')
    ]::trend_directory.trend_descr[]
);

SELECT columns_are(
    'trend',
    'test1_some_entity_type_name_qtr',
    ARRAY[
        'entity_id',
        'timestamp',
        'modified',
        'x'
    ]
);

SELECT trend_directory.alter_trend_name(
    table_trend_store,
    'x',
    'y'
)
FROM trend_directory.table_trend_store;

SELECT columns_are(
    'trend',
    'test1_some_entity_type_name_qtr',
    ARRAY[
        'entity_id',
        'timestamp',
        'modified',
        'y'
    ]
);

SELECT * FROM finish();
ROLLBACK;

Add test of name in trend record

BEGIN;

SELECT plan(3);

SELECT trend_directory.create_table_trend_store(
    'test1',
    'some_entity_type_name',
    '900',
    ARRAY[
        ('x', 'integer', 'some column with integer values')
    ]::trend_directory.trend_descr[]
);

SELECT columns_are(
    'trend',
    'test1_some_entity_type_name_qtr',
    ARRAY[
        'entity_id',
        'timestamp',
        'modified',
        'x'
    ]
);

SELECT trend_directory.alter_trend_name(
    table_trend_store,
    'x',
    'y'
)
FROM trend_directory.table_trend_store;

SELECT is(name, 'y'::name, 'trend should have new name')
FROM trend_directory.table_trend
JOIN trend_directory.table_trend_store ON table_trend_store.id = table_trend.trend_store_id
WHERE table_trend_store::name = 'test1_some_entity_type_name_qtr';

SELECT columns_are(
    'trend',
    'test1_some_entity_type_name_qtr',
    ARRAY[
        'entity_id',
        'timestamp',
        'modified',
        'y'
    ]
);

SELECT * FROM finish();
ROLLBACK;


set head off
set newp none
set recsep off
set echo off
set serveroutput off
set tab off
set line 500
set wrap off
set feedback off
set verify off

SELECT  'OPTIONS(DIRECT=TRUE,ROWS=1000000) LOAD DATA TRUNCATE INTO TABLE ' || upper('A2_&1') ||
        ' FIELDS TERMINATED BY ''\t''' ||
        ' TRAILING NULLCOLS (' || Listagg(Column_Name ||
          Decode(Data_Type, 'VARCHAR2', ' CHAR(' || data_length || ')', 'DATE', ' DATE "YYYY-MM-DD HH24:MI:SS"' ), ',') WITHIN GROUP (ORDER BY column_id) || ')'
FROM user_tab_columns WHERE table_name=upper('A2_&1');

quit;

Use WM_CONCAT - exists in Oracle < 11.2

set head off
set newp none
set recsep off
set echo off
set serveroutput off
set tab off
set line 500
set wrap off
set feedback off
set verify off

SELECT  'OPTIONS(DIRECT=TRUE,ROWS=1000000) LOAD DATA TRUNCATE INTO TABLE ' || upper('A2_&1') ||
        ' FIELDS TERMINATED BY ''\t''' ||
        ' TRAILING NULLCOLS (' || WM_CONCAT(Column_Name ||
          Decode(Data_Type, 'VARCHAR2', ' CHAR(' || data_length || ')', 'DATE', ' DATE "YYYY-MM-DD HH24:MI:SS"' )) || ')'
FROM user_tab_columns WHERE table_name=upper('A2_&1');

quit;


# Script to drop and recreate all databases and users

# Do some dummy grants, which will create the user if it didn't already
# exist, so that the following DROP USER won't give an error:
GRANT USAGE ON *.* TO 'toolkit'@'localhost';
# Now drop the user
DROP USER 'toolkit'@'localhost';

# And re-create
CREATE USER 'toolkit'@'localhost' IDENTIFIED BY 'devserver_db_password';

DROP DATABASE IF EXISTS toolkit;
CREATE DATABASE `toolkit` CHARACTER SET 'utf8';

# Give the general user permissions on the django db:
GRANT ALTER,CREATE,DELETE,DROP,INDEX,INSERT,SELECT,SHOW VIEW,UPDATE ON `toolkit`.* to `toolkit`@`localhost`;

FLUSH PRIVILEGES;

Fix issues with database script

# Script to drop and recreate all databases and users

# Now drop the user if present
DROP USER IF EXISTS 'toolkit'@'localhost';

# And re-create
CREATE USER 'toolkit'@'localhost' IDENTIFIED BY 'devserver_db_password';

DROP DATABASE IF EXISTS toolkit;
CREATE DATABASE `toolkit` CHARACTER SET 'utf8';

# Give the general user permissions on the django db:
GRANT ALTER,CREATE,DELETE,DROP,INDEX,INSERT,SELECT,SHOW VIEW,REFERENCES,UPDATE ON `toolkit`.* to `toolkit`@`localhost`;

FLUSH PRIVILEGES;


-- Author: dan.leehr@nescent.org
--

-- Organizations
CREATE SEQUENCE organization_seq;
CREATE TABLE organization
(
  organization_id INTEGER PRIMARY KEY not null default nextval('organization_seq'),
  code VARCHAR(32) not null,
  name VARCHAR(255) not null
);

CREATE UNIQUE INDEX org_code_idx on organization(code);

-- Manuscripts
CREATE SEQUENCE manuscript_seq;
CREATE TABLE manuscript
(
  manuscript_id INTEGER PRIMARY KEY not null default nextval('manuscript_seq'),
  organization_id INTEGER not null REFERENCES organization(organization_id),
  id VARCHAR(255) not null,
  version INTEGER not null default 1,
  json_data text
);

CREATE UNIQUE INDEX manuscript_id_ver_idx on manuscript(id, version);
CREATE INDEX manuscript_id_idx ON manuscript(id);

-- OAuth2 Tokens
CREATE SEQUENCE oauth_token_seq;
CREATE TABLE oauth_token
(
  oauth_token_id INTEGER PRIMARY KEY not null default nextval('oauth_token_seq'),
  eperson_id INTEGER not null REFERENCES eperson(eperson_id),
  token VARCHAR(32) not null,
  expires DATE
);

-- API users and permissions
-- should these just be tied to dspace resource policy?

Change id column to msid

-- Author: dan.leehr@nescent.org
--

-- Organizations
CREATE SEQUENCE organization_seq;
CREATE TABLE organization
(
  organization_id INTEGER PRIMARY KEY not null default nextval('organization_seq'),
  code VARCHAR(32) not null,
  name VARCHAR(255) not null
);

CREATE UNIQUE INDEX org_code_idx on organization(code);

-- Manuscripts
CREATE SEQUENCE manuscript_seq;
CREATE TABLE manuscript
(
  manuscript_id INTEGER PRIMARY KEY not null default nextval('manuscript_seq'),
  organization_id INTEGER not null REFERENCES organization(organization_id),
  msid VARCHAR(255) not null,
  version INTEGER not null default 1,
  json_data text
);

CREATE UNIQUE INDEX manuscript_msid_ver_idx on manuscript(msid, version);
CREATE INDEX manuscript_msid_idx ON manuscript(msid);

-- OAuth2 Tokens
CREATE SEQUENCE oauth_token_seq;
CREATE TABLE oauth_token
(
  oauth_token_id INTEGER PRIMARY KEY not null default nextval('oauth_token_seq'),
  eperson_id INTEGER not null REFERENCES eperson(eperson_id),
  token VARCHAR(32) not null,
  expires DATE
);

-- API users and permissions
-- should these just be tied to dspace resource policy?


CREATE USER cachito WITH PASSWORD 'mypassword';
CREATE DATABASE cachito;
GRANT ALL PRIVILEGES ON DATABASE cachito TO koji;
GRANT ALL PRIVILEGES ON DATABASE cachito TO cachito;

Remove koji user privileges on cachito DB

CREATE USER cachito WITH PASSWORD 'mypassword';
CREATE DATABASE cachito;
GRANT ALL PRIVILEGES ON DATABASE cachito TO cachito;


-- hash index takes too long to create
CREATE INDEX posts_post_type_id_idx on Posts USING btree (PostTypeId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_score_idx on Posts USING btree (Score)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_creation_date_idx on Posts USING btree (CreationDate)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_owner_user_id_idx on Posts USING hash (OwnerUserId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_answer_count_idx on Posts USING btree (AnswerCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_comment_count_idx on Posts USING btree (CommentCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_favorite_count_idx on Posts USING btree (FavoriteCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_viewcount_idx on Posts USING btree (ViewCount)
       WITH (FILLFACTOR = 100);

-- Composite indexes (optional)
CREATE INDEX posts_id_post_type_id_idx on Posts USING btree (Id, PostTypeId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_id_parent_id_idx on Posts USING btree (Id, ParentId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_id_accepted_answers_id_idx on Posts USING btree (Id, AcceptedAnswerId)
       WITH (FILLFACTOR = 100);

Add another composite index on Posts.

-- hash index takes too long to create
CREATE INDEX posts_post_type_id_idx ON Posts USING btree (PostTypeId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_score_idx ON Posts USING btree (Score)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_creation_date_idx ON Posts USING btree (CreationDate)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_owner_user_id_idx ON Posts USING hash (OwnerUserId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_answer_count_idx ON Posts USING btree (AnswerCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_comment_count_idx ON Posts USING btree (CommentCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_favorite_count_idx ON Posts USING btree (FavoriteCount)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_viewcount_idx ON Posts USING btree (ViewCount)
       WITH (FILLFACTOR = 100);

-- Composite indexes (optional)
CREATE INDEX posts_id_post_type_id_idx ON Posts USING btree (Id, PostTypeId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_id_parent_id_idx ON Posts USING btree (Id, ParentId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_id_accepted_answers_id_idx ON Posts USING btree (Id, AcceptedAnswerId)
       WITH (FILLFACTOR = 100);
CREATE INDEX posts_owner_user_id_creation_date_idx ON Posts USING btree (OwnerUserId, CreationDate)
       WITH (FILLFACTOR = 100);


-- o/` Leave the past behind, just walk away o/`

DROP TABLE IF EXISTS auth_user_groups;
DROP TABLE IF EXISTS auth_user_user_permissions;
DROP TABLE IF EXISTS django_admin_log;
DROP TABLE IF EXISTS auth_user;
DROP TABLE IF EXISTS addons_categories;
DROP TABLE IF EXISTS categories;

ALTER TABLE files DROP COLUMN is_packaged;
ALTER TABLE addon_payment_account DROP COLUMN set_price;

Change foreign key, don't kill entire table

-- o/` Leave the past behind, just walk away o/`

ALTER TABLE django_admin_log DROP FOREIGN KEY `user_id_refs_id_c8665aa`;
ALTER TABLE django_admin_log ADD FOREIGN KEY `django_admin_log_user_id_52fdd58701c5f563_fk_users_id` (`user_id`) REFERENCES `users` (`id`);
DROP TABLE IF EXISTS auth_user_groups;
DROP TABLE IF EXISTS auth_user_user_permissions;
DROP TABLE IF EXISTS auth_user;
DROP TABLE IF EXISTS addons_categories;
DROP TABLE IF EXISTS categories;

ALTER TABLE files DROP COLUMN is_packaged;
ALTER TABLE addon_payment_account DROP COLUMN set_price;


SELECT
       v.research_entity as research_entity,
       rit.type as item_type,
       rit.key as item_key,
       MIN(p.filing_year) AS min,
       MAX(p.filing_year) AS max
FROM verify v
       JOIN patent p on v.research_item = p.id
       JOIN research_item_type rit ON p.type = rit.id
WHERE v.research_entity = $1
GROUP BY research_entity, item_key, item_type;

Add queries for patents min max years

SELECT
       v.research_entity as research_entity,
       rit.type as item_type,
       'prosecutions' as item_key,
       CAST(MIN(p.filing_year) AS text) AS min,
       CAST(MAX(p.filing_year) AS text) AS max
FROM verify v
       JOIN patent p on v.research_item = p.id
       JOIN research_item_type rit ON p.type = rit.id
WHERE p.translation = false AND priority = false AND v.research_entity = $1
GROUP BY research_entity, item_type, item_key

UNION ALL

SELECT
       v.research_entity as research_entity,
       rit.type as item_type,
       'priorities' as item_key,
       CAST(MIN(p.filing_year) AS text) AS min,
       CAST(MAX(p.filing_year) AS text) AS max
FROM verify v
       JOIN patent p on v.research_item = p.id
       JOIN research_item_type rit ON p.type = rit.id
WHERE p.translation = false AND priority = true AND v.research_entity = $1
GROUP BY research_entity, item_type, item_key

UNION ALL

SELECT
       v.research_entity as research_entity,
       rit.type as item_type,
       'all' as item_key,
       CAST(MIN(p.filing_year) AS text) AS min,
       CAST(MAX(p.filing_year) AS text) AS max
FROM verify v
       JOIN patent p on v.research_item = p.id
       JOIN research_item_type rit ON p.type = rit.id
WHERE p.translation = false AND v.research_entity = $1
GROUP BY research_entity, item_type, item_key

UNION ALL

SELECT
       research_entity,
       item_type,
       item_key,
       MIN(subquery.min) AS min,
       MAX(subquery.max) AS max
FROM (
       SELECT
              v.research_entity as research_entity,
              rit.type as item_type,
              'all_translations' as item_key,
              CAST(LEAST(p.filing_year, p.issue_year) AS text) AS min,
              CAST(GREATEST(p.filing_year, p.issue_year) AS text) AS max
	FROM verify v
              JOIN patent p on v.research_item = p.id
              JOIN research_item_type rit ON p.type = rit.id
       WHERE v.research_entity = $1
) subquery
GROUP BY research_entity, item_type, item_key;


CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TABLE applications(
uuid uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
name text,
original_name text
);

CREATE TABLE traces(
uuid uuid PRIMARY KEY,
transaction_uuid uuid,
origin_uuid uuid,
application_uuid uuid,
name text,
start_time timestamp(6),
end_time timestamp(6),
meta jsonb
);

CREATE TABLE spans(
trace_uuid uuid,
uuid uuid,
name text,
start_time timestamp(6),
end_time timestamp(6),
meta jsonb,
FOREIGN KEY (trace_uuid) REFERENCES traces(uuid)
);

Add application foreign key to traces database representation

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TABLE applications(
uuid uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
name text,
original_name text
);

CREATE TABLE traces(
uuid uuid PRIMARY KEY,
transaction_uuid uuid,
origin_uuid uuid,
application_uuid uuid,
name text,
start_time timestamp(6),
end_time timestamp(6),
meta jsonb,
FOREIGN KEY (application_uuid) REFERENCES applications(uuid)
);

CREATE TABLE spans(
trace_uuid uuid,
uuid uuid,
name text,
start_time timestamp(6),
end_time timestamp(6),
meta jsonb,
FOREIGN KEY (trace_uuid) REFERENCES traces(uuid)
);


CREATE OR REPLACE FORCE VIEW db_dashboard.v_session_sys_stat (
    sid,
    name,
    value )
AS
SELECT stat.sid,
        s.name,
        stat.value
    FROM v$sesstat stat
    JOIN v$sysstat s
        ON ( stat.statistic = s.statistic# )
    WHERE s.name IN (
                'bytes received via SQL*Net from client', 'bytes received via SQL*Net from dblink',
                'bytes sent via SQL*Net to client', 'bytes sent via SQL*Net to dblink', 'consistent changes',
                'consistent gets', 'consistent gets from cache', 'db block changes', 'db block gets',
                'db block gets from cache', 'physical read bytes', 'physical reads', 'physical reads cache',
                'physical read total bytes', 'physical write bytes', 'physical writes', 'physical write total bytes',
                'redo buffer allocation retries', 'session logical reads' ) ;

COMMENT ON TABLE db_dashboard.v_session_sys_stat IS 'Stats of interest by session' ;

Adjust indentation on wrapped IN clause


@&&run_dir_begin

SET SERVEROUTPUT ON

prompt Dropping types
BEGIN
    FOR i IN (SELECT 'DROP TYPE '|| o.object_name ||' FORCE' sql_comm
                   , o.*
                FROM all_objects o
               WHERE object_name LIKE 'QUILT_%'
                 AND object_type = 'TYPE'
               ORDER BY object_id DESC) LOOP
    BEGIN
        --EXECUTE IMMEDIATE i.sql_comm;
        dbms_output.put_line(i.sql_comm);
        dbms_output.put_line('Drop type :'|| i.object_name ||' in schema :'|| i.owner);
    EXCEPTION
        WHEN OTHERS THEN
            dbms_output.put_line('Don''t drop type :'|| i.object_name ||' ERROR:'|| sqlerrm);
    END;
    END LOOP;
END;
/

@&&run_dir_end

Rename type - oprava SQL skriptu pro drop typu

@&&run_dir_begin

SET SERVEROUTPUT ON

prompt Dropping types
BEGIN
    FOR i IN (SELECT 'DROP TYPE '|| o.object_name ||' FORCE' sql_comm
                   , o.*
                FROM all_objects o
               WHERE object_name LIKE 'QUILT_%'
                 AND object_type = 'TYPE'
               ORDER BY object_id DESC) LOOP
    BEGIN
        EXECUTE IMMEDIATE i.sql_comm;
        --dbms_output.put_line(i.sql_comm);
        dbms_output.put_line('Drop type :'|| i.object_name ||' in schema :'|| i.owner);
    EXCEPTION
        WHEN OTHERS THEN
            dbms_output.put_line('Don''t drop type :'|| i.object_name ||' ERROR:'|| sqlerrm);
    END;
    END LOOP;
END;
/

@&&run_dir_end


-- Generate core schema
\i schema/generate/01-schema.sql
\i schema/generate/02-augur_data.sql
\i schema/generate/03-augur_operations.sql
\i schema/generate/04-spdx.sql
\i schema/generate/05-seed_data.sql

-- Update scripts
\i schema/generate/06-schema_update_8.sql
\i schema/generate/07-schema_update_9.sql
\i schema/generate/08-schema_update_10.sql
\i schema/generate/09-schema_update_11.sql
\i schema/generate/10-schema_update_12.sql
\i schema/generate/10-schema_update_12.sql
\i schema/generate/11-schema_update_13.sql
\i schema/generate/12-schema_update_14.sql
\i schema/generate/13-schema_update_15.sql
\i schema/generate/14-schema_update_16.sql

Add v17 update script to schema creation script

-- Generate core schema
\i schema/generate/01-schema.sql
\i schema/generate/02-augur_data.sql
\i schema/generate/03-augur_operations.sql
\i schema/generate/04-spdx.sql
\i schema/generate/05-seed_data.sql

-- Update scripts
\i schema/generate/06-schema_update_8.sql
\i schema/generate/07-schema_update_9.sql
\i schema/generate/08-schema_update_10.sql
\i schema/generate/09-schema_update_11.sql
\i schema/generate/10-schema_update_12.sql
\i schema/generate/10-schema_update_12.sql
\i schema/generate/11-schema_update_13.sql
\i schema/generate/12-schema_update_14.sql
\i schema/generate/13-schema_update_15.sql
\i schema/generate/14-schema_update_16.sql
\i schema/generate/15-schema_update_17.sql


use x2data
SELECT
  'local_id',
  'course_number',
  'school_local_id',
  'section_number',
  'term_local_id'
UNION ALL
SELECT
  STF_ID_LOCAL,
  CSK_COURSE_NUMBER,
  SKL_SCHOOL_ID,
  MST_COURSE_VIEW,
  MST_TERM_VIEW
FROM district_school_year_context
LEFT JOIN SCHEDULE
  ON district_school_year_context.CTX_OID = schedule.SCH_CTX_OID
LEFT JOIN schedule_master
  ON schedule.SCH_OID = schedule_master.MST_SCH_OID
LEFT JOIN schedule_master_teacher
  ON schedule_master.MST_OID = schedule_master_teacher.MTC_MST_OID
LEFT JOIN course_school
  ON schedule_master.MST_CSK_OID = course_school.CSK_OID
INNER JOIN school
  ON course_school.CSK_SKL_OID = school.SKL_OID
INNER JOIN staff
  ON schedule_master_teacher.MTC_STF_OID = staff.STF_OID
AND CTX_SCHOOL_YEAR=2018
  INTO OUTFILE "E:/_BACKUP_MYSQL/CodeForAmerica/educator_section_assignment_export.txt"
  FIELDS TERMINATED BY ','
  ENCLOSED BY '"'
  LINES TERMINATED BY '\r\n'

Add login_name to EducatorSectionAssignment export SQL

use x2data
SELECT
  'local_id',
  'login_name',
  'course_number',
  'school_local_id',
  'section_number',
  'term_local_id'
UNION ALL
SELECT
  STF_ID_LOCAL,
  USR_LOGIN_NAME,
  CSK_COURSE_NUMBER,
  SKL_SCHOOL_ID,
  MST_COURSE_VIEW,
  MST_TERM_VIEW
FROM district_school_year_context
LEFT JOIN SCHEDULE
  ON district_school_year_context.CTX_OID = schedule.SCH_CTX_OID
LEFT JOIN schedule_master
  ON schedule.SCH_OID = schedule_master.MST_SCH_OID
LEFT JOIN schedule_master_teacher
  ON schedule_master.MST_OID = schedule_master_teacher.MTC_MST_OID
LEFT JOIN course_school
  ON schedule_master.MST_CSK_OID = course_school.CSK_OID
INNER JOIN school
  ON course_school.CSK_SKL_OID = school.SKL_OID
INNER JOIN staff
  ON schedule_master_teacher.MTC_STF_OID = staff.STF_OID
INNER JOIN person
  ON staff.STF_PSN_OID=person.PSN_OID
INNER JOIN user_info
  ON person.PSN_OID=user_info.USR_PSN_OID
AND CTX_SCHOOL_YEAR=2018
  INTO OUTFILE "E:/_BACKUP_MYSQL/CodeForAmerica/educator_section_assignment_export.txt"
  FIELDS TERMINATED BY ','
  ENCLOSED BY '"'
  LINES TERMINATED BY '\r\n'


create table table1 (col1 int,col2 int);
create table table2 (col1 int,col2 int);

insert into table1 (col1,col2) values (1,10),(2,20),(3,30);
insert into table2 (col1,col2) values (1,100),(2,200);

select * from table1;
select * from table2;

update table1 set col2=(select table2.col2 from table2 where table2.col1=table1.col1) where exists (select * from table2 where table1.col1=table2.col1);

select * from table1;

Drop tables at end of test.

create table table1 (col1 int,col2 int);
create table table2 (col1 int,col2 int);

insert into table1 (col1,col2) values (1,10),(2,20),(3,30);
insert into table2 (col1,col2) values (1,100),(2,200);

select * from table1;
select * from table2;

update table1 set col2=(select table2.col2 from table2 where table2.col1=table1.col1) where exists (select * from table2 where table1.col1=table2.col1);

select * from table1;

drop table table1;
drop table table2;


SELECT distinct
  ir.rowId as runId,
  replace(a.uw_udds, '-', '')  as Department,
  a.uw_fund as Fund,
  '4' as Program,
  a.uw_account as Project,
  a.charge_grant_accounts_Id as Account,
  invoicedItems.totalcost as Amount,
  'Primate Center ' || to_char(ir.billingPeriodStart,'MON') as Description,
  to_char(ir.billingPeriodEnd, 'MMyy') || a.uw_account as Jnl_Ln_Ref,
  to_char(ir.billingPeriodEnd, 'MMyy') as billingPeriodMMyy,
  NULL as Class,
  NULL as PurchRefNo,
  NULL as VoucherNo,
  NULL as InvoiceNo,
  NULL as ActivityID
FROM
  ehr_billing.invoicedItems
  left join ehr_billing.aliases a
    on invoicedItems.debitedAccount = a.alias
  left join ehr_billing.invoiceRuns ir
    on ir.objectid = invoicedItems.invoiceId
  WHERE
    a.type like '%internal%'

Fix jetInvoiceItem query to sum the total cost per Account.

SELECT
  ii.invoiceId.rowId as runId,
  replace(a.uw_udds, '-', '')  as Department,
  a.uw_fund as Fund,
  '4' as Program,
  a.uw_account as Project,
  a.charge_grant_accounts_Id as Account,
  sum(ii.totalcost) as Amount,
  'Primate Center ' || to_char(ii.invoiceId.billingPeriodStart,'MON') as Description,
  to_char(ii.invoiceId.billingPeriodEnd, 'MMyy') || a.uw_account as Jnl_Ln_Ref,
  to_char(ii.invoiceId.billingPeriodEnd, 'MMyy') as billingPeriodMMyy,
  NULL as Class,
  NULL as PurchRefNo,
  NULL as VoucherNo,
  NULL as InvoiceNo,
  NULL as ActivityID
FROM
  ehr_billing.invoicedItems ii
  left join ehr_billing.aliases a
    on ii.debitedAccount = a.alias
  WHERE
    a.type like '%internal%'
GROUP BY
     ii.invoiceId.rowId,
     a.uw_udds,
     a.uw_fund,
     a.uw_account,
     a.charge_grant_accounts_Id,
     ii.invoiceId.billingPeriodStart,
     ii.invoiceId.billingPeriodEnd


\i schema/generate/1-schema.sql
\i schema/generate/2-augur_data.sql
\i schema/generate/3-augur_operations.sql
\i schema/generate/4-spdx.sql
\i schema/generate/5-seed-data.sql
\i schema/generate/6-schema_update_8.sql
\i schema/generate/7-schema_update_9.sql
\i schema/generate/8-schema_update_10.sql
\i schema/generate/8-schema_update_11_pr_commits.sql

Fix incorrect version 11 schema update script name

\i schema/generate/1-schema.sql
\i schema/generate/2-augur_data.sql
\i schema/generate/3-augur_operations.sql
\i schema/generate/4-spdx.sql
\i schema/generate/5-seed-data.sql
\i schema/generate/6-schema_update_8.sql
\i schema/generate/7-schema_update_9.sql
\i schema/generate/8-schema_update_10.sql
\i schema/generate/9-schema_update_11_pr_commits.sql


DROP DATABASE IF EXISTS ouija;

CREATE DATABASE ouija;
USE ouija;

CREATE TABLE IF NOT EXISTS `testjobs` (
  `id` int(11) NOT NULL,
  `log` varchar(1024) NOT NULL,
  `slave` varchar(64) NOT NULL,
  `result` varchar(32) NOT NULL,
  `duration` int(11) NOT NULL,
  `platform` varchar(32) NOT NULL,
  `buildtype` varchar(32) NOT NULL,
  `testtype` varchar(64) NOT NULL,
  `bugid` varchar(32) NOT NULL,
  `branch` varchar(64) NOT NULL,
  `revision` varchar(32) NOT NULL,
  `date` datetime NOT NULL,
  primary key(id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Add index on date to testjobs table

DROP DATABASE IF EXISTS ouija;

CREATE DATABASE ouija;
USE ouija;

CREATE TABLE IF NOT EXISTS `testjobs` (
  `id` int(11) NOT NULL,
  `log` varchar(1024) NOT NULL,
  `slave` varchar(64) NOT NULL,
  `result` varchar(32) NOT NULL,
  `duration` int(11) NOT NULL,
  `platform` varchar(32) NOT NULL,
  `buildtype` varchar(32) NOT NULL,
  `testtype` varchar(64) NOT NULL,
  `bugid` varchar(32) NOT NULL,
  `branch` varchar(64) NOT NULL,
  `revision` varchar(32) NOT NULL,
  `date` datetime NOT NULL,
  primary key(id),
  index `date` (`date`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


--

ALTER TABLE `storages` ADD `wowza_dvr` tinyint default 0;
ALTER TABLE `storages` CHANGE `flussonic_server` `flussonic_dvr` tinyint default 0;
ALTER TABLE `itv` ADD `wowza_dvr` tinyint default 0;

--//@UNDO

ALTER TABLE `storages` DROP `wowza_dvr`;
ALTER TABLE `storages` CHANGE `flussonic_dvr` `flussonic_server` tinyint default 0;
ALTER TABLE `itv` DROP `wowza_dvr`;

--

Fix wowza_dvr in itv table

--

ALTER TABLE `storages` ADD `wowza_dvr` tinyint default 0;
ALTER TABLE `storages` CHANGE `flussonic_server` `flussonic_dvr` tinyint default 0;

--//@UNDO

ALTER TABLE `storages` DROP `wowza_dvr`;
ALTER TABLE `storages` CHANGE `flussonic_dvr` `flussonic_server` tinyint default 0;

--


insert into speakeasy_petition_metrics (activity, campaign_id , npeople) select 'unique_recipient', cp.id, count(Distinct contact_id) from civicrm_mailing m join civicrm_mailing_recipients r on r.mailing_id=m.id and m.name not like "%-Reminder-%" join civicrm_campaign cp on cp.id=m.campaign_id group by campaign_id;

Format script for unique recipients

INSERT INTO speakeasy_petition_metrics (activity, campaign_id, npeople) SELECT
  'unique_recipient', cp.id, count(DISTINCT contact_id)
FROM civicrm_mailing m
  JOIN civicrm_mailing_recipients r ON r.mailing_id = m.id AND m.name NOT LIKE '%-Reminder-%'
  JOIN civicrm_campaign cp ON cp.id = m.campaign_id
GROUP BY campaign_id;


create type distribution as enum('stable', 'testing', 'unstable', 'experimental');
create type component as enum('main');

create table source (
    name varchar(255) not null,
    distribution distribution not null,
    component component not null default 'main',
    version varchar(255) not null,
    primary key(name, distribution)
);

create table source_folder (
    path varchar(255) primary key,
    created timestamp not null default current_timestamp
);

Fix the primary key uniqueness.

create type distribution as enum('stable', 'testing', 'unstable', 'experimental');
create type component as enum('main');

create table source (
    name varchar(255) not null,
    distribution distribution not null,
    component component not null default 'main',
    version varchar(255) not null,
    primary key(name, distribution, version)
);

create table source_folder (
    path varchar(255) primary key,
    created timestamp not null default current_timestamp
);


CREATE TABLE scrobble (
  id SERIAL PRIMARY KEY
, artist TEXT NOT NULL
, album TEXT NOT NULL
, track TEXT NOT NULL
, scrobble_timestamp TIMESTAMPTZ NOT NULL
);

COPY scrobble(artist, album, track, scrobble_timestamp) FROM '/dataimport/scrobbles.csv' DELIMITER ',' CSV;

CREATE VIEW artist_plays_per_year AS
WITH artist_plays_per_year AS (
  SELECT
    CAST(TO_CHAR(s.scrobble_timestamp, 'YYYY') AS INTEGER) y
  , artist
  , COUNT(*) play_count
  , ROW_NUMBER() OVER (
      PARTITION BY CAST(TO_CHAR(s.scrobble_timestamp, 'YYYY') AS INTEGER)
      ORDER BY COUNT(*) DESC
    ) play_rank
  FROM scrobble s
  GROUP BY
    y
  , artist
  ORDER BY
    y DESC
  , play_rank DESC
)
SELECT
  y AS "year"
, artist
, play_count
, play_rank
FROM artist_plays_per_year
WHERE play_rank <= 10
ORDER BY
  y DESC
, play_rank;

Allow NULL album information in database

CREATE TABLE scrobble (
  id SERIAL PRIMARY KEY
, artist TEXT NOT NULL
, album TEXT
, track TEXT NOT NULL
, scrobble_timestamp TIMESTAMPTZ NOT NULL
);

COPY scrobble(artist, album, track, scrobble_timestamp) FROM '/dataimport/scrobbles.csv' DELIMITER ',' CSV;

CREATE VIEW artist_plays_per_year AS
WITH artist_plays_per_year AS (
  SELECT
    CAST(TO_CHAR(s.scrobble_timestamp, 'YYYY') AS INTEGER) y
  , artist
  , COUNT(*) play_count
  , ROW_NUMBER() OVER (
      PARTITION BY CAST(TO_CHAR(s.scrobble_timestamp, 'YYYY') AS INTEGER)
      ORDER BY COUNT(*) DESC
    ) play_rank
  FROM scrobble s
  GROUP BY
    y
  , artist
  ORDER BY
    y DESC
  , play_rank DESC
)
SELECT
  y AS "year"
, artist
, play_count
, play_rank
FROM artist_plays_per_year
WHERE play_rank <= 10
ORDER BY
  y DESC
, play_rank;


ALTER TABLE module_config
DROP COLUMN IF EXISTS certificate CASCADE,
DROP COLUMN IF EXISTS private_key CASCADE,
DROP COLUMN IF EXISTS expiration_ts CASCADE;

DROP TABLE IF EXISTS app_certificates;

Update down migration for app certs

DROP VIEW IF EXISTS view_module_config;
DROP VIEW IF EXISTS view_module_config_staging;
DROP VIEW IF EXISTS view_module_config_production;

ALTER TABLE module_config
DROP COLUMN IF EXISTS certificate CASCADE,
DROP COLUMN IF EXISTS private_key CASCADE,
DROP COLUMN IF EXISTS expiration_ts CASCADE;

DROP TABLE IF EXISTS app_certificates;

CREATE OR REPLACE VIEW view_module_config AS
SELECT module_config.*
FROM (
SELECT status, max(id) AS id
    FROM module_config
    GROUP BY status
) AS vmc
INNER JOIN module_config ON vmc.id = module_config.id;

CREATE OR REPLACE VIEW view_module_config_staging AS
SELECT module_config.*
FROM (
    SELECT max(id) AS id
    FROM module_config
) mc
INNER JOIN module_config
ON module_config.id = mc.id;

CREATE OR REPLACE VIEW view_module_config_production AS
SELECT module_config.*
FROM (
    SELECT max(id) AS id
    FROM module_config
    WHERE status='PRODUCTION'
) mc
INNER JOIN module_config
ON module_config.id = mc.id;


-- SQL to show number of records recorded earlier than tracking_start_date_time.
-- Those records should be removed.
-- https://lifewatch-inbo.cartodb.com/viz/5d42a40a-9951-11e3-8315-0ed66c7bc7f3/table

select
  count(*)
from
bird_tracking as t
left join bird_tracking_devices as d
on t.device_info_serial = d.device_info_serial
where
  t.date_time < d.tracking_start_date_time

Remove link that does not work

-- SQL to show number of records recorded earlier than tracking_start_date_time.
-- Those records should be removed.

select
  count(*)
from
bird_tracking as t
left join bird_tracking_devices as d
on t.device_info_serial = d.device_info_serial
where
  t.date_time < d.tracking_start_date_time


CREATE KEYSPACE IF NOT EXISTS dev1 WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': '3', 'dc2': '3', 'dc3': '3'}  AND durable_writes = true;

//CassAstyanaxPlugin Plugin

CREATE TABLE IF NOT EXISTS dev1.emp_thrift (key text, column1 int, value text, PRIMARY KEY ((key), column1)) WITH COMPACT STORAGE;

//CassJavaDriverPlugin Plugin
CREATE TABLE IF NOT EXISTS dev1.empl (emp_uname varchar primary key, emp_first varchar, emp_last varchar, emp_dept varchar);

//CassJavaDriverGeneric Plugin
CREATE TABLE IF NOT EXISTS dev1.emp (key text, column1 int, value text, PRIMARY KEY (key, column1)) WITH CLUSTERING ORDER BY (column1 ASC)

//CassJavaDriverBatch Plugin
CREATE TABLE IF NOT EXISTS dev1.emp (cyclist_name text, expense_id int, amount float, balance float static, description text, paid boolean, PRIMARY KEY (cyclist_name, expense_id)) WITH CLUSTERING ORDER BY (expense_id ASC)
CREATE TABLE IF NOT EXISTS dev1.test2 (expense_id int, cyclist_name text, PRIMARY KEY (expense_id, cyclist_name)) WITH CLUSTERING ORDER BY (cyclist_name ASC)

Add semicolons to cql for easier copy-paste.

CREATE KEYSPACE IF NOT EXISTS dev1 WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': '3', 'dc2': '3', 'dc3': '3'}  AND durable_writes = true;

//CassAstyanaxPlugin Plugin

CREATE TABLE IF NOT EXISTS dev1.emp_thrift (key text, column1 int, value text, PRIMARY KEY ((key), column1)) WITH COMPACT STORAGE;

//CassJavaDriverPlugin Plugin
CREATE TABLE IF NOT EXISTS dev1.empl (emp_uname varchar primary key, emp_first varchar, emp_last varchar, emp_dept varchar);

//CassJavaDriverGeneric Plugin
CREATE TABLE IF NOT EXISTS dev1.emp (key text, column1 int, value text, PRIMARY KEY (key, column1)) WITH CLUSTERING ORDER BY (column1 ASC);

//CassJavaDriverBatch Plugin
CREATE TABLE IF NOT EXISTS dev1.emp (cyclist_name text, expense_id int, amount float, balance float static, description text, paid boolean, PRIMARY KEY (cyclist_name, expense_id)) WITH CLUSTERING ORDER BY (expense_id ASC);
CREATE TABLE IF NOT EXISTS dev1.test2 (expense_id int, cyclist_name text, PRIMARY KEY (expense_id, cyclist_name)) WITH CLUSTERING ORDER BY (cyclist_name ASC);


--
-- Copyright 2019 The Android Open Source Project
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--

CREATE VIEW error_stats_view AS
SELECT TraceMetadata_Entry(
  'name', name,
  'idx', idx,
  'value', value) as entry
FROM stats
WHERE severity IN ('data_loss', 'error')
AND value > 0;

CREATE VIEW trace_metadata_output AS
SELECT TraceMetadata(
  'error_stats_entry', (SELECT RepeatedField(entry) FROM error_stats_view),
  'trace_duration_ns', (SELECT end_ts - start_ts FROM trace_bounds),
  'trace_uuid', (SELECT str_value FROM metadata WHERE name = 'trace_uuid'),
  'android_build_fingerprint', (
    SELECT str_value FROM metadata WHERE name = 'android_build_fingerprint'
  ),
  'statsd_triggering_subscription_id', (
    SELECT int_value FROM metadata
    WHERE name = 'statsd_triggering_subscription_id'
  )
);

Fix non-reentrant metadata am: e6b3c2f713

--
-- Copyright 2019 The Android Open Source Project
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--

CREATE VIEW IF NOT EXISTS error_stats_view AS
SELECT TraceMetadata_Entry(
  'name', name,
  'idx', idx,
  'value', value) as entry
FROM stats
WHERE severity IN ('data_loss', 'error')
AND value > 0;

CREATE VIEW IF NOT EXISTS trace_metadata_output AS
SELECT TraceMetadata(
  'error_stats_entry', (SELECT RepeatedField(entry) FROM error_stats_view),
  'trace_duration_ns', (SELECT end_ts - start_ts FROM trace_bounds),
  'trace_uuid', (SELECT str_value FROM metadata WHERE name = 'trace_uuid'),
  'android_build_fingerprint', (
    SELECT str_value FROM metadata WHERE name = 'android_build_fingerprint'
  ),
  'statsd_triggering_subscription_id', (
    SELECT int_value FROM metadata
    WHERE name = 'statsd_triggering_subscription_id'
  )
);


INSERT INTO `users` (`username`) VALUES ('someuser'), ('anotheruser');
INSERT INTO `teams` (`name`, `title`) VALUES ('sample', 'Sample');
INSERT INTO `teammembers` (`teamId`, `userId`) VALUES (1, 1), (1, 2);

Add user for "anonymous" (default user) in sample data

INSERT INTO `users` (`username`) VALUES ('anonymous'), ('anotheruser');
INSERT INTO `teams` (`name`, `title`) VALUES ('sample', 'Sample');
INSERT INTO `teammembers` (`teamId`, `userId`) VALUES (1, 1), (1, 2);


CREATE TABLE knowledgeedges (
	userid INTEGER NOT NULL,
	startnodeid INTEGER NOT NULL,
	endnodeid INTEGER NOT NULL,
	nodepath INTEGER ARRAY NOT NULL,
	confidence INTEGER NOT NULL DEFAULT 50, -- between 0 and 100
	createdat TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
	updatedat TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
	PRIMARY KEY (startnodeid, endnodeid, nodepath, userid)
);

Add startnodeterm to knowledgeedges migration

CREATE TABLE knowledgeedges (
	userid INTEGER NOT NULL,
	startnodeid INTEGER NOT NULL,
	endnodeid INTEGER NOT NULL,
	nodepath INTEGER ARRAY NOT NULL,
	startnodeterm VARCHAR(255) NOT NULL,
	confidence INTEGER NOT NULL DEFAULT 50, -- between 0 and 100
	createdat TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
	updatedat TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
	PRIMARY KEY (startnodeid, endnodeid, nodepath, userid)
);


CREATE TABLE IF NOT EXISTS "user_aliases"(
    "id" VARCHAR NOT NULL,
    "user_id" VARCHAR NOT NULL,
    "alias" VARCHAR NOT NULL
);
ALTER TABLE "user_aliases" ADD CONSTRAINT IF NOT EXISTS "user_alias_pk" PRIMARY KEY("id");
ALTER TABLE "user_aliases" ADD CONSTRAINT IF NOT EXISTS "user_alias_pk" UNIQUE("user_id", "alias");

Change constraint from pair (userId, alias) to alias only, as there must not be two identical email adresses

CREATE TABLE IF NOT EXISTS "user_aliases"(
    "id" VARCHAR NOT NULL,
    "user_id" VARCHAR NOT NULL,
    "alias" VARCHAR NOT NULL
);
ALTER TABLE "user_aliases" ADD CONSTRAINT IF NOT EXISTS "user_alias_pk" PRIMARY KEY("id");
ALTER TABLE "user_aliases" ADD CONSTRAINT IF NOT EXISTS "unique_alias" UNIQUE("alias");


-- +migrate Up
UPDATE users SET github_token = NULL

-- +migrate Down

Update migrations to support empty down statements

-- +migrate Up
UPDATE users SET github_token = NULL;

-- +migrate Down
-- +migrate StatementBegin
-- +migrate StatementEnd


INSERT INTO media
(
  title,
  uri,
  rating,
  viewed_at,
  created_at
)
VALUES
('The Scorch Trials', 'http://www.imdb.com/title/tt4046784/', 1000, '2016-07-06', now()),
('Heaven\'s Door', 'http://www.imdb.com/title/tt2321269/', 1000, '2016-07-06', now())

Fix syntax error in SQL script

INSERT INTO media
(
  title,
  uri,
  rating,
  viewed_at,
  created_at
)
VALUES
('The Scorch Trials', 'http://www.imdb.com/title/tt4046784/', 1000, '2016-07-06', now()),
('Heaven''s Door', 'http://www.imdb.com/title/tt2321269/', 1000, '2016-07-06', now())


DROP TABLE IF EXISTS `civicrm_sms_conversation`;
DROP TABLE IF EXISTS `civicrm_sms_conversation_question`;
DROP TABLE IF EXISTS `civicrm_sms_conversation_contact`;
DROP TABLE IF EXISTS `civicrm_sms_conversation_action`;

Rearrange drop tables for uninstall

DROP TABLE IF EXISTS `civicrm_sms_conversation_action`;
DROP TABLE IF EXISTS `civicrm_sms_conversation_contact`;
DROP TABLE IF EXISTS `civicrm_sms_conversation`;
DROP TABLE IF EXISTS `civicrm_sms_conversation_question`;


DROP TABLE IF EXISTS MediaDirectoryListing;
CREATE TABLE MediaDirectoryListing(
FileName VARCHAR(255) NOT NULL PRIMARY KEY );

LOAD DATA LOCAL INFILE 'source/media-list.txt' INTO TABLE MediaDirectoryListing;

Remove blank images from directory listing

DROP TABLE IF EXISTS MediaDirectoryListing;
CREATE TABLE MediaDirectoryListing(
FileName VARCHAR(255) NOT NULL PRIMARY KEY );

LOAD DATA LOCAL INFILE 'source/media-list.txt' INTO TABLE MediaDirectoryListing;
DELETE FROM MediaDirectoryListing WHERE FileName IS NULL OR FileName = '';


CREATE DATABASE creditdb;

USE creditdb;

CREATE TABLE `CUSTOMER_CREDIT` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `CUSTOMER_ID` varchar(45) DEFAULT NULL,
  `REFERENCE_NUMBER` varchar(45) DEFAULT NULL,
  `TOTALAMOUT` varchar(45) DEFAULT NULL,
  `OUTSTANDING_BALANCE` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=82781213 DEFAULT CHARSET=latin1;

Update credit service table definition

CREATE DATABASE creditdb;

USE creditdb;

CREATE TABLE `CUSTOMER_CREDIT` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `CUSTOMER_ID` VARCHAR(45) DEFAULT NULL,
  `REFERENCE_NUMBER` VARCHAR(45) DEFAULT NULL,
  `AMOUNT` DECIMAL(20,2) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=82781213 DEFAULT CHARSET=latin1;


CREATE TABLE player (
       id serial PRIMARY KEY,
       name varchar(40) UNIQUE NOT NULL
);

CREATE TABLE game (
       id serial PRIMARY KEY,
       name varchar(40) UNIQUE NOT NULL
);

CREATE TABLE win (
       id serial PRIMARY KEY,
       winner integer REFERENCES player(id) NOT NULL,
       loser integer REFERENCES player(id) NOT NULL,
       happened timestamp NOT NULL
);

Make database setup resistant to multiple runs

CREATE TABLE IF NOT EXISTS player (
       id serial PRIMARY KEY,
       name varchar(40) UNIQUE NOT NULL
);

CREATE TABLE IF NOT EXISTS game (
       id serial PRIMARY KEY,
       name varchar(40) UNIQUE NOT NULL
);

CREATE TABLE IF NOT EXISTS win (
       id serial PRIMARY KEY,
       winner integer REFERENCES player(id) NOT NULL,
       loser integer REFERENCES player(id) NOT NULL,
       happened timestamp NOT NULL
);