-- UPDATE SCRIOT FOR CLIENT SCHEMA
-- This script will set any null UpdateTimes to now
-- and then explicitly set the UpdateTimes of
-- future rows to update

UPDATE JobRecords SET UpdateTime = CURRENT_TIMESTAMP WHERE UpdateTime IS NULL;
ALTER TABLE JobRecords MODIFY COLUMN UpdateTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

UPDATE SuperSummaries SET UpdateTime = CURRENT_TIMESTAMP WHERE UpdateTime IS NULL;
ALTER TABLE SuperSummaries MODIFY COLUMN UpdateTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

UPDATE LastUpdated SET UpdateTime = CURRENT_TIMESTAMP WHERE UpdateTime IS NULL;
ALTER TABLE LastUpdated MODIFY COLUMN UpdateTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

Fix a typo in comment

-- UPDATE SCRIPT FOR CLIENT SCHEMA
-- This script will set any null UpdateTimes to now
-- and then explicitly set the UpdateTimes of
-- future rows to update

UPDATE JobRecords SET UpdateTime = CURRENT_TIMESTAMP WHERE UpdateTime IS NULL;
ALTER TABLE JobRecords MODIFY COLUMN UpdateTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

UPDATE SuperSummaries SET UpdateTime = CURRENT_TIMESTAMP WHERE UpdateTime IS NULL;
ALTER TABLE SuperSummaries MODIFY COLUMN UpdateTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

UPDATE LastUpdated SET UpdateTime = CURRENT_TIMESTAMP WHERE UpdateTime IS NULL;
ALTER TABLE LastUpdated MODIFY COLUMN UpdateTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;


--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_client UPDATE TO '0.3.0'" to load this file. \quit
DROP FUNCTION IF EXISTS cdb_dataservices_client._obs_get_demographic_snapshot (text, text, geometry(Geometry, 4326), text, text)
DROP FUNCTION IF EXISTS cdb_dataservices_client._obs_get_segment_snapshot (text, text, geometry(Geometry, 4326), text)
DROP FUNCTION IF EXISTS cdb_dataservices_client.obs_get_demographic_snapshot (geometry(Geometry, 4326), text, text)
DROP FUNCTION IF EXISTS cdb_dataservices_client.obs_get_segment_snapshot (geometry(Geometry, 4326), text)

Fix client downgrade script problem

--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_client UPDATE TO '0.3.0'" to load this file. \quit
DROP FUNCTION IF EXISTS cdb_dataservices_client._obs_get_demographic_snapshot (text, text, geometry(Geometry, 4326), text, text);
DROP FUNCTION IF EXISTS cdb_dataservices_client._obs_get_segment_snapshot (text, text, geometry(Geometry, 4326), text);
DROP FUNCTION IF EXISTS cdb_dataservices_client.obs_get_demographic_snapshot (geometry(Geometry, 4326), text, text);
DROP FUNCTION IF EXISTS cdb_dataservices_client.obs_get_segment_snapshot (geometry(Geometry, 4326), text);


CREATE TABLE IF NOT EXISTS search_count (id64 BIGINT UNSIGNED, ip VARCHAR(200));

CREATE TABLE IF NOT EXISTS profile_cache (id64 BIGINT UNSIGNED PRIMARY KEY, vanity TEXT, profile BLOB, timestamp INTEGER);

CREATE TABLE IF NOT EXISTS unique_views (id64 BIGINT UNSIGNED PRIMARY KEY, count INTEGER UNSIGNED DEFAULT 1, persona TEXT, valve BOOLEAN);

CREATE TABLE IF NOT EXISTS items (id64 BIGINT UNSIGNED PRIMARY KEY,
                                  oid64 BIGINT UNSIGNED,
                                  owner BIGINT UNSIGNED,
                                  sid INTEGER UNSIGNED,
                                  level INTEGER UNSIGNED,
                                  untradeable BOOLEAN,
                                  token INTEGER UNSIGNED,
                                  quality TINYINT UNSIGNED,
                                  custom_name TEXT,
                                  custom_desc TEXT,
                                  style TINYINT UNSIGNED,
                                  attributes BLOB,
                                  quantity INTEGER UNSIGNED DEFAULT 1);

CREATE TABLE IF NOT EXISTS backpacks (id64 BIGINT UNSIGNED, backpack BLOB, timestamp INTEGER UNSIGNED);

CREATE TABLE IF NOT EXISTS sessions (session_id CHAR(128) UNIQUE NOT NULL, atime timestamp NOT NULL default current_timestamp, data TEXT);

Create an index in the backpacks table during creation

CREATE TABLE IF NOT EXISTS search_count (id64 BIGINT UNSIGNED, ip VARCHAR(200));

CREATE TABLE IF NOT EXISTS profile_cache (id64 BIGINT UNSIGNED PRIMARY KEY, vanity TEXT, profile BLOB, timestamp INTEGER);

CREATE TABLE IF NOT EXISTS unique_views (id64 BIGINT UNSIGNED PRIMARY KEY, count INTEGER UNSIGNED DEFAULT 1, persona TEXT, valve BOOLEAN);

CREATE TABLE IF NOT EXISTS items (id64 BIGINT UNSIGNED PRIMARY KEY,
                                  oid64 BIGINT UNSIGNED,
                                  owner BIGINT UNSIGNED,
                                  sid INTEGER UNSIGNED,
                                  level INTEGER UNSIGNED,
                                  untradeable BOOLEAN,
                                  token INTEGER UNSIGNED,
                                  quality TINYINT UNSIGNED,
                                  custom_name TEXT,
                                  custom_desc TEXT,
                                  style TINYINT UNSIGNED,
                                  attributes BLOB,
                                  quantity INTEGER UNSIGNED DEFAULT 1);

CREATE TABLE IF NOT EXISTS backpacks (id64 BIGINT UNSIGNED, backpack BLOB, timestamp INTEGER UNSIGNED, INDEX (id64, timestamp));

CREATE TABLE IF NOT EXISTS sessions (session_id CHAR(128) UNIQUE NOT NULL, atime timestamp NOT NULL default current_timestamp, data TEXT);


drop table if exists :tablename;

create table :tablename as
select distinct
  xref.upi
from xref
left join rnc_rna_precomputed pre
on
  pre.upi = xref.upi
  and pre.taxid = xref.taxid
where
  pre.id is null
  or xref.last > pre.last_release
;

alter table :tablename
  add constraint fk_to_precompute__upi FOREIGN KEY (upi) REFERENCES rna(upi),
  add column id bigserial primary key
;

Handle case where last_release is null

drop table if exists :tablename;

create table :tablename as
select distinct
  xref.upi
from xref
left join rnc_rna_precomputed pre
on
  pre.upi = xref.upi
  and pre.taxid = xref.taxid
where
  pre.id is null
  or xref.last > pre.last_release
  or pre.last_release is null
;

alter table :tablename
  add constraint fk_to_precompute__upi FOREIGN KEY (upi) REFERENCES rna(upi),
  add column id bigserial primary key
;


CREATE OR REPLACE FUNCTION public.column_names(namespace name, "table" name)
	RETURNS SETOF name
AS $$
	SELECT a.attname
	FROM pg_catalog.pg_class c
	JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
	JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid
	WHERE
		n.nspname = $1 AND
		c.relname = $2 AND
		a.attisdropped = false AND
		a.attnum > 0;
$$ LANGUAGE SQL STABLE;

CREATE OR REPLACE FUNCTION public.fst(anyelement, anyelement)
	RETURNS anyelement
AS $$
	SELECT $1;
$$ LANGUAGE SQL IMMUTABLE STRICT;

CREATE OR REPLACE FUNCTION public.snd(anyelement, anyelement)
	RETURNS anyelement
AS $$
	SELECT $2;
$$ LANGUAGE SQL IMMUTABLE STRICT;

Add function to parse WAL location.

CREATE OR REPLACE FUNCTION public.column_names(namespace name, "table" name)
	RETURNS SETOF name
AS $$
	SELECT a.attname
	FROM pg_catalog.pg_class c
	JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
	JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid
	WHERE
		n.nspname = $1 AND
		c.relname = $2 AND
		a.attisdropped = false AND
		a.attnum > 0;
$$ LANGUAGE SQL STABLE;

CREATE OR REPLACE FUNCTION public.fst(anyelement, anyelement)
	RETURNS anyelement
AS $$
	SELECT $1;
$$ LANGUAGE SQL IMMUTABLE STRICT;

CREATE OR REPLACE FUNCTION public.snd(anyelement, anyelement)
	RETURNS anyelement
AS $$
	SELECT $2;
$$ LANGUAGE SQL IMMUTABLE STRICT;

CREATE OR REPLACE FUNCTION public.wal_location_to_int(text)
	RETURNS bigint
AS $$
	SELECT ('x' || lpad((regexp_split_to_array($1, '/'))[1] || lpad((regexp_split_to_array($1, '/'))[2], 8, '0'), 16, '0'))::bit(64)::bigint;
$$ LANGUAGE SQL IMMUTABLE STRICT;

COMMENT ON FUNCTION public.wal_location_to_int(text) IS
'Convert a textual WAL location in the form of ''1752F/CDC6E050'' into a bigint.
Use this function to monitor slave delay on the master:

SELECT
  client_addr,
  (public.wal_location_to_int(pg_current_xlog_location()) - public.wal_location_to_int(replay_location)) / 2^20 AS distance_mb
FROM pg_stat_replication;';


CREATE DATABASE notes;

USE notes;

CREATE TABLE note_users (
    UserId VARCHAR(60) PRIMARY KEY,
    UserEmail VARCHAR(255),
    UserPassword VARCHAR(512),
    TagColor VARCHAR(6) DEFAULT 'red'
);

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

Add field for email confirmation

CREATE DATABASE notes;

USE notes;

CREATE TABLE note_users (
    UserId VARCHAR(60) PRIMARY KEY,
    UserEmail VARCHAR(255),
    UserPassword VARCHAR(512),
    TagColor VARCHAR(6) DEFAULT 'red',
    EmailConfirmation VARCHAR(20)
);

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


-- $Header$

DROP TABLE pgpool_catalog.insert_lock;

CREATE SCHEMA pgpool_catalog;
CREATE TABLE pgpool_catalog.insert_lock(reloid OID PRIMARY KEY);

-- this row is used as the row lock target when pgpool inserts new oid
INSERT INTO pgpool_catalog.insert_lock VALUES (0);

-- allow "SELECT ... FOR UPDATE" and "INSERT ..." to all roles
GRANT SELECT ON pgpool_catalog.insert_lock TO PUBLIC;
GRANT UPDATE ON pgpool_catalog.insert_lock TO PUBLIC;
GRANT INSERT ON pgpool_catalog.insert_lock TO PUBLIC;

Fix that the script forgets to allow public access to pgpool_catalog.

-- Create lock control table for tables using sequence in native replication mode.

DROP TABLE pgpool_catalog.insert_lock;

CREATE SCHEMA pgpool_catalog;
CREATE TABLE pgpool_catalog.insert_lock(reloid OID PRIMARY KEY);

-- this row is used as the row lock target when pgpool inserts new oid
INSERT INTO pgpool_catalog.insert_lock VALUES (0);

-- allow "SELECT ... FOR UPDATE" and "INSERT ..." to all roles
GRANT USAGE ON SCHEMA pgpool_catalog TO PUBLIC;
GRANT SELECT ON pgpool_catalog.insert_lock TO PUBLIC;
GRANT UPDATE ON pgpool_catalog.insert_lock TO PUBLIC;
GRANT INSERT ON pgpool_catalog.insert_lock TO PUBLIC;


CREATE OR REPLACE FUNCTION CDB_QueryTables_Updated_At(query text)
    RETURNS TABLE(dbname text, schema_name text, table_name text, updated_at timestamptz)
AS $$
    SELECT
    'analysis_api_test_db'::text,
    'public'::text,
    CASE WHEN position('atm_machines' in query) > 0 THEN 'atm_machines'::text
         WHEN position('multiple_tables' in query) > 0 THEN unnest(ARRAY['table_a', 'table_b']::text[])
         ELSE 'fixture_table_name'::text
    END,
    CASE WHEN position('nulltime' in query) > 0
        THEN null::timestamptz
        ELSE '2016-07-01 11:40:05.699712+00'::timestamptz
    END
$$ LANGUAGE SQL;

Fix tests for PostgreSQL 10

CREATE OR REPLACE FUNCTION CDB_QueryTables_Updated_At(query text)
    RETURNS TABLE(dbname text, schema_name text, table_name text, updated_at timestamptz)
AS
$BODY$
DECLARE
    db_name text;
    schema_name text;
    table_name text[];
    updated_at timestamptz;
BEGIN
    db_name := 'analysis_api_test_db';
    schema_name := 'public';

    IF position('atm_machines' in query) > 0 THEN
        table_name := ARRAY['atm_machines']::text[];
    ELSIF position('multiple_tables' in query) > 0 THEN
        table_name := ARRAY['table_a', 'table_b']::text[];
    ELSE
        table_name := ARRAY['fixture_table_name']::text[];
    END IF;

    IF position('nulltime' in query) > 0 THEN
        updated_at := null::timestamptz;
    ELSE
        updated_at := '2016-07-01 11:40:05.699712+00'::timestamptz;
    END IF;

    RETURN QUERY EXECUTE 'SELECT $1, $2, unnest($3), $4' USING db_name, schema_name, table_name, updated_at;
END
$BODY$ LANGUAGE plpgsql;


-- 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(); -- replaced by:
CREATE OR REPLACE FUNCTION CDB_UserTables(perm text DEFAULT 'all')
RETURNS SETOF information_schema.sql_identifier
AS $$
  WITH usertables AS (
    SELECT table_name as t
    FROM information_schema.tables
    WHERE
         table_type='BASE TABLE'
     AND table_schema='public'
     AND table_name NOT IN (
      'cdb_tablemetadata',
      'spatial_ref_sys'
     )
  ), perms AS (
    SELECT t, has_table_privilege('publicuser', 'public.'||t, 'SELECT') as p
    FROM usertables
  )
  SELECT t FROM perms
  WHERE p = CASE WHEN $1 = 'private' THEN false
                 WHEN $1 = 'public' THEN true
                 ELSE not p -- none
            END
    OR $1 = 'all'
   ;
$$ LANGUAGE 'sql';

-- This is a private function, so only the db owner need privileges
REVOKE ALL ON FUNCTION CDB_UserTables(text) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION CDB_UserTables(text) TO :DATABASE_USERNAME;

Add TODO item about using CDB_TableMetadata

-- 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(); -- replaced by:
CREATE OR REPLACE FUNCTION CDB_UserTables(perm text DEFAULT 'all')
RETURNS SETOF information_schema.sql_identifier
AS $$
  WITH usertables AS (
    -- TODO: query CDB_TableMetadata for this ?
    -- See http://github.com/CartoDB/cartodb/issues/254#issuecomment-26044777
    SELECT table_name as t
    FROM information_schema.tables
    WHERE
         table_type='BASE TABLE'
     AND table_schema='public'
     AND table_name NOT IN (
      'cdb_tablemetadata',
      'spatial_ref_sys'
     )
  ), perms AS (
    SELECT t, has_table_privilege('publicuser', 'public.'||t, 'SELECT') as p
    FROM usertables
  )
  SELECT t FROM perms
  WHERE p = CASE WHEN $1 = 'private' THEN false
                 WHEN $1 = 'public' THEN true
                 ELSE not p -- none
            END
    OR $1 = 'all'
   ;
$$ LANGUAGE 'sql';

-- This is a private function, so only the db owner need privileges
REVOKE ALL ON FUNCTION CDB_UserTables(text) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION CDB_UserTables(text) TO :DATABASE_USERNAME;


CREATE TABLE [dbo].ApprenticeshipFlexibleEmployment
(
	[ApprenticeshipId] BIGINT NOT NULL,
	[EmploymentPrice] INT NOT NULL,
	[EmploymentEndDate] DATETIME2 NOT NULL,
    CONSTRAINT [PK_FlexibleEmployment] PRIMARY KEY ([ApprenticeshipId])
)
GO

Make flexible employment fields nullable in database

CREATE TABLE [dbo].ApprenticeshipFlexibleEmployment
(
	[ApprenticeshipId] BIGINT NOT NULL,
	[EmploymentPrice] INT NULL,
	[EmploymentEndDate] DATETIME2 NULL,
    CONSTRAINT [PK_FlexibleEmployment] PRIMARY KEY ([ApprenticeshipId])
)
GO


GRANT ALL PRIVILEGES ON DATABASE cumulus TO cumulus;
SET client_encoding = 'UTF8';

CREATE TABLE feeds (
    id integer NOT NULL,
    url text NOT NULL,
    title text NOT NULL,
    timedate timestamp NOT NULL,
    author integer NOT NULL
);

CREATE TABLE feeds_tags (
    id integer NOT NULL,
    tag text NOT NULL,
    id_feed integer NOT NULL
);

CREATE TABLE users (
  id integer NOT NULL,
  name text NOT NULL,
  password text NOT NULL,
  email text NOT NULL
);

CREATE SEQUENCE users_id_seq;
CREATE SEQUENCE feeds_id_seq;
CREATE SEQUENCE feeds_tags_id_seq;

Add is_admin (cc jpdeplaix) for 500 internal error

GRANT ALL PRIVILEGES ON DATABASE cumulus TO cumulus;
SET client_encoding = 'UTF8';

CREATE TABLE feeds (
    id integer NOT NULL,
    url text NOT NULL,
    title text NOT NULL,
    timedate timestamp NOT NULL,
    author integer NOT NULL
);

CREATE TABLE feeds_tags (
    id integer NOT NULL,
    tag text NOT NULL,
    id_feed integer NOT NULL
);

CREATE TABLE users (
  id integer NOT NULL,
  name text NOT NULL,
  password text NOT NULL,
  email text NOT NULL,
  is_admin boolean NOT NULL DEFAULT(false)
);

CREATE SEQUENCE users_id_seq;
CREATE SEQUENCE feeds_id_seq;
CREATE SEQUENCE feeds_tags_id_seq;


CREATE DATABASE notes;

USE notes;

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

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

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

Add ColorTheme column for the user to save their chosen theme

CREATE DATABASE notes;

USE notes;

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

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

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


CREATE VIRTUAL TABLE documents using fts4(title,text,from,to,date,tags,tokenize=porter);

Split date column into year and month

CREATE VIRTUAL TABLE documents USING fts4(id,title,scanned_text,sender,recipients,year,month,tags,tokenize=porter);


-- Table: languages
insert into languages values (1,'es','ES',null);
insert into languages values (2,'en','UK',null);
insert into languages values (3,'en','US',null);

-- Table: users
insert into users values (1,'admin','$2a$10$fdCTnC8xIL5HhvFKJIGDiecG91buB6Lj9IB/US2xqxFiKhCcMCXBq', true, 1);
insert into users values (2,'user','$2a$10$4qzMEbvFWnBPqxWLzFLGs.Mir//KKkvoorx6g47ogxxxpprvxMnse', true, 2);
insert into users values (3,'disabled','$2a$10$W/D92o1yKHHkOvWsLo50jeNOPT2bCaZq3H3V.4gZ1B4.4ROyvSIjm', false, 3);

-- Table: authorities
insert into authorities values (1,'admin','ROLE_ADMIN');
insert into authorities values (2,'user','ROLE_USER');
insert into authorities values (3,'disabled','ROLE_ADMIN');

Fix broken tests - a previous commit removed a user referenced in some tests

-- Table: languages
insert into languages values (1,'es','ES',null);
insert into languages values (2,'en','UK',null);
insert into languages values (3,'en','US',null);

-- Table: users
insert into users values (1,'admin','$2a$10$fdCTnC8xIL5HhvFKJIGDiecG91buB6Lj9IB/US2xqxFiKhCcMCXBq', true, 1);
insert into users values (2,'user','$2a$10$4qzMEbvFWnBPqxWLzFLGs.Mir//KKkvoorx6g47ogxxxpprvxMnse', true, 2);
insert into users values (3,'disabled','$2a$10$W/D92o1yKHHkOvWsLo50jeNOPT2bCaZq3H3V.4gZ1B4.4ROyvSIjm', false, 3);
insert into users values (4,'test','test', true, 1);

-- Table: authorities
insert into authorities values (1,'admin','ROLE_ADMIN');
insert into authorities values (2,'user','ROLE_USER');
insert into authorities values (3,'disabled','ROLE_ADMIN');


CREATE INDEX events_instance_id_started_at_desc_idx ON events USING btree(instance_id, started_at DESC);

CREATE INDEX jobs_instance_id_idx ON jobs USING btree(instance_id);
CREATE INDEX jobs_busy_instance_id_idx ON jobs USING btree(instance_id) WHERE claimed_at IS NOT NULL AND finished_at IS NULL;
CREATE INDEX jobs_queue_order_idx ON jobs USING btree((-1 * priority), scheduled_at, submitted_at) WHERE finished_at IS NULL AND claimed_at IS NULL;
CREATE INDEX jobs_instance_id_unfinished_idx ON jobs USING btree(instance_id) WHERE finished_at IS NULL;

Add minor comment to indexes

-- Optimise per-instance history queries
CREATE INDEX events_instance_id_started_at_desc_idx ON events USING btree(instance_id, started_at DESC);

-- These optimise queries performed by flux 0.3.x
CREATE INDEX jobs_instance_id_idx ON jobs USING btree(instance_id);
CREATE INDEX jobs_busy_instance_id_idx ON jobs USING btree(instance_id) WHERE claimed_at IS NOT NULL AND finished_at IS NULL;
CREATE INDEX jobs_queue_order_idx ON jobs USING btree((-1 * priority), scheduled_at, submitted_at) WHERE finished_at IS NULL AND claimed_at IS NULL;
CREATE INDEX jobs_instance_id_unfinished_idx ON jobs USING btree(instance_id) WHERE finished_at IS NULL;


-- **********************************************************
-- *                                                        *
-- * IMPORTANT NOTE                                         *
-- *                                                        *
-- * Do not import this file manually but use the TYPOlight *
-- * install tool to create and maintain database tables!   *
-- *                                                        *
-- **********************************************************

--
-- Table `tl_content`
--

CREATE TABLE `tl_content` (
  `navigation_article` varchar(10) NOT NULL default '',
  `navigation_min_level` varchar(10) NOT NULL default '0',
  `navigation_max_level` varchar(10) NOT NULL default '0',
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Set default values for min_level and max_level fields.

-- **********************************************************
-- *                                                        *
-- * IMPORTANT NOTE                                         *
-- *                                                        *
-- * Do not import this file manually but use the TYPOlight *
-- * install tool to create and maintain database tables!   *
-- *                                                        *
-- **********************************************************

--
-- Table `tl_content`
--

CREATE TABLE `tl_content` (
  `navigation_article` varchar(10) NOT NULL default '',
  `navigation_min_level` varchar(10) NOT NULL default '1',
  `navigation_max_level` varchar(10) NOT NULL default '6',
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


DROP DATABASE IF EXISTS italian_workflow;

CREATE DATABASE italian_workflow;

USE italian_workflow;

CREATE TABLE Users (
    user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    username VARCHAR(40) NOT NULL,
    password CHAR(60) NOT NULL,
    last_name VARCHAR(20),
    first_name VARCHAR(20),
    PRIMARY KEY (user_id),
    UNIQUE (username)
);

CREATE TABLE GiftCertificates (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    amount DECIMAL(10, 2) NOT NULL,
    sale_price NOT NULL,
    date_sold DATE NOT NULL,
    redeemed_date DATE,
    issuer_id INT UNSIGNED NOT NULL,
    memo VARCHAR(140),
    PRIMARY KEY (id),
    FOREIGN KEY (issuer_id) REFERENCES Users (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION
);

Fix data types in db creation script

DROP DATABASE IF EXISTS italian_workflow;

CREATE DATABASE italian_workflow;

USE italian_workflow;

CREATE TABLE Users (
    user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    username VARCHAR(40) NOT NULL,
    password CHAR(60) NOT NULL,
    last_name VARCHAR(20),
    first_name VARCHAR(20),
    PRIMARY KEY (user_id),
    UNIQUE (username)
);

CREATE TABLE GiftCertificates (
    gift_certificate_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    amount DECIMAL(10, 2) NOT NULL,
    sale_price DECIMAL(10, 2) NOT NULL,
    date_sold DATE NOT NULL,
    date_redeemed DATE,
    issuer_id INT UNSIGNED NOT NULL,
    memo VARCHAR(140),
    PRIMARY KEY (id),
    FOREIGN KEY (issuer_id) REFERENCES Users (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION
);


DROP PROCEDURE IF EXISTS `GET_POSTS_BY_VIEW_COUNT`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GET_POSTS_BY_VIEW_COUNT`(IN `_limit` int, IN `_with_covers` tinyint)
BEGIN
		IF _with_covers > 0 THEN
		    PREPARE stmt FROM "SELECT p.*
					FROM `all_posts` AS p
					WHERE `covers` IS NOT NULL
					ORDER BY p.`viewed` DESC, p.`created` DESC
					LIMIT ?;";
		ELSE
				PREPARE stmt FROM "SELECT p.*
					FROM `all_posts` AS p
					ORDER BY p.`viewed` DESC, p.`created` DESC
					LIMIT ?;";
		END IF;

    CALL ALL_POSTS();

		SET @rows = _limit;
    EXECUTE stmt USING @rows;
END
;;
DELIMITER ;

Fix get posts by view count

DROP PROCEDURE IF EXISTS `GET_POSTS_BY_VIEW_COUNT`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `GET_POSTS_BY_VIEW_COUNT`(IN `_limit` int, IN `_with_covers` tinyint)
BEGIN
		CALL ALL_POSTS();

		IF _with_covers > 0 THEN
		    PREPARE stmt FROM "SELECT p.*
					FROM `all_posts` AS p
					WHERE `covers` IS NOT NULL
					ORDER BY p.`viewed` DESC, p.`created` DESC
					LIMIT ?;";
		ELSE
				PREPARE stmt FROM "SELECT p.*
					FROM `all_posts` AS p
					ORDER BY p.`viewed` DESC, p.`created` DESC
					LIMIT ?;";
		END IF;

    SET @rows = _limit;
    EXECUTE stmt USING @rows;
END
;;
DELIMITER ;


INSERT INTO speakeasy_petition_metrics
(campaign_id, activity, is_opt_out, npeople)
  SELECT
    campaign_id AS campaign_id,
    status AS activity,
    is_opt_out AS is_opt_out,
    COUNT(*) AS npeople
  FROM
    civicrm_contact c
    JOIN civicrm_group_contact g ON g.contact_id = c.id AND g.group_id = 42 AND c.is_deleted = 0
    JOIN (SELECT
            CONCAT('speakout petition ', CAST(camp.external_identifier AS CHAR(10))) COLLATE utf8_unicode_ci AS source_string,
            camp.external_identifier AS speakout_id,
            camp.name AS name,
            camp.title AS title,
            camp.id AS campaign_id
          FROM
            civicrm_campaign AS camp) AS kampagne ON kampagne.source_string = c.source
  GROUP BY campaign_id, status, is_opt_out;

Optimize member metrics for campaigns

INSERT INTO speakeasy_petition_metrics
(campaign_id, activity, is_opt_out, npeople)
  SELECT
    camp.id AS campaign_id,
    status AS activity,
    is_opt_out AS is_opt_out,
    COUNT(*) AS npeople
  FROM
    civicrm_contact c
    JOIN civicrm_group_contact g ON g.contact_id = c.id AND g.group_id = 42 AND c.is_deleted = 0
    JOIN civicrm_campaign AS camp ON camp.external_identifier = substr(c.source, 19)
  WHERE c.source LIKE 'speakout petition %'
  GROUP BY camp.id, status, is_opt_out;


drop table if exists users;
create table users (
    userid text primary key not null,
    username text not null,
    email text not null,
    passwordhash not null
);
drop table if exists submissions;
create table submissions (
    submissionid text primary key not null,
    userid text not null,
    submissiondate timestamp,
    problemid text not null,
    submissiontext text,
    submissionstatus text,
    executiontime text
);

Add files table in database template

drop table if exists users;
create table users (
    userid text primary key not null,
    username text not null,
    email text not null,
    passwordhash not null
);
drop table if exists submissions;
create table submissions (
    submissionid text primary key not null,
    userid text not null,
    submissiondate timestamp,
    problemid text not null,
    submissiontext text,
    submissionstatus text,
    executiontime text
);
drop table if exists files;
create table files (
    fileid text primary key not null,
    userid text not null,
    creationdate timestamp,
    lastupdateddate timestamp,
    filename text not null
);


-- List of invalid indexes

-- Use it to see invalid indexes list

-- This query doesn't need any additional extensions to be installed
-- (except plpgsql), and doesn't create anything (like views or smth)
-- -- so feel free to use it in your clouds (Heroku, AWS RDS, etc)

-- (Keep in mind, that on replicas, the whole picture of index usage
-- is usually very different from master).

select
    coalesce(nullif(pn.nspname, 'public') || '.', '') || pct.relname as "relation_name",
    pci.relname as index_name,
    pn.nspname as schema_name,
    pct.relname as table_name,
    format('DROP INDEX CONCURRENTLY %s; -- %s, table %s', pidx.indexrelid::regclass::text, 'Invalid index', pct.relname) as drop_code,
    replace(
      format('%s; -- table %s', pg_get_indexdef(pidx.indexrelid), pct.relname),
      'CREATE INDEX',
      'CREATE INDEX CONCURRENTLY'
    ) as revert_code
from pg_index pidx
join pg_class as pci on pci.oid = pidx.indexrelid
join pg_class as pct on pct.oid = pidx.indrelid
left join pg_namespace pn on pn.oid = pct.relnamespace
where pidx.indisvalid = false;

Index size added to i4:invalid indexes report

-- List of invalid indexes

-- Use it to see invalid indexes list

-- This query doesn't need any additional extensions to be installed
-- (except plpgsql), and doesn't create anything (like views or smth)
-- -- so feel free to use it in your clouds (Heroku, AWS RDS, etc)

-- (Keep in mind, that on replicas, the whole picture of index usage
-- is usually very different from master).

select
    coalesce(nullif(pn.nspname, 'public') || '.', '') || pct.relname as "relation_name",
    pci.relname as index_name,
    pn.nspname as schema_name,
    pct.relname as table_name,
    pg_size_pretty(pg_relation_size(pidx.indexrelid)) index_size,
    format('DROP INDEX CONCURRENTLY %s; -- %s, table %s', pidx.indexrelid::regclass::text, 'Invalid index', pct.relname) as drop_code,
    replace(
      format('%s; -- table %s', pg_get_indexdef(pidx.indexrelid), pct.relname),
      'CREATE INDEX',
      'CREATE INDEX CONCURRENTLY'
    ) as revert_code
from pg_index pidx
join pg_class as pci on pci.oid = pidx.indexrelid
join pg_class as pct on pct.oid = pidx.indrelid
left join pg_namespace pn on pn.oid = pct.relnamespace
where pidx.indisvalid = false;


-- NOTE: To manually execute this script, you must replace {databaseOwner} and {objectQualifier} with real values:
-- defaults is "dbo." for {databaseOwner} and "" for {objectQualifier}

-- Assume all previously added edu. standards are state ones GH-401
UPDATE {databaseOwner}[{objectQualifier}University_DocumentTypes] SET [Type] = N'StateEduStandard' WHERE [Type] = N'EduStandard'
GO

Set proper EduLevelID based on TitleSuffix, clear TitleSuffix GH-398

-- NOTE: To manually execute this script, you must replace {databaseOwner} and {objectQualifier} with real values:
-- defaults is "dbo." for {databaseOwner} and "" for {objectQualifier}

-- Assume all previously added edu. standards are state ones GH-401

UPDATE {databaseOwner}[{objectQualifier}University_DocumentTypes] SET [Type] = N'StateEduStandard' WHERE [Type] = N'EduStandard'
GO

-- Set proper EduLevelID based on TitleSuffix, clear TitleSuffix GH-398

UPDATE {databaseOwner}[{objectQualifier}University_EmployeeAchievements]
    SET EduLevelID = (select EduLevelID from {databaseOwner}[{objectQualifier}University_EduLevels] where ShortTitle = N'Бакалавриат'),
        TitleSuffix = N''
    WHERE TitleSuffix = N'(%бакалавр%)'
GO

UPDATE {databaseOwner}[{objectQualifier}University_EmployeeAchievements]
    SET EduLevelID = (select EduLevelID from {databaseOwner}[{objectQualifier}University_EduLevels] where ShortTitle = N'Специалитет СПО'),
        TitleSuffix = N''
    WHERE TitleSuffix LIKE N'(%средне%)'
GO

UPDATE {databaseOwner}[{objectQualifier}University_EmployeeAchievements]
    SET EduLevelID = (select EduLevelID from {databaseOwner}[{objectQualifier}University_EduLevels] where ShortTitle = N'Специалитет ВО'),
        TitleSuffix = N''
    WHERE TitleSuffix = N'(%специал%)'
GO

UPDATE {databaseOwner}[{objectQualifier}University_EmployeeAchievements]
    SET EduLevelID = (select EduLevelID from {databaseOwner}[{objectQualifier}University_EduLevels] where ShortTitle = N'Магистратура'),
        TitleSuffix = N''
    WHERE TitleSuffix = N'(%магистр%)'
GO

UPDATE {databaseOwner}[{objectQualifier}University_EmployeeAchievements]
    SET EduLevelID = (select EduLevelID from {databaseOwner}[{objectQualifier}University_EduLevels] where ShortTitle = N'Ординатура'),
        TitleSuffix = N''
    WHERE TitleSuffix = N'(%ординат%)'
GO

UPDATE {databaseOwner}[{objectQualifier}University_EmployeeAchievements]
    SET EduLevelID = (select EduLevelID from {databaseOwner}[{objectQualifier}University_EduLevels] where ShortTitle = N'Аспирантура'),
        TitleSuffix = N''
    WHERE TitleSuffix = N'(%кадр%)'
GO


drop table if exists users;
create table users (
    userid text primary key not null,
    username text not null,
    email text not null,
    passwordhash not null
);
drop table if exists submissions;
create table submissions (
    submissionid text primary key not null,
    userid text not null,
    submissiondate timestamp,
    problemid text not null,
    submissiontext text,
    submissionstatus text
);

Add CPU time to submission data

drop table if exists users;
create table users (
    userid text primary key not null,
    username text not null,
    email text not null,
    passwordhash not null
);
drop table if exists submissions;
create table submissions (
    submissionid text primary key not null,
    userid text not null,
    submissiondate timestamp,
    problemid text not null,
    submissiontext text,
    submissionstatus text,
    executiontime text
);


create table blog_post_subject(
    post_id int UNSIGNED NOT NULL,
    subject_id int UNSIGNED NOT NULL,
    CONSTRAINT pk_ps PRIMARY KEY(post_id, subject_id),
    FOREIGN KEY (post_id) REFERENCES blog_post(id),
    FOREIGN KEY (subject_id) REFERENCES blog_subject(id)
);

insert blog_post_subject (post_id, subject_id)
    select id, subject_id from blog_post;

Create blog_prost_selector association table and remove foreign of Post to subjects.

create table blog_post_subject(
    post_id int UNSIGNED NOT NULL,
    subject_id int UNSIGNED NOT NULL,
    CONSTRAINT pk_ps PRIMARY KEY(post_id, subject_id),
    FOREIGN KEY (post_id) REFERENCES blog_post(id),
    FOREIGN KEY (subject_id) REFERENCES blog_subject(id)
);

insert blog_post_subject (post_id, subject_id)
    select id, subject_id from blog_post;

ALTER TABLE blog_post
  DROP FOREIGN KEY blog_post_ibfk_1;


CREATE TABLE IF NOT EXISTS `KV` (
    -- MySQL InnoDB indexes are limited to 767 bytes
    -- You can go up to 3072 bytes if you set innodb_large_prefix
    -- See: http://dev.mysql.com/doc/refman/5.5/en/innodb-restrictions.html
    -- Also recommended: innodb_file_per_table
   `kv_key` VARBINARY(767) NOT NULL,
   `kv_value` LONGBLOB NOT NULL,
   PRIMARY KEY(`kv_key`)
) ENGINE=InnoDB default charset=utf8 collate=utf8_bin

Update MySQL init script with more comments.

CREATE TABLE IF NOT EXISTS `KV` (
   `kv_key` VARBINARY(767) NOT NULL,
   `kv_value` LONGBLOB NOT NULL,
   PRIMARY KEY(`kv_key`)
) ENGINE=InnoDB default charset=utf8 collate=utf8_bin

--
-- MySQL InnoDB indexes are normally limited to 767 bytes, but
-- you can go up to 3072 bytes if you set innodb_large_prefix=true;
-- see http://dev.mysql.com/doc/refman/5.5/en/innodb-restrictions.html
--
-- For example:
--
--  CREATE TABLE IF NOT EXISTS `KV` (
--      `kv_key` VARBINARY(3072) NOT NULL,
--      `kv_value` LONGBLOB NOT NULL,
--      PRIMARY KEY(`kv_key`)
--  ) ENGINE=InnoDB DEFAULT charset=utf8 collate=utf8_bin ROW_FORMAT=DYNAMIC;
--
-- And in /etc/my.cnf:
--
--  [mysqld]
--  innodb_large_prefix      = true
--  innodb_file_per_table    = true
--  innodb_file_format       = barracuda
--


-- Create the tables.
CREATE TABLE users (
    name NVARCHAR(320) PRIMARY KEY, -- 320 is the maximum email length.
    salt CHAR(256),
    password CHAR(256) -- Password is salted and encrypted.
);
CREATE TABLE projects (
    id INT PRIMARY KEY, -- Is this required??
    name NVARCHAR(100), -- Type??
    percentage SMALLINT, -- Needs constraint...
    description NVARCHAR(512), -- Size??
    flag BOOL
);
CREATE TABLE views (
    name NVARCHAR(320) REFERENCES users,
    pid INT REFERENCES projects,
    PRIMARY KEY (name, pid)
);

Add two test projects to start with

-- Create the tables.
CREATE TABLE users (
    name NVARCHAR(320) PRIMARY KEY, -- 320 is the maximum email length.
    salt CHAR(256),
    password CHAR(256) -- Password is salted and encrypted.
);
CREATE TABLE projects (
    id INT PRIMARY KEY, -- Is this required??
    name NVARCHAR(100), -- Type??
    percentage SMALLINT, -- Needs constraint...
    description NVARCHAR(512), -- Size??
    flag BOOL
);
CREATE TABLE views (
    name NVARCHAR(320) REFERENCES users,
    pid INT REFERENCES projects,
    PRIMARY KEY (name, pid)
);

-- Populate the projects table.
INSERT INTO projects VALUES (0, "Test Project 1", 30, "First test project", 1);
INSERT INTO projects VALUES (1, "Test Project 2", 80, "Second test project", 0);


-- Coalesce returns the first non-null value
SELECT
  meter_id, reading, read_timestamp
FROM readings
WHERE meter_id = ${meterID}
  AND read_timestamp BETWEEN
    COALESCE(${startDate}, DATE '1970-01-01')
    AND COALESCE(${endDate}, DATE '50000-01-01');

Clarify a comment about COALESCE

SELECT
  meter_id, reading, read_timestamp
FROM readings
WHERE meter_id = ${meterID}
  AND read_timestamp BETWEEN
  -- Coalesce returns the first non-null value, so this defaults the start date to 1970 and end to 50000,
  -- effectively not restricting them
    COALESCE(${startDate}, DATE '1970-01-01')
    AND COALESCE(${endDate}, DATE '50000-01-01');


-- There are differences between upgrading from a iPeer v2.x installation
-- and upgrading from an iPeer v3.0.x installation.

-- This file contains queries specific to upgrading from a iPeer v3.0.x
-- installation. It should run after the full delta_6 patch file.

ALTER TABLE mixeval_question_descs DROP FOREIGN KEY mixeval_question_descs_ibfk_1;
ALTER TABLE mixeval_question_descs DROP KEY question_num;
ALTER TABLE mixeval_question_descs ADD FOREIGN KEY (`question_id`) REFERENCES `mixeval_questions` (`id`) ON DELETE CASCADE;

ALTER TABLE simple_evaluations ADD UNIQUE KEY `name` (`name`);

-- Add the system.version that wasn't included in the sql template, this should
-- be the very last operation to indicate that the update was successful

INSERT INTO `sys_parameters` (`parameter_code`, `parameter_value`, `parameter_type`, `description`, `record_status`, `creator_id`, `created`, `updater_id`, `modified`) VALUES
('system.version', '3.1.0', 'S', NULL, 'A', 0, NOW(), NULL, NOW());

Remove the orphan entries in mixeval_question_descs

-- There are differences between upgrading from a iPeer v2.x installation
-- and upgrading from an iPeer v3.0.x installation.

-- This file contains queries specific to upgrading from a iPeer v3.0.x
-- installation. It should run after the full delta_6 patch file.

ALTER TABLE mixeval_question_descs DROP FOREIGN KEY mixeval_question_descs_ibfk_1;
ALTER TABLE mixeval_question_descs DROP KEY question_num;

-- Remove the orphan records before adding the foreign key so that it will not fail.
DELETE FROM mixeval_question_descs WHERE question_id NOT IN (SELECT id FROM mixeval_questions);
ALTER TABLE mixeval_question_descs ADD FOREIGN KEY (`question_id`) REFERENCES `mixeval_questions` (`id`) ON DELETE CASCADE;

ALTER TABLE simple_evaluations ADD UNIQUE KEY `name` (`name`);

-- Add the system.version that wasn't included in the sql template, this should
-- be the very last operation to indicate that the update was successful

INSERT INTO `sys_parameters` (`parameter_code`, `parameter_value`, `parameter_type`, `description`, `record_status`, `creator_id`, `created`, `updater_id`, `modified`) VALUES
('system.version', '3.1.0', 'S', NULL, 'A', 0, NOW(), NULL, NOW());


-- SQL commands to update an 0.8.x version of Laconica
-- to 0.9.x.

--these are just comments
/*
alter table notice
     modify column content text comment 'update content';

alter table message
     modify column content text comment 'message content';

alter table profile
     modify column bio text comment 'descriptive biography';

alter table user_group
     modify column description text comment 'group description';
*/

alter table file_oembed
     add column mimetype varchar(50) /*comment 'mime type of resource'*/;

create table config (

    section varchar(32) /* comment 'configuration section'*/,
    setting varchar(32) /* comment 'configuration setting'*/,
    value varchar(255) /* comment 'configuration value'*/,

    primary key (section, setting)

);

create table user_role (

    user_id integer not null /* comment 'user having the role'*/ references "user" (id),
    role    varchar(32) not null /* comment 'string representing the role'*/,
    created timestamp /* not null comment 'date the role was granted'*/,

    primary key (user_id, role)

);

Revert "Revert "fixed up some invalid comment syntax - this is ANSI SQL""


--drop table products;
--drop table repos;
--drop table gitlog;

create table products (
    id            integer primary key asc,
    name          text
);

create table repos (
    id            integer primary key asc,
    product       integer,
    name          text,
    url           text
);

create table commits (
    id            integer primary key asc,
    product       integer, -- foreign key to products
    repo          integer, -- foreign key to repos
    branch        text,
    sha           text,
    message       text,
    author        text,
    date          date,
    files_changed integer,
    insertions    integer,
    deletions     integer
);

create table changed_files (
    id            integer primary key,
    commit_id     integer,
    file_name     text,
    operation     text
);

insert into products(name) values('Product #1');
insert into products(name) values('Product #2');

insert into repos(product, name, url) values ((select id from products where name='Product #1'), 'repo#1', 'git@github.com:tisnik/testrepo.git');
insert into repos(product, name, url) values ((select id from products where name='Product #1'), 'repo#2', 'git@github.com:tisnik/testrepo.ggithub.com:tisnik/testrepo.git');
insert into repos(product, name, url) values ((select id from products where name='Product #2'), 'repo#1', 'git@github.com:tisnik/testrepo.ggithub.com:tisnik/testrepo.git');

Update DB schema to contain table with branches per commit

--drop table products;
--drop table repos;
--drop table gitlog;

create table products (
    id            integer primary key asc,
    name          text
);

create table repos (
    id            integer primary key asc,
    product       integer,
    name          text,
    url           text
);

create table branches_for_commit (
    id            integer primary key asc,
    commit_id     integer, -- foreign key to commits
    branch        text
);

create table commits (
    id            integer primary key asc,
    product       integer, -- foreign key to products
    repo          integer, -- foreign key to repos
    branch        text,
    sha           text,
    message       text,
    author        text,
    date          date,
    files_changed integer,
    insertions    integer,
    deletions     integer
);

create table changed_files (
    id            integer primary key,
    commit_id     integer,
    file_name     text,
    operation     text
);

insert into products(name) values('Product #1');
insert into products(name) values('Product #2');

insert into repos(product, name, url) values ((select id from products where name='Product #1'), 'repo#1', 'git@github.com:tisnik/testrepo.git');
insert into repos(product, name, url) values ((select id from products where name='Product #1'), 'repo#2', 'git@github.com:tisnik/testrepo.ggithub.com:tisnik/testrepo.git');
insert into repos(product, name, url) values ((select id from products where name='Product #2'), 'repo#1', 'git@github.com:tisnik/testrepo.ggithub.com:tisnik/testrepo.git');


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

Fix the bad sql instruction for Oracle

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


ALTER TABLE EPS_PROPOSAL ADD COLUMN ANTICIPATED_AWARD_TYPE_CODE NUMBER(3)
/

Correct syntax error in script

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


CREATE TABLE IF NOT EXISTS `locations` (
  `locid` mediumint(8) unsigned NOT NULL,
  `latitude` float(8,4) NOT NULL,
  `longitude` float(8,4) NOT NULL,
  `ipcount` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`locid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Change Location table to use Auto Increment key.

CREATE TABLE IF NOT EXISTS `locations` (
  `locid` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `latitude` float(8,4) NOT NULL,
  `longitude` float(8,4) NOT NULL,
  `ipcount` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`locid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0;


-- trigger for å øke eksemplarnummer på biblios automatisk
-- bruker coalesce for å defaulte til 1 hvis ingen eksemplarer fra før
-- legger også på strekkode inkrementert med 1
DROP TRIGGER IF EXISTS autoCopyNumberAndBarcode;
DELIMITER $$;
CREATE TRIGGER autoCopyNumberAndBarcode BEFORE INSERT ON items
FOR EACH ROW
BEGIN
  SET NEW.copynumber = (SELECT COALESCE((MAX(CAST(copynumber AS SIGNED)) + 1), 1) FROM items WHERE biblionumber = NEW.biblionumber);
  SET NEW.barcode = (SELECT (MAX(barcode) + 1) FROM items);
END $$;
DELIMITER ;

Use COALESCE on autobarcode trigger to avoid writing NULL

-- trigger for å øke eksemplarnummer på biblios automatisk
-- bruker coalesce for å defaulte til 1 hvis ingen eksemplarer fra før
-- legger også på strekkode inkrementert med 1
DROP TRIGGER IF EXISTS autoCopyNumberAndBarcode;
DELIMITER $$;
CREATE TRIGGER autoCopyNumberAndBarcode BEFORE INSERT ON items
FOR EACH ROW
BEGIN
  SET NEW.copynumber = (SELECT COALESCE((MAX(CAST(copynumber AS SIGNED)) + 1), 1) FROM items WHERE biblionumber = NEW.biblionumber);
  SET NEW.barcode = (SELECT COALESCE(MAX(barcode) + 1, 1) FROM items);
END $$;
DELIMITER ;


ALTER PROCEDURE dw.p_lataa_f_virta_otp_55_suppea AS

TRUNCATE TABLE dw.f_virta_otp_55_suppea

INSERT INTO dw.f_virta_otp_55_suppea (
  d_organisaatio_id,
  d_koulutusluokitus_id,

  vuosi,

  suorittanut55,

  source
)
SELECT
  coalesce(d1.id,-1) AS d_organisaatio_id,
  coalesce(d2.id,-1) AS d_koulutusluokitus_id,

  f.vuosi,

  count(*) as suorittanut55,

  f.source

FROM sa.sa_virta_otp_viisviis as f
LEFT JOIN dw.d_organisaatio d1 ON d1.organisaatio_avain like 'oppilaitosnumero_%' and d1.organisaatio_koodi = f.oppilaitostunnus
LEFT JOIN dw.d_koulutusluokitus d2 ON d2.koulutusluokitus_avain like 'koulutus_%' and d2.koulutusluokitus_koodi = f.tkoodi

WHERE (f.suorittanut55ilmanPankkia = 1 or f.suorittanut55pankinAvulla = 1)
GROUP BY f.vuosi, f.oppilaitostunnus, f.tkoodi

Fix group by query by having correct columns.

ALTER PROCEDURE dw.p_lataa_f_virta_otp_55_suppea AS

TRUNCATE TABLE dw.f_virta_otp_55_suppea

INSERT INTO dw.f_virta_otp_55_suppea (
  d_organisaatio_id,
  d_koulutusluokitus_id,

  vuosi,

  suorittanut55,

  source
)
SELECT
  coalesce(d1.id,-1) AS d_organisaatio_id,
  coalesce(d2.id,-1) AS d_koulutusluokitus_id,

  f.vuosi,

  count(*) as suorittanut55,

  f.source

FROM sa.sa_virta_otp_viisviis as f
LEFT JOIN dw.d_organisaatio d1 ON d1.organisaatio_avain like 'oppilaitosnumero_%' and d1.organisaatio_koodi = f.oppilaitostunnus
LEFT JOIN dw.d_koulutusluokitus d2 ON d2.koulutusluokitus_avain like 'koulutus_%' and d2.koulutusluokitus_koodi = f.tkoodi

WHERE (f.suorittanut55ilmanPankkia = 1 or f.suorittanut55pankinAvulla = 1)
GROUP BY f.vuosi, d1.id, d2.id


CREATE KEYSPACE IF NOT EXISTS unifiedpush_server WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};

Set default replication_factor to 2

CREATE KEYSPACE IF NOT EXISTS unifiedpush_server WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 2};


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);
CREATE TABLE version (VERSION_NUMBER VARCHAR(7))

Put version number in version table

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);
CREATE TABLE version (VERSION_NUMBER VARCHAR(8))
INSERT into version values ("1.0.0");


SELECT c.id,
  name,
  iso_3,
  COALESCE(percentage_pa_land_cover,0) AS percentage_pa_land_cover,
  COALESCE(percentage_pa_marine_cover,0) AS percentage_pa_marine_cover,
  COALESCE(percentage_well_connected,0) AS percentage_well_connected,
  COALESCE(percentage_importance,0) AS percentage_importance,
  COALESCE(pame_percentage_pa_land_cover,0) AS pame_percentage_pa_land_cover,
  COALESCE(pame_percentage_pa_marine_cover,0) AS pame_percentage_pa_marine_cover,
  'country' AS obj_type
FROM countries c
JOIN country_statistics cs ON cs.country_id = c.id
LEFT JOIN pame_statistics ps ON ps.country_id = c.id

UNION

SELECT region_id AS id,
  r.name,
  r.iso,
  percentage_pa_land_cover,
  percentage_pa_marine_cover,
  percentage_well_connected,
  percentage_importance,
  pame_percentage_pa_land_cover,
  pame_percentage_pa_marine_cover,
  'region' AS obj_type
FROM regional_statistics_view rs
JOIN regions r ON rs.region_id = r.id

Make sure iso codes column has the same name across countries and regions

SELECT c.id,
  name,
  iso_3 AS iso,
  COALESCE(percentage_pa_land_cover,0) AS percentage_pa_land_cover,
  COALESCE(percentage_pa_marine_cover,0) AS percentage_pa_marine_cover,
  COALESCE(percentage_well_connected,0) AS percentage_well_connected,
  COALESCE(percentage_importance,0) AS percentage_importance,
  COALESCE(pame_percentage_pa_land_cover,0) AS pame_percentage_pa_land_cover,
  COALESCE(pame_percentage_pa_marine_cover,0) AS pame_percentage_pa_marine_cover,
  'country' AS obj_type
FROM countries c
JOIN country_statistics cs ON cs.country_id = c.id
LEFT JOIN pame_statistics ps ON ps.country_id = c.id

UNION

SELECT region_id AS id,
  r.name,
  r.iso AS iso,
  percentage_pa_land_cover,
  percentage_pa_marine_cover,
  percentage_well_connected,
  percentage_importance,
  pame_percentage_pa_land_cover,
  pame_percentage_pa_marine_cover,
  'region' AS obj_type
FROM regional_statistics_view rs
JOIN regions r ON rs.region_id = r.id


alter table ACT_HI_TASKINST add TASK_INSTANCE_ID_ NVARCHAR2(255);

Fix issue with oracle upgrade script

alter table ACT_HI_TASKINST add PROPAGATED_STAGE_INST_ID_ NVARCHAR2(255);


INSERT INTO media
(
  title,
  uri,
  rating,
  viewed_at,
  created_at
)
VALUES
('Agent Code Banks 2: Destination London', 'http://www.imdb.com/title/tt0358349/', 1000, '2016-06-29', now()),
('A Matter of Faith', 'http://www.imdb.com/title/tt2587914/', 1000, '2016-06-29', now())

Fix typographical error in SQL script

INSERT INTO media
(
  title,
  uri,
  rating,
  viewed_at,
  created_at
)
VALUES
('Agent Cody Banks 2: Destination London', 'http://www.imdb.com/title/tt0358349/', 1000, '2016-06-29', now()),
('A Matter of Faith', 'http://www.imdb.com/title/tt2587914/', 1000, '2016-06-29', now())


USE [master]
GO

-- enable 'TRUSTWORTHY'
-- required for 'external access' of clr code (-> sending tcp packets).
ALTER DATABASE [master] SET TRUSTWORTHY ON;
GO

-- enable clr code
EXEC sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO

-- Add Graphite.TSql.dll assembly
CREATE ASSEMBLY [Graphite.TSql]
AUTHORIZATION [dbo]
FROM '<your/path/to/Graphite.TSql.dll>'
WITH PERMISSION_SET = EXTERNAL_ACCESS
GO

-- Create stored procedure 'sp_graphitesend'
CREATE PROCEDURE sp_graphitesend
(
@host nvarchar(255),
@port int,
@key nvarchar(255),
@value int
)
AS
EXTERNAL NAME [Graphite.TSql].[Graphite.TSql.GraphiteProcedures].GraphiteSend
GO

-- --------------------------------------------------------------------------
-- Example usage:
--
-- exec sp_graphitesend N'192.168.0.1', 2003, 'stats.events.myserver.test', 1
--
-- --------------------------------------------------------------------------

Drop assembly and sp before create

USE [master]
GO

-- enable 'TRUSTWORTHY'
-- required for 'external access' of clr code (-> sending tcp packets).
ALTER DATABASE [master] SET TRUSTWORTHY ON;
GO

-- enable clr code
EXEC sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO

-- Check if procedure and assembly already exist and drop them
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_graphitesend]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_graphitesend]
GO
IF  EXISTS (SELECT * FROM sys.assemblies WHERE name = N'Graphite.TSql')
DROP ASSEMBLY [Graphite.TSql]
GO

-- Add Graphite.TSql.dll assembly
CREATE ASSEMBLY [Graphite.TSql]
AUTHORIZATION [dbo]
FROM '<your/path/to/Graphite.TSql.dll>'
WITH PERMISSION_SET = EXTERNAL_ACCESS
GO

-- Create stored procedure 'sp_graphitesend'
CREATE PROCEDURE sp_graphitesend
(
@host nvarchar(255),
@port int,
@key nvarchar(255),
@value int
)
AS
EXTERNAL NAME [Graphite.TSql].[Graphite.TSql.GraphiteProcedures].GraphiteSend
GO

-- --------------------------------------------------------------------------
-- Example usage:
--
-- exec sp_graphitesend N'192.168.0.1', 2003, 'stats.events.myserver.test', 1
--
-- --------------------------------------------------------------------------


BEGIN;

-- Rename the status_usage view to use v_XXXXXX naming convention
ALTER VIEW IF EXISTS stats_usage RENAME TO v_stats_usage;
ALTER VIEW IF EXISTS active_move_requests RENAME TO v_active_move_requests;
ALTER VIEW IF EXISTS active_blocks RENAME TO v_active_blocks;

-- Create Table: tbl_users_api
CREATE TABLE users_api
(
  api_user_ref uuid NOT NULL DEFAULT uuid_generate_v4(),
  username text NOT NULL,
  password text NOT NULL DEFAULT 0,
  enabled boolean NOT NULL DEFAULT true,
  CONSTRAINT users_api_pkey PRIMARY KEY (api_user_ref),
  CONSTRAINT users_api_username_key UNIQUE (username)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE users_api
  OWNER TO blockbuster;

-- Create Index: username
CREATE INDEX username
  ON tbl_users_api
  USING btree
  (username COLLATE pg_catalog."default");

-- Index: mobile
CREATE INDEX mobile
  ON users
  USING btree
  (mobile COLLATE pg_catalog."default");

-- Index: registration
CREATE INDEX registration
  ON registrations
  USING btree
  (registration COLLATE pg_catalog."default");

-- Update schema version to 1.24.00
UPDATE general
SET value = '1.24.00'
WHERE key = 'version';

COMMIT;

Fix typo in SQL script

BEGIN;

-- Rename the status_usage view to use v_XXXXXX naming convention
ALTER VIEW IF EXISTS stats_usage RENAME TO v_stats_usage;
ALTER VIEW IF EXISTS active_move_requests RENAME TO v_active_move_requests;
ALTER VIEW IF EXISTS active_blocks RENAME TO v_active_blocks;

-- Create Table: tbl_users_api
CREATE TABLE users_api
(
  api_user_ref uuid NOT NULL DEFAULT uuid_generate_v4(),
  username text NOT NULL,
  password text NOT NULL DEFAULT 0,
  enabled boolean NOT NULL DEFAULT true,
  CONSTRAINT users_api_pkey PRIMARY KEY (api_user_ref),
  CONSTRAINT users_api_username_key UNIQUE (username)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE users_api
  OWNER TO blockbuster;

-- Create Index: username
CREATE INDEX username
  ON users_api
  USING btree
  (username COLLATE pg_catalog."default");

-- Index: mobile
CREATE INDEX mobile
  ON users
  USING btree
  (mobile COLLATE pg_catalog."default");

-- Index: registration
CREATE INDEX registration
  ON registrations
  USING btree
  (registration COLLATE pg_catalog."default");

-- Update schema version to 1.24.00
UPDATE general
SET value = '1.24.00'
WHERE key = 'version';

COMMIT;


BEGIN;

SELECT id AS maplayerid, externalid
INTO oskari_maplayer_externalid
FROM oskari_maplayer
WHERE externalid <> '';

ALTER TABLE oskari_maplayer_externalid ADD PRIMARY KEY (maplayerid);
ALTER TABLE oskari_maplayer_externalid ADD FOREIGN KEY (maplayerid) REFERENCES oskari_maplayer (id) ON DELETE CASCADE;
ALTER TABLE oskari_maplayer_externalid ALTER externalid SET NOT NULL;

COMMIT;

ANALYZE oskari_maplayer_externalid;

Add UNIQUE constraint to oskari_maplayer_externalid.externalid

BEGIN;

SELECT id AS maplayerid, externalid
INTO oskari_maplayer_externalid
FROM oskari_maplayer
WHERE externalid <> '';

ALTER TABLE oskari_maplayer_externalid ADD PRIMARY KEY (maplayerid);
ALTER TABLE oskari_maplayer_externalid ADD FOREIGN KEY (maplayerid) REFERENCES oskari_maplayer (id) ON DELETE CASCADE;
ALTER TABLE oskari_maplayer_externalid ALTER externalid SET NOT NULL;
ALTER TABLE oskari_maplayer_externalid ADD UNIQUE (externalid);

COMMIT;

ANALYZE oskari_maplayer_externalid;


INSERT INTO version_db_world (`sql_rev`) VALUES ('1527682153565076000');

DELETE FROM `smart_scripts` WHERE `entryorguid` = 177385;
INSERT INTO `smart_scripts` (`entryorguid`,`source_type`,`id`,`link`,`event_type`,`event_phase_mask`,`event_chance`,`event_flags`,`event_param1`,`event_param2`,`event_param3`,`event_param4`,`action_type`,`action_param1`,`action_param2`,`action_param3`,`action_param4`,`action_param5`,`action_param6`,`target_type`,`target_param1`,`target_param2`,`target_param3`,`target_x`,`target_y`,`target_z`,`target_o`,`comment`) VALUES
(177385,1,0,1,70,0,100,0,2,0,0,0,9,0,0,0,0,0,0,14,43178,175610,0,0,0,0,0,'Torch - On Gossip Hello - Set Gameobject State'),
(177385,1,1,0,61,0,100,0,0,0,0,0,106,16,0,0,0,0,0,20,176944,200,0,0,0,0,0,'Torch - On Gossip Hello - Remove Gameobject Flag');

Change to UPDATE command to be compliant with AC's guidelines

INSERT INTO version_db_world (`sql_rev`) VALUES ('1527682153565076000');

UPDATE `smart_scripts` SET
`event_type` = 70,
`event_param1` = 2,
`action_type` = 9,
`action_param1` = 0,
`target_type` = 14,
`target_param1` = 43178,
`target_param2` = 175610
WHERE `entryorguid` = 177385 AND `id` = 0;


#Theres already an unsed table relating to this, drop it
DROP TABLE talk_link_types;
#switch talks to innodb so FKs work
ALTER TABLE `joindin`.`talks` ENGINE=INNODB;

CREATE TABLE `talk_link_types` (
  `ID` INT(11) NOT NULL AUTO_INCREMENT,
  `display_name` VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=INNODB;

CREATE TABLE `joindin`.`talk_links`(
  `ID` INT NOT NULL AUTO_INCREMENT,
  `talk_id` INT NOT NULL,
  `talk_type` INT NOT NULL,
  `url` TEXT NOT NULL,
  `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`ID`),
  FOREIGN KEY (`talk_id`) REFERENCES `joindin`.`talks`(`ID`),
  FOREIGN KEY (`talk_type`) REFERENCES `joindin`.`talk_link_types`(`ID`)
);

INSERT INTO `talk_link_types`(`ID`,`display_name`) VALUES
(1,'slides_link'),
(2,'video_link'),
(3,'audio_link'),
(4,'code_link'), #github / bitbucket links
(5,'joindin_link'); #Links to another talk on the same topic by the speaker

INSERT INTO patch_history SET patch_number = 70;

Sort the problem of some queries referencing the database name

#Because of potential issuesm drop the talk_links table to be on the safe side
DROP TABLE talk_links;
#Theres already an unsed table relating to this, drop it
DROP TABLE talk_link_types;

#switch talks to innodb so FKs work
ALTER TABLE `talks` ENGINE=INNODB;

CREATE TABLE `talk_link_types` (
  `ID` INT(11) NOT NULL AUTO_INCREMENT,
  `display_name` VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=INNODB;

CREATE TABLE `talk_links`(
  `ID` INT NOT NULL AUTO_INCREMENT,
  `talk_id` INT NOT NULL,
  `talk_type` INT NOT NULL,
  `url` TEXT NOT NULL,
  `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`ID`),
  FOREIGN KEY (`talk_id`) REFERENCES `talks`(`ID`),
  FOREIGN KEY (`talk_type`) REFERENCES `talk_link_types`(`ID`)
);

INSERT INTO `talk_link_types`(`ID`,`display_name`) VALUES
(1,'slides_link'),
(2,'video_link'),
(3,'audio_link'),
(4,'code_link'), #github / bitbucket links
(5,'joindin_link'); #Links to another talk on the same topic by the speaker

INSERT INTO patch_history SET patch_number = 70;


CREATE TABLE IF NOT EXISTS users (
  id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
  created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
  modified_at timestamptz NOT NULL DEFAULT clock_timestamp(),
  deleted_at timestamptz DEFAULT NULL,
  fullname text NOT NULL DEFAULT '',
  username text NOT NULL,
  email text NOT NULL,
  password text NOT NULL,
  metadata bytea NOT NULL,
  deleted boolean DEFAULT false
) 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);

CREATE INDEX deleted_users_idx
  ON users USING btree (deleted)
  WHERE deleted = true;

CREATE TRIGGER users_modified_at_tgr BEFORE UPDATE ON users
  FOR EACH ROW EXECUTE PROCEDURE update_modified_at();

Add missing photo field on users table.

CREATE TABLE IF NOT EXISTS users (
  id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
  created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
  modified_at timestamptz NOT NULL DEFAULT clock_timestamp(),
  deleted_at timestamptz DEFAULT NULL,
  fullname text NOT NULL DEFAULT '',
  username text NOT NULL,
  email text NOT NULL,
  photo text NOT NULL,
  password text NOT NULL,
  metadata bytea NOT NULL,
  deleted boolean DEFAULT false
) 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);

CREATE INDEX deleted_users_idx
  ON users USING btree (deleted)
  WHERE deleted = true;

CREATE TRIGGER users_modified_at_tgr BEFORE UPDATE ON users
  FOR EACH ROW EXECUTE PROCEDURE update_modified_at();


CREATE TABLE `pb_bot` (
	`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(64) NOT NULL COMMENT 'i.e. snusbot',
	`twitch_access_token` VARCHAR(64) NULL DEFAULT NULL COMMENT 'Bot level access-token',
	`twitch_refresh_token` VARCHAR(64) NULL DEFAULT NULL COMMENT 'Bot level refresh-token',
	PRIMARY KEY (`id`)
)
COMMENT='Store available bot accouns, requires an access token with all chat/PubSub scopes'
COLLATE='utf8mb4_general_ci'
ENGINE=InnoDB
;

Revert change in migration file

CREATE TABLE `pb_bot` (
	`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(64) NOT NULL COMMENT 'i.e. snusbot',
	`twitch_access_token` VARCHAR(64) NULL DEFAULT NULL COMMENT 'Bot level access-token',
	`twitch_refresh_token` VARCHAR(64) NULL DEFAULT NULL COMMENT 'Bot level refresh-token',
	PRIMARY KEY (`id`)
)
COMMENT='Store available bot accouns, requires an access token with chat_login scope'
COLLATE='utf8mb4_general_ci'
ENGINE=InnoDB
;


INSERT INTO KRCR_PARM_T (NMSPC_CD, CMPNT_CD, PARM_NM, OBJ_ID, VER_NBR, PARM_TYP_CD, VAL, PARM_DESC_TXT, EVAL_OPRTR_CD, APPL_ID)
VALUES ('KC-COIDISCLOSURE', 'Document', 'ANNUAL_DISCLOSURE_ADVANCE_NOTICE', SYS_GUID(), 1, 'CONFG', '30', 'Number of days in advance of Annual Disclosure due date to start displaying message in COI channel', 'A', 'KC')
/
INSERT INTO KRCR_PARM_T (NMSPC_CD, CMPNT_CD, PARM_NM, OBJ_ID, VER_NBR, PARM_TYP_CD, VAL, PARM_DESC_TXT, EVAL_OPRTR_CD, APPL_ID)
VALUES ('KC-COIDISCLOSURE', 'Document', 'ANNUAL_DISCLOSURE_RENEWAL_DATE', SYS_GUID(), 1, 'CONFG', '0', 'Date on which Annual Disclosures are due for renewal, in MM/DD/YYYY format.  Or, use 0 if renewal is due on anniversary of last Annual Disclosure Certification', 'A', 'KC')
/

Delete COI Annual Review Due date from table for now


DROP TABLE IF EXISTS roads;

CREATE TABLE roads AS
  SELECT
  DISTINCT ON (osm_id)
    osm_id as id,
    name,
    CASE WHEN oneway = 'yes' THEN true ELSE false END AS oneway,
    way as geom
  FROM
    planet_osm_line
  WHERE
    highway NOT IN ('cycleway', 'footway', 'pedestrian', 'steps', 'service', 'path', 'platform', 'construction')
;

Add primary key and constraints to roads

DROP TABLE IF EXISTS roads;

CREATE TABLE roads AS
  SELECT
  DISTINCT ON (osm_id)
    osm_id as id,
    name,
    CASE WHEN oneway = 'yes' THEN true ELSE false END AS oneway,
    way as geom
  FROM
    planet_osm_line
  WHERE
    highway NOT IN ('cycleway', 'footway', 'pedestrian', 'steps', 'service', 'path', 'platform', 'construction')
;

ALTER TABLE roads ADD PRIMARY KEY (id);
ALTER TABLE roads ALTER COLUMN geom SET NOT NULL;
ALTER TABLE roads ALTER COLUMN oneway SET NOT NULL;


/*
Author: Tim Ford
Original link: http://sqlmag.com/database-administration/estimate-when-long-running-sql-processes-will-finish
*/

SET NOCOUNT ON;

SELECT R.session_id
     , R.percent_complete
     , R.total_elapsed_time/1000 AS elapsed_seconds
     , R.wait_type
     , R.wait_time
     , R.last_wait_type,
     , DATEADD(s,100/((R.percent_complete)/ (R.total_elapsed_time/1000)), R.start_time) AS est_complete_time
     , ST.text AS batch_text
     , CAST(SUBSTRING(ST.text, R.statement_start_offset / 2,
             (
               CASE WHEN R.statement_end_offset = -1 THEN DATALENGTH(ST.text)
               ELSE R.statement_end_offset
               END - R.statement_start_offset
             ) / 2
     ) AS varchar(1024)) AS statement_executing
FROM sys.dm_exec_requests AS R
        CROSS APPLY sys.dm_exec_sql_text(R.sql_handle) AS ST
WHERE R.percent_complete > 0
  AND R.session_id <> @@spid;

Fix typos - extra comma

/*
Author: Tim Ford
Original link: http://sqlmag.com/database-administration/estimate-when-long-running-sql-processes-will-finish
*/

SET NOCOUNT ON;

SELECT R.session_id
     , R.percent_complete
     , R.total_elapsed_time/1000 AS elapsed_seconds
     , R.wait_type
     , R.wait_time
     , R.last_wait_type
     , DATEADD(s,100/((R.percent_complete)/ (R.total_elapsed_time/1000)), R.start_time) AS est_complete_time
     , ST.text AS batch_text
     , CAST(SUBSTRING(ST.text, R.statement_start_offset / 2,
             (
               CASE WHEN R.statement_end_offset = -1 THEN DATALENGTH(ST.text)
               ELSE R.statement_end_offset
               END - R.statement_start_offset
             ) / 2
     ) AS varchar(1024)) AS statement_executing
FROM sys.dm_exec_requests AS R
        CROSS APPLY sys.dm_exec_sql_text(R.sql_handle) AS ST
WHERE R.percent_complete > 0
  AND R.session_id <> @@spid;


CREATE SCHEMA IF NOT EXISTS cdb_crankshaft;

CREATE OR REPLACE FUNCTION
  cdb_crankshaft.CDB_AreasOfInterestLocal(
      subquery TEXT,
      column_name TEXT,
      w_type TEXT,
      num_ngbrs INT,
      permutations INT,
      geom_col TEXT,
      id_col TEXT)
RETURNS TABLE (
    moran NUMERIC,
    quads TEXT,
    significance NUMERIC,
    rowid INT,
    vals NUMERIC)
AS $$
BEGIN
    EXECUTE subquery;
    SELECT 1, 'QUADS', 0.01, 1, 1;
END
$$ LANGUAGE plpgsql VOLATILE PARALLEL UNSAFE;

Remove keywords not compatible with PG 9.5

CREATE SCHEMA IF NOT EXISTS cdb_crankshaft;

CREATE OR REPLACE FUNCTION
  cdb_crankshaft.CDB_AreasOfInterestLocal(
      subquery TEXT,
      column_name TEXT,
      w_type TEXT,
      num_ngbrs INT,
      permutations INT,
      geom_col TEXT,
      id_col TEXT)
RETURNS TABLE (
    moran NUMERIC,
    quads TEXT,
    significance NUMERIC,
    rowid INT,
    vals NUMERIC)
AS $$
BEGIN
    EXECUTE subquery;
    SELECT 1, 'QUADS', 0.01, 1, 1;
END
$$ LANGUAGE plpgsql;


CREATE TABLE IF NOT EXISTS minecord (
    id      TINYINT(1) PRIMARY KEY CHECK (id = 0),
    version TINYINT(2) NOT NULL
);
INSERT INTO minecord (id, version)
    VALUES(0, 1);
CREATE TABLE IF NOT EXISTS guild (
    id       BIGINT(20) PRIMARY KEY NOT NULL,
    banned   TINYINT(1) NOT NULL DEFAULT 0,
    prefix   TEXT(8),
    lang     TEXT(5),
    use_menu TINYINT(1)
);
CREATE TABLE IF NOT EXISTS channel (
    id       BIGINT(20) PRIMARY KEY NOT NULL,
    guild_id BIGINT(20) NOT NULL UNIQUE,
    prefix   TEXT(8),
    lang     TEXT(5),
    use_menu TINYINT(1)
);
CREATE TABLE IF NOT EXISTS user (
    id       BIGINT(20) PRIMARY KEY NOT NULL,
    banned   TINYINT(1) NOT NULL DEFAULT 0,
    elevated TINYINT(1) NOT NULL DEFAULT 0,
    prefix   TEXT(8),
    lang     TEXT(5)
);

Add banned field for channel in db

CREATE TABLE IF NOT EXISTS minecord (
    id      TINYINT(1) PRIMARY KEY CHECK (id = 0),
    version TINYINT(2) NOT NULL
);
INSERT INTO minecord (id, version)
    VALUES(0, 1);
CREATE TABLE IF NOT EXISTS guild (
    id       BIGINT(20) PRIMARY KEY NOT NULL,
    banned   TINYINT(1) NOT NULL DEFAULT 0,
    prefix   TEXT(8),
    lang     TEXT(5),
    use_menu TINYINT(1)
);
CREATE TABLE IF NOT EXISTS channel (
    id       BIGINT(20) PRIMARY KEY NOT NULL,
    guild_id BIGINT(20) NOT NULL UNIQUE,
    banned   TINYINT(1) NOT NULL DEFAULT 0,
    prefix   TEXT(8),
    lang     TEXT(5),
    use_menu TINYINT(1)
);
CREATE TABLE IF NOT EXISTS user (
    id       BIGINT(20) PRIMARY KEY NOT NULL,
    banned   TINYINT(1) NOT NULL DEFAULT 0,
    elevated TINYINT(1) NOT NULL DEFAULT 0,
    prefix   TEXT(8),
    lang     TEXT(5)
);


--;
-- Schema upgrade from 5.3.0 to 5.3.1;
--;

Increase URL fields to 2048 charachters to match the VO

--;
-- Schema upgrade from 5.3.0 to 5.3.1;
--;

-- Increase URL fields to 2048 charachters to match the VO
ALTER TABLE `cloud`.`volume_host_ref` MODIFY COLUMN `url` varchar(2048);
ALTER TABLE `cloud`.`object_datastore_ref` MODIFY COLUMN `url` varchar(2048);
ALTER TABLE `cloud`.`image_store` MODIFY COLUMN `url` varchar(2048);
ALTER TABLE `cloud`.`template_store_ref` MODIFY COLUMN `url` varchar(2048);
ALTER TABLE `cloud`.`volume_store_ref` MODIFY COLUMN `url` varchar(2048);
ALTER TABLE `cloud`.`volume_store_ref` MODIFY COLUMN `download_url` varchar(2048);


-- database: presto; groups: tpch,quarantine; tables: lineitem
SELECT sum(l_extendedprice * l_discount) AS revenue
FROM
  lineitem
WHERE
  l_shipdate >= DATE '1994-01-01'
  AND l_shipdate < DATE '1994-01-01' + INTERVAL '1' YEAR
AND l_discount BETWEEN 0.06 - 0.01 AND 0.06 + 0.01
AND l_quantity < 24

Use decimal literal to avoid precision problems in TPCH Q6

-- database: presto; groups: tpch,quarantine; tables: lineitem
SELECT sum(l_extendedprice * l_discount) AS revenue
FROM
  lineitem
WHERE
  l_shipdate >= DATE '1994-01-01'
  AND l_shipdate < DATE '1994-01-01' + INTERVAL '1' YEAR
AND l_discount BETWEEN decimal '0.06' - decimal '0.01' AND decimal '0.06' + decimal '0.01'
AND l_quantity < 24


-- Shows codes for a game
SELECT `code_lookup`.`code`, `code_lookup`.`type`, `code_lookup`.`location_id`, `locations`.`internal_note`, `locations`.`is_start`, `locations`.`is_end` FROM `code_lookup` LEFT OUTER JOIN `locations` ON `code_lookup`.`game_id` = `locations`.`game_id` AND `code_lookup`.`location_id` = `locations`.`location_id` WHERE `code_lookup`.`game_id` = 1;

Add new location and code query

-- Shows codes for a game
SELECT `code_lookup`.`code`, `code_lookup`.`type`, `code_lookup`.`location_id`, `locations`.`internal_note`, `locations`.`is_start`, `locations`.`is_end` FROM `code_lookup` LEFT OUTER JOIN `locations` ON `code_lookup`.`game_id` = `locations`.`game_id` AND `code_lookup`.`location_id` = `locations`.`location_id` WHERE `code_lookup`.`game_id` = 1;

-- Shows codes and clusters for locations
SELECT `locations`.`location_id`, `locations`.`internal_note`, `code_lookup`.`code`, `game_location_clusters`.`cluster_id`, `game_location_clusters`.`description` FROM `locations` LEFT OUTER JOIN `code_lookup` ON `locations`.`game_id` = `code_lookup`.`game_id` AND `locations`.`location_id` = `code_lookup`.`location_id` LEFT OUTER JOIN `game_location_clusters` ON `game_location_clusters`.`game_id` = `locations`.`game_id` AND `game_location_clusters`.`cluster_id` = `locations`.`cluster_id` WHERE `locations`.`game_id` = 1 ORDER BY `game_location_clusters`.`cluster_id` ASC, `locations`.`location_id` ASC


-- Keyspace -------------------------------------------------------------------

CREATE KEYSPACE uuuurrrrllll
WITH replication = {
    -- 'class': 'NetworkTopologyStrategy', 'replication_factor': '3'
    'class': 'SimpleStrategy', 'replication_factor': '1'
};

CREATE TABLE uuuurrrrllll.message (
    short_url text,
    channel   text,
    nick      text,
    url       text,
    PRIMARY KEY (url, short_url)
);

Add IF NOT EXISTS modifiers to table defs

-- Keyspace -------------------------------------------------------------------

CREATE KEYSPACE IF NOT EXISTS uuuurrrrllll
WITH replication = {
    -- 'class': 'NetworkTopologyStrategy', 'replication_factor': '3'
    'class': 'SimpleStrategy', 'replication_factor': '1'
};

CREATE TABLE IF NOT EXISTS uuuurrrrllll.message (
    short_url text,
    channel   text,
    nick      text,
    url       text,
    PRIMARY KEY (url, short_url)
);


-- Create tables

CREATE TABLE mentors (
  id SERIAL PRIMARY KEY,
  first_name VARCHAR(100),
  last_name VARCHAR(100),
  email VARCHAR(100),
  company VARCHAR(100),
  job_title VARCHAR(100),
  zip INT,
  race VARCHAR(100),
  gender VARCHAR(40),
  orientation VARCHAR(40),
  birthday DATE,
  school VARCHAR(100),
  degree VARCHAR(100),
  major VARCHAR(100),
  languages VARCHAR(100),
  admin BOOLEAN DEFAULT FALSE
);

CREATE TABLE students (
	id SERIAL PRIMARY KEY,
	name VARCHAR(100),
	email VARCHAR(100)
);

CREATE TABLE faq (
	id SERIAL PRIMARY KEY,
	mentor_id INT REFERENCES mentors(id),
	question VARCHAR(5000),
	answer VARCHAR(5000)
);

CREATE TABLE messages (
	id SERIAL PRIMARY KEY,
	mentor_id INT REFERENCES mentors(id),
	student_id INT REFERENCES students(id),
	date_sent DATE,
	date_replied DATE,
	subject VARCHAR(100),
	message VARCHAR(5000),
  reply VARCHAR(5000),
	student_name VARCHAR(100),
	message_read BOOLEAN DEFAULT FALSE
);

Add comment to stementor.sql file explaining the queries and test data

-- The SQL queries below create the necessary tables in your SQL database.
-- The database needs to be called stementor (all lower case)
-- Test data can be found in the "test-data" folder

CREATE TABLE mentors (
  id SERIAL PRIMARY KEY,
  first_name VARCHAR(100),
  last_name VARCHAR(100),
  email VARCHAR(100),
  company VARCHAR(100),
  job_title VARCHAR(100),
  zip INT,
  race VARCHAR(100),
  gender VARCHAR(40),
  orientation VARCHAR(40),
  birthday DATE,
  school VARCHAR(100),
  degree VARCHAR(100),
  major VARCHAR(100),
  languages VARCHAR(100),
  admin BOOLEAN DEFAULT FALSE
);

CREATE TABLE students (
	id SERIAL PRIMARY KEY,
	name VARCHAR(100),
	email VARCHAR(100)
);

CREATE TABLE faq (
	id SERIAL PRIMARY KEY,
	mentor_id INT REFERENCES mentors(id),
	question VARCHAR(5000),
	answer VARCHAR(5000)
);

CREATE TABLE messages (
	id SERIAL PRIMARY KEY,
	mentor_id INT REFERENCES mentors(id),
	student_id INT REFERENCES students(id),
	date_sent DATE,
	date_replied DATE,
	subject VARCHAR(100),
	message VARCHAR(5000),
  reply VARCHAR(5000),
	student_name VARCHAR(100),
	message_read BOOLEAN DEFAULT FALSE
);


-- SQL commands to update an 0.8.x version of Laconica
-- to 0.9.x.

--these are just comments
/*
alter table notice
     modify column content text comment 'update content';

alter table message
     modify column content text comment 'message content';

alter table profile
     modify column bio text comment 'descriptive biography';

alter table user_group
     modify column description text comment 'group description';
*/

alter table file_oembed
     add column mimetype varchar(50) /*comment 'mime type of resource'*/;

create table config (

    section varchar(32) /* comment 'configuration section'*/,
    setting varchar(32) /* comment 'configuration setting'*/,
    value varchar(255) /* comment 'configuration value'*/,

    primary key (section, setting)

);

create table user_role (

    user_id integer not null /* comment 'user having the role'*/ references "user" (id),
    role    varchar(32) not null /* comment 'string representing the role'*/,
    created timestamp /* not null comment 'date the role was granted'*/,

    primary key (user_id, role)

);

Revert "Revert "upgrade script for postgres""


exec sp_rename 'sb_reminder.trigger_durationProp', trigger_prop, 'COLUMN';

ALTER TABLE sb_reminder
    ADD process_name VARCHAR(200);

UPDATE sb_reminder
SET process_name = 'CalendarEventUserNotification'
WHERE sb_reminder.trigger_prop = 'NEXT_START_DATE_TIME';

ALTER TABLE sb_reminder
    ALTER COLUMN process_name VARCHAR(200) NOT NULL;

Fix the migration script of the reminder module when upgrading to version 003


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 := 5;
   -- The version the database should have _after_ the migration
   new_version numeric := 6;

   -- 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__dependencies ADD COLUMN inCard boolean DEFAULT true;

END$$;

COMMIT;

Make lddb__dependencies.inCard default to false

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 := 5;
   -- The version the database should have _after_ the migration
   new_version numeric := 6;

   -- 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__dependencies ADD COLUMN inCard boolean DEFAULT false;

END$$;

COMMIT;


begin;

create table ncaa_sr.polls (
	year				integer,
	school_id			text,
	school_name			text,
	week				text,
	rank				integer,
	primary key (year,school_id,week)
);

copy ncaa_sr.polls from '/tmp/polls.csv' with delimiter as ',' csv header quote as '"';

commit;

Create table if not exist.

begin;

create table if not exists ncaa_sr.polls (
	year				integer,
	school_id			text,
	school_name			text,
	week				text,
	rank				integer,
	primary key (year,school_id,week)
);

copy ncaa_sr.polls from '/tmp/polls.csv' with delimiter as ',' csv header quote as '"';

commit;


CREATE DATABASE notes;

USE notes;

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

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

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

Change strings to integers in DEFAULT

CREATE DATABASE notes;

USE notes;

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

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

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


/* The function system_user_schema.util_get_user_state retuns the current state of the user
* indicated by the _login parameter. If the submitted login doesn't correspond
* to a system user it returns "Unknown"

*/

CREATE OR REPLACE FUNCTION system_user_schema.util_get_user_state (_login text) RETURNS text
AS $$

DECLARE

	_integer_var integer;

	_sysuser_id	uuid;
	_is_logged_in	boolean;
	_user_state	text;

BEGIN

	_sysuser_id := (	SELECT
						sysuser_id
					FROM system_user_schema.system_users
					WHERE	login = lower(_login)
				);

	IF _sysuser_id IS NOT NULL THEN

		_user_state :=	(SELECT
							user_state
						FROM	system_user_schema.system_user_state
						WHERE	sysuser_id = _sysuser_id
						);

	ELSE

		_user_state := 'Unknown';

	END IF;

	RETURN _user_state;

END;
$$ LANGUAGE plpgsql;

Add code to record time user invoked an action in he system

/* The function system_user_schema.util_get_user_state retuns the current state of the user
* indicated by the _login parameter. If the submitted login doesn't correspond
* to a system user it returns "Unknown"
*
* The function also records the time the function ran as the time the user was
* last active on the system.
*/

CREATE OR REPLACE FUNCTION system_user_schema.util_get_user_state (_login text) RETURNS text
AS $$

DECLARE

	_integer_var integer;

	_sysuser_id	uuid;
	_is_logged_in	boolean;
	_user_state	text;

BEGIN

	_sysuser_id := (	SELECT
						sysuser_id
					FROM system_user_schema.system_users
					WHERE	login = lower(_login)
				);

	IF _sysuser_id IS NOT NULL THEN

		_user_state :=	(SELECT
							user_state
						FROM	system_user_schema.system_user_state
						WHERE	sysuser_id = _sysuser_id
						);

		IF _user_state = 'Logged In' THEN
			UPDATE system_user_schema.system_user_last_active
			SET datetime_last_active = clock_timestamp()
			WHERE sysuser_id = _sysuser_id
			;
		END IF;

	ELSE

		_user_state := 'Unknown';

	END IF;

	RETURN _user_state;

END;
$$ LANGUAGE plpgsql;


ALTER table `sentences` ADD COLUMN `hash` BINARY(16) NOT NULL;

Add murmur_hash_V3 sql queries to database updates.

ALTER table `sentences` ADD COLUMN `hash` BINARY(16) NOT NULL;

UPDATE sentences SET hash=LOWER(CONV(murmur_hash_v3(CONCAT(lang, text), 0), 10, 32));

# Must update users_vocabulary before updating the vocabulary table!
UPDATE IGNORE users_vocabulary
    INNER JOIN vocabulary ON users_vocabulary.vocabulary_id = vocabulary.id
    SET users_vocabulary.vocabulary_id=LOWER(CONV(murmur_hash_v3(CONCAT(vocabulary.lang, vocabulary.text), 0), 10, 32));

UPDATE IGNORE vocabulary SET id=LOWER(CONV(murmur_hash_v3(CONCAT(lang, text), 0), 10, 32));


IF (NOT EXISTS(SELECT TransactionType FROM [employer_financial].[PaymentTransactionTypes] WHERE TransactionType = 1))
BEGIN
	INSERT [employer_financial].[PaymentTransactionTypes] ([TransactionType], [Description]) VALUES (N'1', N'Monthly Payment')
END
IF (NOT EXISTS(SELECT TransactionType FROM [employer_financial].[PaymentTransactionTypes] WHERE TransactionType = 2))
BEGIN
	INSERT [employer_financial].[PaymentTransactionTypes] ([TransactionType], [Description]) VALUES (N'2', N'Completion Payment')
END

Add balance payment transaction type to enable pulling Balancing payments into download transaction

IF (NOT EXISTS(SELECT TransactionType FROM [employer_financial].[PaymentTransactionTypes] WHERE TransactionType = 1))
BEGIN
	INSERT [employer_financial].[PaymentTransactionTypes] ([TransactionType], [Description]) VALUES (N'1', N'Monthly Payment')
END
IF (NOT EXISTS(SELECT TransactionType FROM [employer_financial].[PaymentTransactionTypes] WHERE TransactionType = 2))
BEGIN
	INSERT [employer_financial].[PaymentTransactionTypes] ([TransactionType], [Description]) VALUES (N'2', N'Completion Payment')
END
IF (NOT EXISTS(SELECT TransactionType FROM [employer_financial].[PaymentTransactionTypes] WHERE TransactionType = 3))
BEGIN
	INSERT [employer_financial].[PaymentTransactionTypes] ([TransactionType], [Description]) VALUES (N'3', N'Balance Payment')
END


DROP DATABASE cosmos_gui;
CREATE DATABASE cosmos_gui;
USE cosmos_gui;

CREATE TABLE cosmos_user (idm_username VARCHAR(128) NOT NULL PRIMARY KEY UNIQUE, username TEXT NOT NULL, password TEXT NOT NULL, registrationTime TIMESTAMP NOT NULL);

MODIFY the mysql sentence for creating the cosmos_user table

DROP DATABASE cosmos_gui;
CREATE DATABASE cosmos_gui;
USE cosmos_gui;

CREATE TABLE cosmos_user (idm_username VARCHAR(128) NOT NULL PRIMARY KEY UNIQUE, username TEXT NOT NULL, password TEXT NOT NULL, registration_time TIMESTAMP NOT NULL);


-- import.sql for TicketManor project

insert into venues(id, name, streetAddress, city, provState, country, lat, lng) values(1, 'Carnegie Hall', '881 Seventh Avenue', 'New York', 'NY', 'US', 40.764938, -73.979897);
insert into venues(id, name, streetAddress, city, provState, country, lat, lng) values(2, 'Roy Thompson Hall', '60 Simcoe Street', 'Toronto', 'ON', 'CA', 43.646596, -79.386413);

insert into acts(id, title, year) values(-1, 'Rush', 1980);
insert into acts(id, title, year) values(-2, 'Foo Fish', 2020);

insert into acts (id, title, type, year) values (-3, 'Star Wars Bloopers', 0, 2001);
insert into movies (id, director) values (-3, 'George Lucas');

insert into events (id, what_id, date_time, where_id) values (-1, -3, '2016-06-22 14:00:00', null);

insert into people(id, firstName, lastName) values(-1, 'System', 'Administrator');
insert into members(id) values(-1);

Comment out date field until date-is-blob problem gets resolved.

-- import.sql for TicketManor project

insert into venues(id, name, streetAddress, city, provState, country, lat, lng) values(1, 'Carnegie Hall', '881 Seventh Avenue', 'New York', 'NY', 'US', 40.764938, -73.979897);
insert into venues(id, name, streetAddress, city, provState, country, lat, lng) values(2, 'Roy Thompson Hall', '60 Simcoe Street', 'Toronto', 'ON', 'CA', 43.646596, -79.386413);

insert into acts(id, title, year) values(-1, 'Rush', 1980);
insert into acts(id, title, year) values(-2, 'Foo Fish', 2020);

insert into acts (id, title, type, year) values (-3, 'Star Wars Bloopers', 0, 2001);
insert into movies (id, director) values (-3, 'George Lucas');

-- ert into events (id, what_id, date_time, where_id) values (-1, -3, '2016-06-22 14:00:00', null);
insert into events (id, what_id, date_time, where_id) values (-1, -3, null, null);

insert into people(id, firstName, lastName) values(-1, 'System', 'Administrator');
insert into members(id) values(-1);


alter table DOCUMENT_VERSION add column ID bigint;
alter table DOCUMENT_VERSION add column NAME varchar(255);

alter table ENTITY add column NAME varchar(255);
alter table ENTITY_VERSION add column COMMENT varchar(255);

Add index to speed up tests

alter table DOCUMENT_VERSION add column ID bigint;
alter table DOCUMENT_VERSION add column NAME varchar(255);

alter table ENTITY add column NAME varchar(255);
alter table ENTITY_VERSION add column COMMENT varchar(255);

create index ENTITY_VERSION_PROPERTY_STATUS_IDX on ENTITY_VERSION_PROPERTY (STATUS);


update clinlims.test set description=replace(description, ' Total', '') where description like '%Sang Total%';
update clinlims.sampletype_test set sample_type_id=(select id from clinlims.type_of_sample where description='Sang') where sample_type_id=(select id from clinlims.type_of_sample where description='Sang Total');
update clinlims.sampletype_panel set sample_type_id=(select id from clinlims.type_of_sample where description='Sang') where sample_type_id=(select id from clinlims.type_of_sample where description='Sang Total');
update clinlims.sample_item set typeosamp_id=(select id from clinlims.type_of_sample where description='Sang') where typeosamp_id=(select id from clinlims.type_of_sample where description='Sang Total');
update clinlims.type_of_sample set is_active='N' where description='Sang Total';

Fix for Haiti LNSP conversion from Sang to Sang Total

update clinlims.test set description=replace(description, '(Sang)', '(Sang Total)') where description like '%(Sang)%';
update clinlims.sampletype_test set sample_type_id=(select id from clinlims.type_of_sample where description='Sang Total') where sample_type_id=(select id from clinlims.type_of_sample where description='Sang');
update clinlims.sampletype_panel set sample_type_id=(select id from clinlims.type_of_sample where description='Sang Total') where sample_type_id=(select id from clinlims.type_of_sample where description='Sang');
update clinlims.sample_item set typeosamp_id=(select id from clinlims.type_of_sample where description='Sang Total') where typeosamp_id=(select id from clinlims.type_of_sample where description='Sang');
update clinlims.type_of_sample set is_active='N' where description='Sang';
update clinlims.type_of_sample set sort_order=5 where description='Sang Total';


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

Fix bung upgrade in 29 where an extra "synonyms_html =" got through un-noticed until staging.

update tree_element ute
set synonyms = synonyms_as_jsonb(ute.instance_id, 'id.biodiversity.org.au'),
    synonyms_html = coalesce(synonyms_as_html(ute.instance_id), '<synonyms></synonyms>')
where ute.id in (select distinct(te.id)
                 from tree_element te
                        join tree_version_element tve on te.id = tve.tree_element_id
                        join tree t on (t.current_tree_version_id = tve.tree_version_id) OR
                                       (t.default_draft_tree_version_id = tve.tree_version_id)
                 where te.synonyms <> synonyms_as_jsonb(te.instance_id, 'id.biodiversity.org.au'));

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


-- +goose Up
alter table post add column hidden boolean;

update post set hidden=0;

alter table post rename to tmp_post;

create table post (
    id serial primary key,
    author_id integer not null references author(id) on delete cascade on update cascade,
    title text,
    date bigint,
    url text,
    body text,
    hidden boolean not null
);

insert into post(id, author_id, title, date, url, body, hidden)
select id, author_id, title, date, url, body, hidden
from tmp_post;

drop table tmp_post;

-- +goose Down
alter table post rename to tmp_post;

create table post (
    id serial primary key,
    author_id integer not null references author(id) on delete cascade on update cascade,
    title text,
    date bigint,
    url text,
    body text
);

insert into post(id, author_id, title, date, url, body)
select id, author_id, title, date, url, body
from tmp_post;

drop table tmp_post;

Change column type from boolean to integer

-- +goose Up
alter table post add column hidden integer;

update post set hidden=0;

alter table post rename to tmp_post;

create table post (
    id serial primary key,
    author_id integer not null references author(id) on delete cascade on update cascade,
    title text,
    date bigint,
    url text,
    body text,
    hidden integer not null
);

insert into post(id, author_id, title, date, url, body, hidden)
select id, author_id, title, date, url, body, hidden
from tmp_post;

drop table tmp_post;

-- +goose Down
alter table post rename to tmp_post;

create table post (
    id serial primary key,
    author_id integer not null references author(id) on delete cascade on update cascade,
    title text,
    date bigint,
    url text,
    body text
);

insert into post(id, author_id, title, date, url, body)
select id, author_id, title, date, url, body
from tmp_post;

drop table tmp_post;


SELECT LatestVersionHistoryID
	FROM
	(
		SELECT MAX(VersionHistoryID) OVER (PARTITION BY DocumentID) AS LatestVersionHistoryID
			FROM CMS_VersionHistory
	) AS LatestVersionHistoryIDs
	GROUP BY LatestVersionHistoryID

Update latest version history to filter out draft versions

SELECT LatestVersionHistoryID
	FROM
	(
		SELECT MAX(VersionHistoryID) OVER (PARTITION BY DocumentID) AS LatestVersionHistoryID
			FROM CMS_VersionHistory
			WHERE WasPublishedFrom IS NOT NULL
	) AS LatestVersionHistoryIDs
	GROUP BY LatestVersionHistoryID


drop index ACT_IDX_HI_PRO_INST_END on ACT_HI_PROCINST;
drop index ACT_IDX_HI_PRO_I_BUSKEY on ACT_HI_PROCINST;
drop index ACT_IDX_HI_ACT_INST_START on ACT_HI_ACTINST;
drop index ACT_IDX_HI_ACT_INST_END on ACT_HI_ACTINST;
drop index ACT_IDX_HI_DETAIL_PROC_INST on ACT_HI_DETAIL;
drop index ACT_IDX_HI_DETAIL_ACT_INST on ACT_HI_DETAIL;
drop index ACT_IDX_HI_DETAIL_TIME on ACT_HI_DETAIL;
drop index ACT_IDX_HI_DETAIL_NAME on ACT_HI_DETAIL;
drop index ACT_IDX_HI_DETAIL_TASK_ID on ACT_HI_DETAIL;
drop index ACT_IDX_HI_PROCVAR_PROC_INST on ACT_HI_VARINST;
drop index ACT_IDX_HI_PROCVAR_NAME_TYPE on ACT_HI_VARINST;
drop index ACT_IDX_HI_ACT_INST_PROCINST;

drop table if exists ACT_HI_PROCINST;
drop table if exists ACT_HI_ACTINST;
drop table if exists ACT_HI_VARINST;
drop table if exists ACT_HI_TASKINST;
drop table if exists ACT_HI_DETAIL;
drop table if exists ACT_HI_COMMENT;
drop table if exists ACT_HI_ATTACHMENT;

Fix failing drop script on MySQL

drop index ACT_IDX_HI_PRO_INST_END on ACT_HI_PROCINST;
drop index ACT_IDX_HI_PRO_I_BUSKEY on ACT_HI_PROCINST;
drop index ACT_IDX_HI_ACT_INST_START on ACT_HI_ACTINST;
drop index ACT_IDX_HI_ACT_INST_END on ACT_HI_ACTINST;
drop index ACT_IDX_HI_DETAIL_PROC_INST on ACT_HI_DETAIL;
drop index ACT_IDX_HI_DETAIL_ACT_INST on ACT_HI_DETAIL;
drop index ACT_IDX_HI_DETAIL_TIME on ACT_HI_DETAIL;
drop index ACT_IDX_HI_DETAIL_NAME on ACT_HI_DETAIL;
drop index ACT_IDX_HI_DETAIL_TASK_ID on ACT_HI_DETAIL;
drop index ACT_IDX_HI_PROCVAR_PROC_INST on ACT_HI_VARINST;
drop index ACT_IDX_HI_PROCVAR_NAME_TYPE on ACT_HI_VARINST;
drop index ACT_IDX_HI_ACT_INST_PROCINST on ACT_HI_ACTINST;

drop table if exists ACT_HI_PROCINST;
drop table if exists ACT_HI_ACTINST;
drop table if exists ACT_HI_VARINST;
drop table if exists ACT_HI_TASKINST;
drop table if exists ACT_HI_DETAIL;
drop table if exists ACT_HI_COMMENT;
drop table if exists ACT_HI_ATTACHMENT;


INSERT INTO users (email, first_name, last_name, password, role, shipping_address)
VALUES ('dj@gmail.com', 'Djidjely', 'Siclait', '1234', 0, 'nowhere');

INSERT INTO users (email, first_name, last_name, password, role, shipping_address)
VALUES ('ev@gmail.com', 'Eduardo', 'Veras', '1234', 0, 'nowhere');

INSERT INTO users (email, first_name, last_name, password, role, shipping_address)
VALUES ('er@gmail.com', 'Ernesto', 'Rodriguez', '1234', 0, 'nowhere');


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

Add missing SVN id keyword

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


INSERT INTO citation_datasource (id,name) VALUES (1,'TYLER');
INSERT INTO citation_datasource_municipality (citation_datasource_id,municipality_id) VALUES (1,90);

CREATE TABLE tyler_court_mapping(
  court_id				INTEGER			NOT NULL,
  tyler_court_identifier VARCHAR(25)
)ENGINE=InnoDB;

ALTER TABLE tyler_court_mapping ADD CONSTRAINT tyler_court_mapping_fk_1 FOREIGN KEY (court_id) REFERENCES courts (id);

INSERT INTO tyler_court_mapping (court_id,tyler_court_identifier) VALUES (35,'S');
INSERT INTO tyler_court_mapping (court_id,tyler_court_identifier) VALUES (51,'N');
INSERT INTO tyler_court_mapping (court_id,tyler_court_identifier) VALUES (79,'C');
INSERT INTO tyler_court_mapping (court_id,tyler_court_identifier) VALUES (80,'W');

Fix another changelog issues with mysql and existing state

INSERT INTO citation_datasource (id,name) VALUES (1,'TYLER');
INSERT INTO citation_datasource_municipality (citation_datasource_id,municipality_id) VALUES (1,90);

CREATE TABLE tyler_court_mapping(
  court_id				INTEGER			NOT NULL,
  tyler_court_identifier VARCHAR(25)
)ENGINE=InnoDB;

ALTER TABLE tyler_court_mapping ADD CONSTRAINT tyler_court_mapping_fk_1 FOREIGN KEY (court_id) REFERENCES court (court_id);

INSERT INTO tyler_court_mapping (court_id,tyler_court_identifier) VALUES (35,'S');
INSERT INTO tyler_court_mapping (court_id,tyler_court_identifier) VALUES (51,'N');
INSERT INTO tyler_court_mapping (court_id,tyler_court_identifier) VALUES (79,'C');
INSERT INTO tyler_court_mapping (court_id,tyler_court_identifier) VALUES (80,'W');