CREATE TABLE IF NOT EXISTS cd_profiles
(
  id character varying,
  name character varying,
  user_id character varying,
  alias character varying,
  dob date,
  "country" json,
  city json,
  private boolean,
  place json,
  gender character varying,
  address character varying,
  last_edited timestamp default CURRENT_TIMESTAMP,
  email character varying,
  phone character varying,
  parents text[],
  children text[],
  linkedin character varying,
  twitter character varying,
  languages_spoken text[],
  programming_languages text[],
  notes character varying,
  projects text[],
  badges text[],
  countryName character varying,
  countryNumber character varying,
  continent character varying,
  alpha2 character varying,
  alpha3 character varying,
  admin1_code character varying,
  admin1_name character varying,
  admin2_code character varying,
  admin2_name character varying,
  admin3_code character varying,
  admin3_name character varying,
  admin4_code character varying,
  admin4_name character varying,
  state json,
  county json,
  place_geoname_id character varying,
  place_name character varying,
  CONSTRAINT pk_cd_profiles_id PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);

Use timestamp instead of date

CREATE TABLE IF NOT EXISTS cd_profiles
(
  id character varying,
  name character varying,
  user_id character varying,
  alias character varying,
  dob timestamp with time zone,
  "country" json,
  city json,
  private boolean,
  place json,
  gender character varying,
  address character varying,
  last_edited timestamp default CURRENT_TIMESTAMP,
  email character varying,
  phone character varying,
  parents text[],
  children text[],
  linkedin character varying,
  twitter character varying,
  languages_spoken text[],
  programming_languages text[],
  notes character varying,
  projects text[],
  badges text[],
  countryName character varying,
  countryNumber character varying,
  continent character varying,
  alpha2 character varying,
  alpha3 character varying,
  admin1_code character varying,
  admin1_name character varying,
  admin2_code character varying,
  admin2_name character varying,
  admin3_code character varying,
  admin3_name character varying,
  admin4_code character varying,
  admin4_name character varying,
  state json,
  county json,
  place_geoname_id character varying,
  place_name character varying,
  CONSTRAINT pk_cd_profiles_id PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);


create type STATUS as enum ('WAITING', 'REVIEWED', 'ACCEPTED');
create table peer_reviews (
  task_id text not null,
  comment text,
  score int,
  reviewer_id text not null,
  status STATUS not null
);

Use 'IF EXISTS' on db creation. This way it won't fail even when same migration is ran multiple times.

-- create types
DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'status') THEN
    CREATE TYPE status AS enum (
        'WAITING',
        'REVIEWED',
        'ACCEPTED'
    );
  END IF;
END$$;

-- create tables
CREATE TABLE IF NOT EXISTS peer_reviews (
  task_id text NOT NULL,
  comment text,
  score int,
  reviewer_id text NOT NULL,
  status STATUS NOT NULL
);


CREATE ROLE metacpan;
CREATE ROLE "metacpan-api";

-- make things easier for when we're poking around from inside the container
CREATE USER root;

Add LOGIN permissions to new roles

CREATE ROLE metacpan WITH LOGIN;
CREATE ROLE "metacpan-api" WITH LOGIN;

-- make things easier for when we're poking around from inside the container
CREATE USER root;


INSERT INTO `users_permissions` (`permName`, `permDesc`, `level`, `type`, `admin`, `feature_check`) VALUES('tiki_p_promote_page', 'Can promote a page (email, twitter, facebook)', 'Basic', 'tiki', NULL, NULL);

Add IGNORE to a perms schema that causes an error each time it's run (for some reason).

INSERT IGNORE INTO `users_permissions` (`permName`, `permDesc`, `level`, `type`, `admin`, `feature_check`) VALUES('tiki_p_promote_page', 'Can promote a page (email, twitter, facebook)', 'Basic', 'tiki', NULL, NULL);


--
-- Copyright 2018 ThoughtWorks, Inc.
--
-- 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.
--

ALTER TABLE PipelineSelections ADD COLUMN filters CLOB;
ALTER TABLE PipelineSelections ADD COLUMN version INT DEFAULT 0 NOT NULL;

--//@UNDO

ALTER TABLE PipelineSelections DROP COLUMN version;
ALTER TABLE PipelineSelections DROP COLUMN filters;

Use TEXT type instead of CLOB as it's compatible with postgres.

--
-- Copyright 2018 ThoughtWorks, Inc.
--
-- 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.
--

ALTER TABLE PipelineSelections ADD COLUMN filters TEXT;
ALTER TABLE PipelineSelections ADD COLUMN version INT DEFAULT 0 NOT NULL;

--//@UNDO

ALTER TABLE PipelineSelections DROP COLUMN version;
ALTER TABLE PipelineSelections DROP COLUMN filters;


DELETE FROM `applications_versions` WHERE application_id = 60;
DELETE FROM `appversions` WHERE application_id = 60;
DELETE FROM `appsupport` WHERE app_id = 60;

Fix migration 942: file_uploads can have a FK to the rows we're deleting

DELETE FROM `file_uploads` WHERE compat_with_app_id = 60;
DELETE FROM `applications_versions` WHERE application_id = 60;
DELETE FROM `appversions` WHERE application_id = 60;
DELETE FROM `appsupport` WHERE app_id = 60;


-- Function returning list of cartodb user tables
--
-- The optional argument restricts the result to tables
-- of the specified access type.
--
-- Currently accepted permissions are: 'public', 'private' or 'all'
--
CREATE OR REPLACE FUNCTION CDB_UserTables(perm text DEFAULT 'all')
RETURNS SETOF name
AS $$

SELECT c.relname
FROM pg_class c
JOIN pg_roles r ON r.oid = c.relowner
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE r.rolname = current_user
AND c.relkind = 'r'
AND c.relname NOT IN ('cdb_tablemetadata', 'spatial_ref_sys')
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
AND CASE WHEN perm = 'public' THEN has_table_privilege('public', c.oid, 'SELECT')
         WHEN perm = 'private' THEN has_table_privilege(c.oid, 'SELECT') AND NOT
                                    has_table_privilege('public', c.oid, 'SELECT')
         WHEN perm = 'all' THEN has_table_privilege(c.oid, 'SELECT')
         ELSE false END;

$$ LANGUAGE 'sql';

-- This is to migrate from pre-0.2.0 version
-- See http://github.com/CartoDB/cartodb-postgresql/issues/36
GRANT EXECUTE ON FUNCTION CDB_UserTables(text) TO public;

Fix for upgrade issue from 0.7.4 to 0.8.0

-- Function returning list of cartodb user tables
--
-- The optional argument restricts the result to tables
-- of the specified access type.
--
-- Currently accepted permissions are: 'public', 'private' or 'all'
--
DROP FUNCTION IF EXISTS cdb_usertables(text);
CREATE OR REPLACE FUNCTION CDB_UserTables(perm text DEFAULT 'all')
RETURNS SETOF name
AS $$

SELECT c.relname
FROM pg_class c
JOIN pg_roles r ON r.oid = c.relowner
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE r.rolname = current_user
AND c.relkind = 'r'
AND c.relname NOT IN ('cdb_tablemetadata', 'spatial_ref_sys')
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
AND CASE WHEN perm = 'public' THEN has_table_privilege('public', c.oid, 'SELECT')
         WHEN perm = 'private' THEN has_table_privilege(c.oid, 'SELECT') AND NOT
                                    has_table_privilege('public', c.oid, 'SELECT')
         WHEN perm = 'all' THEN has_table_privilege(c.oid, 'SELECT')
         ELSE false END;

$$ LANGUAGE 'sql';

-- This is to migrate from pre-0.2.0 version
-- See http://github.com/CartoDB/cartodb-postgresql/issues/36
GRANT EXECUTE ON FUNCTION CDB_UserTables(text) TO public;


CREATE PROCEDURE [employer_account].[Cleardown]
	@INCLUDEUSERTABLE TINYINT = 0
AS
	DELETE FROM [employer_account].[AccountEmployerAgreement];
	DELETE FROM [employer_account].[EmployerAgreement];
	DELETE FROM [employer_account].[Invitation];
	DELETE FROM [employer_account].[Membership];

	IF @INCLUDEUSERTABLE = 1
	BEGIN
		DELETE FROM [employer_account].[User];
	END

	DELETE FROM [employer_account].[Paye];
	DELETE FROM [employer_account].[LegalEntity];
	DELETE FROM [employer_account].[AccountHistory]
	DELETE FROM [employer_account].[Account];
	DELETE FROM [employer_account].[Role];
	DELETE FROM [employer_account].[EmployerAgreementTemplate];
RETURN 0

Remove delete from table that does not exist

CREATE PROCEDURE [employer_account].[Cleardown]
	@INCLUDEUSERTABLE TINYINT = 0
AS
	DELETE FROM [employer_account].[AccountEmployerAgreement];
	DELETE FROM [employer_account].[EmployerAgreement];
	DELETE FROM [employer_account].[Invitation];
	DELETE FROM [employer_account].[Membership];

	IF @INCLUDEUSERTABLE = 1
	BEGIN
		DELETE FROM [employer_account].[User];
	END

	DELETE FROM [employer_account].[Paye];
	DELETE FROM [employer_account].[LegalEntity];
	DELETE FROM [employer_account].[AccountHistory]
	DELETE FROM [employer_account].[Account];
	DELETE FROM [employer_account].[EmployerAgreementTemplate];
RETURN 0


-- Example like joins.sql but joining on multiple columns.
drop table if exists t1;
drop table if exists t2;

create table t1 (
    id int primary key,
    name text,
    ranking int);

create table t2 (
    code char(1) primary key,
    id int,
    ranking int);

insert into t1 values(1, 'Joanne', 7);
insert into t1 values(2, 'Sam', 7);
insert into t1 values(3, 'Emmanuel', 6);
insert into t1 values(4, 'Brayden', 2);

insert into t2 values('x', 2, 8);
insert into t2 values('z', 3, 6);

select * from t1 inner join t2 on t1.id = t2.id and t1.ranking = t2.ranking;
select * from t1 inner join t2 using (id, ranking);
select * from t1 natural inner join t2;

Add more multicolumn sample lines

-- Example like joins.sql but joining on multiple columns.
drop table if exists t1;
drop table if exists t2;

create table t1 (
    id int primary key,
    name text,
    ranking int);

create table t2 (
    code char(1) primary key,
    id int,
    ranking int);

insert into t1 values(1, 'Joanne', 7);
insert into t1 values(2, 'Sam', 7);
insert into t1 values(3, 'Emmanuel', 6);
insert into t1 values(4, 'Brayden', 2);

insert into t2 values('x', 2, 8);
insert into t2 values('z', 3, 6);

select * from t1;
select * from t2;

select * from t1 inner join t2 on t1.id = t2.id and t1.ranking = t2.ranking;
select * from t1 inner join t2 using (id, ranking);
select * from t1 natural inner join t2;

select * from t1 left outer join t2 using (id, ranking);


/********************************************************************************
	file-centric-snapshot-mdrs-referenced-module-inactive.sql

	Assertion:
	Referenced module in the MDRS is inactive
********************************************************************************/

	insert into qa_result (runid, assertionuuid, concept_id, details)
	select
		<RUNID>,
		'<ASSERTIONUUID>',
		a.referencedcomponentid,
		concat('Referenced module ', a.referencedcomponentid, ' in module dependency refset is inactive.')
	from curr_moduledependencyrefset_s a
	left join curr_concept_s c on a.referencedcomponentid = c.id
	where c.active = 0
		and a.active = 1;

Add check for source module ids that are inactive

/********************************************************************************
	file-centric-snapshot-mdrs-referenced-module-inactive.sql

	Assertion:
	Referenced module in the MDRS is inactive
********************************************************************************/

	insert into qa_result (runid, assertionuuid, concept_id, details)
	select
		<RUNID>,
		'<ASSERTIONUUID>',
		a.referencedcomponentid,
		concat('Referenced module ', a.referencedcomponentid, ' in module dependency refset is inactive.')
	from curr_moduledependencyrefset_s a
	left join curr_concept_s c on a.referencedcomponentid = c.id
	where c.active = 0
		and a.active = 1;

	insert into qa_result (runid, assertionuuid, concept_id, details)
	select
		<RUNID>,
		'<ASSERTIONUUID>',
		a.moduleid,
		concat('Sourced module ', a.moduleid, ' in module dependency refset is inactive.')
	from curr_moduledependencyrefset_s a
	left join curr_concept_s c on a.moduleid = c.id
	where c.active = 0
		and a.active = 1;


SET XACT_ABORT ON;
BEGIN TRANSACTION;
  -- update the version
  UPDATE usr_schema_version SET version_value='46' WHERE version_key='schema_patch';

  DROP INDEX ix_usr_oguser_name ON usr_oguser;

  ALTER TABLE sec_future ADD COLUMN userid varchar(255);
  UPDATE usr_oguser SET userid = name;
  ALTER TABLE sec_future ALTER COLUMN userid varchar(255) NOT NULL;
  ALTER TABLE sec_future DROP COLUMN name;

  ALTER TABLE usr_oguser ADD COLUMN name varchar(255);
  ALTER TABLE usr_oguser ADD COLUMN time_zone varchar(255);
  ALTER TABLE usr_oguser ADD COLUMN email_address varchar(255);

  UPDATE usr_oguser SET name = userid;
  UPDATE usr_oguser SET time_zone = 'Europe/London';
  ALTER TABLE usr_oguser ALTER COLUMN time_zone varchar(255) NOT NULL;

  CREATE INDEX ix_usr_oguser_userid ON usr_oguser(userid);

COMMIT;

Fix SQL Server 2008 ALTER TABLE syntax (ADD COLUMN -> ADD) in usr_db migration script

SET XACT_ABORT ON;
BEGIN TRANSACTION;
  -- update the version
  UPDATE usr_schema_version SET version_value='46' WHERE version_key='schema_patch';

  DROP INDEX ix_usr_oguser_name ON usr_oguser;

  ALTER TABLE sec_future ADD userid varchar(255);
  UPDATE usr_oguser SET userid = name;
  ALTER TABLE sec_future ALTER COLUMN userid varchar(255) NOT NULL;
  ALTER TABLE sec_future DROP COLUMN name;

  ALTER TABLE usr_oguser ADD name varchar(255);
  ALTER TABLE usr_oguser ADD time_zone varchar(255);
  ALTER TABLE usr_oguser ADD email_address varchar(255);

  UPDATE usr_oguser SET name = userid;
  UPDATE usr_oguser SET time_zone = 'Europe/London';
  ALTER TABLE usr_oguser ALTER COLUMN time_zone varchar(255) NOT NULL;

  CREATE INDEX ix_usr_oguser_userid ON usr_oguser(userid);

COMMIT;


-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements.  See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership.  The ASF licenses this file
-- to you 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.

--;
-- Schema upgrade from 4.8.1 to 4.9.0;
--;

Set indexes on event table

-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements.  See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership.  The ASF licenses this file
-- to you 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.

--;
-- Schema upgrade from 4.8.1 to 4.9.0;
--;

ALTER TABLE `event` ADD INDEX `archived` (`archived`);
ALTER TABLE `event` ADD INDEX `state` (`state`);


-- Aggregate bird_migration_altitude_profile data:
-- - Aggregate on time frame (e.g. 20 min)
-- - Aggregate on altitude band (e.g. 200-1600m, 1600+ m)
-- - Average values

SELECT
  radar_id,
  date_trunc('hour', start_time) + date_part('minute', start_time)::int / 20 * interval '20 min' AS interval_start_time,
  CASE
    WHEN altitude >= 0.2 AND altitude < 1.6 THEN 'low'
    WHEN altitude >= 1.6 THEN 'high'
  END AS altitude_band,
  count(*) AS number_of_measurements,
  avg(u_speed) AS avg_u_speed,
  avg(v_speed) AS avg_v_speed,
  avg(bird_density) AS avg_bird_density
FROM
  bird_migration_altitude_profiles
WHERE
  radial_velocity_std >= 2
  AND bird_density >= 10
  AND altitude >= 0.2
GROUP BY
  radar_id,
  interval_start_time,
  altitude_band
ORDER BY
  radar_id,
  interval_start_time,
  altitude_band DESC

Update SQL with WITH statement

-- Aggregate bird_migration_altitude_profile data:
-- - Aggregate on time frame (e.g. 20 min)
-- - Aggregate on altitude band (e.g. 200-1600m, 1600+ m)
-- - Average values

WITH aggregated_data AS (
    SELECT
        radar_id,
        date_trunc('hour', start_time) + date_part('minute', start_time)::int / 20 * interval '20 min' AS interval_start_time,
        CASE
            WHEN altitude >= 0.2 AND altitude < 1.6 THEN 'low'
            WHEN altitude >= 1.6 THEN 'high'
        END AS altitude_band,
        count(*) AS number_of_measurements,
        avg(u_speed) AS avg_u_speed,
        avg(v_speed) AS avg_v_speed,
        avg(bird_density) AS avg_bird_density
    FROM
        bird_migration_altitude_profiles
    WHERE
        radial_velocity_std >= 2
        AND bird_density >= 10
        AND altitude >= 0.2
    GROUP BY
        radar_id,
        interval_start_time,
        altitude_band
    ORDER BY
        radar_id,
        interval_start_time,
        altitude_band DESC
)

SELECT
    *
FROM
    aggregated_data


CREATE Class customer
CREATE PROPERTY customer.customer_id INTEGER
CREATE PROPERTY customer.company_name STRING

CREATE Class contacts
CREATE PROPERTY contacts.contacts_id INTEGER
CREATE PROPERTY contacts.type EMBEDDEDLIST
CREATE PROPERTY contacts.salutation EMBEDDEDLIST
CREATE PROPERTY contacts.firstname STRING
CREATE PROPERTY contacts.surename STRING
CREATE PROPERTY contacts.phone STRING
CREATE PROPERTY contacts.mobile_phone STRING
CREATE PROPERTY contacts.fax STRING
CREATE PROPERTY contacts.email_address STRING
CREATE PROPERTY contacts.street STRING
CREATE PROPERTY contacts.street2 STRING
CREATE PROPERTY contacts.postcode INTEGER
CREATE PROPERTY contacts.country STRING
CREATE PROPERTY contacts.city STRING
CREATE PROPERTY contacts.vatid INTEGER
CREATE PROPERTY contacts.parent_customer INTEGER
CREATE PROPERTY contacts.ouser_id INTEGER

CREATE PROPERTY customer.contacts LINKSET contacts
CREATE PROPERTY contacts.users LINKSET OUser

CREATE LINK contacts TYPE LINKSET FROM contacts.parent_customer TO customer.customer_id INVERSE

Update SQL for customer class

CREATE Class Customer
CREATE PROPERTY Customer.customerId DOUBLE
CREATE PROPERTY Customer.companyName STRING
CREATE PROPERTY Customer.street STRING
CREATE PROPERTY Customer.street2 STRING
CREATE PROPERTY Customer.postcode DOUBLE
CREATE PROPERTY Customer.country STRING
CREATE PROPERTY Customer.city STRING
CREATE PROPERTY Customer.vatid DOUBLE

CREATE Class CustomerContacts
CREATE PROPERTY CustomerContacts.contactsId DOUBLE
CREATE PROPERTY CustomerContacts.type EMBEDDEDLIST
CREATE PROPERTY CustomerContacts.salutation EMBEDDEDLIST
CREATE PROPERTY CustomerContacts.firstname STRING
CREATE PROPERTY CustomerContacts.surename STRING
CREATE PROPERTY CustomerContacts.phone STRING
CREATE PROPERTY CustomerContacts.mobilePhone STRING
CREATE PROPERTY CustomerContacts.fax STRING
CREATE PROPERTY CustomerContacts.emailAddress STRING

CREATE INDEX Customer.companyName UNIQUE
CREATE INDEX Customer.street UNIQUE
CREATE INDEX Customer.country UNIQUE
CREATE INDEX Customer.city UNIQUE
CREATE INDEX CustomerContacts.firstname UNIQUE
CREATE INDEX CustomerContacts.surename UNIQUE

CREATE SEQUENCE customerIdSeq TYPE ORDERED

CREATE PROPERTY Customer.contacts LINKSET CustomerContacts
CREATE PROPERTY Customer.users LINKSET OUser
CREATE PROPERTY Customer.parentCustomer LINK Customer


/*
 Pre-Deployment Script Template
--------------------------------------------------------------------------------------
 This file contains SQL statements that will be executed before the build script.
 Use SQLCMD syntax to include a file in the pre-deployment script.
 Example:      :r .\myfile.sql
 Use SQLCMD syntax to reference a variable in the pre-deployment script.
 Example:      :setvar TableName MyTable
               SELECT * FROM [$(TableName)]
--------------------------------------------------------------------------------------
*/

IF EXISTS(select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'EnglishFraction' and COLUMN_NAME = 'Amount' and NUMERIC_SCALE = 4)
BEGIN
	ALTER TABLE [employer_financial].[EnglishFraction]
	ALTER COLUMN AMOUNT DECIMAL(18,5) NULL
END
IF EXISTS(select 1  from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'EnglishFraction' and COLUMN_NAME='EmpRef' AND DATA_TYPE = 'nchar')
BEGIN
	ALTER TABLE [employer_financial].[EnglishFraction]
	ALTER COLUMN EmpRef NVARCHAR(50) NULL
END

Add seed data for new column

/*
 Pre-Deployment Script Template
--------------------------------------------------------------------------------------
 This file contains SQL statements that will be executed before the build script.
 Use SQLCMD syntax to include a file in the pre-deployment script.
 Example:      :r .\myfile.sql
 Use SQLCMD syntax to reference a variable in the pre-deployment script.
 Example:      :setvar TableName MyTable
               SELECT * FROM [$(TableName)]
--------------------------------------------------------------------------------------
*/

IF EXISTS(select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'EnglishFraction' and COLUMN_NAME = 'Amount' and NUMERIC_SCALE = 4)
BEGIN
	ALTER TABLE [employer_financial].[EnglishFraction]
	ALTER COLUMN AMOUNT DECIMAL(18,5) NULL
END
IF EXISTS(select 1  from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'EnglishFraction' and COLUMN_NAME='EmpRef' AND DATA_TYPE = 'nchar')
BEGIN
	ALTER TABLE [employer_financial].[EnglishFraction]
	ALTER COLUMN EmpRef NVARCHAR(50) NULL
END
IF NOT EXISTS(select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'LevyDeclaration' and COLUMN_NAME = 'CreatedDate')
BEGIN
	ALTER TABLE [employer_financial].[LevyDeclaration]
	Add CreatedDate DATETIME NOT NULL DEFAULT GETDATE()
END


CREATE TABLE smr_new.player_has_mission
(
	game_id INT UNSIGNED NOT NULL,
	account_id INT UNSIGNED NOT NULL,
	mission_id INT UNSIGNED NOT NULL,
	on_step INT UNSIGNED NOT NULL,
	progress INT UNSIGNED NOT NULL,
	next_step INT UNSIGNED NOT NULL,
	total_steps INT UNSIGNED NOT NULL,
	starting_sector INT UNSIGNED NOT NULL,
	mission_sector INT UNSIGNED NOT NULL,
	step_fails INT UNSIGNED NOT NULL,
	PRIMARY KEY (game_id, account_id, mission_id)
) ENGINE = InnoDB;

Remove schema name from sql. Flyway knows which schema to update and on different machines we use different schemas

CREATE TABLE player_has_mission
(
	game_id INT UNSIGNED NOT NULL,
	account_id INT UNSIGNED NOT NULL,
	mission_id INT UNSIGNED NOT NULL,
	on_step INT UNSIGNED NOT NULL,
	progress INT UNSIGNED NOT NULL,
	next_step INT UNSIGNED NOT NULL,
	total_steps INT UNSIGNED NOT NULL,
	starting_sector INT UNSIGNED NOT NULL,
	mission_sector INT UNSIGNED NOT NULL,
	step_fails INT UNSIGNED NOT NULL,
	PRIMARY KEY (game_id, account_id, mission_id)
) ENGINE = InnoDB;


-- +goose Up
-- SQL in section 'Up' is executed when this migration is applied

CREATE TABLE `fqdnSets` (
       `id` INT(11) NOT NULL AUTO_INCREMENT,
       -- SHA256 hash of alphabetically sorted, lowercased, comma joined
       -- DNS names contained in a certificate
       `setHash` BINARY(32) NOT NULL,
       `serial` VARCHAR(255) UNIQUE NOT NULL,
       `issued` DATETIME NOT NULL,
       `expires` DATETIME NOT NULL,
       PRIMARY KEY (`id`),
       KEY `setHash` (`setHash`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- +goose Down
-- SQL section 'Down' is executed when this migration is rolled back

DROP TABLE `fqdnSets`;

Make fqdnSets index across setHash and issued

-- +goose Up
-- SQL in section 'Up' is executed when this migration is applied

CREATE TABLE `fqdnSets` (
       `id` INT(11) NOT NULL AUTO_INCREMENT,
       -- SHA256 hash of alphabetically sorted, lowercased, comma joined
       -- DNS names contained in a certificate
       `setHash` BINARY(32) NOT NULL,
       `serial` VARCHAR(255) UNIQUE NOT NULL,
       `issued` DATETIME NOT NULL,
       `expires` DATETIME NOT NULL,
       PRIMARY KEY (`id`),
       KEY `setHash_issued_idx` (`setHash`, `issued`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- +goose Down
-- SQL section 'Down' is executed when this migration is rolled back

DROP TABLE `fqdnSets`;


update lfv2_account set cup_cagnoute = false, cup_points = 0, cup_rank = 99;
delete from lfv2_cup_vote;
delete from lfv2_cup_match;
update lfv2_cup set name = 'EURO 2016';

Update SQL script for reset

update lfv2_account set cup_cagnoute = false, cup_points = 0, cup_rank = 99, stat_cup_scores = 0, stat_cup_matchs = 0, stat_cup_results = 0;
delete from lfv2_cup_vote;
delete from lfv2_cup_match;
update lfv2_cup set name = 'EURO 2016';


CREATE TABLE genre( id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT UNIQUE );

CREATE TABLE stream_url( id INTEGER PRIMARY KEY AUTOINCREMENT,
                         url TEXT UNIQUE,
                         bitrate INTEGER,
                         format TEXT );

CREATE TABLE country( id INTEGER PRIMARY KEY AUTOINCREMENT,
                      name TEXT UNIQUE );

CREATE TABLE city( id INTEGER PRIMARY KEY AUTOINCREMENT,
                   name TEXT,
                   country_id INTEGER,
                   FOREIGN KEY(country_id) REFERENCES country(id) );

CREATE TABLE radio( id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT,
                    logo BLOB,
                    homepage TEXT,
                    country_id INTEGER,
                    city_id INTEGER,
                    valid INTEGER,
                    webonly INTEGER,
                    FOREIGN KEY(country_id) REFERENCES country(id),
                    FOREIGN KEY(city_id) REFERENCES city(id) );

CREATE TABLE joingenre( id INTEGER PRIMARY KEY AUTOINCREMENT,
                        radio_id INTEGER,
                        genre_id INTEGER,
                        FOREIGN KEY(radio_id) REFERENCES radio(id),
                        FOREIGN KEY(genre_id) REFERENCES genre(id) );

CREATE TABLE joinurl( id INTEGER PRIMARY KEY AUTOINCREMENT,
                      radio_id INTEGER,
                      stream_url_id INTEGER,
                      FOREIGN KEY(radio_id) REFERENCES radio(id),
                      FOREIGN KEY(stream_url_id) REFERENCES stream_url(id) );

Remove useless key country from radios since we have city

CREATE TABLE genre( id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT UNIQUE );

CREATE TABLE stream_url( id INTEGER PRIMARY KEY AUTOINCREMENT,
                         url TEXT UNIQUE,
                         bitrate INTEGER,
                         format TEXT );

CREATE TABLE country( id INTEGER PRIMARY KEY AUTOINCREMENT,
                      name TEXT UNIQUE );

CREATE TABLE city( id INTEGER PRIMARY KEY AUTOINCREMENT,
                   name TEXT,
                   country_id INTEGER,
                   FOREIGN KEY(country_id) REFERENCES country(id) );

CREATE TABLE radio( id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT,
                    logo BLOB,
                    homepage TEXT,
                    city_id INTEGER,
                    valid INTEGER,
                    webonly INTEGER,
                    FOREIGN KEY(city_id) REFERENCES city(id) );

CREATE TABLE joingenre( id INTEGER PRIMARY KEY AUTOINCREMENT,
                        radio_id INTEGER,
                        genre_id INTEGER,
                        FOREIGN KEY(radio_id) REFERENCES radio(id),
                        FOREIGN KEY(genre_id) REFERENCES genre(id) );

CREATE TABLE joinurl( id INTEGER PRIMARY KEY AUTOINCREMENT,
                      radio_id INTEGER,
                      stream_url_id INTEGER,
                      FOREIGN KEY(radio_id) REFERENCES radio(id),
                      FOREIGN KEY(stream_url_id) REFERENCES stream_url(id) );


begin;
alter table journals drop constraint "$1";
alter table journals add foreign key (submitted_by) references users (name) on update cascade;
end;

Support renaming users for roles.

begin;
alter table journals drop constraint "$1";
alter table journals add foreign key (submitted_by) references users (name) on update cascade;
end;
begin;
alter table roles drop constraint "$1";
alter table roles add foreign key (user_name) references users (name) on update cascade;
end;


--
-- 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

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


create table skinny_sessions (
  id bigserial not null primary key,
  created_at timestamp not null,
  expire_at timestamp not null
);

create table servlet_sessions (
  jsession_id varchar(32) not null primary key,
  skinny_session_id bigint not null,
  created_at timestamp not null,
  foreign key(skinny_session_id) references skinny_sessions(id)
);

create table skinny_session_attributes (
  skinny_session_id bigint not null,
  attribute_name varchar(128) not null,
  attribute_value varbinary(10485760),
  foreign key(skinny_session_id) references skinny_sessions(id)
);

alter table skinny_session_attributes add constraint
  skinny_session_attributes_unique_idx
  unique(skinny_session_id, attribute_name);

Fix insertion query error in example app

create table skinny_sessions (
  id bigserial not null primary key,
  created_at timestamp not null,
  expire_at timestamp not null
);

create table servlet_sessions (
  jsession_id varchar(50) not null primary key,
  skinny_session_id bigint not null,
  created_at timestamp not null,
  foreign key(skinny_session_id) references skinny_sessions(id)
);

create table skinny_session_attributes (
  skinny_session_id bigint not null,
  attribute_name varchar(128) not null,
  attribute_value varbinary(10485760),
  foreign key(skinny_session_id) references skinny_sessions(id)
);

alter table skinny_session_attributes add constraint
  skinny_session_attributes_unique_idx
  unique(skinny_session_id, attribute_name);


CREATE TABLE IF NOT EXISTS users (
  id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
  created_at timestamptz DEFAULT current_timestamp,
  username text,
  email text,
  password text
) WITH (OIDS=FALSE);

CREATE TABLE IF NOT EXISTS tokens (
  id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
  created_at timestamptz DEFAULT current_timestamp,
  salt text,
  user_id uuid references users(id)
) WITH (OIDS=FALSE);

CREATE UNIQUE INDEX users_username_idx
  ON users USING btree (username);

CREATE UNIQUE INDEX users_email_idx
  ON users USING btree (email);

Add modified_at and photo fields to user table.

CREATE TABLE IF NOT EXISTS users (
  id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
  created_at timestamptz DEFAULT current_timestamp,
  modified_at timestamptz DEFAULT current_timestamp,
  photo text,
  username text,
  email text,
  password text
) WITH (OIDS=FALSE);

CREATE TABLE IF NOT EXISTS tokens (
  id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
  created_at timestamptz DEFAULT current_timestamp,
  salt text,
  user_id uuid references users(id)
) WITH (OIDS=FALSE);

CREATE UNIQUE INDEX users_username_idx
  ON users USING btree (username);

CREATE UNIQUE INDEX users_email_idx
  ON users USING btree (email);


ALTER TABLE gbif_dataset_metrics
ADD COLUMN dataset_key text,
ADD COLUMN occurrences integer,
ADD COLUMN bor_preserved_specimen integer,
ADD COLUMN bor_fossil_specimen integer,
ADD COLUMN bor_living_specimen integer,
ADD COLUMN bor_material_sample integer,
ADD COLUMN bor_observation integer,
ADD COLUMN bor_human_observation integer,
ADD COLUMN bor_machine_observation integer,
ADD COLUMN bor_literature integer,
ADD COLUMN bor_unknown integer,
ADD COLUMN coordinates_not_provided integer,
ADD COLUMN coordinates_major_issues integer,
ADD COLUMN coordinates_minor_issues integer,
ADD COLUMN coordinates_valid integer;

Add taxon + media to SQL

ALTER TABLE gbif_dataset_metrics
ADD COLUMN dataset_key text,
ADD COLUMN occurrences integer,
ADD COLUMN bor_preserved_specimen integer,
ADD COLUMN bor_fossil_specimen integer,
ADD COLUMN bor_living_specimen integer,
ADD COLUMN bor_material_sample integer,
ADD COLUMN bor_observation integer,
ADD COLUMN bor_human_observation integer,
ADD COLUMN bor_machine_observation integer,
ADD COLUMN bor_literature integer,
ADD COLUMN bor_unknown integer,
ADD COLUMN coordinates_not_provided integer,
ADD COLUMN coordinates_major_issues integer,
ADD COLUMN coordinates_minor_issues integer,
ADD COLUMN coordinates_valid integer,
ADD COLUMN taxon_not_provided integer,
ADD COLUMN taxon_match_none integer,
ADD COLUMN taxon_match_higherrank integer,
ADD COLUMN taxon_match_fuzzy integer,
ADD COLUMN taxon_match_complete integer,
ADD COLUMN media_not_provided integer,
ADD COLUMN media_url_invalid integer,
ADD COLUMN media_audio integer,
ADD COLUMN media_video integer,
ADD COLUMN media_image integer;


BEGIN;

DO $$DECLARE
   -- THESE MUST BE CHANGED WHEN YOU COPY THE SCRIPT!

   -- The version you expect the database to have _before_ the migration
   old_version numeric := 18;
   -- The version the database should have _after_ the migration
   new_version numeric := 19;

   -- hands off
   existing_version numeric;

BEGIN

   -- Check existing version
   SELECT version from lddb__schema INTO existing_version;
   IF ( existing_version <> old_version) THEN
      RAISE EXCEPTION 'ASKED TO MIGRATE FROM INCORRECT EXISTING VERSION!';
      ROLLBACK;
   END IF;
   UPDATE lddb__schema SET version = new_version;

   -- ACTUAL SCHEMA CHANGES HERE:

   ALTER TABLE lddb__identifiers ADD CONSTRAINT unique_uri UNIQUE (iri);

END$$;

COMMIT;

Add a failsafe to make sure the next release does not run into trouble.

BEGIN;

DO $$DECLARE
   -- THESE MUST BE CHANGED WHEN YOU COPY THE SCRIPT!

   -- The version you expect the database to have _before_ the migration
   old_version numeric := 18;
   -- The version the database should have _after_ the migration
   new_version numeric := 19;

   -- hands off
   existing_version numeric;

BEGIN

   -- Check existing version
   SELECT version from lddb__schema INTO existing_version;
   IF ( existing_version <> old_version) THEN
      RAISE EXCEPTION 'ASKED TO MIGRATE FROM INCORRECT EXISTING VERSION!';
      ROLLBACK;
   END IF;
   UPDATE lddb__schema SET version = new_version;

   -- ACTUAL SCHEMA CHANGES HERE:

   -- At the time of writing, there is an IRI conflict on 'https://id.kb.se/marc/SerialsFrequencyType-z'. This has now been fixed in the definitions repo, but the bad data is still live. As a failsafe, if this migrations is run _before_ the definitions are reloaded, delete the conflicting line, to make the constraint possible to add.
   DELETE FROM lddb__identifiers WHERE id = 'kxq3td5nm2lnmx23' AND iri = 'https://id.kb.se/marc/SerialsFrequencyType-z';

   ALTER TABLE lddb__identifiers ADD CONSTRAINT unique_uri UNIQUE (iri);

END$$;

COMMIT;


DROP TABLE book;
DROP VIEW view_book_titles;

CREATE TABLE book
(
    id INTEGER NOT NULL AUTO_INCREMENT COMMENT 'Book Id',
    title VARCHAR(255) NOT NULL COMMENT 'Book Title',
    isbn VARCHAR(24) NOT NULL COMMENT 'ISBN Number',
    price FLOAT COMMENT 'Price of the book.',
    PRIMARY KEY (id)
) ENGINE=InnoDB COMMENT='Book Table';

CREATE VIEW view_book_titles AS SELECT title FROM book;

Fix fixtures to avoid error (mysql safe mode)

DROP TABLE IF EXISTS book;
DROP VIEW IF EXISTS view_book_titles;

CREATE TABLE book
(
    id INTEGER NOT NULL AUTO_INCREMENT COMMENT 'Book Id',
    title VARCHAR(255) NOT NULL COMMENT 'Book Title',
    isbn VARCHAR(24) NOT NULL COMMENT 'ISBN Number',
    price FLOAT COMMENT 'Price of the book.',
    PRIMARY KEY (id)
) ENGINE=InnoDB COMMENT='Book Table';

CREATE VIEW view_book_titles AS SELECT title FROM book;


PROMPT Run user examples
set echo off
set feedback off
set linesize 1000

prompt Common examples from web

exec ut_ansiconsole_helper.color_enabled(true);
@@award_bonus/run_award_bonus_test.sql

@@between_string/run_betwnstr_test.sql

@@remove_rooms_by_name/run_remove_rooms_by_name_test.sql

@@demo_of_expectations/run.sql

prompt Additional examples
prompt RunExampleTestAnnotationBasedForCurrentSchema
@@RunExampleTestAnnotationBasedForCurrentSchema.sql
prompt RunExpectations
@@RunExpectations.sql

@@RunWithDocumentationReporter.sql

Set echo on and feedback on to see what's going on

PROMPT Run user examples
set echo on
set feedback on
set linesize 1000

prompt Common examples from web

exec ut_ansiconsole_helper.color_enabled(true);
@@award_bonus/run_award_bonus_test.sql

@@between_string/run_betwnstr_test.sql

@@remove_rooms_by_name/run_remove_rooms_by_name_test.sql

@@demo_of_expectations/run.sql

prompt Additional examples
prompt RunExampleTestAnnotationBasedForCurrentSchema
@@RunExampleTestAnnotationBasedForCurrentSchema.sql
prompt RunExpectations
@@RunExpectations.sql

@@RunWithDocumentationReporter.sql


-- Target versions: pre v2.2.0
-- MUST be executed when upgrading to SlipStream v2.2.0 and BEFORE restarting SlipStream server

-- Migrating MAPKEY and MODULE_RESOURCE_URI fields from MODULE_NODE
update NODE set MAPKEY = (select MAPKEY from MODULE_NODE where MODULE_NODE.NODES_ID = NODE.ID);
update NODE set MODULE_RESOURCEURI = (select MODULE_RESOURCEURI from MODULE_NODE where MODULE_NODE.NODES_ID = NODE.ID);
drop table MODULE_NODE;

-- Migrating MODULE_RESOURCE_URI field from MODULE_PACKAGE
update PACKAGE set MODULE_RESOURCEURI = (select MODULE_RESOURCEURI from MODULE_PACKAGE where MODULE_PACKAGE.PACKAGES_ID = PACKAGE.ID);
drop table MODULE_PACKAGE;

-- Migrating MODULE_RESOURCE_URI field from MODULE_TARGET
update TARGET set MODULE_RESOURCEURI = (select MODULE_RESOURCEURI from MODULE_TARGET where MODULE_TARGET.TARGETS_ID = TARGET.ID);
drop table MODULE_TARGET;

Correct script adding missing columns and correcting node key

-- Target versions: pre v2.2.0
-- MUST be executed when upgrading to SlipStream v2.2.0 and BEFORE restarting SlipStream server

-- Migrating MAPKEY and MODULE_RESOURCE_URI fields from MODULE_NODE
alter table NODE add column NODES_KEY varchar(255);
update NODE set NODES_KEY = (select MAPKEY from MODULE_NODE where MODULE_NODE.NODES_ID = NODE.ID);
alter table NODE add column MODULE_RESOURCEURI varchar(255);
update NODE set MODULE_RESOURCEURI = (select MODULE_RESOURCEURI from MODULE_NODE where MODULE_NODE.NODES_ID = NODE.ID);
drop table MODULE_NODE;

-- Migrating MODULE_RESOURCE_URI field from MODULE_PACKAGE
alter table PACKAGE add column MODULE_RESOURCEURI varchar(255);
update PACKAGE set MODULE_RESOURCEURI = (select MODULE_RESOURCEURI from MODULE_PACKAGE where MODULE_PACKAGE.PACKAGES_ID = PACKAGE.ID);
drop table MODULE_PACKAGE;

-- Migrating MODULE_RESOURCE_URI field from MODULE_TARGET
alter table TARGET add column MODULE_RESOURCEURI varchar(255);
update TARGET set MODULE_RESOURCEURI = (select MODULE_RESOURCEURI from MODULE_TARGET where MODULE_TARGET.TARGETS_ID = TARGET.ID);
drop table MODULE_TARGET;


--- System Setup
SET application_name="container_setup";

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
CREATE EXTENSION IF NOT EXISTS pgaudit;

CREATE USER PGHA_USER LOGIN;
ALTER USER PGHA_USER PASSWORD 'PGHA_USER_PASSWORD';

CREATE DATABASE PGHA_DATABASE;
GRANT ALL PRIVILEGES ON DATABASE PGHA_DATABASE TO PGHA_USER;

--- PGHA_DATABASE Setup

\c PGHA_DATABASE

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
CREATE EXTENSION IF NOT EXISTS pgaudit;

CREATE SCHEMA IF NOT EXISTS PGHA_USER;

Allow regular PostgreSQL user to create objects in its own schema

--- System Setup
SET application_name="container_setup";

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
CREATE EXTENSION IF NOT EXISTS pgaudit;

CREATE USER PGHA_USER LOGIN;
ALTER USER PGHA_USER PASSWORD 'PGHA_USER_PASSWORD';

CREATE DATABASE PGHA_DATABASE;
GRANT ALL PRIVILEGES ON DATABASE PGHA_DATABASE TO PGHA_USER;

--- PGHA_DATABASE Setup

\c PGHA_DATABASE

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
CREATE EXTENSION IF NOT EXISTS pgaudit;

CREATE SCHEMA IF NOT EXISTS AUTHORIZATION PGHA_USER;


CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TABLE repositories (
  id             UUID PRIMARY KEY                           DEFAULT gen_random_uuid(),
  name           VARCHAR(100) NOT NULL,
  description    TEXT,
  website        TEXT,
  default_branch TEXT         NOT NULL,
  private        BOOLEAN                                    DEFAULT TRUE,
  bare           BOOLEAN                                    DEFAULT TRUE,
  created_at     TIMESTAMPTZ  NOT NULL                      DEFAULT now(),
  updated_at     TIMESTAMPTZ  NOT NULL                      DEFAULT now(),
  owner_id       UUID REFERENCES users NOT NULL
);

Use TEXT instead of VARCHAR for repository name in postgres

CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TABLE repositories (
  id             UUID PRIMARY KEY                           DEFAULT gen_random_uuid(),
  name           TEXT NOT NULL,
  description    TEXT,
  website        TEXT,
  default_branch TEXT         NOT NULL,
  private        BOOLEAN                                    DEFAULT TRUE,
  bare           BOOLEAN                                    DEFAULT TRUE,
  created_at     TIMESTAMPTZ  NOT NULL                      DEFAULT now(),
  updated_at     TIMESTAMPTZ  NOT NULL                      DEFAULT now(),
  owner_id       UUID REFERENCES users NOT NULL
);


-- rambler up

--
-- This table defines the liturigal seasons that set the base color, name,
-- notes, and services for each part of the year
--

CREATE TABLE liturigal_seasons (
    season_id serial,
    name text NOT NULL,
    code text NOT NULL,
    color text NOT NULL,
    sort_order integer NOT NULL,
    calculate_from text NOT NULL,
    church_year integer NOT NULL DEFAULT 0,
    algorithm text NOT NULL,
    distance integer,
    weekday_precedence integer NOT NULL,
    has_last_sunday boolean NOT NULL DEFAULT FALSE,
    continue_counting boolean NOT NULL,
    schedule_pattern text NOT NULL,
    name_pattern_mon text NOT NULL,
    name_pattern_tue text NOT NULL,
    name_pattern_wed text NOT NULL,
    name_pattern_thu text NOT NULL,
    name_pattern_fri text NOT NULL,
    name_pattern_sat text NOT NULL,
    name_pattern_sat_vigil text NOT NULL,
    name_pattern_sun text NOT NULL,
    default_note_mon text,
    default_note_tue text,
    default_note_wed text,
    default_note_thu text,
    default_note_fri text,
    default_note_sat text,
    default_note_sun text,
    CONSTRAINT liturigal_seasons_pk PRIMARY KEY (season_id),
    CONSTRAINT liturigal_seasons_calc_from CHECK (calculate_from IN ('easter', 'christmas', NULL))
);

-- rambler down

DROP TABLE liturigal_seasons;

Add valid start and end dates, in case the boundaries of the summer season change

-- rambler up

--
-- This table defines the liturigal seasons that set the base color, name,
-- notes, and services for each part of the year
--

CREATE TABLE liturigal_seasons (
    season_id serial,
    name text NOT NULL,
    code text NOT NULL,
    color text NOT NULL,
    sort_order integer NOT NULL,
    calculate_from text NOT NULL,
    church_year integer NOT NULL DEFAULT 0,
    algorithm text NOT NULL,
    distance integer,
    weekday_precedence integer NOT NULL,
    has_last_sunday boolean NOT NULL DEFAULT FALSE,
    continue_counting boolean NOT NULL,
    schedule_pattern text NOT NULL,
    name_pattern_mon text NOT NULL,
    name_pattern_tue text NOT NULL,
    name_pattern_wed text NOT NULL,
    name_pattern_thu text NOT NULL,
    name_pattern_fri text NOT NULL,
    name_pattern_sat text NOT NULL,
    name_pattern_sat_vigil text NOT NULL,
    name_pattern_sun text NOT NULL,
    default_note_mon text,
    default_note_tue text,
    default_note_wed text,
    default_note_thu text,
    default_note_fri text,
    default_note_sat text,
    default_note_sun text,
    valid_start timestamp with time zone NULL,
    valid_end timestamp with time zone NULL,
    CONSTRAINT liturigal_seasons_pk PRIMARY KEY (season_id),
    CONSTRAINT liturigal_seasons_calc_from CHECK (calculate_from IN ('easter', 'christmas', NULL))
);

-- rambler down

DROP TABLE liturigal_seasons;


CREATE SCHEMA main;
ALTER USER "www-data" PASSWORD 'www-data';
GRANT SELECT ON spatial_ref_sys TO "www-data";
GRANT ALL ON SCHEMA main TO "www-data";
GRANT ALL ON geometry_columns TO "www-data";

Update travis database creation script

CREATE SCHEMA main;
CREATE SCHEMA main_static;
ALTER USER "www-data" PASSWORD 'www-data';
GRANT SELECT ON spatial_ref_sys TO "www-data";
GRANT ALL ON SCHEMA main TO "www-data";
GRANT ALL ON SCHEMA main_static TO "www-data";
GRANT ALL ON geometry_columns TO "www-data";


--
-- Copyright 2010-2017 Boxfuse GmbH
--
-- 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.
--

DROP INDEX "${schema}"."${table}_vr_idx";
DROP INDEX "${schema}"."${table}_ir_idx";
ALTER TABLE "${schema}"."${table}" DROP COLUMN "version_rank";
ALTER TABLE "${schema}"."${table}" DROP CONSTRAINT "${table}_pk";
ALTER TABLE "${schema}"."${table}" ALTER COLUMN "version" DROP NOT NULL;
call ADMIN_CMD('REORG TABLE "${schema}"."${table}"');
ALTER TABLE "${schema}"."${table}" ADD CONSTRAINT "${table}_pk" PRIMARY KEY ("installed_rank");
UPDATE "${schema}"."${table}" SET "type"='BASELINE' WHERE "type"='INIT';
DROP INDEX "${schema}"."${table}_pk";

Revert "drop the _pk index to resolve issue with repeatable migrations"


-- Add the ratings column to the event_comments table
ALTER TABLE event_comments ADD COLUMN `rating` int(11) default NULL, ;

-- Increase patch count
INSERT INTO patch_history SET patch_number = 55;

Fix typo in db patch

-- Add the ratings column to the event_comments table
ALTER TABLE event_comments ADD COLUMN `rating` int(11) default NULL;

-- Increase patch count
INSERT INTO patch_history SET patch_number = 55;


-- DROP DATABASE ykval;
CREATE DATABASE ykval;
USE ykval;

CREATE TABLE clients (
  id INT NOT NULL AUTO_INCREMENT,
  active BOOLEAN DEFAULT TRUE,
  created DATETIME NOT NULL,
  secret VARCHAR(60) NOT NULL DEFAULT '',
  email VARCHAR(255),
  notes VARCHAR(100),
  PRIMARY KEY (id)
);

CREATE TABLE yubikeys (
  id INT NOT NULL UNIQUE AUTO_INCREMENT,
  active BOOLEAN DEFAULT TRUE,
  created DATETIME NOT NULL,
  accessed DATETIME,
  publicName VARCHAR(16) UNIQUE NOT NULL,
  internalName VARCHAR(12) NOT NULL,
  counter INT,
  low INT,
  high INT,
  sessionUse INT,
  PRIMARY KEY (id)
);

-- DROP USER 'ykval_verifier'@'localhost';
CREATE USER 'ykval_verifier'@'localhost';
GRANT SELECT,INSERT,UPDATE(accessed, counter, low, high, sessionUse)
       ON ykval.yubikeys to 'ykval_verifier'@'localhost';
GRANT SELECT(id, secret, active)
       ON ykval.clients to 'ykval_verifier'@'localhost';

CREATE USER 'ykval_getapikey'@'localhost';
GRANT SELECT(id),INSERT
	ON ykval.clients to 'ykval_getapikey'@'localhost';

FLUSH PRIVILEGES;

Add otp field to clients column.

-- DROP DATABASE ykval;
CREATE DATABASE ykval;
USE ykval;

CREATE TABLE clients (
  id INT NOT NULL AUTO_INCREMENT,
  active BOOLEAN DEFAULT TRUE,
  created DATETIME NOT NULL,
  secret VARCHAR(60) NOT NULL DEFAULT '',
  email VARCHAR(255),
  otp VARCHAR(100) DEFAULT '',
  notes VARCHAR(100) DEFAULT '',
  PRIMARY KEY (id)
);

CREATE TABLE yubikeys (
  id INT NOT NULL UNIQUE AUTO_INCREMENT,
  active BOOLEAN DEFAULT TRUE,
  created DATETIME NOT NULL,
  accessed DATETIME,
  publicName VARCHAR(16) UNIQUE NOT NULL,
  internalName VARCHAR(12) NOT NULL,
  counter INT,
  low INT,
  high INT,
  sessionUse INT,
  PRIMARY KEY (id)
);

-- DROP USER 'ykval_verifier'@'localhost';
CREATE USER 'ykval_verifier'@'localhost';
GRANT SELECT,INSERT,UPDATE(accessed, counter, low, high, sessionUse)
       ON ykval.yubikeys to 'ykval_verifier'@'localhost';
GRANT SELECT(id, secret, active)
       ON ykval.clients to 'ykval_verifier'@'localhost';

CREATE USER 'ykval_getapikey'@'localhost';
GRANT SELECT(id),INSERT
	ON ykval.clients to 'ykval_getapikey'@'localhost';

FLUSH PRIVILEGES;


CREATE TABLE IF NOT EXISTS `posts_{{ board }}` (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `thread` int(11) DEFAULT NULL,
  `subject` varchar(100) DEFAULT NULL,
  `email` varchar(30) DEFAULT NULL,
  `name` varchar(35) DEFAULT NULL,
  `trip` varchar(15) DEFAULT NULL,
  `capcode` varchar(50) DEFAULT NULL,
  `body` text NOT NULL,
  `body_nomarkup` text DEFAULT NULL,
  `time` int(11) NOT NULL,
  `bump` int(11) DEFAULT NULL,
  `thumb` varchar(50) DEFAULT NULL,
  `thumbwidth` int(11) DEFAULT NULL,
  `thumbheight` int(11) DEFAULT NULL,
  `file` varchar(50) DEFAULT NULL,
  `filewidth` int(11) DEFAULT NULL,
  `fileheight` int(11) DEFAULT NULL,
  `filesize` int(11) DEFAULT NULL,
  `filename` text DEFAULT NULL,
  `filehash` text DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  `ip` varchar(45) NOT NULL,
  `sticky` int(1) NOT NULL,
  `locked` int(1) NOT NULL,
  `sage` int(1) NOT NULL,
  `embed` text,
  UNIQUE KEY `id` (`id`),
  KEY `thread` (`thread`),
  KEY `time` (`time`),
  FULLTEXT KEY `body` (`body`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Add (`thread`, `id`) multi-column key to optimize rebuilding index pages.

CREATE TABLE IF NOT EXISTS `posts_{{ board }}` (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `thread` int(11) DEFAULT NULL,
  `subject` varchar(100) DEFAULT NULL,
  `email` varchar(30) DEFAULT NULL,
  `name` varchar(35) DEFAULT NULL,
  `trip` varchar(15) DEFAULT NULL,
  `capcode` varchar(50) DEFAULT NULL,
  `body` text NOT NULL,
  `body_nomarkup` text DEFAULT NULL,
  `time` int(11) NOT NULL,
  `bump` int(11) DEFAULT NULL,
  `thumb` varchar(50) DEFAULT NULL,
  `thumbwidth` int(11) DEFAULT NULL,
  `thumbheight` int(11) DEFAULT NULL,
  `file` varchar(50) DEFAULT NULL,
  `filewidth` int(11) DEFAULT NULL,
  `fileheight` int(11) DEFAULT NULL,
  `filesize` int(11) DEFAULT NULL,
  `filename` text DEFAULT NULL,
  `filehash` text DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  `ip` varchar(45) NOT NULL,
  `sticky` int(1) NOT NULL,
  `locked` int(1) NOT NULL,
  `sage` int(1) NOT NULL,
  `embed` text,
  UNIQUE KEY `id` (`id`),
  KEY `thread` (`thread`),
  KEY `thread_id` (`thread`, `id`),
  KEY `time` (`time`),
  FULLTEXT KEY `body` (`body`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;


CREATE DATABASE `dbs_statistics` /*!40100 DEFAULT CHARACTER SET utf8 */

CREATE TABLE `citations` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `data_source_id` mediumint(8) unsigned NOT NULL,
  `collection_count` int(11) DEFAULT '0',
  `fullCitation_count` int(11) DEFAULT '0',
  `citationMetadata_count` int(11) DEFAULT '0',
  `timestamp` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Fix Stats table full script to include R10.2-3 updates

CREATE DATABASE `dbs_statistics` /*!40100 DEFAULT CHARACTER SET utf8 */

CREATE TABLE `citations` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `data_source_id` mediumint(8) unsigned NOT NULL,
  `collection_count` int(11) DEFAULT '0',
  `fullCitation_count` int(11) DEFAULT '0',
  `citationMetadata_count` int(11) DEFAULT '0',
  `timestamp` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `identifiers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `data_source_id` int(11) NOT NULL,
  `doi` int(11) NOT NULL DEFAULT '0',
  `orcid` int(11) NOT NULL DEFAULT '0',
  `handle` int(11) NOT NULL DEFAULT '0',
  `timestamp` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `relationships` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `data_source_id` int(11) NOT NULL,
  `collection_party` int(11) NOT NULL DEFAULT '0',
  `collection_arc` int(11) NOT NULL DEFAULT '0',
  `collection_nhmrc` int(11) NOT NULL DEFAULT '0',
  `collection_other` int(11) NOT NULL DEFAULT '0',
  `researcher_collection` int(11) NOT NULL DEFAULT '0',
  `party_activity` int(11) NOT NULL DEFAULT '0',
  `arc_collection` int(11) NOT NULL DEFAULT '0',
  `timestamp` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


DROP TABLE IF EXISTS users;
CREATE TABLE users (
	uid INTEGER PRIMARY KEY AUTOINCREMENT,
	username TEXT UNIQUE NOT NULL,
	name TEXT NOT NULL,
	email TEXT NOT NULL
);

drop table if exists courses;
CREATE TABLE courses (
	cid INTEGER PRIMARY KEY AUTOINCREMENT,
	name TEXT UNIQUE NOT NULL,
	displayname TEXT NOT NULL
);

DROP TABLE IF EXISTS entries;
CREATE TABLE entries (
	eid INTEGER PRIMARY KEY AUTOINCREMENT,
	uid INTEGER NOT NULL,
	cid INTEGER NOT NULL,
	level INTEGER DEFAULT 0,

	FOREIGN KEY(uid) REFERENCES users(uid),
	FOREIGN KEY(cid) REFERENCES courses(cid)
);

DROP TABLE IF EXISTS assignments;
CREATE TABLE assignments (
	aid INTEGER PRIMARY KEY AUTOINCREMENT,
	cid INTEGER NOT NULL,
	points INTEGER NOT NULL,
	name TEXT NOT NULL,
	body TEXT NOT NULL,

	FOREIGN KEY(cid) REFERENCES courses(cid)
);

DROP TABLE IF EXISTS grades;
CREATE TABLE grades (
	gid INTEGER PRIMARY KEY AUTOINCREMENT,
	uid INTEGER NOT NULL,
	aid INTEGER NOT NULL,
	score INTEGER NOT NULL,
	hash TEXT,
	message TEXT,

	FOREIGN KEY(uid) REFERENCES users(uid),
	FOREIGN KEY(aid) REFERENCES assignments(aid)
);

DROP TABLE IF EXISTS messages;
CREATE TABLE messages (
	mid INTEGER PRIMARY KEY AUTOINCREMENT,
	cid INTEGER NOT NULL,
	title TEXT NOT NULL,
	body TEXT NOT NULL,

	FOREIGN KEY(cid) REFERENCES courses(cid)
);

Remove hash from grades table

DROP TABLE IF EXISTS users;
CREATE TABLE users (
	uid INTEGER PRIMARY KEY AUTOINCREMENT,
	username TEXT UNIQUE NOT NULL,
	name TEXT NOT NULL,
	email TEXT NOT NULL
);

drop table if exists courses;
CREATE TABLE courses (
	cid INTEGER PRIMARY KEY AUTOINCREMENT,
	name TEXT UNIQUE NOT NULL,
	displayname TEXT NOT NULL
);

DROP TABLE IF EXISTS entries;
CREATE TABLE entries (
	eid INTEGER PRIMARY KEY AUTOINCREMENT,
	uid INTEGER NOT NULL,
	cid INTEGER NOT NULL,
	level INTEGER DEFAULT 0,

	FOREIGN KEY(uid) REFERENCES users(uid),
	FOREIGN KEY(cid) REFERENCES courses(cid)
);

DROP TABLE IF EXISTS assignments;
CREATE TABLE assignments (
	aid INTEGER PRIMARY KEY AUTOINCREMENT,
	cid INTEGER NOT NULL,
	points INTEGER NOT NULL,
	name TEXT NOT NULL,
	body TEXT NOT NULL,

	FOREIGN KEY(cid) REFERENCES courses(cid)
);

DROP TABLE IF EXISTS grades;
CREATE TABLE grades (
	gid INTEGER PRIMARY KEY AUTOINCREMENT,
	uid INTEGER NOT NULL,
	aid INTEGER NOT NULL,
	score INTEGER NOT NULL,
	message TEXT,

	FOREIGN KEY(uid) REFERENCES users(uid),
	FOREIGN KEY(aid) REFERENCES assignments(aid)
);

DROP TABLE IF EXISTS messages;
CREATE TABLE messages (
	mid INTEGER PRIMARY KEY AUTOINCREMENT,
	cid INTEGER NOT NULL,
	title TEXT NOT NULL,
	body TEXT NOT NULL,

	FOREIGN KEY(cid) REFERENCES courses(cid)
);


--
-- Add demo user
--

CREATE USER 'demo'@'localhost' IDENTIFIED BY 'welcome1';
GRANT SELECT, INSERT, UPDATE, DELETE, LOCK TABLES, EXECUTE ON *.* TO 'demo'@'localhost';
CREATE USER 'demo'@'%' IDENTIFIED BY 'welcome1';
GRANT SELECT, INSERT, UPDATE, DELETE, LOCK TABLES, EXECUTE ON *.* TO 'demo'@'%';

Add APM user for monitoring MySQL

--
-- Add demo user
--

CREATE USER 'demo'@'localhost' IDENTIFIED BY 'welcome1';
GRANT SELECT, INSERT, UPDATE, DELETE, LOCK TABLES, EXECUTE ON *.* TO 'demo'@'localhost';
CREATE USER 'demo'@'%' IDENTIFIED BY 'welcome1';
GRANT SELECT, INSERT, UPDATE, DELETE, LOCK TABLES, EXECUTE ON *.* TO 'demo'@'%';

--
-- Add APM user
--

CREATE USER 'newrelic'@'localhost' IDENTIFIED BY 'welcome1';
GRANT REPLICATION CLIENT ON *.* TO 'newrelic'@'localhost' WITH MAX_USER_CONNECTIONS 5;


-- Article metadata types
CREATE TABLE /*_*/pagetriage_tags (
	ptrt_tag_id int unsigned NOT NULL PRIMARY KEY auto_increment,
	ptrt_tag_name varbinary(20) NOT NULL,
	ptrt_tag_desc varbinary(255) NOT NULL
) /*$wgDBTableOptions*/;

CREATE UNIQUE INDEX /*i*/ptrt_tag_id ON /*_*/pagetriage_tags (ptrt_tag_name);

INSERT INTO /*_*/pagetriage_tags (ptrt_tag_name, ptrt_tag_desc)
VALUES
('linkcount', 'Number of inbound links'),
('category_count', 'Category mapping count'),
('csd_status', 'CSD status'),
('prod_status', 'PROD status'),
('blp_prod_status', 'BLP PROD status'),
('afd_status', 'AFD status'),
('rev_count', 'Number of edits to the article'),
('page_len', 'Number of bytes of article'),
('snippet', 'Beginning of article snippet'),
('user_name', 'User name'),
('user_editcount', 'User total edit'),
('user_creation_date', 'User registration date'),
('user_autoconfirmed', 'Check if user is autoconfirmed' ),
('user_bot', 'Check if user is in bot group'),
('user_block_status', 'User block status'),
('user_id', 'User id');

Add db change to the original sql file

-- Article metadata types
CREATE TABLE /*_*/pagetriage_tags (
	ptrt_tag_id int unsigned NOT NULL PRIMARY KEY auto_increment,
	ptrt_tag_name varbinary(20) NOT NULL,
	ptrt_tag_desc varbinary(255) NOT NULL
) /*$wgDBTableOptions*/;

CREATE UNIQUE INDEX /*i*/ptrt_tag_id ON /*_*/pagetriage_tags (ptrt_tag_name);

INSERT INTO /*_*/pagetriage_tags (ptrt_tag_name, ptrt_tag_desc)
VALUES
('linkcount', 'Number of inbound links'),
('category_count', 'Category mapping count'),
('csd_status', 'CSD status'),
('prod_status', 'PROD status'),
('blp_prod_status', 'BLP PROD status'),
('afd_status', 'AFD status'),
('rev_count', 'Number of edits to the article'),
('page_len', 'Number of bytes of article'),
('snippet', 'Beginning of article snippet'),
('user_name', 'User name'),
('user_editcount', 'User total edit'),
('user_creation_date', 'User registration date'),
('user_autoconfirmed', 'Check if user is autoconfirmed' ),
('user_bot', 'Check if user is in bot group'),
('user_block_status', 'User block status'),
('user_id', 'User id'),
('reference', 'Check if page has references');


# ---!Ups
create table users(
  id bigserial not null primary key,
  username varchar(255) not null,
  password varchar(64) not null,
  salt varchar(36) not null,
  name varchar(255) not null,
  email varchar(255) not null
);

create index on users (username, password, salt);

create table applications(
  id bigserial not null primary key,
  name varchar(255) not null,
  api_secret varchar(36) not null
);

create index on applications (api_secret);

create table application_users(
  id bigserial not null primary key,
  user_id bigint not null references users (id),
  application_id bigint not null references applications (id),
  secret_key varchar(36) not null,
  owner boolean not null default false
);

create index on application_users (user_id);
create index on application_users (user_id, secret_key);

# ---!Downs
drop table if exists users cascade;
drop table if exists applications cascade;
drop table if exists application_users cascade;

Add a few timestamps to the tables.

# ---!Ups
create table users(
  id bigserial not null primary key,
  username varchar(255) not null,
  password varchar(64) not null,
  salt varchar(36) not null,
  name varchar(255) not null,
  email varchar(255) not null,
  registered_at timestamp not null default current_timestamp
);

create index on users (username, password, salt);

create table applications(
  id bigserial not null primary key,
  name varchar(255) not null,
  api_secret varchar(36) not null,
  created_at timestamp not null default current_timestamp
);

create index on applications (api_secret);

create table application_users(
  id bigserial not null primary key,
  user_id bigint not null references users (id),
  application_id bigint not null references applications (id),
  secret_key varchar(36) not null,
  owner boolean not null default false,
  granted_at timestamp not null default current_timestamp
);

create index on application_users (user_id);
create index on application_users (user_id, secret_key);

# ---!Downs
drop table if exists users cascade;
drop table if exists applications cascade;
drop table if exists application_users cascade;


CREATE TABLE IF NOT EXISTS reservation (
  id                              SERIAL,
  reservation_title                VARCHAR(255) NOT NULL,
  address_line_one                  VARCHAR(500),
  address_line_two                  VARCHAR(500),
  address_city                     VARCHAR(255),
  address_state                    VARCHAR(20),
  address_zip_code                  VARCHAR(20),
  rsvp_code                        VARCHAR(6) NOT NULL,
  rsvp_code_source                  VARCHAR(500) NOT NULL,
  email_address                    VARCHAR(255),
  reservation_notes                VARCHAR(2048),
  dietary_restrictions             VARCHAR(2048),
  notes_for_bride_groom              VARCHAR(2048),
  is_invited_to_rehearsal_dinner      BOOLEAN,
  is_attending_big_day               BOOLEAN,
  is_attending_rehearsal_dinner      BOOLEAN,
  create_date                     TIMESTAMP NOT NULL,
  modified_date                   TIMESTAMP NOT NULL,
  PRIMARY KEY(id, rsvp_code)
);

CREATE TABLE IF NOT EXISTS contact (
  id                          SERIAL,
  reservation_id              INT,
  first_name                   VARCHAR(255) NOT NULL,
  middle_name                  VARCHAR(255),
  last_name                    VARCHAR(255) NOT NULL,
  is_child                     BOOLEAN,
  is_attending_big_day           BOOLEAN,
  is_attending_rehearsal_dinner  BOOLEAN
);

Format the RSVP Schema script.


-- Table names are flush left, and column definitions are
-- indented by at least one space or tab. Blank lines and
-- lines beginning with a double hyphen are comments.

tracks
	id serial primary key
	artist varchar not null default ''
	title varchar not null default ''
	filename varchar not null default ''
	artwork bytea not null default ''
	length double precision not null default 0
	xfade int not null default 0
	itrim double precision not null default 0
	otrim double precision not null default 0
	lyrics text not null default ''
	story text not null default ''
	status smallint not null default 0
	submitted timestamptz not null default now()
	submitter varchar not null default ''
	submitteremail varchar not null default ''
	comments varchar not null default ''
	enqueued int not null default 0
	played int not null default 0
	sequence int not null default 0
	keywords varchar not null default ''
	url varchar not null default ''
	analysis varchar not null default ''
	userid int not null default 0

users
	id serial primary key
	username varchar not null unique
	email varchar not null unique
	password varchar not null default ''
	user_level int not null default 1 -- banned=0, user=1, admin=2
	status int not null default 0
	hex_key varchar not null default ''

outreach
	id serial primary key
	message varchar not null default ''
	created timestamptz not null default now()
	processed int not null default 0

Redefine itrim and otrim to be integer milliseconds

-- Table names are flush left, and column definitions are
-- indented by at least one space or tab. Blank lines and
-- lines beginning with a double hyphen are comments.

tracks
	id serial primary key
	artist varchar not null default ''
	title varchar not null default ''
	filename varchar not null default ''
	artwork bytea not null default ''
	length double precision not null default 0
	xfade int not null default 0
	itrim int not null default 0
	otrim int not null default 0
	lyrics text not null default ''
	story text not null default ''
	status smallint not null default 0
	submitted timestamptz not null default now()
	submitter varchar not null default ''
	submitteremail varchar not null default ''
	comments varchar not null default ''
	enqueued int not null default 0
	played int not null default 0
	sequence int not null default 0
	keywords varchar not null default ''
	url varchar not null default ''
	analysis varchar not null default ''
	userid int not null default 0

users
	id serial primary key
	username varchar not null unique
	email varchar not null unique
	password varchar not null default ''
	user_level int not null default 1 -- banned=0, user=1, admin=2
	status int not null default 0
	hex_key varchar not null default ''

outreach
	id serial primary key
	message varchar not null default ''
	created timestamptz not null default now()
	processed int not null default 0


SELECT *
INTO wdpa.wdpa_poly_fin
FROM wdpa.wdpa_poly
WHERE iso3 = 'FIN';

-- Define a primary key
ALTER TABLE wdpa.wdpa_poly_fin ADD PRIMARY KEY (gid);

-- Spatially enable it
SELECT Populate_Geometry_Columns('wdpa.wdpa_poly_fin'::regclass);

Add SQL to extract Finnish PAs

SELECT *
INTO wdpa.wdpa_poly_geom_fin
FROM wdpa.wdpa_poly_geom
WHERE iso3 = 'FIN';

-- Define a primary key
ALTER TABLE wdpa.wdpa_poly_geom_fin ADD PRIMARY KEY (gid);

-- Spatially enable it
SELECT Populate_Geometry_Columns('wdpa.wdpa_poly_geom_fin'::regclass);


UPDATE linked_system SET beskrivelse = 'Det Fælles Medicinkort' where kode = 'FMK';
UPDATE linked_system SET beskrivelse = 'Det Danske Vaccinationsregister' where kode = 'DDV';
UPDATE linked_system SET beskrivelse = 'Tilskudsadministration' where kode = 'TAS';

Fix long name for TAS in update sql

UPDATE linked_system SET beskrivelse = 'Det Fælles Medicinkort' where kode = 'FMK';
UPDATE linked_system SET beskrivelse = 'Det Danske Vaccinationsregister' where kode = 'DDV';
UPDATE linked_system SET beskrivelse = 'Tilskudsansøgningsservicen' where kode = 'TAS';


DROP TABLE IF EXISTS `glpi_plugin_fusinvinventory_criteria`;

CREATE TABLE `glpi_plugin_fusinvinventory_criteria` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `comment` text COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`),
  KEY `name` (`name`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Add global criteria in DB

DROP TABLE IF EXISTS `glpi_plugin_fusinvinventory_criteria`;

CREATE TABLE `glpi_plugin_fusinvinventory_criteria` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `comment` text COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`),
  KEY `name` (`name`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `glpi_plugin_fusinvinventory_criteria` (`id`, `name`, `comment`) VALUES
(1, 'Serial number', NULL),
(2, 'uuid', NULL),
(3, 'Mac address', NULL),
(4, 'Windows product key', NULL),
(5, 'Model', NULL),
(6, 'storage serial', NULL),
(7, 'drives serial', NULL);


INSERT INTO oauth_client_details (
  client_id,
  client_secret,
  scope,
  resource_ids,
  authorized_grant_types,
  authorities
)
VALUES (
  'testClient',
  'testClientSecret',
  'read_data_points,write_data_points,delete_data_points',
  'dataPoint',
  'authorization_code,implicit,password,refresh_token',
  'ROLE_CLIENT'
);

Fix the data point resource ID in the sample data.

INSERT INTO oauth_client_details (
  client_id,
  client_secret,
  scope,
  resource_ids,
  authorized_grant_types,
  authorities
)
VALUES (
  'testClient',
  'testClientSecret',
  'read_data_points,write_data_points,delete_data_points',
  'dataPoints',
  'authorization_code,implicit,password,refresh_token',
  'ROLE_CLIENT'
);


/* 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 refresh_tokens(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    token TEXT NOT NULL,
    user_id TEXT NOT NULL,
    UNIQUE (token)
);

Remove autoincrement since we incrementing the ID in the storage layer

/* 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 refresh_tokens(
    id INTEGER PRIMARY KEY,
    token TEXT NOT NULL,
    user_id TEXT NOT NULL,
    UNIQUE (token)
);


-- Add refreshTokens

CREATE TABLE refreshTokens (
  token BINARY(32) PRIMARY KEY,
  clientId BINARY(8) NOT NULL,
  INDEX tokens_client_id(clientId),
  FOREIGN KEY (clientId) REFERENCES clients(id) ON DELETE CASCADE,
  userId BINARY(16) NOT NULL,
  INDEX tokens_user_id(userId),
  email VARCHAR(256) NOT NULL,
  scope VARCHAR(256) NOT NULL,
  createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_unicode_ci;

-- Add expiresAt column for access tokens

ALTER TABLE tokens ADD COLUMN expiresAt TIMESTAMP NOT NULL;
UPDATE tokens SET expiresAt = DATE_ADD(CURRENT_TIMESTAMP, INTERVAL 2 WEEK);

-- Add offline column to codes

ALTER TABLE codes ADD COLUMN offline BOOLEAN NOT NULL DEFAULT FALSE;

UPDATE dbMetadata SET value = '6' WHERE name = 'schema-patch-level';

Fix an old db patch to apply cleanly in local dev.

-- Add refreshTokens

CREATE TABLE refreshTokens (
  token BINARY(32) PRIMARY KEY,
  clientId BINARY(8) NOT NULL,
  INDEX tokens_client_id(clientId),
  FOREIGN KEY (clientId) REFERENCES clients(id) ON DELETE CASCADE,
  userId BINARY(16) NOT NULL,
  INDEX tokens_user_id(userId),
  email VARCHAR(256) NOT NULL,
  scope VARCHAR(256) NOT NULL,
  createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_unicode_ci;

-- Add expiresAt column for access tokens

ALTER TABLE tokens ADD COLUMN expiresAt TIMESTAMP NOT NULL DEFAULT "1980-01-01 00:00:00";
UPDATE tokens SET expiresAt = DATE_ADD(CURRENT_TIMESTAMP, INTERVAL 2 WEEK);

-- Add offline column to codes

ALTER TABLE codes ADD COLUMN offline BOOLEAN NOT NULL DEFAULT FALSE;

UPDATE dbMetadata SET value = '6' WHERE name = 'schema-patch-level';


CREATE VIEW {# geotrek.core #}.v_trails AS (
    SELECT core_topology.geom, core_topology.id, core_trail.*
    FROM core_trail, core_topology
    WHERE core_trail.topo_object_id = core_topology.id
    AND core_topology.deleted = FALSE
);

Add UUID to trails view

CREATE VIEW {# geotrek.core #}.v_trails AS (
    SELECT core_topology.geom, core_topology.id, core_topology.uuid, core_trail.*
    FROM core_trail, core_topology
    WHERE core_trail.topo_object_id = core_topology.id
    AND core_topology.deleted = FALSE
);


-- Select top 10 result in total

DELIMITER //
CREATE PROCEDURE GetGlobalTopTen ()
   BEGIN
      SELECT nickname, score
      FROM (Score
           JOIN Player ON Score.player = Player.playerId)
      ORDER BY score DESC
      LIMIT 10;
   END
//
DELIMITER ;

-- Select top 10 result for player

DELIMITER //
CREATE PROCEDURE GetPlayerTopTen (IN player VARCHAR(50))
   BEGIN
      SELECT nickname, score
      FROM
       (SELECT *
        FROM (Score
             JOIN Player ON Score.player = Player.playerId)) AS S
        WHERE S.player = player
        ORDER BY score DESC
        LIMIT 10;
   END
//
DELIMITER ;

Fix sql procedure to give better names.

-- Select top 10 result in total

DELIMITER //
CREATE PROCEDURE GetGlobalTopTen ()
   BEGIN
      SELECT nickname AS name, score
      FROM (Score
           JOIN Player ON Score.player = Player.playerId)
      ORDER BY score DESC
      LIMIT 10;
   END
//
DELIMITER ;

-- Select top 10 result for player

DELIMITER //
CREATE PROCEDURE GetPlayerTopTen (IN player VARCHAR(50))
   BEGIN
      SELECT nickname AS name, score
      FROM
       (SELECT *
        FROM (Score
             JOIN Player ON Score.player = Player.playerId)) AS S
        WHERE S.player = player
        ORDER BY score DESC
        LIMIT 10;
   END
//
DELIMITER ;


--
-- Telefónica Digital - Product Development and Innovation
--
-- THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
-- EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
--
-- Copyright (c) Telefónica Investigación y Desarrollo S.A.U.
-- All rights reserved.
--

# Support multiple authentication backends

# --- !Ups
DROP INDEX `tu_id_UNIQUE` ON `user`;
ALTER TABLE `user` ADD `auth_realm` VARCHAR(45) NOT NULL DEFAULT 'default';
ALTER TABLE `user` CHANGE `user_id` `auth_id` VARCHAR(45) NOT NULL;
ALTER TABLE `user` ADD UNIQUE `auth_UNIQUE` (`auth_realm` ASC, `auth_id` ASC);
ALTER TABLE `user` ADD UNIQUE `handle_UNIQUE` (`handle` ASC);

# --- !Downs
DROP INDEX `auth_UNIQUE` ON `user`;
ALTER TABLE `user` DROP COLUMN `auth_realm`;
ALTER TABLE `user` CHANGE `auth_id` `user_id` VARCHAR(45) NULL;
CREATE INDEX `tu_id_UNIQUE` on `user` (`user_id` ASC);

Improve back-compatibility of database evolutions

--
-- Telefónica Digital - Product Development and Innovation
--
-- THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
-- EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
--
-- Copyright (c) Telefónica Investigación y Desarrollo S.A.U.
-- All rights reserved.
--

# Support multiple authentication backends

# --- !Ups
DROP INDEX `tu_id_UNIQUE` ON `user`;
ALTER TABLE `user` ADD `auth_realm` VARCHAR(45) NOT NULL DEFAULT 'tuid';
ALTER TABLE `user` CHANGE `user_id` `auth_id` VARCHAR(45) NOT NULL;
ALTER TABLE `user` ADD UNIQUE `auth_UNIQUE` (`auth_realm` ASC, `auth_id` ASC);
ALTER TABLE `user` ADD UNIQUE `handle_UNIQUE` (`handle` ASC);

# --- !Downs
DROP INDEX `auth_UNIQUE` ON `user`;
ALTER TABLE `user` DROP COLUMN `auth_realm`;
ALTER TABLE `user` CHANGE `auth_id` `user_id` VARCHAR(45) NULL;
CREATE INDEX `tu_id_UNIQUE` on `user` (`user_id` ASC);


ALTER TABLE cluster
	ADD COLUMN zone VARCHAR(50) NOT NULL;

CREATE INDEX cluster_zone_idx
	ON cluster (zone(767));

Fix cluster zone index syntax error

ALTER TABLE cluster
	ADD COLUMN zone VARCHAR(50) NOT NULL;

CREATE INDEX cluster_zone_idx
	ON cluster (zone ASC);


R"**(
BEGIN TRANSACTION;
    ALTER TABLE trans
        ADD comment TEXT DEFAULT "";
    UPDATE config
        SET value = "1.2"
        WHERE key = 'version';
COMMIT;
)**"

Use single-quotes around string literals used in SQL statements

R"**(
BEGIN TRANSACTION;
    ALTER TABLE trans
        ADD comment TEXT DEFAULT '';
    UPDATE config
        SET value = '1.2'
        WHERE key = 'version';
COMMIT;
)**"


update xcolab_StaffMember set role="CCI Associate Director" where id_=149;
update xcolab_StaffMember set role="Project Manager" where id_=150;
update xcolab_StaffMember set categoryId=8, role="" where id_=155;
update xcolab_StaffMember set userId=1003305, photoUrl="" where id_=159;
update xcolab_StaffMember set photoUrl="https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-frc3/v/t1.0-9/559760_529631463785266_1319441340_n.jpg?oh=888f25bc1e9033c472058ca30bee0534&oe=550F9D89&__gda__=1426450045_30abccd54194dc9bd928c74a12dca7fe" where id_=161;
delete from xcolab_StaffMember where id_ = 317;
insert into xcolab_StaffMember (id_,userID, categoryId, firstNames, lastName, url, photoUrl, role, organization, sort) values(317, 1947856, 5,"","","","", "Software Engineer","", 9);

Change Robs position to Project Advisor.

update xcolab_StaffMember set role="Project Advisor" where id_=149;
update xcolab_StaffMember set role="Project Manager" where id_=150;
update xcolab_StaffMember set categoryId=8, role="" where id_=155;
update xcolab_StaffMember set userId=1003305, photoUrl="" where id_=159;
update xcolab_StaffMember set photoUrl="https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-frc3/v/t1.0-9/559760_529631463785266_1319441340_n.jpg?oh=888f25bc1e9033c472058ca30bee0534&oe=550F9D89&__gda__=1426450045_30abccd54194dc9bd928c74a12dca7fe" where id_=161;
delete from xcolab_StaffMember where id_ = 317;
insert into xcolab_StaffMember (id_,userID, categoryId, firstNames, lastName, url, photoUrl, role, organization, sort) values(317, 1947856, 5,"","","","", "Software Engineer","", 9);


insert into annotation(id,api,name,usage) values(-1,'Lang', 'Override','Ensure method overrides superclass method');
insert into annotation(id,api,name,usage) values(-2,'JSF', 'EJB',  'Request injection of EJB proxy into JSF bean');
insert into annotation(id,api,name,usage) values(-3,'EJB', 'Stateless',  'Define class as Stateless Session Bean (SLSB)');

Put @ on annotation names.

insert into annotation(id,api,name,usage) values(-1,'Lang', '@Override','Ensure method overrides superclass method');
insert into annotation(id,api,name,usage) values(-2,'JSF', '@EJB',  'Request injection of EJB proxy into JSF bean');
insert into annotation(id,api,name,usage) values(-3,'EJB', '@Stateless',  'Define class as Stateless Session Bean (SLSB)');


\set ECHO none
SET search_path TO provsql_test, provsql;

CREATE TABLE test(id varchar PRIMARY KEY, v integer);

INSERT INTO test(id,v) VALUES
	('hello',4),
	('hi',8);

SELECT add_provenance('test');
SELECT set_prob(provenance(), 0.2) from test where id = 'hello' \g ;
SELECT set_prob(provenance(), 0.3) from test where id = 'hi' \g ;

SELECT dump_data();
SELECT set_prob(provenance(), 0.4) from test where id = 'hello' \g ;

SELECT read_data_dump();

CREATE TABLE result AS SELECT get_prob(provenance()) FROM test;
SELECT remove_provenance('result');
SELECT * FROM result;
DROP TABLE result;
DROP TABLE test;

Change test to use anonymous code block instead of redirection to file

\set ECHO none
SET search_path TO provsql_test, provsql;

CREATE TABLE test(id varchar PRIMARY KEY, v integer);

INSERT INTO test(id,v) VALUES
	('hello',4),
	('hi',8);

SELECT add_provenance('test');

do $$begin
PERFORM set_prob(provenance(), 0.2) from test where id = 'hello';
PERFORM set_prob(provenance(), 0.3) from test where id = 'hi';
end $$;

SELECT dump_data();
do $$ begin
PERFORM set_prob(provenance(), 0.4) from test where id = 'hello';
end $$;

SELECT read_data_dump();

CREATE TABLE result AS SELECT get_prob(provenance()) FROM test;
SELECT remove_provenance('result');
SELECT * FROM result;
DROP TABLE result;
DROP TABLE test;


/* Copyright 2019 The Matrix.org Foundation C.I.C.
 *
 * 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.
 */

-- Start a background job to cleanup extremities that were incorrectly added
-- by bug #5269.
INSERT INTO background_updates (update_name, progress_json) VALUES
  ('delete_soft_failed_extremities', '{}');

DROP TABLE IF EXISTS _extremities_to_check;  -- To make this delta schema file idempotent.
CREATE TABLE _extremities_to_check AS SELECT event_id FROM event_forward_extremities;

Add index to temp table

/* Copyright 2019 The Matrix.org Foundation C.I.C.
 *
 * 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.
 */

-- Start a background job to cleanup extremities that were incorrectly added
-- by bug #5269.
INSERT INTO background_updates (update_name, progress_json) VALUES
  ('delete_soft_failed_extremities', '{}');

DROP TABLE IF EXISTS _extremities_to_check;  -- To make this delta schema file idempotent.
CREATE TABLE _extremities_to_check AS SELECT event_id FROM event_forward_extremities;
CREATE INDEX _extremities_to_check_id ON _extremities_to_check(event_id);


ALTER TABLE ACCOUNT ADD COLUMN IMAGE VARCHAR(100);

Expand column COMMENT.ACTION to VARCHAR(20).

ALTER TABLE ACCOUNT ADD COLUMN IMAGE VARCHAR(100);

ALTER TABLE COMMENT ALTER COLUMN ACTION VARCHAR(20);
UPDATE COMMENT SET ACTION = 'close_comment'  WHERE ACTION = 'close';
UPDATE COMMENT SET ACTION = 'reopen_comment' WHERE ACTION = 'reopen';


--
-- RaiseActorError
--
--

if not exists ( select * from sys.procedures where name = 'RaiseActorError' )
    exec sp_executesql N'create procedure RaiseActorError as begin return 0; end;'
go

alter procedure RaiseActorError(
    @errorId varchar(100),
    @arg1 nvarchar(100) = null,
    @arg2 nvarchar(100) = null,
    @arg3 nvarchar(100) = null,
    @arg4 nvarchar(100) = null
)
as
begin

    declare @errorMessage nvarchar(400);

    set @errorMessage = N'' + @errorId;

    if ( @arg1 is not null )
        set @errorMessage = @errorMessage + N' ' + @arg1;

    if ( @arg2 is not null )
        set @errorMessage = @errorMessage + N' ' + @arg2;

    if ( @arg3 is not null )
        set @errorMessage = @errorMessage + N' ' + @arg3;

    if ( @arg4 is not null )
        set @errorMessage = @errorMessage + N' ' + @arg4;

    raiserror( @errorMessage, 16, 1 );
end;
go

-- eof

Fix encoding of SQL file

--
-- RaiseActorError
--
--

if not exists ( select * from sys.procedures where name = 'RaiseActorError' )
    exec sp_executesql N'create procedure RaiseActorError as begin return 0; end;'
go

alter procedure RaiseActorError(
    @errorId varchar(100),
    @arg1 nvarchar(100) = null,
    @arg2 nvarchar(100) = null,
    @arg3 nvarchar(100) = null,
    @arg4 nvarchar(100) = null
)
as
begin

    declare @errorMessage nvarchar(400);

    set @errorMessage = N'Æ' + @errorId;

    if ( @arg1 is not null )
        set @errorMessage = @errorMessage + N' Æ' + @arg1;

    if ( @arg2 is not null )
        set @errorMessage = @errorMessage + N' Æ' + @arg2;

    if ( @arg3 is not null )
        set @errorMessage = @errorMessage + N' Æ' + @arg3;

    if ( @arg4 is not null )
        set @errorMessage = @errorMessage + N' Æ' + @arg4;

    raiserror( @errorMessage, 16, 1 );
end;
go

-- eof


BEGIN;

CREATE TABLE "cache" (
  "identifier" VARCHAR(250) NOT NULL,
  "cache" VARCHAR(250) NOT NULL,
  "context" VARCHAR(150) NOT NULL,
  "created" INTEGER UNSIGNED NOT NULL,
  "lifetime" INTEGER UNSIGNED DEFAULT '0' NOT NULL,
  "content" TEXT,
  PRIMARY KEY ("identifier", "cache", "context")
);

CREATE TABLE "tags" (
  "identifier" VARCHAR(250) NOT NULL,
  "cache" VARCHAR(250) NOT NULL,
  "context" VARCHAR(150) NOT NULL,
  "tag" VARCHAR(250) NOT NULL
);
CREATE INDEX "identifier" ON "tags" ("identifier", "cache", "context");
CREATE INDEX "tag" ON "tags" ("tag");

COMMIT;

Increase max-length for cache entries in PdoBackend

BEGIN;

CREATE TABLE "cache" (
  "identifier" VARCHAR(250) NOT NULL,
  "cache" VARCHAR(250) NOT NULL,
  "context" VARCHAR(150) NOT NULL,
  "created" INTEGER UNSIGNED NOT NULL,
  "lifetime" INTEGER UNSIGNED DEFAULT '0' NOT NULL,
  "content" MEDIUMTEXT,
  PRIMARY KEY ("identifier", "cache", "context")
);

CREATE TABLE "tags" (
  "identifier" VARCHAR(250) NOT NULL,
  "cache" VARCHAR(250) NOT NULL,
  "context" VARCHAR(150) NOT NULL,
  "tag" VARCHAR(250) NOT NULL
);
CREATE INDEX "identifier" ON "tags" ("identifier", "cache", "context");
CREATE INDEX "tag" ON "tags" ("tag");

COMMIT;


INSERT INTO speakeasy_petition_metrics (activity, campaign_id, npeople)
  SELECT
    'unsub', campaign_id, sum(r.value)
  FROM civicrm_mailing m
  LEFT JOIN data_mailing_counter r ON r.mailing_id = m.id AND r.counter = 'unsubs' AND r.timebox = 144000
  GROUP BY campaign_id;

Read speakeasy unsub from 10d timebox

INSERT INTO speakeasy_petition_metrics (activity, campaign_id, npeople)
  SELECT
    'unsub', campaign_id, sum(r.value)
  FROM civicrm_mailing m
  LEFT JOIN data_mailing_counter r ON r.mailing_id = m.id AND r.counter = 'unsubs' AND r.timebox = 14400
  GROUP BY campaign_id;


# add a study_id column in the tables structural_variation and variation_annotation

ALTER TABLE structural_variation ADD COLUMN study_id int(10);
ALTER TABLE structural_variation ADD INDEX study_idx (study_id);

ALTER TABLE variation_annotation ADD COLUMN local_study_id int(10);
ALTER TABLE variation_annotation ADD INDEX local_study_idx (local_study_id);
ALTER TABLE variation_annotation DROP COLUMN local_stable_id;

# patch identifier
INSERT INTO meta (species_id, meta_key, meta_value) VALUES (NULL,'patch', 'patch_61_62_f.sql|add a study_id column in the tables structural_variation and variation_annotation');

Update the study table and the relative foreign keys in the variatiation_annotation table

# add a study_id column in the tables structural_variation and variation_annotation

ALTER TABLE structural_variation ADD COLUMN study_id int(10);
ALTER TABLE structural_variation ADD INDEX study_idx (study_id);

ALTER TABLE variation_annotation ADD COLUMN study_id int(10);
ALTER TABLE variation_annotation INDEX study_idx (study_id);
ALTER TABLE variation_annotation ADD COLUMN local_study_id int(10);
ALTER TABLE variation_annotation ADD INDEX local_study_idx (local_study_id);

ALTER TABLE variation_annotation DROP COLUMN local_stable_id;
ALTER TABLE variation_annotation DROP COLUMN study;
ALTER TABLE variation_annotation DROP COLUMN study_type;
ALTER TABLE variation_annotation DROP COLUMN source_id;

# patch identifier
INSERT INTO meta (species_id, meta_key, meta_value) VALUES (NULL,'patch', 'patch_61_62_f.sql|add a study_id column in the tables structural_variation and variation_annotation');


-- :name find-all-tasks :? :*
select id, description, done from todo

-- :name find-incomplete-tasks :? *
select id, description, done from todo where not done

Add query to complete task

-- :name find-all-tasks :? :*
select id, description, done from todo

-- :name find-incomplete-tasks :? *
select id, description, done from todo where not done

-- :name complete-task :! :n
update todo set done=true where id=:v:id


CREATE TABLE wcf1_packageserver_package_to_group (
	packageIdentifier VARCHAR(255),
	groupID INT(10),
	permissionString MEDIUMTEXT,
	PRIMARY KEY(packageIdentifier,groupID)
);

CREATE TABLE wcf1_packageserver_package_to_user (
	packageIdentifier VARCHAR(255),
	userID INT(10),
	permissionString MEDIUMTEXT,
	PRIMARY KEY(packageIdentifier,userID)
);

CREATE TABLE wcf1_packageserver_package_permission_general (
	packageIdentifier VARCHAR(255) PRIMARY KEY,
	permissionString MEDIUMTEXT
);

-- foreign keys
ALTER TABLE wcf1_packageserver_package_to_group ADD FOREIGN KEY (groupID) REFERENCES wcf1_user_group (groupID) ON DELETE CASCADE;
ALTER TABLE wcf1_packageserver_package_to_user ADD FOREIGN KEY (userID) REFERENCES wcf1_user (userID) ON DELETE CASCADE;

Add additional indicies to database tables

CREATE TABLE wcf1_packageserver_package_to_group (
	packageIdentifier VARCHAR(255),
	groupID INT(10),
	permissionString MEDIUMTEXT,
	PRIMARY KEY(packageIdentifier, groupID),
	KEY (groupID)
);

CREATE TABLE wcf1_packageserver_package_to_user (
	packageIdentifier VARCHAR(255),
	userID INT(10),
	permissionString MEDIUMTEXT,
	PRIMARY KEY(packageIdentifier, userID),
	KEY (userID)
);

CREATE TABLE wcf1_packageserver_package_permission_general (
	packageIdentifier VARCHAR(255) PRIMARY KEY,
	permissionString MEDIUMTEXT
);

-- foreign keys
ALTER TABLE wcf1_packageserver_package_to_group ADD FOREIGN KEY (groupID) REFERENCES wcf1_user_group (groupID) ON DELETE CASCADE;
ALTER TABLE wcf1_packageserver_package_to_user ADD FOREIGN KEY (userID) REFERENCES wcf1_user (userID) ON DELETE CASCADE;


CONNECT itwiki_p itwiki.labsdb;
SELECT CONCAT('# [[Template:', page_title, ']] -> [[', pl_title, ']]')
FROM pagelinks,
     page
WHERE page_namespace = 10
  AND page_id = pl_from
  AND pl_namespace = 0
  AND pl_title IN
    (SELECT page_title
     FROM pagelinks,
          page
     WHERE page_namespace = 0
       AND page_id = pl_from
       AND page_is_redirect = 1
       AND pl_title IN
         (SELECT page_title
          FROM page_props,
               page
          WHERE pp_page = page_id
            AND page_namespace = 0
            AND pp_propname = 'disambiguation')
     UNION SELECT page_title
     FROM page_props,
          page
     WHERE pp_page = page_id
       AND page_namespace = 0
       AND pp_propname = 'disambiguation')
  AND page_title NOT LIKE '%/man'
  AND page_title NOT LIKE '%/sandbox'
  AND page_title NOT LIKE '%/test'
  AND page_title NOT LIKE '%/esempi'
  AND page_title NOT LIKE '%/prove'
  AND page_title NOT LIKE 'Nota_disambigua%'
ORDER BY page_title;

Fix query to avoid some unwanted results

CONNECT itwiki_p itwiki.labsdb;
SELECT CONCAT('# [[Template:', page_title, ']] -> [[', pl_title, ']]')
FROM pagelinks,
     page
WHERE page_namespace = 10
  AND page_id = pl_from
  AND pl_namespace = 0
  AND pl_title IN
    (SELECT page_title
     FROM pagelinks,
          page
     WHERE page_namespace = 0
       AND page_id = pl_from
       AND page_is_redirect = 1
       AND pl_title IN
         (SELECT page_title
          FROM page_props,
               page
          WHERE pp_page = page_id
            AND page_namespace = 0
            AND pp_propname = 'disambiguation')
     UNION SELECT page_title
     FROM page_props,
          page
     WHERE pp_page = page_id
       AND page_namespace = 0
       AND pp_propname = 'disambiguation')
  AND page_title NOT LIKE '%/man'
  AND page_title NOT LIKE '%/man/%'
  AND page_title NOT REGEXP '[^/]*/(S|s)andbox'
  AND page_title NOT REGEXP '[^/]*/(T|t)est'
  AND page_title NOT REGEXP '[^/]*/(E|e)sempi'
  AND page_title NOT REGEXP '[^/]*/(P|p)rove'
  AND page_title NOT LIKE 'Nota_disambigua%'
ORDER BY page_title;


##version: 1.0.0
CREATE TABLE info (DB_SCHEMA_VERSION VARCHAR(8));
INSERT INTO info VALUES ("1.0.0");

##version: 1.1.0
CREATE TABLE sample_list LIKE patient_list;
INSERT sample_list SELECT * FROM patient_list;
CREATE TABLE sample_list_list LIKE patient_list_list;
INSERT sample_list_list SELECT * FROM patient_list_list;
DROP TABLE micro_rna;
DROP TABLE micro_rna_alteration;
DROP TABLE mutation_frequency;
ALTER TABLE sample_list_list CHANGE PATIENT_ID SAMPLE_ID INT(11);
INSERT INTO info VALUES ("1.1.0");

Update instead of adding new records to info table

##version: 1.0.0
CREATE TABLE info (DB_SCHEMA_VERSION VARCHAR(8));
INSERT INTO info VALUES ("1.0.0");

##version: 1.1.0
CREATE TABLE sample_list LIKE patient_list;
INSERT sample_list SELECT * FROM patient_list;
CREATE TABLE sample_list_list LIKE patient_list_list;
INSERT sample_list_list SELECT * FROM patient_list_list;
DROP TABLE micro_rna;
DROP TABLE micro_rna_alteration;
DROP TABLE mutation_frequency;
ALTER TABLE sample_list_list CHANGE PATIENT_ID SAMPLE_ID INT(11);
UPDATE info SET DB_SCHEMA_VERSION="1.1.0";


-- Put upgrade SQL here
CREATE TABLE _auth_verify_code (
    id text PRIMARY KEY,
    user_id text NOT NULL REFERENCES app_next._core_user(id),
    record_key text NOT NULL,
    record_value text NOT NULL,
    code text NOT NULL,
    consumed boolean NOT NULL DEFAULT false,
    created_at timestamp without time zone NOT NULL
);

Remove schema name "app_next" in migration script

-- Put upgrade SQL here
CREATE TABLE _auth_verify_code (
    id text PRIMARY KEY,
    user_id text NOT NULL REFERENCES _core_user(id),
    record_key text NOT NULL,
    record_value text NOT NULL,
    code text NOT NULL,
    consumed boolean NOT NULL DEFAULT false,
    created_at timestamp without time zone NOT NULL
);


CREATE TABLE Countries(
	Name VARCHAR(30) CLUSTERED PRIMARY KEY
);

CREATE TABLE Persons(
	Name VARCHAR(30) CLUSTERED PRIMARY KEY,
	Country VARCHAR(30),
	FOREIGN KEY Country REFERENCES(Countries)
);

CREATE TABLE Organizations(
	SID VARCHAR(10) CLUSTERED PRIMARY KEY,
	Name VARCHAR(30) NOT NULL,
	Icon VARCHAR(100),/* can be saved locally or as URL to RSI */
);

CREATE TABLE OrgsInCog(
	SID VARCHAR(10) CLUSTERED NOT NULL,
	Representative VARCHAR(30) NOT NULL,
	FOREIGN KEY SID REFERENCES(Organizations),
	FOREIGN KEY Representative REFERENCES(Persons)
);

Edit SQL statements to correct syntax

CREATE TABLE tbl_Countries(
	Name VARCHAR(30) PRIMARY KEY ENGINE=NDBCLUSTER
);

CREATE TABLE tbl_Persons(
	Name VARCHAR(30) CLUSTERED PRIMARY KEY,
	Country VARCHAR(30),
	FOREIGN KEY Country REFERENCES(Countries)
);

CREATE TABLE tbl_Organizations(
	SID VARCHAR(10) CLUSTERED PRIMARY KEY,
	Name VARCHAR(30) NOT NULL,
	Icon VARCHAR(100),/* can be saved locally or as URL to RSI */
);

CREATE TABLE tbl_OrgsInCog(
	SID VARCHAR(10) CLUSTERED NOT NULL,
	Representative VARCHAR(30) NOT NULL,
	FOREIGN KEY SID REFERENCES(Organizations),
	FOREIGN KEY Representative REFERENCES(Persons)
);


select
	Blog_Article.ID,
	Blog.ID as ID_Blog,
	Blog_User.ID as ID_User,
	Blog_User.username,
	Blog_User.firstName,
	Blog_User.lastName,
	title,
	content,
	coverImageUrl,
	dateTimeCreated,
	dateTimePublished,
	dateTimeFeatured,
	dateTimeUnfeatured,
	count(Blog_Article_Comment) as commentCount
from
	Blog_Article

inner join Blog
on
	Blog_Article.FK_Blog = Blog.ID

inner join Blog_User
on
	Blog_Article.FK_Blog_User__author = Blog_User.ID

where
	Blog.name = :name_Blog
and
	dateTimeDeleted is null

limit :Limit

Add table names to all fields.

select
	Blog_Article.ID,
	Blog.ID as ID_Blog,
	Blog_User.ID as ID_User,
	Blog_User.username,
	Blog_User.firstName,
	Blog_User.lastName,
	Blog_Article.title,
	Blog_Article.content,
	Blog_Article.coverImageUrl,
	Blog_Article.dateTimeCreated,
	Blog_Article.dateTimePublished,
	Blog_Article.dateTimeFeatured,
	Blog_Article.dateTimeUnfeatured,
	count(Blog_Article_Comment.ID) as commentCount
from
	Blog_Article

inner join Blog
on
	Blog_Article.FK_Blog = Blog.ID

inner join Blog_User
on
	Blog_Article.FK_Blog_User__author = Blog_User.ID

-- Left join because there may not necessarily be any comments.
left join Blog_Article_Comment
on
	Blog_Article.ID = Blog_Article_Comment.FK_Blog_Article

where
	Blog.name = :name_Blog
and
	dateTimeDeleted is null

-- We group on the comment's ID field so that the count() function doesn't
-- force an empty row on an empty result.
group by Blog_Article_Comment.ID

limit :Limit


CREATE TABLE IF NOT EXISTS ip_storage (
    ip CIDR PRIMARY KEY,
    country_code TEXT CHECK (char_length(country_code) = 2),

    accessed BIGINT DEFAULT 1,
    last_updated TIMESTAMP DEFAULT now()
);

Fix for places with no origin

CREATE TABLE IF NOT EXISTS ip_storage (
    ip CIDR PRIMARY KEY,
    country_code TEXT CHECK (char_length(country_code) <= 2),

    accessed BIGINT DEFAULT 1,
    last_updated TIMESTAMP DEFAULT now()
);