-- git_hash table
--
-- Stores ONLY metadata about commits that MediaWiki CANNOT store.
--
-- The other tables git_status_modify_hash and git_edit_hash store
-- actual CHANGES of a commit that MediaWiki cannot store or cannot
-- store in a suitable format.

CREATE TABLE IF NOT EXISTS /*_*/git_hash(
    -- The primary key, contains the Git commit hash in a 40-character
    -- hex representation of SHA-1
    commit_hash VARBINARY(40) NOT NULL PRIMARY KEY,

    -- Parent commit hashes (up to 15, separated by commas) in 40-char
    -- hex of SHA-1
    commit_hash_parents VARBINARY(615),

    -- Email addresses and usernames can be changed in MediaWiki,
    -- however this shouldn't change every previous commit (since that would
    -- change the hashes). Also necessary for edits made via pull requests.
    author_name VARBINARY(255),
    author_email VARBINARY(255),
    author_timestamp VARBINARY(14),
    author_tzOffset VARBINARY(5),

    -- With rebases sometimes you have different authors and committers. This
    -- has to be stored somehow to keep the "real" Git repository in sync.
    committer_name VARBINARY(255),
    committer_email VARBINARY(255),
    committer_timestamp VARBINARY(14),
    committer_tzOffset VARBINARY(5)
) /*$wgDBTableOptions*/;

Use UNIX time format for timestamps in hash table

-- git_hash table
--
-- Stores ONLY metadata about commits that MediaWiki CANNOT store.
--
-- The other tables git_status_modify_hash and git_edit_hash store
-- actual CHANGES of a commit that MediaWiki cannot store or cannot
-- store in a suitable format.

CREATE TABLE IF NOT EXISTS /*_*/git_hash(
    -- The primary key, contains the Git commit hash in a 40-character
    -- hex representation of SHA-1
    commit_hash VARBINARY(40) NOT NULL PRIMARY KEY,

    -- Parent commit hashes (up to 15, separated by commas) in 40-char
    -- hex of SHA-1
    commit_hash_parents VARBINARY(615),

    -- Email addresses and usernames can be changed in MediaWiki,
    -- however this shouldn't change every previous commit (since that would
    -- change the hashes). Also necessary for edits made via pull requests.
    author_name VARBINARY(255),
    author_email VARBINARY(255),

    -- Timestamps need to be easily fetched for commits without looking up log
    -- entries or revisions. Unix time format.
    author_timestamp INTEGER,
    author_tzOffset INTEGER,

    -- With rebases sometimes you have different authors and committers. This
    -- has to be stored somehow to keep the "real" Git repository in sync.
    committer_name VARBINARY(255),
    committer_email VARBINARY(255),
    committer_timestamp INTEGER,
    committer_tzOffset INTEGER
) /*$wgDBTableOptions*/;


CREATE TABLE lysr_user (
	id BIGSERIAL PRIMARY KEY,
	email VARCHAR(255) UNIQUE,
	password VARCHAR(60)
);

CREATE TABLE lysr_user_settings (
	id BIGSERIAL PRIMARY KEY,
	user BIGINT NOT NULL REFERENCES lysr_user (id) ON DELETE CASCADE
);

CREATE TABLE lysr_feed (
	id BIGSERIAL PRIMARY KEY,
	url TEXT UNIQUE
);

CREATE TABLE lysr_user_feed (
	id BIGSERIAL PRIMARY KEY,
	user BIGINT NOT NULL REFERENCES lysr_user (id) ON DELETE CASCADE,
	feed BIGINT NOT NULL REFERENCES lysr_feed (id) ON DELETE CASCADE
);

CREATE TABLE lysr_feed_entry (
	id BIGSERIAL PRIMARY KEY,
	feed BIGINT NOT NULL REFERENCES lysr_feed (id) ON DELETE CASCADE,
	-- feed contents
);

CREATE TABLE lysr_feed_entry_status (
	id BIGSERIAL PRIMARY KEY,
	user BIGINT NOT NULL REFERENCES lysr_user (id) ON DELETE CASCADE,
	feed_entry BIGINT NOT NULL REFERENCES lysr_feed_entry (id) ON DELETE CASCADE,
	read BOOLEAN,
	starred BOOLEAN
);

-- tags
CREATE TABLE lysr_tag (
	id BIGSERIAL PRIMARY KEY,
	name TEXT
);

CREATE TABLE lysr_tag_assoc (
	id BIGSERIAL PRIMARY KEY,
	tag BIGINT REFERENCES lysr_tag (id) ON DELETE CASCADE,
	feed BIGINT REFENECES lysr_user_feed (id) ON DELETE CASCADE
);
-- /tags

Add guid and content column to lysr_feed_entry

CREATE TABLE lysr_user (
	id BIGSERIAL PRIMARY KEY,
	email VARCHAR(255) UNIQUE,
	password VARCHAR(60)
);

CREATE TABLE lysr_user_settings (
	id BIGSERIAL PRIMARY KEY,
	user BIGINT NOT NULL REFERENCES lysr_user (id) ON DELETE CASCADE
);

CREATE TABLE lysr_feed (
	id BIGSERIAL PRIMARY KEY,
	url TEXT UNIQUE
);

CREATE TABLE lysr_user_feed (
	id BIGSERIAL PRIMARY KEY,
	user BIGINT NOT NULL REFERENCES lysr_user (id) ON DELETE CASCADE,
	feed BIGINT NOT NULL REFERENCES lysr_feed (id) ON DELETE CASCADE
);

CREATE TABLE lysr_feed_entry (
	id BIGSERIAL PRIMARY KEY,
	feed BIGINT NOT NULL REFERENCES lysr_feed (id) ON DELETE CASCADE,
	guid TEXT NOT NULL,
	content TEXT NOT NULL
	-- feed contents
);

CREATE TABLE lysr_feed_entry_status (
	id BIGSERIAL PRIMARY KEY,
	user BIGINT NOT NULL REFERENCES lysr_user (id) ON DELETE CASCADE,
	feed_entry BIGINT NOT NULL REFERENCES lysr_feed_entry (id) ON DELETE CASCADE,
	read BOOLEAN,
	starred BOOLEAN
);

-- tags
CREATE TABLE lysr_tag (
	id BIGSERIAL PRIMARY KEY,
	name TEXT
);

CREATE TABLE lysr_tag_assoc (
	id BIGSERIAL PRIMARY KEY,
	tag BIGINT REFERENCES lysr_tag (id) ON DELETE CASCADE,
	feed BIGINT REFENECES lysr_user_feed (id) ON DELETE CASCADE
);
-- /tags


/*
Rename the duplicate names before adding "UNIQUE" constraint
*/
DO $$
BEGIN
    WHILE EXISTS (SELECT count(*) FROM user_group GROUP BY group_name HAVING count(*) > 1) LOOP
        UPDATE user_group AS r
        SET group_name = (
            /*
            truncate the name if it is too long after appending the sequence number
            */
            CASE WHEN (length(group_name)+length(v.seq::text)+1) > 256
            THEN
                substring(group_name from 1 for (255-length(v.seq::text))) || '_' || v.seq
            ELSE
                group_name || '_' || v.seq
            END
        )
        FROM (SELECT id, row_number() OVER (PARTITION BY group_name ORDER BY id) AS seq FROM user_group) AS v
        WHERE r.id = v.id AND v.seq > 1;
    END LOOP;
END $$;

ALTER TABLE user_group ADD CONSTRAINT unique_group_name UNIQUE (group_name);

Delete the nono scan all schedule in migration

/*
Rename the duplicate names before adding "UNIQUE" constraint
*/
DO $$
BEGIN
    WHILE EXISTS (SELECT count(*) FROM user_group GROUP BY group_name HAVING count(*) > 1) LOOP
        UPDATE user_group AS r
        SET group_name = (
            /*
            truncate the name if it is too long after appending the sequence number
            */
            CASE WHEN (length(group_name)+length(v.seq::text)+1) > 256
            THEN
                substring(group_name from 1 for (255-length(v.seq::text))) || '_' || v.seq
            ELSE
                group_name || '_' || v.seq
            END
        )
        FROM (SELECT id, row_number() OVER (PARTITION BY group_name ORDER BY id) AS seq FROM user_group) AS v
        WHERE r.id = v.id AND v.seq > 1;
    END LOOP;
END $$;

ALTER TABLE user_group ADD CONSTRAINT unique_group_name UNIQUE (group_name);

/*
Fix issue https://github.com/goharbor/harbor/issues/8526, delete the none scan_all schedule.
 */
UPDATE admin_job SET deleted='true' WHERE cron_str='{"type":"none"}';


set optimizer='inline,remap,evaluate,costModel,coercions,emptySet,mitosis,aliases,mergetable,octopus,commonTerms,accumulators,deadcode,reduce,garbageCollector,dataflow,history,multiplex';
explain select Bid from squidA;
select Bid from squidA;

Use the offline performance profiling.

set optimizer='inline,remap,evaluate,costModel,coercions,emptySet,mitosis,aliases,mergetable,commonTerms,accumulators,octopus,deadcode,reduce,garbageCollector,dataflow,history,multiplex';
explain select Bid from squidA;
trace select Bid from squidA;


create or replace function add_item_key_to_entry(item_content_key text) returns void as $$
BEGIN
    IF item_content_key is NULL or item_content_key='' then
        RAISE EXCEPTION 'Item key parameter cannot be null or empty';
    end if;

    IF exists(select 1 from item) and not exists(select 1 from item where content ? item_content_key) then
        RAISE EXCEPTION 'Item content does not have key: %', item_content_key;
    end if;

    IF NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='entry' AND COLUMN_NAME='key') then
        alter table entry add column key varchar;
    ELSE
        RAISE NOTICE 'Column key already exists in entry table';
    END IF;

    IF EXISTS(select 1 from entry where not exists(select 1 from item where item.content->>item_content_key=entry.key)) THEN
        update entry set key = content->>item_content_key from item where entry.sha256hex=item.sha256hex;
    ELSE
        RAISE NOTICE 'Data already copied from items[%]', item_content_key;
    END IF;
END;
$$ language plpgsql;

BEGIN;
-- item content has a "primary" key which maps to the register name
select add_item_key_to_entry('${registerName}');
COMMIT;

drop function if exists add_item_key_to_entry(item_content_key text);

Remove additional checks for column and data existance from 'add_item_key_to_entry' migration script

create or replace function add_item_key_to_entry(item_content_key text) returns void as $$
BEGIN
    IF item_content_key is NULL or item_content_key='' then
        RAISE EXCEPTION 'Item key parameter cannot be null or empty';
    end if;

    IF exists(select 1 from item) and not exists(select 1 from item where content ? item_content_key) then
        RAISE EXCEPTION 'Item content does not have key: %', item_content_key;
    end if;

    alter table entry add column key varchar;
    update entry set key = content->>item_content_key from item where entry.sha256hex=item.sha256hex;
END;
$$ language plpgsql;

BEGIN;
-- item content has a "primary" key which maps to the register name
select add_item_key_to_entry('${registerName}');
COMMIT;

drop function if exists add_item_key_to_entry(item_content_key text);


/*
 * Copyright (c) 2010-2012 LabKey Corporation
 *
 * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
 */
SELECT
  v.Id,
  max(v.ViralLoad) as MaxViralLoad,
  min(v.ViralLoad) as MinViralLoad,
  min(v.date) as FirstViralLoadDate,
  max(v.date) as LastViralLoadDate,
  (select avg(v1.viralLoad) as viralLoad FROM study.ViralLoads v1 WHERE v1.Id=v.Id AND max(v.date)=v1.date) as LatestViralLoad

FROM study.ViralLoads v

group by v.Id

Change to demographic ViralLoad query.

/*
 * Copyright (c) 2010-2012 LabKey Corporation
 *
 * Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
 */
SELECT
  v.Id,
  max(v.AverageViralLoad) as MaxViralLoad,
  min(v.AverageViralLoad) as MinViralLoad,
  min(v.date) as FirstViralLoadDate,
  max(v.date) as LastViralLoadDate,
  (select avg(v1.AverageViralLoad) as viralLoad FROM study.ViralLoads v1 WHERE v1.Id=v.Id AND max(v.date)=v1.date) as LatestViralLoad

FROM study.ViralLoads v

group by v.Id


CREATE PROCEDURE [employer_financial].[GetLevyDetail_ByAccountIdAndDateRange]
	@accountId bigint,
	@fromDate datetime,
	@toDate datetime

AS
select
    tl.AccountId,
    tl.LevyDeclared as Amount,
    t.Amount as EnglishFraction,
    ldt.Amount as TopUp,
    tl.EmpRef,
	null as CourseName,
	null as CourseLevel,
	null as CourseStartDate,
	null as ProviderName,
	null as ApprenticeName,
	null as ApprenticeNINumber,
    tl.TransactionDate,
    tl.Amount as LineAmount,
    tl.TransactionType,
	null as UkPrn,
	null as PeriodEnd,
	DateCreated,
	ld.PayrollYear,
	ld.PayrollMonth,
	tl.SfaCoInvestmentAmount,
	tl.EmployerCoInvestmentAmount
from [employer_financial].TransactionLine tl
inner join [employer_financial].LevyDeclarationTopup ldt on ldt.SubmissionId = tl.SubmissionId
inner join [employer_financial].LevyDeclaration ld on ld.submissionid = tl.submissionid
OUTER APPLY
(
	SELECT TOP 1 Amount
	FROM [employer_financial].[EnglishFraction] ef
	WHERE ef.EmpRef = tl.empRef
		AND ef.[DateCalculated] <= tl.TransactionDate
	ORDER BY [DateCalculated] DESC
) t
where    tl.DateCreated >= @fromDate AND
        tl.DateCreated <= @toDate AND
        tl.AccountId = @accountId

Change to EF default value when getting LineDetail

CREATE PROCEDURE [employer_financial].[GetLevyDetail_ByAccountIdAndDateRange]
	@accountId bigint,
	@fromDate datetime,
	@toDate datetime

AS
select
    tl.AccountId,
    tl.LevyDeclared as Amount,
    isnull(t.Amount,1) as EnglishFraction,
    ldt.Amount as TopUp,
    tl.EmpRef,
	null as CourseName,
	null as CourseLevel,
	null as CourseStartDate,
	null as ProviderName,
	null as ApprenticeName,
	null as ApprenticeNINumber,
    tl.TransactionDate,
    tl.Amount as LineAmount,
    tl.TransactionType,
	null as UkPrn,
	null as PeriodEnd,
	DateCreated,
	ld.PayrollYear,
	ld.PayrollMonth,
	tl.SfaCoInvestmentAmount,
	tl.EmployerCoInvestmentAmount
from [employer_financial].TransactionLine tl
inner join [employer_financial].LevyDeclarationTopup ldt on ldt.SubmissionId = tl.SubmissionId
inner join [employer_financial].LevyDeclaration ld on ld.submissionid = tl.submissionid
OUTER APPLY
(
	SELECT TOP 1 Amount
	FROM [employer_financial].[EnglishFraction] ef
	WHERE ef.EmpRef = tl.empRef
		AND ef.[DateCalculated] <= tl.TransactionDate
	ORDER BY [DateCalculated] DESC
) t
where    tl.DateCreated >= @fromDate AND
        tl.DateCreated <= @toDate AND
        tl.AccountId = @accountId


CREATE SEQUENCE "augur_operations"."worker_oauth_oauth_id_seq"
INCREMENT 1
MINVALUE  1
MAXVALUE 9223372036854775807
START 1000
CACHE 1;

ALTER TABLE "augur_operations"."worker_oauth" ALTER COLUMN "oauth_id" TYPE int8 USING "oauth_id"::int8;

ALTER TABLE "augur_operations"."worker_oauth" ALTER COLUMN "oauth_id" SET DEFAULT nextval('"augur_operations".worker_oauth_oauth_id_seq'::regclass);

ALTER TABLE "augur_operations"."worker_oauth" ADD CONSTRAINT "worker_oauth_pkey" PRIMARY KEY ("oauth_id");

SELECT setval('"augur_operations"."worker_oauth_oauth_id_seq"', 1000, false);

ALTER SEQUENCE "augur_operations"."worker_oauth_oauth_id_seq" OWNER TO "augur";

CREATE INDEX "repos_id,statusops" ON "augur_operations"."repos_fetch_log" USING btree (
  "repos_id" "pg_catalog"."int4_ops" ASC NULLS LAST,
  "status" COLLATE "pg_catalog"."default" "pg_catalog"."text_ops" ASC NULLS LAST
);

update "augur_operations"."augur_settings" set value = 12 where setting = 'augur_data_version';

Remove index from DB version update 12 script

CREATE SEQUENCE "augur_operations"."worker_oauth_oauth_id_seq"
INCREMENT 1
MINVALUE  1
MAXVALUE 9223372036854775807
START 1000
CACHE 1;

ALTER TABLE "augur_operations"."worker_oauth" ALTER COLUMN "oauth_id" TYPE int8 USING "oauth_id"::int8;

ALTER TABLE "augur_operations"."worker_oauth" ALTER COLUMN "oauth_id" SET DEFAULT nextval('"augur_operations".worker_oauth_oauth_id_seq'::regclass);

ALTER TABLE "augur_operations"."worker_oauth" ADD CONSTRAINT "worker_oauth_pkey" PRIMARY KEY ("oauth_id");

SELECT setval('"augur_operations"."worker_oauth_oauth_id_seq"', 1000, false);

ALTER SEQUENCE "augur_operations"."worker_oauth_oauth_id_seq" OWNER TO "augur";

update "augur_operations"."augur_settings" set value = 12 where setting = 'augur_data_version';


--
-- Store session data in here.
-- Idea originally from: http://www.developertutorials.com/tutorials/php/saving-php-session-data-database-050711
--

CREATE TABLE `test`.`sess_tmp` (
  `session_store_id` int  NOT NULL AUTO_INCREMENT,
  `session_id` varchar(32)  NOT NULL,
  `user_id` varchar(16)  NOT NULL,
  `date_created` datetime  NOT NULL,
  `last_updated` datetime  NOT NULL,
  `session_data` LONGTEXT  NOT NULL,
  PRIMARY KEY (`session_store_id`)
)
ENGINE = MyISAM;

Make sure all tables are using InnoDB as the engine (for transaction support).

--
-- Store session data in here.
-- Idea originally from: http://www.developertutorials.com/tutorials/php/saving-php-session-data-database-050711
--

CREATE TABLE `test`.`sess_tmp` (
  `session_store_id` int  NOT NULL AUTO_INCREMENT,
  `session_id` varchar(32)  NOT NULL,
  `user_id` varchar(16)  NOT NULL,
  `date_created` datetime  NOT NULL,
  `last_updated` datetime  NOT NULL,
  `session_data` LONGTEXT  NOT NULL,
  PRIMARY KEY (`session_store_id`)
)
ENGINE = InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


-- ALTER TABLE "subscription" ADD COLUMN "uuid" uuid;
-- ALTER TABLE "subscription" ADD COLUMN "eventpublished" boolean NOT NULL DEFAULT false;
-- ALTER TABLE "subscriptionhistory" ADD "eventpublished" boolean NOT NULL DEFAULT false;

run:MigrateSubscriptions;

Add sql for altering table

ALTER TABLE "subscription" ADD COLUMN "uuid" uuid;
ALTER TABLE "subscription" ADD COLUMN "eventpublished" boolean NOT NULL DEFAULT false;
ALTER TABLE "subscriptionhistory" ADD "eventpublished" boolean NOT NULL DEFAULT false;

run:MigrateSubscriptions;


CREATE TABLE IF NOT EXISTS `sgf_sessions` (
  `session_id` varchar(40) collate utf8_bin NOT NULL default '0',
  `ip_address` varchar(16) collate utf8_bin NOT NULL default '0',
  `user_agent` varchar(150) collate utf8_bin NOT NULL,
  `last_activity` int(10) unsigned NOT NULL default '0',
  `user_data` text collate utf8_bin DEFAULT '',
  PRIMARY KEY  (`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

CREATE TABLE IF NOT EXISTS `sgf_user_session` (
	`session_id` VARCHAR(36) NOT NULL,
	`user_id` VARCHAR(36) NOT NULL,
	PRIMARY KEY ( `session_id` )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

CREATE TABLE IF NOT EXISTS `sgf_user_settings` (
	`user_id` VARCHAR(36) NOT NULL,
	`style` VARCHAR(16) NOT NULL,
	PRIMARY KEY ( `user_id` )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

CREATE TABLE IF NOT EXISTS `sgf_user_validation` (
	`user_id` VARCHAR(36) NOT NULL,
	`validation_code` VARCHAR(36) NOT NULL,
	`validation_type` VARCHAR(16) NOT NULL,
	PRIMARY KEY ( `user_id` )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

Simplify the column creation sql for user_data

CREATE TABLE IF NOT EXISTS `sgf_sessions` (
  `session_id` varchar(40) collate utf8_bin NOT NULL default '0',
  `ip_address` varchar(16) collate utf8_bin NOT NULL default '0',
  `user_agent` varchar(150) collate utf8_bin NOT NULL,
  `last_activity` int(10) unsigned NOT NULL default '0',
  `user_data` text,
  PRIMARY KEY  (`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

CREATE TABLE IF NOT EXISTS `sgf_user_session` (
	`session_id` VARCHAR(36) NOT NULL,
	`user_id` VARCHAR(36) NOT NULL,
	PRIMARY KEY ( `session_id` )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

CREATE TABLE IF NOT EXISTS `sgf_user_settings` (
	`user_id` VARCHAR(36) NOT NULL,
	`style` VARCHAR(16) NOT NULL,
	PRIMARY KEY ( `user_id` )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

CREATE TABLE IF NOT EXISTS `sgf_user_validation` (
	`user_id` VARCHAR(36) NOT NULL,
	`validation_code` VARCHAR(36) NOT NULL,
	`validation_type` VARCHAR(16) NOT NULL,
	PRIMARY KEY ( `user_id` )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;


CREATE VIEW {# geotrek.maintenance #}.v_interventions AS (

	SELECT e.geom, i.*
	FROM maintenance_intervention AS i, core_topology AS e,  signage_blade as b
	WHERE (i.target_id = e.id AND i.target_type_id NOT IN (SELECT id FROM django_content_type  AS ct WHERE ct.model = 'blade')) OR
	(i.target_id = b.id AND i.target_type_id IN (SELECT id FROM django_content_type  AS ct WHERE ct.model = 'blade') AND e.id=b.signage_id)
	AND i.deleted = FALSE
);

CREATE VIEW {# geotrek.maintenance #}.v_projects AS (
	SELECT ST_Union(t.geom) AS geom, s.*
	FROM v_interventions AS t, maintenance_project AS s
	WHERE t.project_id = s.id
	GROUP BY t.project_id, s.id
);

Add UUID to interventions view

CREATE VIEW {# geotrek.maintenance #}.v_interventions AS (

	SELECT e.geom, e.uuid, i.*
	FROM maintenance_intervention AS i, core_topology AS e,  signage_blade as b
	WHERE (i.target_id = e.id AND i.target_type_id NOT IN (SELECT id FROM django_content_type  AS ct WHERE ct.model = 'blade')) OR
	(i.target_id = b.id AND i.target_type_id IN (SELECT id FROM django_content_type  AS ct WHERE ct.model = 'blade') AND e.id=b.signage_id)
	AND i.deleted = FALSE
);

CREATE VIEW {# geotrek.maintenance #}.v_projects AS (
	SELECT ST_Union(t.geom) AS geom, s.*
	FROM v_interventions AS t, maintenance_project AS s
	WHERE t.project_id = s.id
	GROUP BY t.project_id, s.id
);


/**
 * Creates database tables for storing security data.
 *
 * Copyright 2014 Mohiva Organisation (license at mohiva dot com)
 *
 * 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
 *
 *     http://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.
 */

-- TODO users, login info, profiles, etc.

CREATE TABLE USERS
(
  ID UUID PRIMARY KEY NOT NULL,
  USERNAME VARCHAR NOT NULL,
  CREATION_TIME_UTC TIMESTAMP NOT NULL,
  UPDATE_TIME_UTC TIMESTAMP NOT NULL,
  IS_SOFT_DELETED BOOLEAN NOT NULL DEFAULT FALSE
);

Create additional security database fields

/**
 * Creates database tables for storing security data.
 *
 * Copyright 2014 Mohiva Organisation (license at mohiva dot com)
 *
 * 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
 *
 *     http://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.
 */

-- TODO users, login info, profiles, etc.

-- Application users.
CREATE TABLE USERS
(
  ID UUID PRIMARY KEY NOT NULL,
  FIRSTNAME VARCHAR NOT NULL,
  LASTNAME VARCHAR,
  FULLNAME VARCHAR,
  EMAIL VARCHAR,
  AVATAR VARCHAR,
  CREATION_TIME_UTC TIMESTAMP NOT NULL,
  UPDATE_TIME_UTC TIMESTAMP NOT NULL,
  IS_SOFT_DELETED BOOLEAN NOT NULL DEFAULT FALSE
);

-- Entries that link application users to authentication provider accounts.
-- An application user can be linked to multiple authentication provider accounts.
-- An authentication provider account can be linked to a single application user.
CREATE TABLE USER_LOGIN_INFO
(
  PROVIDER_ID VARCHAR NOT NULL,
  PROVIDER_KEY VARCHAR NOT NULL,
  USER_ID UUID NOT NULL,
  PRIMARY KEY (PROVIDER_ID, PROVIDER_KEY)
);


CREATE FUNCTION admin.select_organization_by_name(org_name text) RETURNS SETOF public.organizations
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
BEGIN
	RETURN QUERY SELECT id,name FROM organizations WHERE name=org_name;
	IF NOT FOUND THEN
		RAISE EXCEPTION 'Organization with name % not found', org_name;
	END IF;

	RETURN;
END
$$;

CREATE OR REPLACE FUNCTION on that file

CREATE OR REPLACE FUNCTION admin.select_organization_by_name(org_name text) RETURNS SETOF public.organizations
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
BEGIN
	RETURN QUERY SELECT id,name FROM organizations WHERE name=org_name;
	IF NOT FOUND THEN
		RAISE EXCEPTION 'Organization with name % not found', org_name;
	END IF;

	RETURN;
END
$$;


-- $ heroku pg:psql < create.sql

DROP TABLE requests;
DROP TABLE members;
DROP TABLE teams;
DROP TABLE shifts;

-- days_in_shift: The days included in a shift table
-- max_shift_count_in_routine: The max shift tables generated in one routine
CREATE TABLE IF NOT EXISTS teams(
  id bigserial PRIMARY KEY,
  name varchar(80),
  days_in_shift bigint,
  max_shift_count_in_routine bigint
);

CREATE TABLE IF NOT EXISTS members(
  id bigserial PRIMARY KEY,
  name varchar(80),
  line_id varchar(80),
  team bigint references teams(id)
);

CREATE TABLE IF NOT EXISTS requests(
  id bigserial PRIMARY KEY,
  member bigint references members(id),
  team bigint references teams(id),
  start_time timestamp,
  end_time timestamp,
  availability real
);

CREATE TABLE IF NOT EXISTS shifts(
  id bigserial PRIMARY KEY,
  team bigint references teams(id),
  start_date date,
  time_table json
);

Update drop table order to clean all tables

-- $ heroku pg:psql < create.sql

DROP TABLE requests;
DROP TABLE shifts;
DROP TABLE members;
DROP TABLE teams;

-- days_in_shift: The days included in a shift table
-- max_shift_count_in_routine: The max shift tables generated in one routine
CREATE TABLE IF NOT EXISTS teams(
  id bigserial PRIMARY KEY,
  name varchar(80),
  days_in_shift bigint,
  max_shift_count_in_routine bigint
);

CREATE TABLE IF NOT EXISTS members(
  id bigserial PRIMARY KEY,
  name varchar(80),
  line_id varchar(80),
  team bigint references teams(id)
);

CREATE TABLE IF NOT EXISTS requests(
  id bigserial PRIMARY KEY,
  member bigint references members(id),
  team bigint references teams(id),
  start_time timestamp,
  end_time timestamp,
  availability real
);

CREATE TABLE IF NOT EXISTS shifts(
  id bigserial PRIMARY KEY,
  team bigint references teams(id),
  start_date date,
  time_table json
);


CREATE TABLE if not EXISTS articles (articleID TEXT NOT NULL PRIMARY KEY, feedID TEXT NOT NULL, uniqueID TEXT NOT NULL, title TEXT, contentHTML TEXT, contentText TEXT, url TEXT, externalURL TEXT, summary TEXT, imageURL TEXT, bannerImageURL TEXT, datePublished DATE, dateModified DATE);

CREATE TABLE if not EXISTS statuses (articleID TEXT NOT NULL PRIMARY KEY, read BOOL NOT NULL DEFAULT 0, starred BOOL NOT NULL DEFAULT 0, userDeleted BOOL NOT NULL DEFAULT 0, dateArrived DATE NOT NULL DEFAULT 0);

CREATE TABLE if not EXISTS authors (authorID TEXT NOT NULL PRIMARY KEY, name TEXT, url TEXT, avatarURL TEXT, emailAddress TEXT);
CREATE TABLE if not EXISTS authorsLookup (authorID TEXT NOT NULL, articleID TEXT NOT NULL, PRIMARY KEY(authorID, articleID));

CREATE TABLE if not EXISTS tags(tagName TEXT NOT NULL, articleID TEXT NOT NULL, PRIMARY KEY(tagName, articleID));

CREATE TABLE if not EXISTS attachments(attachmentID TEXT NOT NULL PRIMARY KEY, url TEXT NOT NULL, mimeType TEXT, title TEXT, sizeInBytes INTEGER, durationInSeconds INTEGER);
CREATE TABLE if not EXISTS attachmentsLookup(attachmentID TEXT NOT NULL, articleID TEXT NOT NULL, PRIMARY KEY(attachmentID, articleID));

CREATE INDEX if not EXISTS articles_feedID_index on articles (feedID);

CREATE INDEX if not EXISTS tags_tagName_index on tags (tagName COLLATE NOCASE);

Create index on statuses (read) for performance reasons.

CREATE TABLE if not EXISTS articles (articleID TEXT NOT NULL PRIMARY KEY, feedID TEXT NOT NULL, uniqueID TEXT NOT NULL, title TEXT, contentHTML TEXT, contentText TEXT, url TEXT, externalURL TEXT, summary TEXT, imageURL TEXT, bannerImageURL TEXT, datePublished DATE, dateModified DATE);

CREATE TABLE if not EXISTS statuses (articleID TEXT NOT NULL PRIMARY KEY, read BOOL NOT NULL DEFAULT 0, starred BOOL NOT NULL DEFAULT 0, userDeleted BOOL NOT NULL DEFAULT 0, dateArrived DATE NOT NULL DEFAULT 0);

CREATE TABLE if not EXISTS authors (authorID TEXT NOT NULL PRIMARY KEY, name TEXT, url TEXT, avatarURL TEXT, emailAddress TEXT);
CREATE TABLE if not EXISTS authorsLookup (authorID TEXT NOT NULL, articleID TEXT NOT NULL, PRIMARY KEY(authorID, articleID));

CREATE TABLE if not EXISTS tags(tagName TEXT NOT NULL, articleID TEXT NOT NULL, PRIMARY KEY(tagName, articleID));

CREATE TABLE if not EXISTS attachments(attachmentID TEXT NOT NULL PRIMARY KEY, url TEXT NOT NULL, mimeType TEXT, title TEXT, sizeInBytes INTEGER, durationInSeconds INTEGER);
CREATE TABLE if not EXISTS attachmentsLookup(attachmentID TEXT NOT NULL, articleID TEXT NOT NULL, PRIMARY KEY(attachmentID, articleID));

CREATE INDEX if not EXISTS articles_feedID_index on articles (feedID);

CREATE INDEX if not EXISTS tags_tagName_index on tags (tagName COLLATE NOCASE);

CREATE INDEX if not EXISTS statuses_read_index on statuses (read);


/********************************************************************************
file-centric-snapshot-mdrs-no-version-skew.sql
    Assertion:
        "Target modules in the MDRS must have the same version"
********************************************************************************/

	insert into qa_result (runid, assertionuuid, concept_id, details)
	select
		<RUNID>,
		'<ASSERTIONUUID>',
		a.referencedcomponentid,
		concat('Version skew in dependency on module: ', b.referencedcomponentid, ' - ', a.targeteffectivetime, ' and ', b.targeteffectivetime)
	from curr_moduledependencyrefset_s a, curr_moduledependencyrefset_s b
	where a.active = '1' and b.active = '1'
		and a.referencedcomponentid = b.referencedcomponentid
		and a.sourceeffectivetime = b.sourceeffectivetime
		and a.targeteffectivetime != b.targeteffectivetime;

Remove sourceeffectivetime check. Any modules that are referenced should only have one version referenced in the snapshot

/********************************************************************************
file-centric-snapshot-mdrs-no-version-skew.sql
    Assertion:
        "Target modules in the MDRS must have the same version"
********************************************************************************/

	insert into qa_result (runid, assertionuuid, concept_id, details)
	select
		<RUNID>,
		'<ASSERTIONUUID>',
		a.referencedcomponentid,
		concat('Version skew in dependency on module: ', b.referencedcomponentid, ' - ', a.targeteffectivetime, ' and ', b.targeteffectivetime)
	from curr_moduledependencyrefset_s a, curr_moduledependencyrefset_s b
	where a.active = '1' and b.active = '1'
		and a.referencedcomponentid = b.referencedcomponentid
		and a.targeteffectivetime != b.targeteffectivetime;


DROP TABLE IF EXISTS `plm_file`;
CREATE TABLE  `plm_file` (
  `id` bigint(20) NOT NULL,
  `filename` varchar(255) NULL,
  `file_type` varchar(255) NOT NULL,
  `data` MEDIUMBLOB NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Make sure the table name is recognized on linux

DROP TABLE IF EXISTS `PLM_FILE`;
CREATE TABLE  `PLM_FILE` (
  `id` bigint(20) NOT NULL,
  `filename` varchar(255) NULL,
  `file_type` varchar(255) NOT NULL,
  `data` MEDIUMBLOB NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


create user vagrant with createdb password '';
create database vagrant with owner vagrant;
grant all on database vagrant to vagrant;
\c template1
create extension tablefunc;

Repair vagrant: core postgres database init script.

create user vagrant with createdb password '';
create database vagrant with owner vagrant;
grant all on database vagrant to vagrant;
\c vagrant
create extension tablefunc;


ALTER TABLE EPS_PROPOSAL ADD COLUMN ANTICIPATED_AWARD_TYPE_CODE NUMBER(3)
/

Correct syntax error in script

ALTER TABLE EPS_PROPOSAL ADD COLUMN ANTICIPATED_AWARD_TYPE_CODE NUMBER(3,0)
/


-- Inizio script
/*!40101 SET character_set_client = latin1 */;
/*!40103 SET TIME_ZONE='+00:00' */;

SET AUTOCOMMIT=0;
START TRANSACTION;

-- Add schedule details to csi prova 2
update meeting_sessions
set warm_up_time = '14:00:00',
begin_time = '14:50:00',
day_part_type_id = (select dpt.id from day_part_types dpt where dpt.code = 'P')
where meeting_id = 14102;

COMMIT;
-- Fine script

Add settings for has_invitation field of csiprova2 meeting

-- Inizio script
/*!40101 SET character_set_client = latin1 */;
/*!40103 SET TIME_ZONE='+00:00' */;

SET AUTOCOMMIT=0;
START TRANSACTION;

-- Add schedule details to csi prova 2
update meeting_sessions
set warm_up_time = '14:00:00',
begin_time = '14:50:00',
day_part_type_id = (select dpt.id from day_part_types dpt where dpt.code = 'P')
where meeting_id = 14102;

-- Set meeting invitation (assumes the invitation file has been copied into the filed
update meetings set has_invitation = true where id = 14102;

COMMIT;
-- Fine script


INSERT INTO KRIM_PERM_T (PERM_ID,OBJ_ID,VER_NBR,PERM_TMPL_ID,NMSPC_CD,NM,DESC_TXT,ACTV_IND)
VALUES (KRIM_PERM_ID_BS_S.nextval,SYS_GUID,1,(SELECT PERM_TMPL_ID from KRIM_PERM_TMPL_T WHERE NMSPC_CD='KC-IDM' AND NM='Questionnaire Permission'),'KC-IACUC','Maintain Questionnaire Usage','Add/Edit Questionnaire Usages for IACUC Protocol','Y')
/
INSERT INTO KRIM_ROLE_PERM_T (ROLE_PERM_ID,ROLE_ID,PERM_ID,ACTV_IND,OBJ_ID,VER_NBR)
  VALUES (KRIM_ROLE_PERM_ID_BS_S.NEXTVAL,(SELECT ROLE_ID FROM KRIM_ROLE_T WHERE ROLE_NM = 'IACUC Administrator' AND NMSPC_CD='KC-UNT'),
    (SELECT PERM_ID FROM KRIM_PERM_T WHERE NM = 'Maintain Questionnaire Usage' AND NMSPC_CD='KC-IACUC'),'Y',SYS_GUID(),1)
/

Implement Questionnaire functionality in IACUC

INSERT INTO KRIM_PERM_T (PERM_ID,OBJ_ID,VER_NBR,PERM_TMPL_ID,NMSPC_CD,NM,DESC_TXT,ACTV_IND)
VALUES (KRIM_PERM_ID_BS_S.nextval,SYS_GUID(),1,(SELECT PERM_TMPL_ID from KRIM_PERM_TMPL_T WHERE NMSPC_CD='KC-IDM' AND NM='Questionnaire Permission'),'KC-IACUC','Maintain Questionnaire Usage','Add/Edit Questionnaire Usages for IACUC Protocol','Y')
/
INSERT INTO KRIM_ROLE_PERM_T (ROLE_PERM_ID,ROLE_ID,PERM_ID,ACTV_IND,OBJ_ID,VER_NBR)
  VALUES (KRIM_ROLE_PERM_ID_BS_S.NEXTVAL,(SELECT ROLE_ID FROM KRIM_ROLE_T WHERE ROLE_NM = 'IACUC Administrator' AND NMSPC_CD='KC-UNT'),
    (SELECT PERM_ID FROM KRIM_PERM_T WHERE NM = 'Maintain Questionnaire Usage' AND NMSPC_CD='KC-IACUC'),'Y',SYS_GUID(),1)
/


# patch_39_40_c
#
# title: xref version
#
# description:
# Change version column in xref to be default 0, not allow null

ALTER TABLE xref CHANGE COLUMN version version VARCHAR(10) DEFAULT '0' NOT NULL;

UPDATE xref SET version = '0' WHERE version = NULL OR version = '';

# patch identifier
INSERT INTO meta (meta_key, meta_value) VALUES ('patch', 'patch_39_40_c.sql|xref_version');

# Similarly make all seq_region_start & seq_region_end columns INT(10) UNSIGNED
# Although these are not used as keys, they are used in many joins and having
# the same column type should make joins faster as MySQL will not have to do
# any type casting.

Add fix for versions that contain the NULL string.

# patch_39_40_c
#
# title: xref version
#
# description:
# Change version column in xref to be default 0, not allow null

ALTER TABLE xref CHANGE COLUMN version version VARCHAR(10) DEFAULT '0' NOT NULL;

UPDATE xref SET version = '0' WHERE version = NULL OR version = '' OR version = "NULL";

# patch identifier
INSERT INTO meta (meta_key, meta_value) VALUES ('patch', 'patch_39_40_c.sql|xref_version');

# Similarly make all seq_region_start & seq_region_end columns INT(10) UNSIGNED
# Although these are not used as keys, they are used in many joins and having
# the same column type should make joins faster as MySQL will not have to do
# any type casting.


INSERT INTO KRCR_PARM_T (NMSPC_CD, CMPNT_CD, PARM_NM, OBJ_ID, VER_NBR, PARM_TYP_CD, VAL, PARM_DESC_TXT, EVAL_OPRTR_CD, APPL_ID)
VALUES ('KC-IACUC', 'Document', 'PROTOCOL_DISCLOSE_STATUS_CODES', SYS_GUID(), 1, 'CONFG', '100;101;102;200;202', 'IACUC Protocol status codes for which a COI disclosure event will be considered active.', 'A', 'KC')
/
INSERT INTO KRCR_PARM_T (NMSPC_CD, CMPNT_CD, PARM_NM, OBJ_ID, VER_NBR, PARM_TYP_CD, VAL, PARM_DESC_TXT, EVAL_OPRTR_CD, APPL_ID)
VALUES ('KC-IACUC', 'Document', 'ALL_SPONSORS_FOR_IACUC_PROTOCOL_DISCLOSE', SYS_GUID(), '1', 'CONFG', 'N', 'All IACUC protocols require disclosure, irrespective to funding sponsor code.', 'A', 'KC')
/

Implement COI event type of "IACUC Protocol"

INSERT INTO KRCR_PARM_T (NMSPC_CD, CMPNT_CD, PARM_NM, OBJ_ID, VER_NBR, PARM_TYP_CD, VAL, PARM_DESC_TXT, EVAL_OPRTR_CD, APPL_ID)
VALUES ('KC-IACUC', 'Document', 'IACUC_DISCLOSE_STATUS_CODES', SYS_GUID(), 1, 'CONFG', '100;101;102;200;202', 'IACUC Protocol status codes for which a COI disclosure event will be considered active.', 'A', 'KC')
/
INSERT INTO KRCR_PARM_T (NMSPC_CD, CMPNT_CD, PARM_NM, OBJ_ID, VER_NBR, PARM_TYP_CD, VAL, PARM_DESC_TXT, EVAL_OPRTR_CD, APPL_ID)
VALUES ('KC-IACUC', 'Document', 'ALL_SPONSORS_FOR_IACUC_PROTOCOL_DISCLOSE', SYS_GUID(), '1', 'CONFG', 'N', 'All IACUC protocols require disclosure, irrespective to funding sponsor code.', 'A', 'KC')
/


BEGIN;

DROP TABLE IF EXISTS Model_Views;

CREATE TABLE Model_Views AS
SELECT logged_at, ip_address, node_id
  FROM Logged_Actions
 WHERE controller = 'browse'
   AND action = 'one_model'
   AND is_searchbot = 'false'
;

DROP TABLE IF EXISTS Model_Downloads;

CREATE TABLE Model_Downloads AS
SELECT logged_at, ip_address, node_id
  FROM Logged_Actions
 WHERE controller = 'browse'
   AND action = 'download_model'
   AND is_searchbot = 'false'
;

COMMIT;

Add person_id column to table

BEGIN;

DROP TABLE IF EXISTS Model_Views;

CREATE TABLE Model_Views AS
SELECT logged_at, ip_address, node_id, person_id
  FROM Logged_Actions
 WHERE controller = 'browse'
   AND action = 'one_model'
   AND is_searchbot = 'false'
;

DROP TABLE IF EXISTS Model_Downloads;

CREATE TABLE Model_Downloads AS
SELECT logged_at, ip_address, node_id, person_id
  FROM Logged_Actions
 WHERE controller = 'browse'
   AND action = 'download_model'
   AND is_searchbot = 'false'
;

COMMIT;


DROP INDEX profile_email__profile_id__idx;
DROP INDEX profile_email__email__idx;
DROP TABLE profile_email;

Add missing sql sentence on migration 0009.

DROP INDEX profile_email__profile_id__idx;
DROP INDEX profile_email__email__idx;
DROP TABLE profile_email;

ALTER TABLE profile
  ADD COLUMN pending_email text NULL;


-- run as a cronjob: psql packages -f tools/daily.sql -o /dev/null
delete from cookies where last_seen < now()-INTERVAL'1day';
delete from openid_sessions where expires < now();
delete from openid_nonces where created < now()-INTERVAL'1day';
delete from users where name in (select name from rego_otk where date < now()-INTERVAL'7days');

Delete openids of expired users.

-- run as a cronjob: psql packages -f tools/daily.sql -o /dev/null
delete from cookies where last_seen < now()-INTERVAL'1day';
delete from openid_sessions where expires < now();
delete from openid_nonces where created < now()-INTERVAL'1day';
delete from openids where name in (select name from rego_otk where date < now()-INTERVAL'7days');
delete from users where name in (select name from rego_otk where date < now()-INTERVAL'7days');


INSERT INTO rfam_go_terms (
    ontology_term_id,
    rfam_model_id
) (
SELECT
    ontology_term_id,
    rfam_model_id
FROM load_rfam_go_terms
)
ON CONFLICT (ontology_term_id, rfam_model_id) DO UPDATE SET
    ontology_term_id = excluded.ontology_term_id,
    rfam_model_id = excluded.rfam_model_id
;

DROP TABLE load_rfam_go_terms;

Delete old GO annotations prior to loading

DELETE FROM rfam_go_terms rfam
USING load_rfam_go_terms load
WHERE
  load.rfam_model_id = rfam.rfam_model_id
;

INSERT INTO rfam_go_terms (
  ontology_term_id,
  rfam_model_id
) (
SELECT
  ontology_term_id,
  rfam_model_id
FROM load_rfam_go_terms
)
ON CONFLICT (ontology_term_id, rfam_model_id) DO UPDATE SET
  ontology_term_id = excluded.ontology_term_id,
  rfam_model_id = excluded.rfam_model_id
;

DROP TABLE load_rfam_go_terms;


# 04/30/2010

ALTER TABLE osdial_hopper MODIFY status `status` enum('READY','QUEUE','INCALL','DONE','HOLD','API') DEFAULT 'READY';##|##
 ##    Added status for API insertion.;

UPDATE system_settings SET version='2.2.1.055',last_update_check=DATE_SUB(NOW(), INTERVAL 1 DAY);##|##
 ##    Updating database to version 2.2.1.055 and clearing last_update_check flag.;

Fix DB command for API status hopper entries.

# 04/30/2010

ALTER TABLE osdial_hopper MODIFY status enum('READY','QUEUE','INCALL','DONE','HOLD','API') DEFAULT 'READY';##|##
 ##    Added status for API insertion.;

UPDATE system_settings SET version='2.2.1.055',last_update_check=DATE_SUB(NOW(), INTERVAL 1 DAY);##|##
 ##    Updating database to version 2.2.1.055 and clearing last_update_check flag.;


-- +migrate Up
INSERT INTO tools (name, url, path, args, `regexp`) VALUES
    ("gosimple", "https://github.com/dominikh/go-tools", "gosimple", "./...", ""),
    ("staticcheck", "https://github.com/dominikh/go-tools", "staticcheck", "./...", ""),
    ("unused", "https://github.com/dominikh/go-tools", "unused", "./...", "");

-- +migrate Down

Fix migrations where this is no down

-- +migrate Up
INSERT INTO tools (name, url, path, args, `regexp`) VALUES
    ("gosimple", "https://github.com/dominikh/go-tools", "gosimple", "./...", ""),
    ("staticcheck", "https://github.com/dominikh/go-tools", "staticcheck", "./...", ""),
    ("unused", "https://github.com/dominikh/go-tools", "unused", "./...", "");

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


# ---!Ups
alter table application_users drop column secret_key;
alter table users add column secret_key varchar(36) not null;
drop index application_users_idx;
create index users_secret_key_idx on users (username, secret_key);

# ---!Downs
alter table application_users add column secret_key varchar(36) not null;
alter table users drop column secret_key;
create index application_users_idx on application_users (user_id, secret_key);

Drop the index before the column to prevent weirdness, and add an 'allow_anonymous_evals' boolean for apps that want to do things that way.

# ---!Ups
drop index application_users_idx;
alter table application_users drop column secret_key;
alter table users add column secret_key varchar(36) not null;
create index users_secret_key_idx on users (username, secret_key);
alter table applications add column allow_anonymous_evals boolean not null;

# ---!Downs
alter table application_users add column secret_key varchar(36) not null;
alter table users drop column secret_key;
create index application_users_idx on application_users (user_id, secret_key);
alter table applications drop column allow_anonymous_evals;


--add new column
ALTER TABLE user
ADD c4sg_developer_flg CHAR(1) NOT NULL DEFAULT 'N';

--load data in the column
UPDATE User
SET c4sg_developer_flg = 'Y'
WHERE id IN (2,8, 12, 18,22,28,33,35,45,49,52,58,61,70,72,78,90,100);


CREATE OR REPLACE FUNCTION _gc2_notify_transaction()
  RETURNS TRIGGER AS $$
DECLARE
  t text;
BEGIN
  IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE'
  THEN
    EXECUTE 'SELECT $1.'||TG_ARGV[0] USING NEW INTO t;
    PERFORM pg_notify('_gc2_notify_transaction',  TG_OP || ',' || TG_ARGV[1] || ',' || TG_ARGV[2] || ',' || TG_ARGV[0] || ',' ||t);
  ELSEIF TG_OP = 'DELETE'
    THEN
      EXECUTE 'SELECT $1.'||TG_ARGV[0] USING OLD INTO t;
      PERFORM pg_notify('_gc2_notify_transaction',  TG_OP || ',' || TG_ARGV[1] || ',' || TG_ARGV[2] || ',' || t);
  END IF;
  RETURN null;
END;
$$ LANGUAGE plpgsql;

Delete will also send the key

CREATE OR REPLACE FUNCTION _gc2_notify_transaction()
  RETURNS TRIGGER AS $$
DECLARE
  t text;
BEGIN
  IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE'
  THEN
    EXECUTE 'SELECT $1.'||TG_ARGV[0] USING NEW INTO t;
    PERFORM pg_notify('_gc2_notify_transaction',  TG_OP || ',' || TG_ARGV[1] || ',' || TG_ARGV[2] || ',' || TG_ARGV[0] || ',' ||t);
  ELSEIF TG_OP = 'DELETE'
    THEN
      EXECUTE 'SELECT $1.'||TG_ARGV[0] USING OLD INTO t;
      PERFORM pg_notify('_gc2_notify_transaction',  TG_OP || ',' || TG_ARGV[1] || ',' || TG_ARGV[2] || ',' || TG_ARGV[0] || ',' ||t);
  END IF;
  RETURN null;
END;
$$ LANGUAGE plpgsql;


INSERT INTO groups (id, name, rules, notes, created, modified) VALUES
  (50052, 'Submit experiments (auto signed)', 'Experiments:submit', '', NOW(), NOW());

Remove fixed ID from migration adding 'Experiments:submit' group

INSERT INTO groups (name, rules, notes, created, modified) VALUES
  ('Submit experiments (auto signed)', 'Experiments:submit', '', NOW(), NOW());


CREATE DATABASE `ssbo_ticketing` CHARACTER SET utf8 COLLATE utf8_general_ci;

USE ssbo_ticketing;

CREATE TABLE IF NOT EXISTS tickets (
	code		VARCHAR(27) NOT NULL,
	firstname	VARCHAR(50) NOT NULL,
	lastname	VARCHAR(50) NOT NULL,
	street		VARCHAR(50) NOT NULL,
	housenumber	VARCHAR(5) NOT NULL,
	postalcode	INT(5) UNSIGNED NOT NULL,
	town		VARCHAR(50) NOT NULL,
	email		VARCHAR(50) NOT NULL,
	date		TIMESTAMP NOT NULL,
	payed		BOOLEAN NOT NULL DEFAULT false,
	used		BOOLEAN NOT NULL DEFAULT false,
	PRIMARY KEY (code)
);

Improve security by using user management for DB

CREATE DATABASE `ssbo_ticketing` CHARACTER SET utf8 COLLATE utf8_general_ci;
USE ssbo_ticketing;

CREATE USER 'admin'@'localhost' IDENTIFIED BY 'password';
GRANT SELECT, INSERT, UPDATE ON `ssbo_ticketing`.* TO 'admin'@'localhost';

CREATE TABLE IF NOT EXISTS tickets (
	code		VARCHAR(27) NOT NULL,
	firstname	VARCHAR(50) NOT NULL,
	lastname	VARCHAR(50) NOT NULL,
	street		VARCHAR(50) NOT NULL,
	housenumber	VARCHAR(5) NOT NULL,
	postalcode	INT(5) UNSIGNED NOT NULL,
	town		VARCHAR(50) NOT NULL,
	email		VARCHAR(50) NOT NULL,
	date		TIMESTAMP NOT NULL,
	payed		BOOLEAN NOT NULL DEFAULT false,
	used		BOOLEAN NOT NULL DEFAULT false,
	PRIMARY KEY (code)
);


#
# Table structure for table 'tx_tevglossary_domain_model_entry'
#

CREATE TABLE tx_tevglossary_domain_model_entry (
    uid int(11) unsigned NOT NULL auto_increment,
    pid int(11) unsigned DEFAULT '0' NOT NULL,
    crdate int(11) unsigned DEFAULT '0' NOT NULL,
    tstamp int(11) unsigned DEFAULT '0' NOT NULL,
    cruser_id int(11) unsigned DEFAULT '0' NOT NULL,
    deleted tinyint(4) unsigned DEFAULT '0' NOT NULL,
    hidden tinyint(4) unsigned DEFAULT '0' NOT NULL,
    term varchar(255) NOT NULL,
    definition text NOT NULL,

    PRIMARY KEY (uid),
    KEY parent (pid),
    KEY deleted (deleted),
    KEY deleted (hidden)
);

Fix SQL statement to prevent always asking for updates

#
# Table structure for table 'tx_tevglossary_domain_model_entry'
#

CREATE TABLE tx_tevglossary_domain_model_entry (
    uid int(11) unsigned NOT NULL auto_increment,
    pid int(11) unsigned DEFAULT '0' NOT NULL,
    crdate int(11) unsigned DEFAULT '0' NOT NULL,
    tstamp int(11) unsigned DEFAULT '0' NOT NULL,
    cruser_id int(11) unsigned DEFAULT '0' NOT NULL,
    deleted tinyint(4) unsigned DEFAULT '0' NOT NULL,
    hidden tinyint(4) unsigned DEFAULT '0' NOT NULL,
    term varchar(255) DEFAULT '' NOT NULL,
    definition text NOT NULL,

    PRIMARY KEY (uid),
    KEY parent (pid),
    KEY deleted (deleted),
    KEY deleted (hidden)
);


CREATE TABLE [account].[Account]
(
	[Id] BIGINT NOT NULL PRIMARY KEY IDENTITY,
	[HashedAccountId] NVARCHAR(100) NOT NULL,
    [Name] NVARCHAR(100) NOT NULL
)
GO

CREATE UNIQUE INDEX [IX_Account_HashedAccountId] ON [account].[Account] ([HashedAccountId])

Change for the hashedaccountid to allow nulls.

CREATE TABLE [account].[Account]
(
	[Id] BIGINT NOT NULL PRIMARY KEY IDENTITY,
	[HashedAccountId] NVARCHAR(100) NULL,
    [Name] NVARCHAR(100) NOT NULL
)
GO

CREATE UNIQUE INDEX [IX_Account_HashedAccountId] ON [account].[Account] ([HashedAccountId])


-- Note: When adding new tables, also add the tables to dropSchema.sql and clearSchema in order for tests to work correctly.

CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TABLE IF NOT EXISTS users (
    user_id    bigserial PRIMARY KEY ,
    username   text UNIQUE NOT NULL,
    email      text NOT NULL,
    password   text NOT NULL,
    first_name text NOT NULL,
    last_name  text NOT NULL
);

CREATE TABLE IF NOT EXISTS groups (
    group_id   bigserial PRIMARY KEY,
    name       text      NOT NULL,
    created_on bigint NOT NULL,
    admin bigint REFERENCES users ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS group_contains_user (
    group_id bigint NOT NULL REFERENCES groups,
    user_id  bigint NOT NULL REFERENCES users,
    PRIMARY KEY (group_id, user_id)
);

CREATE TABLE IF NOT EXISTS user_invited_to_group (
    invite_id bigserial PRIMARY KEY,
    user_id bigint NOT NULL references users,
    group_id bigint NOT NULL references groups
);

Add data to populate on re-deploy.

-- Note: When adding new tables, also add the tables to dropSchema.sql and clearSchema in order for tests to work correctly.

CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TABLE IF NOT EXISTS users (
    user_id    bigserial PRIMARY KEY ,
    username   text UNIQUE NOT NULL,
    email      text NOT NULL,
    password   text NOT NULL,
    first_name text NOT NULL,
    last_name  text NOT NULL
);

CREATE TABLE IF NOT EXISTS groups (
    group_id   bigserial PRIMARY KEY,
    name       text      NOT NULL,
    created_on bigint NOT NULL,
    admin bigint REFERENCES users ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS group_contains_user (
    group_id bigint NOT NULL REFERENCES groups,
    user_id  bigint NOT NULL REFERENCES users,
    PRIMARY KEY (group_id, user_id)
);

CREATE TABLE IF NOT EXISTS user_invited_to_group (
    invite_id bigserial PRIMARY KEY,
    user_id bigint NOT NULL references users,
    group_id bigint NOT NULL references groups
);

INSERT INTO users(username, email, password, first_name, last_name) values('jeff', 'fake@email.com', 'password', 'Jeff', 'Fennell');
INSERT INTO users(username, email, password, first_name, last_name) values('SomeDude', 'fake123@email.com', 'password', 'The', 'Dude');

INSERT INTO groups(name, created_on, admin) values ('The best group', 1459821220, 1);

INSERT INTO group_contains_user (group_id, user_id) values(1,1);
INSERT INTO group_contains_user (group_id, user_id) values(1,2);


--
-- The unique constraint got left out of an earlier actioncounters migration,
-- so this schematic migration forcibly cleans up the few duplicates and adds
-- the unique constraint.
--
-- There should only be about 50 duplicates in 180000 or so production records.
--
CREATE TEMPORARY TABLE dup_actioncounter_hashes
    SELECT unique_hash
    FROM actioncounters_actioncounterunique
    GROUP BY unique_hash
    HAVING count(unique_hash) > 1;

DELETE FROM actioncounters_actioncounterunique
    WHERE unique_hash IN
        (SELECT unique_hash FROM dup_actioncounter_hashes);

DROP INDEX actioncounters_actioncounterunique_unique
    ON actioncounters_actioncounterunique;

ALTER TABLE actioncounters_actioncounterunique
    ADD UNIQUE actioncounters_actioncounterunique_unique (unique_hash);

Disable broken migration that prevents tidings migration from executing

-- HACK: This migration is commented out, because it's turned out to be
-- trouble. But, removing it from the sequence entirely also causes trouble.
-- So, this is a no-op.

--
-- The unique constraint got left out of an earlier actioncounters migration,
-- so this schematic migration forcibly cleans up the few duplicates and adds
-- the unique constraint.
--
-- There should only be about 50 duplicates in 180000 or so production records.
--
-- CREATE TEMPORARY TABLE dup_actioncounter_hashes
--     SELECT unique_hash
--     FROM actioncounters_actioncounterunique
--     GROUP BY unique_hash
--     HAVING count(unique_hash) > 1;
--
-- DELETE FROM actioncounters_actioncounterunique
--     WHERE unique_hash IN
--         (SELECT unique_hash FROM dup_actioncounter_hashes);
--
-- DROP INDEX actioncounters_actioncounterunique_unique
--     ON actioncounters_actioncounterunique;
--
-- ALTER TABLE actioncounters_actioncounterunique
--     ADD UNIQUE actioncounters_actioncounterunique_unique (unique_hash);


BEGIN;
    CREATE TABLE emails
    ( id            serial                      PRIMARY KEY
    , address       text                        NOT NULL
    , verified      boolean                     DEFAULT NULL
    , nonce         text
    , ctime         timestamp with time zone    NOT NULL
                                                  DEFAULT CURRENT_TIMESTAMP
    , mtime         timestamp with time zone
    , participant   text                        NOT NULL
                                                  REFERENCES participants
                                                  ON UPDATE CASCADE
                                                  ON DELETE RESTRICT

    , UNIQUE (address, verified) -- A verified email address can't be linked to multiple
                                 -- participants.
    , UNIQUE (participant, address)
     );

    -- The participants table currently has an `email` attribute of type
    -- email_address_with confirmation. This should be deleted in the future,
    -- once the emails are migrated. The column we're going to replace it with
    -- is named `email_address`. This is only for **verified** emails. All
    -- unverified email stuff happens in the emails table and won't touch this
    -- attribute.

    ALTER TABLE participants ADD COLUMN email_address text UNIQUE,
                             ADD COLUMN email_lang text;

    UPDATE events
       SET payload = replace(replace( payload::text, '"set"', '"add"')
                                    , '"current_email"'
                                    , '"email"'
                                     )::json
     WHERE payload->>'action' = 'set'
       AND (payload->'values'->'current_email') IS NOT NULL;

END;

Add a constraint and comment to verified

BEGIN;
    CREATE TABLE emails
    ( id            serial                      PRIMARY KEY
    , address       text                        NOT NULL
    , verified      boolean                     DEFAULT NULL
                                                  CONSTRAINT verified_cant_be_false
                                                    -- Only use TRUE and NULL, so that the unique
                                                    -- constraint below functions properly.
                                                    CHECK (verified IS NOT FALSE)
    , nonce         text
    , ctime         timestamp with time zone    NOT NULL
                                                  DEFAULT CURRENT_TIMESTAMP
    , mtime         timestamp with time zone
    , participant   text                        NOT NULL
                                                  REFERENCES participants
                                                  ON UPDATE CASCADE
                                                  ON DELETE RESTRICT

    , UNIQUE (address, verified) -- A verified email address can't be linked to multiple
                                 -- participants. However, an *un*verified address *can*
                                 -- be linked to multiple participants. We implement this
                                 -- by using NULL instead of FALSE for the unverified
                                 -- state, hence the check constraint on verified.
    , UNIQUE (participant, address)
     );

    -- The participants table currently has an `email` attribute of type
    -- email_address_with confirmation. This should be deleted in the future,
    -- once the emails are migrated. The column we're going to replace it with
    -- is named `email_address`. This is only for **verified** emails. All
    -- unverified email stuff happens in the emails table and won't touch this
    -- attribute.

    ALTER TABLE participants ADD COLUMN email_address text UNIQUE,
                             ADD COLUMN email_lang text;

    UPDATE events
       SET payload = replace(replace( payload::text, '"set"', '"add"')
                                    , '"current_email"'
                                    , '"email"'
                                     )::json
     WHERE payload->>'action' = 'set'
       AND (payload->'values'->'current_email') IS NOT NULL;

END;


-- Table definitions for the tournament project.
--
-- Put your SQL 'create table' statements in this file; also 'create view'
-- statements if you choose to use it.
--
-- You can write comments in this file by starting them with two dashes, like
-- these lines here.

CREATE DATABASE tournament;
\c tournament;

CREATE TABLE players (id SERIAL PRIMARY KEY,
						name VARCHAR(64));

CREATE TABLE matches (id SERIAL PRIMARY KEY,
						winner_id INT REFERENCES players(id),
						loser_id INT REFERENCES players(id));

CREATE VIEW players_standings AS SELECT id, name,
(SELECT COUNT(*) FROM matches WHERE winner_id = players.id) wins,
(SELECT COUNT(*) FROM matches WHERE winner_id = players.id OR loser_id = players.id) matches
FROM players;

CREATE VIEW players_wins AS
SELECT row_number() OVER(ORDER BY wins DESC) as position, ps.id, ps.name, ps.wins
FROM (
	SELECT id, name, wins FROM players_standings
) AS ps;

Add ordering to player_standings view

-- Table definitions for the tournament project.
--
-- Put your SQL 'create table' statements in this file; also 'create view'
-- statements if you choose to use it.
--
-- You can write comments in this file by starting them with two dashes, like
-- these lines here.

CREATE DATABASE tournament;
\c tournament;

CREATE TABLE players (id SERIAL PRIMARY KEY,
						name VARCHAR(64));

CREATE TABLE matches (id SERIAL PRIMARY KEY,
						winner_id INT REFERENCES players(id),
						loser_id INT REFERENCES players(id));

CREATE VIEW players_standings AS SELECT id, name,
(SELECT COUNT(*) FROM matches WHERE winner_id = players.id) wins,
(SELECT COUNT(*) FROM matches WHERE winner_id = players.id OR loser_id = players.id) matches
FROM players
ORDER BY wins DESC;

CREATE VIEW players_wins AS
SELECT row_number() OVER(ORDER BY wins DESC) as position, ps.id, ps.name, ps.wins
FROM (
	SELECT id, name, wins FROM players_standings
) AS ps;


create index if not exists source_dataset_version_log_source_dataset_version_id_create_time_idx on source_dataset_version_log using btree(source_dataset_version_id, create_time)

insert into publisher.version(id) values(85);

Add closing character to sql line

create index if not exists source_dataset_version_log_source_dataset_version_id_create_time_idx on source_dataset_version_log using btree(source_dataset_version_id, create_time);

insert into publisher.version(id) values(85);


--
-- 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 am: 3a05525f32 am: 4ffb570dd9

--
-- 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'
  )
);


ALTER TABLE instance
  ADD CONSTRAINT no_duplicate_synonyms UNIQUE (name_id, reference_id, instance_type_id, page, cites_id, cited_by_id);

ALTER TABLE tree_arrangement
  ADD COLUMN shared BOOLEAN DEFAULT TRUE;

DROP TRIGGER reference_update
ON author;

CREATE TRIGGER reference_update
AFTER INSERT OR UPDATE OR DELETE ON reference
FOR EACH ROW
EXECUTE PROCEDURE reference_notification();

Update namespace set name = 'Algae' where name = 'AusAlgae';
Update namespace set description_html = '(description of Algae)' where name = 'Algae';
Update namespace set rdf_id = 'algae' where name = 'Algae';

INSERT INTO namespace (id, lock_version, name, description_html, rdf_id) VALUES (nextval('nsl_global_seq'), 0, 'Lichen', '(description of Lichen)', 'lichen');
INSERT INTO public.namespace (id, lock_version, name, description_html, rdf_id) VALUES (nextval('nsl_global_seq'), 0, 'Fungi', '(description of Fungi)', 'fungi');

-- version
UPDATE db_version
SET version = 18
WHERE id = 1;

Add an if exists to drop trigger in update to make idempotent

ALTER TABLE instance
  ADD CONSTRAINT no_duplicate_synonyms UNIQUE (name_id, reference_id, instance_type_id, page, cites_id, cited_by_id);

ALTER TABLE tree_arrangement
  ADD COLUMN shared BOOLEAN DEFAULT TRUE;

DROP TRIGGER IF EXISTS reference_update
ON author;

CREATE TRIGGER reference_update
AFTER INSERT OR UPDATE OR DELETE ON reference
FOR EACH ROW
EXECUTE PROCEDURE reference_notification();

Update namespace set name = 'Algae' where name = 'AusAlgae';
Update namespace set description_html = '(description of Algae)' where name = 'Algae';
Update namespace set rdf_id = 'algae' where name = 'Algae';

INSERT INTO namespace (id, lock_version, name, description_html, rdf_id) VALUES (nextval('nsl_global_seq'), 0, 'Lichen', '(description of Lichen)', 'lichen');
INSERT INTO public.namespace (id, lock_version, name, description_html, rdf_id) VALUES (nextval('nsl_global_seq'), 0, 'Fungi', '(description of Fungi)', 'fungi');

-- version
UPDATE db_version
SET version = 18
WHERE id = 1;


delete from PROPOSAL_LOG;
delete from PROPOSAL_LOG_STATUS;
insert into PROPOSAL_LOG_STATUS (PROPOSAL_LOG_STATUS_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER)
values ('1', 'PENDING', SYSDATE, USER);

Change proposal log status to submitted after promoting it to an institutional proposal

delete from PROPOSAL_LOG;
delete from PROPOSAL_LOG_STATUS;
insert into PROPOSAL_LOG_STATUS (PROPOSAL_LOG_STATUS_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER)
values ('1', 'PENDING', SYSDATE, USER);
insert into PROPOSAL_LOG_STATUS (PROPOSAL_LOG_STATUS_CODE, DESCRIPTION, UPDATE_TIMESTAMP, UPDATE_USER)
values ('3', 'SUBMITTED', SYSDATE, USER);


/* Copyright 2015 OpenMarket Ltd
 *
 * 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
 *
 *    http://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 TABLE IF NOT EXISTS server_keys_json (
    server_name TEXT, -- Server name.
    key_id TEXT, -- Requested key id.
    from_server TEXT, -- Which server the keys were fetched from.
    ts_added_ms INTEGER, -- When the keys were fetched
    ts_valid_until_ms INTEGER, -- When this version of the keys exipires.
    key_json BLOB, -- JSON certificate for the remote server.
    CONSTRAINT uniqueness UNIQUE (server_name, key_id, from_server)
);

Use bytea rather than BLOB

/* Copyright 2015 OpenMarket Ltd
 *
 * 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
 *
 *    http://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 TABLE IF NOT EXISTS server_keys_json (
    server_name TEXT, -- Server name.
    key_id TEXT, -- Requested key id.
    from_server TEXT, -- Which server the keys were fetched from.
    ts_added_ms INTEGER, -- When the keys were fetched
    ts_valid_until_ms INTEGER, -- When this version of the keys exipires.
    key_json bytea, -- JSON certificate for the remote server.
    CONSTRAINT uniqueness UNIQUE (server_name, key_id, from_server)
);


DROP TABLE IF EXISTS file CASCADE;

CREATE TABLE file (
    ufn         VARCHAR(64) NOT NULL,
    uhn         VARCHAR(64) NOT NULL,
    hostname    VARCHAR(255) NOT NULL,
    path        TEXT NOT NULL,
    filename    TEXT NOT NULL,
    crcsum      VARCHAR(64) NOT NULL,
    block_size  INTEGER NOT NULL
);

ALTER TABLE file ADD CONSTRAINT file_pkey PRIMARY KEY (ufn);

DROP TABLE IF EXISTS file_block CASCADE;

CREATE TABLE file_block (
    file        VARCHAR(64) NOT NULL,
    id          INTEGER NOT NULL,
    crcsum      VARCHAR(64) NOT NULL,
    compressed  BOOLEAN NOT NULL DEFAULT FALSE
);

ALTER TABLE file_block ADD CONSTRAINT file_block_pkey PRIMARY KEY (file,id);
ALTER TABLE file_block ADD CONSTRAINT file_block_fk FOREIGN KEY
    (file) REFERENCES file (ufn) ON DELETE CASCADE ON UPDATE CASCADE;

Add mod_time, move compressed up one layer.

DROP TABLE IF EXISTS file CASCADE;

CREATE TABLE file (
    ufn         VARCHAR(64) NOT NULL,
    uhn         VARCHAR(64) NOT NULL,
    hostname    VARCHAR(255) NOT NULL,
    path        TEXT NOT NULL,
    filename    TEXT NOT NULL,
    crcsum      VARCHAR(64) NOT NULL,
    mod_time    INTEGER NOT NULL,
    block_size  INTEGER NOT NULL,
    compressed  BOOLEAN NOT NULL DEFAULT FALSE
);

ALTER TABLE file ADD CONSTRAINT file_pkey PRIMARY KEY (ufn);

DROP TABLE IF EXISTS file_block CASCADE;

CREATE TABLE file_block (
    file        VARCHAR(64) NOT NULL,
    id          INTEGER NOT NULL,
    crcsum      VARCHAR(64) NOT NULL
);

ALTER TABLE file_block ADD CONSTRAINT file_block_pkey PRIMARY KEY (file,id);
ALTER TABLE file_block ADD CONSTRAINT file_block_fk FOREIGN KEY
    (file) REFERENCES file (ufn) ON DELETE CASCADE ON UPDATE CASCADE;


#standardSQL

-- Copyright 2018 Google LLC
--
-- 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.

-- This example is using the Google analytics sample data set
-- This script calculates the average amount of money spent per session

SELECT
( SUM(total_transactionrevenue_per_user) / SUM(total_visits_per_user) ) AS
avg_revenue_by_user_per_visit
FROM (
SELECT
fullVisitorId,
SUM( totals.visits ) AS total_visits_per_user,
SUM( totals.transactionRevenue ) AS total_transactionrevenue_per_user
FROM
`bigquery-public-data.google_analytics_sample.ga_sessions_*`
WHERE
_TABLE_SUFFIX BETWEEN '20170701' AND '20170731'
AND
totals.visits > 0
AND totals.transactions >= 1
AND totals.transactionRevenue IS NOT NULL
GROUP BY
fullVisitorId )

Format SQL with Google SQL style

#standardSQL

-- Copyright 2018 Google LLC
--
-- 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.

-- This example is using the Google analytics sample data set
-- This script calculates the average amount of money spent per session

WITH Sessions AS (
  SELECT
    fullVisitorId,
    SUM(totals.visits) AS total_visits_per_user,
    SUM(totals.transactionRevenue) AS total_transactionrevenue_per_user
  FROM
    `bigquery-public-data.google_analytics_sample.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170701' AND '20170731'
    AND totals.visits > 0
    AND totals.transactions >= 1
    AND totals.transactionRevenue IS NOT NULL
  GROUP BY fullVisitorId
)
SELECT
  (SUM(total_transactionrevenue_per_user/1e6) /
      SUM(total_visits_per_user)) AS avg_revenue_by_user_per_visit
FROM Sessions


--liquibase formatted sql

--changeset JAIDEEP:1
CREATE TABLE PERSON (
    ID SERIAL PRIMARY KEY,
    FIRST_NAME VARCHAR(130) NOT NULL,
    MIDDLE_NAME VARCHAR(130),
    LAST_NAME VARCHAR(130),
    CATEGORY varchar(200) NOT NULL remove it
);

--rollback drop table PERSON;

Revert "Intentionally breaking code to check build failure on CI. <Jaideep>" - verified it :)

--liquibase formatted sql

--changeset JAIDEEP:1
CREATE TABLE PERSON (
    ID SERIAL PRIMARY KEY,
    FIRST_NAME VARCHAR(130) NOT NULL,
    MIDDLE_NAME VARCHAR(130),
    LAST_NAME VARCHAR(130),
    CATEGORY varchar(200) NOT NULL
);

--rollback drop table PERSON;


-- These are changes needed to the schema to support moving over to DBIx::Class

begin;

-- table for sessions - needed by Catalyst::Plugin::Session::Store::DBIC
CREATE TABLE sessions (
    id           CHAR(72) PRIMARY KEY,
    session_data TEXT,
    expires      INTEGER
);

-- users table
create table users (
    id              serial  not null primary key,
    email           text    not null unique,
    name            text,
    phone           text,
    password        text    not null default ''
);

--- add PK to contacts table
ALTER TABLE contacts
    ADD COLUMN id SERIAL PRIMARY KEY;

AlTER TABLE contacts_history
    ADD COLUMN contact_id integer;

update contacts_history
    set contact_id = (
        select id
        from contacts
        where contacts_history.category = contacts.category
          and contacts_history.area_id = contacts.area_id
    );

AlTER TABLE contacts_history
    alter COLUMN contact_id SET NOT NULL;

commit;

Add updated function to db alter sql

-- These are changes needed to the schema to support moving over to DBIx::Class

begin;

-- table for sessions - needed by Catalyst::Plugin::Session::Store::DBIC
CREATE TABLE sessions (
    id           CHAR(72) PRIMARY KEY,
    session_data TEXT,
    expires      INTEGER
);

-- users table
create table users (
    id              serial  not null primary key,
    email           text    not null unique,
    name            text,
    phone           text,
    password        text    not null default ''
);

--- add PK to contacts table
ALTER TABLE contacts
    ADD COLUMN id SERIAL PRIMARY KEY;

AlTER TABLE contacts_history
    ADD COLUMN contact_id integer;

update contacts_history
    set contact_id = (
        select id
        from contacts
        where contacts_history.category = contacts.category
          and contacts_history.area_id = contacts.area_id
    );

AlTER TABLE contacts_history
    alter COLUMN contact_id SET NOT NULL;

create or replace function contacts_updated()
    returns trigger as '
    begin
        insert into contacts_history (contact_id, area_id, category, email, editor, whenedited, note, confirmed, deleted) values (new.id, new.area_id, new.category, new.email, new.editor, new.whenedited, new.note, new.confirmed, new.deleted);
        return new;
    end;
' language 'plpgsql';

commit;


/* Copyright 2015 OpenMarket Ltd
 *
 * 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
 *
 *    http://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 TABLE IF NOT EXISTS new_server_keys_json (
    server_name TEXT NOT NULL, -- Server name.
    key_id TEXT NOT NULL, -- Requested key id.
    from_server TEXT NOT NULL, -- Which server the keys were fetched from.
    ts_added_ms BIGINT NOT NULL, -- When the keys were fetched
    ts_valid_until_ms BIGINT NOT NULL, -- When this version of the keys exipires.
    key_json bytea NOT NULL, -- JSON certificate for the remote server.
    CONSTRAINT server_keys_json_uniqueness UNIQUE (server_name, key_id, from_server)
);

INSERT INTO new_server_keys_json
    SELECT server_name, key_id, from_server,ts_added_ms, ts_valid_until_ms, key_json FROM server_keys_json ;

DROP TABLE new_server_keys_json;

ALTER TABLE new_server_keys_json RENAME TO server_keys_json;

Drop the old table not the new table

/* Copyright 2015 OpenMarket Ltd
 *
 * 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
 *
 *    http://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 TABLE IF NOT EXISTS new_server_keys_json (
    server_name TEXT NOT NULL, -- Server name.
    key_id TEXT NOT NULL, -- Requested key id.
    from_server TEXT NOT NULL, -- Which server the keys were fetched from.
    ts_added_ms BIGINT NOT NULL, -- When the keys were fetched
    ts_valid_until_ms BIGINT NOT NULL, -- When this version of the keys exipires.
    key_json bytea NOT NULL, -- JSON certificate for the remote server.
    CONSTRAINT server_keys_json_uniqueness UNIQUE (server_name, key_id, from_server)
);

INSERT INTO new_server_keys_json
    SELECT server_name, key_id, from_server,ts_added_ms, ts_valid_until_ms, key_json FROM server_keys_json ;

DROP TABLE server_keys_json;

ALTER TABLE new_server_keys_json RENAME TO server_keys_json;


CREATE INDEX HPA_KA_SEARCH ON IIS.KNOWN_AS
(
    PERSON_SURNAME,
    PERSON_FORENAME_1,
    PERSON_BIRTH_DATE,
    FK_PERSON_IDENTIFIER
)

CREATE INDEX HPA_LOL_SEARCH ON IIS.LOSS_OF_LIBERTY
(
    INMATE_SURNAME,
    INMATE_FORENAME_1,
    INMATE_BIRTH_DATE,
    FK_PERSON_IDENTIFIER
)

CREATE INDEX HPA_IDENT_SEARCH ON IIS.IIS_IDENTIFIER
(
    PERSON_IDENT_TYPE_CODE,
    PERSON_IDENTIFIER_VALUE,
    FK_PERSON_IDENTIFIER
)

Correct index for identifier search


CREATE TABLE aircraftpatterns (
  mode_s_hex      TEXT,
  report_location GEOGRAPHY(Point, 4326),
  longitude83     DOUBLE PRECISION,
  latitude83      DOUBLE PRECISION,
  report_epoch    INTEGER,
  reporter        TEXT,
  itinerary_id    TEXT
);

ALTER TABLE aircraftpatterns
  OWNER TO postgres;

Update patterns table with new indexesπ

CREATE TABLE aircraftpatterns (
  mode_s_hex              TEXT,
  pattern_centroid        GEOGRAPHY(Point, 4326),
  pattern_cent_long       DOUBLE PRECISION,
  pattern_cent_lat        DOUBLE PRECISION,
  report_epoch            INTEGER,
  reporter                TEXT,
  itinerary_id            TEXT
);

ALTER TABLE aircraftpatterns
  OWNER TO postgres;

CREATE INDEX mode_s_hex_idx
  ON aircraftpatterns USING BTREE (mode_s_hex);

CREATE INDEX pr_epoch
  ON aircraftpatterns USING BTREE (report_epoch);

CREATE INDEX pat_cent_loc
  ON aircraftpatterns USING GIST (pattern_centroid);

GRANT ALL ON TABLE aircraftpatterns TO postgres;


DROP INDEX activity_accounts_account_id_idx;
DROP INDEX activity_accounts_activity_id_account_id_idx;
DROP INDEX activity_manager_node_id_idx;
DROP INDEX activity_manager_node_id_txid_idx;
DROP INDEX issuance_activity_assets_asset_id_idx;
DROP INDEX issuance_activity_assets_issuance_activity_id_asset_id_idx;
DROP INDEX issuance_activity_issuer_node_id_idx;
DROP INDEX issuance_activity_issuer_node_id_txid_idx;

DROP TABLE activity;
DROP TABLE activity_accounts;
DROP TABLE issuance_activity;
DROP TABLE issuance_activity_assets;

Fix migration to drop all tables at once

DROP INDEX activity_accounts_account_id_idx;
DROP INDEX activity_accounts_activity_id_account_id_idx;
DROP INDEX activity_manager_node_id_idx;
DROP INDEX activity_manager_node_id_txid_idx;
DROP INDEX issuance_activity_assets_asset_id_idx;
DROP INDEX issuance_activity_assets_issuance_activity_id_asset_id_idx;
DROP INDEX issuance_activity_issuer_node_id_idx;
DROP INDEX issuance_activity_issuer_node_id_txid_idx;

DROP TABLE
activity,
activity_accounts,
issuance_activity,
issuance_activity_assets;


-- A set of SQL queries to run before migrating from v6 to v7
-- Run with the mysql --table arg to get formatted output
-- e.g.
-- docker exec -i stroom-all-dbs mysql --table -h"localhost" -P"3307" -u"stroomuser" -p"stroompassword1" stroom < v7_db_pre_migration_checks.sql > v7_db_pre_migration_checks.out

\! echo 'Find orphaned USR_GRP_USR records, that will not be migrated';

SELECT *
FROM USR_GRP_USR
WHERE NOT EXISTS (
    SELECT NULL
    FROM USR
    WHERE UUID = USR_UUID)
OR NOT EXISTS (
    SELECT NULL
    FROM USR
    WHERE UUID = GRP_UUID)
ORDER BY ID;

\! echo 'Find orphaned DOC_PERM records, that will not be migrated';

SELECT *
FROM DOC_PERM
WHERE NOT EXISTS (
    SELECT NULL
    FROM USR
    WHERE UUID = USR_UUID)
ORDER BY ID;

\! echo 'Find orphaned DOC_PERM records, that will not be migrated';

SELECT *
FROM APP_PERM ap
JOIN PERM p ON (p.ID = ap.FK_PERM_ID)
WHERE NOT EXISTS (
    SELECT NULL
    FROM USR
    WHERE UUID = ap.USR_UUID)
ORDER BY ap.ID;

\! echo 'Finished';

Add new pre migration check

-- A set of SQL queries to run before migrating from v6 to v7
-- Run with the mysql --table arg to get formatted output
-- e.g.
-- docker exec -i stroom-all-dbs mysql --table -h"localhost" -P"3307" -u"stroomuser" -p"stroompassword1" stroom < v7_db_pre_migration_checks.sql > v7_db_pre_migration_checks.out

\! echo 'Find orphaned USR_GRP_USR records, that will not be migrated';

SELECT *
FROM USR_GRP_USR
WHERE NOT EXISTS (
    SELECT NULL
    FROM USR
    WHERE UUID = USR_UUID)
OR NOT EXISTS (
    SELECT NULL
    FROM USR
    WHERE UUID = GRP_UUID)
ORDER BY ID;

\! echo 'Find orphaned DOC_PERM records, that will not be migrated';

SELECT *
FROM DOC_PERM
WHERE NOT EXISTS (
    SELECT NULL
    FROM USR
    WHERE UUID = USR_UUID)
ORDER BY ID;

\! echo 'Find orphaned DOC_PERM records, that will not be migrated';

SELECT *
FROM APP_PERM ap
JOIN PERM p ON (p.ID = ap.FK_PERM_ID)
WHERE NOT EXISTS (
    SELECT NULL
    FROM USR
    WHERE UUID = ap.USR_UUID)
ORDER BY ap.ID;

\! echo 'Find IDX/IDX_VOL records that would violate new primary key';

SELECT
  iv.FK_VOL_ID,
  i.UUID,
  COUNT(*)
FROM IDX i
INNER JOIN IDX_VOL iv on i.ID = iv.FK_IDX_ID
GROUP BY
  iv.FK_VOL_ID,
  i.UUID
HAVING COUNT(*) > 1;

\! echo 'Finished';


-- Change version of Centreon
UPDATE `informations` SET `value` = '2.8.3' WHERE CONVERT( `informations`.`key` USING utf8 ) = 'version' AND CONVERT ( `informations`.`value` USING utf8 ) = '2.8.2' LIMIT 1;

-- broker option
DELETE FROM `options` WHERE `key` = 'broker';
INSERT INTO `options` (`key`, `value`) VALUES ('broker', 'broker');

Remove relations between contact templates and contactgroups

-- Change version of Centreon
UPDATE `informations` SET `value` = '2.8.3' WHERE CONVERT( `informations`.`key` USING utf8 ) = 'version' AND CONVERT ( `informations`.`value` USING utf8 ) = '2.8.2' LIMIT 1;

-- broker option
DELETE FROM `options` WHERE `key` = 'broker';
INSERT INTO `options` (`key`, `value`) VALUES ('broker', 'broker');

-- Remove relations between contact templates and contactgroups
DELETE FROM contactgroup_contact_relation
WHERE contact_contact_id IN (
    SELECT contact_id FROM contact WHERE contact_register = '0'
);


CREATE TABLE builds (
  id SERIAL,
  created TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),

  key VARCHAR(100) NOT NULL
);

CREATE INDEX builds_idx_key ON builds (key);

CREATE TABLE logs (
	id SERIAL,
	build_id INT NOT NULL,
	created TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),

	type VARCHAR(50),
	content_type VARCHAR(100),
	identifier VARCHAR(200),
	size BIGINT
);

CREATE INDEX logs_idx_type ON logs (type);

Increase the length of content type

CREATE TABLE builds (
  id SERIAL,
  created TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),

  key VARCHAR(100) NOT NULL
);

CREATE INDEX builds_idx_key ON builds (key);

CREATE TABLE logs (
	id SERIAL,
	build_id INT NOT NULL,
	created TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),

	type VARCHAR(50),
	content_type VARCHAR(200),
	identifier VARCHAR(200),
	size BIGINT
);

CREATE INDEX logs_idx_type ON logs (type);


BEGIN;

--
-- Actualización al día 18 de septiembre de 2018
--

-- agregar sucursal a dte_tmp
ALTER TABLE dte_tmp ADD sucursal_sii INTEGER;
CREATE INDEX dte_tmp_sucursal_sii_idx ON dte_tmp (sucursal_sii);

-- agregar usuario a dte_tmp
ALTER TABLE dte_tmp ADD usuario INTEGER; -- debería ser NOT NULL, aplicar en el futuro
ALTER TABLE dte_tmp ADD CONSTRAINT dte_tmp_usuario_fk FOREIGN KEY (usuario)
    REFERENCES usuario (id) MATCH FULL
    ON UPDATE CASCADE ON DELETE RESTRICT;
CREATE INDEX dte_tmp_usuario_idx ON dte_tmp (usuario);

COMMIT;

Fix nombre script SQL actualización

BEGIN;

--
-- Actualización al día 01 de enero de 2019
--

-- agregar sucursal a dte_tmp
ALTER TABLE dte_tmp ADD sucursal_sii INTEGER;
CREATE INDEX dte_tmp_sucursal_sii_idx ON dte_tmp (sucursal_sii);

-- agregar usuario a dte_tmp
ALTER TABLE dte_tmp ADD usuario INTEGER; -- debería ser NOT NULL, aplicar en el futuro
ALTER TABLE dte_tmp ADD CONSTRAINT dte_tmp_usuario_fk FOREIGN KEY (usuario)
    REFERENCES usuario (id) MATCH FULL
    ON UPDATE CASCADE ON DELETE RESTRICT;
CREATE INDEX dte_tmp_usuario_idx ON dte_tmp (usuario);

COMMIT;


CREATE TABLE CWF_DOMAIN (
	ID VARCHAR(20) PRIMARY KEY,
	NAME VARCHAR(255),
	ATTRIBUTES CLOB DEFAULT '');

INSERT INTO CWF_DOMAIN (ID, NAME, ATTRIBUTES) VALUES
	('1', 'General Medicine Clinic', ''),
	('2', 'Emergency Room', ''),
	('3', 'Test Hospital', 'default=true'),
	('*', 'All Domains', '');

CREATE TABLE CWF_USER (
	ID VARCHAR(20) PRIMARY KEY,
	USERNAME VARCHAR(40),
	PASSWORD VARCHAR(40),
	NAME VARCHAR(255),
	DOMAIN VARCHAR(20),
	AUTHORITIES CLOB DEFAULT '');

INSERT INTO CWF_USER (ID, USERNAME, PASSWORD, NAME, DOMAIN, AUTHORITIES) VALUES
	('1', 'doctor', 'doctor', 'Doctor, Test', '1', 'PRIV_PATIENT_SELECT'),
	('2', 'demo', 'demo', 'User, Test', '*', 'PRIV_DEBUG,PRIV_CAREWEB_DESIGNER,PRIV_PATIENT_SELECT');

Change sql to avoid startup errors if already initialized.

CREATE TABLE IF NOT EXISTS CWF_DOMAIN (
	ID VARCHAR(20) PRIMARY KEY,
	NAME VARCHAR(255),
	ATTRIBUTES CLOB DEFAULT '');

MERGE INTO CWF_DOMAIN (ID, NAME, ATTRIBUTES) KEY(ID) VALUES
	('1', 'General Medicine Clinic', ''),
	('2', 'Emergency Room', ''),
	('3', 'Test Hospital', 'default=true'),
	('*', 'All Domains', '');

CREATE TABLE IF NOT EXISTS CWF_USER (
	ID VARCHAR(20) PRIMARY KEY,
	USERNAME VARCHAR(40),
	PASSWORD VARCHAR(40),
	NAME VARCHAR(255),
	DOMAIN VARCHAR(20),
	AUTHORITIES CLOB DEFAULT '');

MERGE INTO CWF_USER (ID, USERNAME, PASSWORD, NAME, DOMAIN, AUTHORITIES) KEY(ID) VALUES
	('1', 'doctor', 'doctor', 'Doctor, Test', '1', 'PRIV_PATIENT_SELECT'),
	('2', 'demo', 'demo', 'User, Test', '*', 'PRIV_DEBUG,PRIV_CAREWEB_DESIGNER,PRIV_PATIENT_SELECT');


--Remember to change the options for production!!!

CREATE SERVER apply_server
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host 'localhost', port '5432', dbname 'apply');

CREATE USER MAPPING FOR homestead
SERVER apply_server
OPTIONS (user 'homestead', password 'secret');

CREATE FOREIGN TABLE public.student_fdw (
    id integer,
    user integer,
    first_name text,
    last_name text,
    gender text,
    date_of_birth date,
    nationality integer,
    graduation_achieved integer,
    generated_email text,
    study_program_id integer,
    created_at timestamp(0) with time zone,
    updated_at timestamp(0) with time zone,
    address text,
    confirmed boolean,
    current_address text,
    current_country character varying(50),
    legal_status_id integer,
    onboarding_page integer,
    latitude double precision,
    longitude double precision,
    map_bounds_north double precision,
    map_bounds_south double precision,
    map_bounds_east double precision,
    map_bounds_west double precision,
    geocode_result json,
    location geometry(Point,4326),
    current_city character varying(50),
    buddy_preferred_gender character varying(50),
    send_study_guides boolean,
    hours_per_week double precision,
    phone text) SERVER student_server OPTIONS (schema_name 'public', table_name 'student');

Add create extension and fix fdw errors

--Remember to change the options for production!!!

CREATE EXTENSION postgres_fdw;

CREATE SERVER apply_server
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host 'localhost', port '5432', dbname 'apply');

CREATE USER MAPPING FOR homestead
SERVER apply_server
OPTIONS (user 'homestead', password 'secret');

CREATE FOREIGN TABLE public.student_fdw (
    id integer,
    "user" integer,
    first_name text,
    last_name text,
    gender text,
    date_of_birth date,
    nationality integer,
    graduation_achieved integer,
    generated_email text,
    study_program_id integer,
    created_at timestamp(0) with time zone,
    updated_at timestamp(0) with time zone,
    address text,
    confirmed boolean,
    current_address text,
    current_country character varying(50),
    legal_status_id integer,
    onboarding_page integer,
    latitude double precision,
    longitude double precision,
    map_bounds_north double precision,
    map_bounds_south double precision,
    map_bounds_east double precision,
    map_bounds_west double precision,
    geocode_result json,
    current_city character varying(50),
    buddy_preferred_gender character varying(50),
    send_study_guides boolean,
    hours_per_week double precision,
    phone text) SERVER student_server OPTIONS (schema_name 'public', table_name 'student');


CREATE TABLE FINANCIAL_ENTITY_ATTACHMENT
   (FINANCIAL_ENTITY_ATTACHMENT_ID NUMBER(12,0) NOT NULL ENABLE,
    FINANCIAL_ENTITY_ID_FK NUMBER(12,0) NOT NULL ENABLE,
    FILE_ID NUMBER(12,0) NOT NULL ENABLE,
    DESCRIPTION VARCHAR2(200) NOT NULL ENABLE,
    CONTACT_NAME VARCHAR2(30),
    EMAIL_ADDRESS VARCHAR2(60),
    PHONE_NUMBER VARCHAR2(20),
    COMMENTS VARCHAR2(300),
    OBJ_ID VARCHAR2(36) DEFAULT SYS_GUID()  NOT NULL ENABLE,
    UPDATE_TIMESTAMP DATE NOT NULL ENABLE,
    UPDATE_USER VARCHAR2(10) NOT NULL ENABLE,
    )
/

Add ability to associate attachments to Financial Entities

CREATE TABLE FINANCIAL_ENTITY_ATTACHMENT
   (FINANCIAL_ENTITY_ATTACHMENT_ID NUMBER(12,0) NOT NULL,
    FINANCIAL_ENTITY_ID_FK NUMBER(12,0) NOT NULL,
    FILE_ID NUMBER(12,0) NOT NULL,
    DESCRIPTION VARCHAR2(200) NOT NULL,
    CONTACT_NAME VARCHAR2(30),
    EMAIL_ADDRESS VARCHAR2(60),
    PHONE_NUMBER VARCHAR2(20),
    COMMENTS VARCHAR2(300),
    OBJ_ID VARCHAR2(36) NOT NULL,
    UPDATE_TIMESTAMP DATE NOT NULL,
    UPDATE_USER VARCHAR2(10) NOT NULL
    )
/


CREATE TABLE IF NOT EXISTS `uploadfile` (
  `id` int(11) NOT NULL auto_increment,
  `filename` varchar(255) NOT NULL,
  `filesize` int(11) NOT NULL DEFAULT '0',
  `sha1sum` varchar(40) NOT NULL,
  PRIMARY KEY(`id`),
  KEY `sha1sum` (`sha1sum`)
);

CREATE TABLE IF NOT EXISTS `build2uploadfile` (
  `fileid` bigint(11) NOT NULL,
  `buildid` bigint(11) NOT NULL,
  KEY `fileid` (`fileid`),
  KEY `buildid` (`buildid`)
);

Add new table to upgrade SQL file

CREATE TABLE IF NOT EXISTS `uploadfile` (
  `id` int(11) NOT NULL auto_increment,
  `filename` varchar(255) NOT NULL,
  `filesize` int(11) NOT NULL DEFAULT '0',
  `sha1sum` varchar(40) NOT NULL,
  PRIMARY KEY(`id`),
  KEY `sha1sum` (`sha1sum`)
);

CREATE TABLE IF NOT EXISTS `build2uploadfile` (
  `fileid` bigint(11) NOT NULL,
  `buildid` bigint(11) NOT NULL,
  KEY `fileid` (`fileid`),
  KEY `buildid` (`buildid`)
);

CREATE TABLE IF NOT EXISTS client_jobschedule2submission (
  scheduleid bigint(20) NOT NULL,
  submissionid bigint(11) NOT NULL,
  PRIMARY KEY (`submissionid`),
  UNIQUE KEY `scheduleid` (`scheduleid`)
);


CREATE TABLE job(
     id INTEGER PRIMARY KEY AUTOINCREMENT,
     description TEXT NOT NULL,
     user_name TEXT NOT NULL,
     calculation_mode TEXT NOT NULL,
     hazard_calculation_id INTEGER REFERENCES job (id) ON DELETE CASCADE,
     status TEXT NOT NULL DEFAULT 'created',
     is_running BOOL NOT NULL DEFAULT false,
     start_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
     stop_time TIMESTAMP,
     relevant BOOL DEFAULT true,
     ds_calc_dir TEXT NOT NULL);

CREATE TABLE log(
     id INTEGER PRIMARY KEY AUTOINCREMENT,
     job_id INTEGER NOT NULL REFERENCES job (id) ON DELETE CASCADE,
     timestamp TIMESTAMP NOT NULL,
     level TEXT NOT NULL,
     process TEXT NOT NULL,
     message TEXT NOT NULL);

CREATE TABLE output(
     id INTEGER PRIMARY KEY AUTOINCREMENT,
     oq_job_id INTEGER NOT NULL REFERENCES job (id) ON DELETE CASCADE,
     display_name TEXT NOT NULL,
     last_update TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
     ds_key TEXT NOT NULL);

CREATE TABLE performance(
     id INTEGER PRIMARY KEY AUTOINCREMENT,
     job_id INTEGER NOT NULL REFERENCES job (id) ON DELETE CASCADE,
     operation TEXT NOT NULL,
     time_sec FLOAT NOT NULL,
     memory_mb FLOAT NOT NULL,
     counts INTEGER NOT NULL);

Set relevant default to 1 instead of true

CREATE TABLE job(
     id INTEGER PRIMARY KEY AUTOINCREMENT,
     description TEXT NOT NULL,
     user_name TEXT NOT NULL,
     calculation_mode TEXT NOT NULL,
     hazard_calculation_id INTEGER REFERENCES job (id) ON DELETE CASCADE,
     status TEXT NOT NULL DEFAULT 'created',
     is_running BOOL NOT NULL DEFAULT false,
     start_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
     stop_time TIMESTAMP,
     relevant BOOL DEFAULT 1,
     ds_calc_dir TEXT NOT NULL);

CREATE TABLE log(
     id INTEGER PRIMARY KEY AUTOINCREMENT,
     job_id INTEGER NOT NULL REFERENCES job (id) ON DELETE CASCADE,
     timestamp TIMESTAMP NOT NULL,
     level TEXT NOT NULL,
     process TEXT NOT NULL,
     message TEXT NOT NULL);

CREATE TABLE output(
     id INTEGER PRIMARY KEY AUTOINCREMENT,
     oq_job_id INTEGER NOT NULL REFERENCES job (id) ON DELETE CASCADE,
     display_name TEXT NOT NULL,
     last_update TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
     ds_key TEXT NOT NULL);

CREATE TABLE performance(
     id INTEGER PRIMARY KEY AUTOINCREMENT,
     job_id INTEGER NOT NULL REFERENCES job (id) ON DELETE CASCADE,
     operation TEXT NOT NULL,
     time_sec FLOAT NOT NULL,
     memory_mb FLOAT NOT NULL,
     counts INTEGER NOT NULL);


CREATE TABLE HELLOWORLD (
   HELLO VARCHAR(15),
   WORLD VARCHAR(15),
   DIALECT VARCHAR(15) NOT NULL,
   PRIMARY KEY (DIALECT)
);
PARTITION TABLE HELLOWORLD ON COLUMN DIALECT;

CREATE PROCEDURE Insert PARTITION ON TABLE Helloworld COLUMN Dialect
   AS INSERT INTO HELLOWORLD (Dialect, Hello, World) VALUES (?, ?, ?);
CREATE PROCEDURE Select PARTITION ON TABLE Helloworld COLUMN Dialect
   AS SELECT HELLO, WORLD FROM HELLOWORLD WHERE DIALECT = ?;

Fix SQL syntax in the examples

CREATE TABLE helloworld (
   hello VARCHAR(15),
   world VARCHAR(15),
   dialect VARCHAR(15) NOT NULL,
   PRIMARY KEY (DIALECT)
);
PARTITION TABLE HELLOWORLD ON COLUMN DIALECT;

CREATE PROCEDURE INSERT PARTITION ON TABLE helloworld COLUMN dialect
   AS INSERT INTO helloworld (dialect, hello, world) VALUES (?, ?, ?);
CREATE PROCEDURE SELECT PARTITION ON TABLE helloworld COLUMN dialect
   AS SELECT hello, world FROM helloworld WHERE dialect = ?;


-- Update the value of the academic grant percentage for both the template competitions
SET @sector_template_name = "Template for the Sector competition type";
SET @programme_template_name = "Template for the Programme competition type";

UPDATE competition
SET academic_grant_percentage=100
WHERE name=@sector_template_name OR name=@programme_template_name AND non_ifs=0;

Update academic grant percentage of all competitions

-- Update the value of the academic grant percentage for all ifs competitions
UPDATE competition
SET academic_grant_percentage=100
WHERE non_ifs=0;


ALTER TABLE `users_history`
    CHANGE COLUMN `user_id` `user_id` INT (11) NOT NULL,
    CHANGE COLUMN `created` `created` DATETIME (6) NOT NULL,
    CHANGE COLUMN `modified` `modified` DATETIME (6) NOT NULL,
    CHANGE COLUMN `id` `id` INT (10) UNSIGNED NOT NULL AUTO_INCREMENT,
    CHANGE COLUMN `email` `email` VARCHAR (75) NOT NULL,
    ADD INDEX `users_history_user_id_358ca354_fk_users_id` (`user_id`),
    ADD CONSTRAINT `users_history_user_id_358ca354_fk_users_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

Add DELETE statement to fix broken data in users_history table

/* There are some old entries in users_history which point to non-existent users, need to delete them to add the missing constraint */
DELETE FROM `users_history` USING `users_history`
    LEFT JOIN `users` ON `users_history`.`user_id` = `users`.`id`
    WHERE `users`.`id` IS NULL AND `users_history`.`user_id` IS NOT NULL;

ALTER TABLE `users_history`
    CHANGE COLUMN `user_id` `user_id` INT (11) NOT NULL,
    CHANGE COLUMN `created` `created` DATETIME (6) NOT NULL,
    CHANGE COLUMN `modified` `modified` DATETIME (6) NOT NULL,
    CHANGE COLUMN `id` `id` INT (10) UNSIGNED NOT NULL AUTO_INCREMENT,
    CHANGE COLUMN `email` `email` VARCHAR (75) NOT NULL,
    ADD INDEX `users_history_user_id_358ca354_fk_users_id` (`user_id`),
    ADD CONSTRAINT `users_history_user_id_358ca354_fk_users_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);


CREATE OR REPLACE VIEW ObjectImagesExport AS
SELECT
    o.ItemType,
    i.Accession_Full_ID,
    o.ItemName,
    ObjectsImagesID,
    CONCAT_WS('/', REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ImageFilePath, '\\', '/'), 'Y:/', ''), 'Y:', ''),
                                           '//Foyer/c/Images Mosaic/', ''), '//Foyer/c/Images Mosaic/', ''),
                           '//SERVER1/Images Mosaic/', ''), ImageFileName) AS ImagePath,
    ImageDescription,
    DisplayImage,
    DefaultImageIndicator

FROM ObjectsImages i
    JOIN Objects o ON (i.Accession_Full_ID = o.Accession_Full_ID)
WHERE TRIM(ImageFileName) <> ''
ORDER BY ObjectsImagesID;

Trim leading and trailing whitespace and replace blanks with null in ObjectImagesExport view

CREATE OR REPLACE VIEW ObjectImagesExport AS
SELECT
    NULLIF(TRIM(o.ItemType), '')                              AS ItemType,
    NULLIF(TRIM(i.Accession_Full_ID), '')                     AS Accession_Full_ID,
    NULLIF(TRIM(o.ItemName), '')                              AS ItemName,
    NULLIF(TRIM(ObjectsImagesID), '')                         AS ObjectsImagesID,
    NULLIF(TRIM(CONCAT_WS('/', REPLACE(
        REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ImageFilePath, '\\', '/'), 'Y:/', ''), 'Y:', ''),
                        '//Foyer/c/Images Mosaic/', ''), '//Foyer/c/Images Mosaic/', ''),
        '//SERVER1/Images Mosaic/', ''), ImageFileName)), '') AS ImagePath,
    NULLIF(TRIM(ImageDescription), '')                        AS ImageDescription,
    NULLIF(TRIM(DisplayImage), '')                            AS DisplayImage,
    NULLIF(TRIM(DefaultImageIndicator), '')                   AS DefaultImageIndicator

FROM ObjectsImages i
    JOIN Objects o ON (i.Accession_Full_ID = o.Accession_Full_ID)
WHERE TRIM(ImageFileName) <> ''
ORDER BY ObjectsImagesID;


DROP PROCEDURE IF EXISTS create_IDX_PK_service_details;
DELIMITER //

CREATE PROCEDURE create_IDX_PK_service_details()
  BEGIN

  CREATE TEMPORARY TABLE `tmp_service_instance_service_detail` (
      `service_instance_details_id` BIGINT(20) NULL DEFAULT NULL,
      `service_detail_id` BIGINT(20) NULL DEFAULT NULL
  );

  INSERT INTO tmp_service_instance_service_detail(service_instance_details_id, service_detail_id)
      SELECT DISTINCT service_instance_details_id, service_detail_id
      FROM service_instance_service_detail;

  ALTER TABLE service_instance_service_detail
      ADD PRIMARY KEY (service_instance_details_id, service_detail_id),
      ADD INDEX service_detail_service_instance_index (service_detail_id, service_instance_details_id);

  TRUNCATE TABLE service_instance_service_detail;

  INSERT INTO service_instance_service_detail(service_instance_details_id, service_detail_id)
      SELECT DISTINCT service_instance_details_id, service_detail_id
      FROM tmp_service_instance_service_detail;

  DROP TABLE tmp_service_instance_service_detail;

  ALTER TABLE service_binding_service_detail
    ADD PRIMARY KEY (service_binding_details_id, service_detail_id),
    ADD INDEX service_detail_service_binding_index (service_detail_id, service_binding_details_id);

  END//

DELIMITER ;
CALL create_IDX_PK_service_details();

Reorder SQL Script (Truncate before Creating PK).

DROP PROCEDURE IF EXISTS create_IDX_PK_service_details;
DELIMITER //

CREATE PROCEDURE create_IDX_PK_service_details()
  BEGIN

  CREATE TEMPORARY TABLE `tmp_service_instance_service_detail` (
      `service_instance_details_id` BIGINT(20) NULL DEFAULT NULL,
      `service_detail_id` BIGINT(20) NULL DEFAULT NULL
  );

  INSERT INTO tmp_service_instance_service_detail(service_instance_details_id, service_detail_id)
      SELECT DISTINCT service_instance_details_id, service_detail_id
      FROM service_instance_service_detail;

  TRUNCATE TABLE service_instance_service_detail;

  ALTER TABLE service_instance_service_detail
      ADD PRIMARY KEY (service_instance_details_id, service_detail_id),
      ADD INDEX service_detail_service_instance_index (service_detail_id, service_instance_details_id);

  INSERT INTO service_instance_service_detail(service_instance_details_id, service_detail_id)
      SELECT DISTINCT service_instance_details_id, service_detail_id
      FROM tmp_service_instance_service_detail;

  DROP TABLE tmp_service_instance_service_detail;

  ALTER TABLE service_binding_service_detail
    ADD PRIMARY KEY (service_binding_details_id, service_detail_id),
    ADD INDEX service_detail_service_binding_index (service_detail_id, service_binding_details_id);

  END//

DELIMITER ;
CALL create_IDX_PK_service_details();