CREATE DATABASE `newsbot` /*!40100 DEFAULT CHARACTER SET utf8 */;

CREATE TABLE GROUP_TELEGRAM (
  `group_id` bigint(20) NOT NULL,
  `registered` varchar(1) DEFAULT NULL,
  PRIMARY KEY (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE NEWS (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `link` varchar(255) DEFAULT NULL,
  `title` varchar(255) DEFAULT NULL,
  `pubblication_date` date DEFAULT NULL,
  `creation_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `sent` varchar(1) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `link` (`link`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;

CREATE TABLE USER_TELEGRAM (
  `user_id` bigint(20) NOT NULL,
  `user_name` varchar(150) DEFAULT NULL,
  `first_name` varchar(150) DEFAULT NULL,
  `last_name` varchar(150) DEFAULT NULL,
  `registered` varchar(1) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Increase varchar size of the link in the db

CREATE DATABASE `newsbot` /*!40100 DEFAULT CHARACTER SET utf8 */;

CREATE TABLE GROUP_TELEGRAM (
  `group_id` bigint(20) NOT NULL,
  `registered` varchar(1) DEFAULT NULL,
  PRIMARY KEY (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE NEWS (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `link` varchar(1000) DEFAULT NULL,
  `title` varchar(255) DEFAULT NULL,
  `pubblication_date` date DEFAULT NULL,
  `creation_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `sent` varchar(1) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `link` (`link`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;

CREATE TABLE USER_TELEGRAM (
  `user_id` bigint(20) NOT NULL,
  `user_name` varchar(150) DEFAULT NULL,
  `first_name` varchar(150) DEFAULT NULL,
  `last_name` varchar(150) DEFAULT NULL,
  `registered` varchar(1) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


SELECT
    study.study_accession,
    P.name LIKE '%HIPC%' AS hipc_funded
FROM
    study
    LEFT OUTER JOIN contract_grant_2_study CG2S ON study.study_accession = CG2S.study_accession
    LEFT OUTER JOIN contract_grant CG ON CG2S.contract_grant_id = CG.contract_grant_id
    LEFT OUTER JOIN program P on CG.program_id = P.program_id
WHERE
    P.name LIKE '%HIPC%'

Fix to the HIPC status query to reflect the new logic from the "immport" module

SELECT
    study.study_accession,
    P.name LIKE '%HIPC%' AS hipc_funded
FROM
    study
    -- LEFT OUTER JOIN contract_grant_2_study CG2S ON study.study_accession = CG2S.study_accession
    LEFT OUTER JOIN (SELECT study_accession, MIN(contract_grant_id) as contract_grant_id FROM immport.contract_grant_2_study GROUP BY study_accession) CG2S ON study.study_accession = CG2S.study_accession
    LEFT OUTER JOIN contract_grant CG ON CG2S.contract_grant_id = CG.contract_grant_id
    LEFT OUTER JOIN program P on CG.program_id = P.program_id
WHERE
    P.name LIKE '%HIPC%'


DROP TABLE IF EXISTS Account, accounts;

CREATE TABLE accounts (
	acc_id integer PRIMARY KEY,
	acc_name text,
	acc_description text
);

Make id to auto-increment field.

DROP TABLE IF EXISTS Account, accounts;

CREATE TABLE accounts (
	acc_id SERIAL PRIMARY KEY,
	acc_name text,
	acc_description text
);


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

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

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

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

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

END;

Make room for longer field names

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

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

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

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

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

END;


DROP TABLE IF EXISTS comments;
DROP TABLE IF EXISTS posts_tags;
DROP TABLE IF EXISTS posts;
DROP TABLE IF EXISTS tags;

CREATE TABLE posts (
	id INT PRIMARY KEY AUTO_INCREMENT
	,title VARCHAR(255) NOT NULL
	,content TEXT NOT NULL
	,created_at TIMESTAMP NOT NULL
	,updated_at TIMESTAMP NOT NULL
);

CREATE TABLE tags (
	id INT PRIMARY KEY AUTO_INCREMENT
	,name VARCHAR(255) NOT NULL
	,created_at TIMESTAMP NOT NULL
	,updated_at TIMESTAMP NOT NULL
);

CREATE TABLE posts_tags (
	post_id INT NOT NULL
	,tag_id INT NOT NULL
  ,PRIMARY KEY (post_id, tag_id)
	,FOREIGN KEY (post_id) REFERENCES posts (id)
	,FOREIGN KEY (tag_id) REFERENCES tags (id)
);

CREATE TABLE comments (
	id INT PRIMARY KEY AUTO_INCREMENT
	,post_id INT NOT NULL
	,author_name VARCHAR(255) NOT NULL
	,author_email VARCHAR(255) NOT NULL
	,content TEXT NOT NULL
	,created_at TIMESTAMP NOT NULL
	,updated_at TIMESTAMP NOT NULL
	,FOREIGN KEY (post_id) REFERENCES posts (id)
);

Fix error on creating test schema for MySQL

DROP TABLE IF EXISTS comments;
DROP TABLE IF EXISTS posts_tags;
DROP TABLE IF EXISTS posts;
DROP TABLE IF EXISTS tags;

CREATE TABLE posts (
	id INT PRIMARY KEY AUTO_INCREMENT
	,title VARCHAR(255) NOT NULL
	,content TEXT NOT NULL
	,created_at TIMESTAMP NOT NULL DEFAULT NOW()
	,updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE TABLE tags (
	id INT PRIMARY KEY AUTO_INCREMENT
	,name VARCHAR(255) NOT NULL
	,created_at TIMESTAMP NOT NULL DEFAULT NOW()
	,updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE TABLE posts_tags (
	post_id INT NOT NULL
	,tag_id INT NOT NULL
	,PRIMARY KEY (post_id, tag_id)
	,FOREIGN KEY (post_id) REFERENCES posts (id)
	,FOREIGN KEY (tag_id) REFERENCES tags (id)
);

CREATE TABLE comments (
	id INT PRIMARY KEY AUTO_INCREMENT
	,post_id INT NOT NULL
	,author_name VARCHAR(255) NOT NULL
	,author_email VARCHAR(255) NOT NULL
	,content TEXT NOT NULL
	,created_at TIMESTAMP NOT NULL DEFAULT NOW()
	,updated_at TIMESTAMP NOT NULL DEFAULT NOW()
	,FOREIGN KEY (post_id) REFERENCES posts (id)
);


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

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

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

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

Standardize on varchar rather than text (they're virtually identical)

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

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

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

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


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

select ts, dur, process.pid as pid, display_frame_token, surface_frame_token, layer_name
from expected_frame_timeline_slice
join process_track on process_track.upid = expected_frame_timeline_slice.upid
join process on process_track.upid = process.upid
where process_track.name = 'Expected Timeline'
order by ts

Make expected timeline test case use the same sql joins as actual

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

select ts, dur, process.pid as pid, display_frame_token, surface_frame_token, layer_name
from
  (select t.*, process_track.name as track_name from
    process_track left join expected_frame_timeline_slice t
    on process_track.id = t.track_id) s
join process using(upid)
where s.track_name = 'Expected Timeline'
order by ts


DROP TABLE IF EXISTS `people`;

CREATE TABLE `people` (
  `id` int(11) NOT NULL auto_increment,
  `first_name` varchar(50) NOT NULL,
  `middle_initial` varchar(10) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `street_address` varchar(200) NOT NULL,
  `city` varchar(100) NOT NULL,
  `state` varchar(100) NOT NULL,
  `postcode` varchar(10) NOT NULL,
  `email` varchar(100) NOT NULL,
  `birthday` datetime NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Check if table exists to prevent erroring.


DROP DATABASE IF EXISTS fizzbuzz_twitterbot;
CREATE DATABASE fizzbuzz_twitterbot CHARACTER SET utf8;
USE fizzbuzz_twitterbot;

DROP TABLE IF EXISTS fizzbuzz_tweets;
CREATE TABLE fizzbuzz_tweets (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  number BIGINT UNSIGNED NOT NULL,
  tweet VARCHAR(140) NOT NULL,
  twitter_tweet_id BIGINT UNSIGNED,
  updated_at DATETIME NOT NULL,
  created_at DATETIME NOT NULL,
  PRIMARY KEY (id)
) ENGINE InnoDB CHARSET utf8;

DROP TABLE IF EXISTS post_errors;
CREATE TABLE post_errors (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  fizzbuzz_tweet_id BIGINT UNSIGNED NOT NULL,
  error_message TEXT NOT NULL,
  updated_at DATETIME NOT NULL,
  created_at DATETIME NOT NULL,
  PRIMARY KEY (id),
  FOREIGN KEY (fizzbuzz_tweet_id) REFERENCES fizzbuzz_tweets (id)
) ENGINE InnoDB CHARSET utf8;

Add default "0" to fizzbuzz_tweets twitter_tweet_id.

DROP DATABASE IF EXISTS fizzbuzz_twitterbot;
CREATE DATABASE fizzbuzz_twitterbot CHARACTER SET utf8;
USE fizzbuzz_twitterbot;

DROP TABLE IF EXISTS fizzbuzz_tweets;
CREATE TABLE fizzbuzz_tweets (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  number BIGINT UNSIGNED NOT NULL,
  tweet VARCHAR(140) NOT NULL,
  twitter_tweet_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
  updated_at DATETIME NOT NULL,
  created_at DATETIME NOT NULL,
  PRIMARY KEY (id)
) ENGINE InnoDB CHARSET utf8;

DROP TABLE IF EXISTS post_errors;
CREATE TABLE post_errors (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  fizzbuzz_tweet_id BIGINT UNSIGNED NOT NULL,
  error_message TEXT NOT NULL,
  updated_at DATETIME NOT NULL,
  created_at DATETIME NOT NULL,
  PRIMARY KEY (id),
  FOREIGN KEY (fizzbuzz_tweet_id) REFERENCES fizzbuzz_tweets (id)
) ENGINE InnoDB CHARSET utf8;


START TRANSACTION;
ALTER TABLE `nk2_orders` MODIFY COLUMN `payment_id` VARCHAR(100) DEFAULT NULL;
ALTER TABLE `nk2_orders` ADD `payment_provider` VARCHAR(50) DEFAULT NULL;
ALTER TABLE `nk2_orders` DROP `reserved_until`;
ALTER TABLE `nk2_orders` DROP `reserved_session_id`;
UPDATE `nk2_orders` SET `payment_provider` = "paytrail";
COMMIT;

Remove migration part of 02 evolutions script

START TRANSACTION;
ALTER TABLE `nk2_orders` MODIFY COLUMN `payment_id` VARCHAR(100) DEFAULT NULL;
ALTER TABLE `nk2_orders` ADD `payment_provider` VARCHAR(50) DEFAULT NULL;
ALTER TABLE `nk2_orders` DROP `reserved_until`;
ALTER TABLE `nk2_orders` DROP `reserved_session_id`;
-- This is just for migration, as payment_provider cannot be null
-- UPDATE `nk2_orders` SET `payment_provider` = "paytrail";
COMMIT;


DROP DATABASE uncovery;
CREATE DATABASE uncovery;

SET foreign_key_checks=0;

USE uncovery;

CREATE TABLE marks (
  id int(5) AUTO_INCREMENT,
  PRIMARY KEY (id),
  x float(10, 6),
  y float(10, 6),
  z float(10, 6),
  timestamp timestamp DEFAULT CURRENT_TIMESTAMP,
  messageId int(5),
  FOREIGN KEY (messageId) REFERENCES messages(id),
  userId int(5),
  FOREIGN KEY (userId) REFERENCES users(id)
);

CREATE TABLE messages (
  id int(5) AUTO_INCREMENT,
  PRIMARY KEY (id),
  messageString text,
  score int(5) DEFAULT 0
);

CREATE TABLE votes (
  id int(5) AUTO_INCREMENT,
  PRIMARY KEY(id),
  userId int(5),
  FOREIGN KEY (userId) REFERENCES users(id),
  messageId int(5),
  FOREIGN KEY (messageId) REFERENCES messages(id)
);

CREATE TABLE users (
  id int(5) AUTO_INCREMENT,
  PRIMARY KEY(id)
);

Include userToken in Schema for auth

DROP DATABASE uncovery;
CREATE DATABASE uncovery;

SET foreign_key_checks=0;

USE uncovery;

CREATE TABLE marks (
  id int(5) AUTO_INCREMENT,
  PRIMARY KEY (id),
  x float(10, 6),
  y float(10, 6),
  z float(10, 6),
  timestamp timestamp DEFAULT CURRENT_TIMESTAMP,
  messageId int(5),
  FOREIGN KEY (messageId) REFERENCES messages(id),
  userId int(5),
  FOREIGN KEY (userId) REFERENCES users(id)
);

CREATE TABLE messages (
  id int(5) AUTO_INCREMENT,
  PRIMARY KEY (id),
  messageString text,
  score int(5) DEFAULT 0
);

CREATE TABLE votes (
  id int(5) AUTO_INCREMENT,
  PRIMARY KEY(id),
  userId int(5),
  FOREIGN KEY (userId) REFERENCES users(id),
  messageId int(5),
  FOREIGN KEY (messageId) REFERENCES messages(id)
);

CREATE TABLE users (
  id int(5) AUTO_INCREMENT,
  PRIMARY KEY(id),
  userToken VARCHAR(255)
);


CREATE TABLE IF NOT EXISTS lddb (
    id text not null unique primary key,
    data jsonb not null,
    manifest jsonb not null,
    quoted jsonb,
    created timestamp with time zone not null default now(),
    modified timestamp with time zone not null default now(),
    deleted boolean default false
    );

CREATE TABLE IF NOT EXISTS lddb__identifiers (
    pk serial,
    id text not null,
    identifier text not null unique
);

CREATE TABLE IF NOT EXISTS lddb__versions (
    pk serial,
    id text not null,
    checksum char(32) not null,
    data jsonb not null,
    manifest jsonb not null,
    modified timestamp with time zone not null default now(),
    unique (id, checksum, modified)
    );

CREATE TABLE IF NOT EXISTS lddb__settings (
    key text not null unique primary key,
    settings jsonb not null
);

Comment out unique constraint on lddb identifier

CREATE TABLE IF NOT EXISTS lddb (
    id text not null unique primary key,
    data jsonb not null,
    manifest jsonb not null,
    quoted jsonb,
    created timestamp with time zone not null default now(),
    modified timestamp with time zone not null default now(),
    deleted boolean default false
    );

CREATE TABLE IF NOT EXISTS lddb__identifiers (
    pk serial,
    id text not null,
    identifier text not null -- unique
);

CREATE TABLE IF NOT EXISTS lddb__versions (
    pk serial,
    id text not null,
    checksum char(32) not null,
    data jsonb not null,
    manifest jsonb not null,
    modified timestamp with time zone not null default now(),
    unique (id, checksum, modified)
    );

CREATE TABLE IF NOT EXISTS lddb__settings (
    key text not null unique primary key,
    settings jsonb not null
);


-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements.  See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership.  The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License.  You may obtain a copy of the License at
--
--   http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied.  See the License for the
-- specific language governing permissions and limitations
-- under the License.

--;
-- Schema upgrade from 4.7.0 to 4.7.1;
--;

Add force_encap field to s2s_customer_gateway table

-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements.  See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership.  The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License.  You may obtain a copy of the License at
--
--   http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied.  See the License for the
-- specific language governing permissions and limitations
-- under the License.

--;
-- Schema upgrade from 4.7.0 to 4.7.1;
--;
ALTER TABLE cloud.s2s_customer_gateway ADD COLUMN force_encap INT(1) NOT NULL DEFAULT 0 AFTER dpd;


-- :name create-user! :! :n
-- :doc creates a new user record
INSERT INTO users
(id, first_name, last_name, email, pass)
VALUES (:id, :first_name, :last_name, :email, :pass)

-- :name update-user! :! :n
-- :doc update an existing user record
UPDATE users
SET first_name = :first_name, last_name = :last_name, email = :email
WHERE id = :id

-- :name get-users :? :*
-- :doc retrieve all users.
SELECT * FROM users

-- :name get-user :? :1
-- :doc retrieve a user given the id.
SELECT * FROM users
WHERE id = :id

-- :name get-merits :? :*
-- :doc retrieve all merits.
SELECT * FROM merits

Add query for adding merits.

-- :name create-user! :! :n
-- :doc creates a new user record
INSERT INTO users
(id, first_name, last_name, email, pass)
VALUES (:id, :first_name, :last_name, :email, :pass)

-- :name update-user! :! :n
-- :doc update an existing user record
UPDATE users
SET first_name = :first_name, last_name = :last_name, email = :email
WHERE id = :id

-- :name get-users :? :*
-- :doc retrieve all users.
SELECT * FROM users

-- :name get-user :? :1
-- :doc retrieve a user given the id.
SELECT * FROM users
WHERE id = :id

-- :name get-merits :? :*
-- :doc retrieve all merits.
SELECT * FROM merits

-- :name add-merit-to-user :! :n
-- :doc Add merit to user
INSERT INTO users_merits (user_id, merit_id) VALUES (:user_id, :merit_id)


UPDATE oskari_statistical_layer SET config = '{"regionType":"seutukunta", "valueProcessor": "fi.nls.oskari.control.statistics.plugins.pxweb.parser.PrefixedRegionsValueProcessor", "statsRegionPrefix": "SK"}'
 where datasource_id = (select id from oskari_statistical_datasource where locale like '%Tilastokeskus%') AND LOWER(config) LIKE '%seutukunta%';

UPDATE oskari_statistical_layer SET config = '{"regionType":"maakunta", "valueProcessor": "fi.nls.oskari.control.statistics.plugins.pxweb.parser.PrefixedRegionsValueProcessor", "statsRegionPrefix": "MK"}'
 where datasource_id = (select id from oskari_statistical_datasource where locale like '%Tilastokeskus%') AND LOWER(config) LIKE '%maakunta%';

Add maakunta regionset for TK datasource

UPDATE oskari_statistical_layer SET config = '{"regionType":"seutukunta", "valueProcessor": "fi.nls.oskari.control.statistics.plugins.pxweb.parser.PrefixedRegionsValueProcessor", "statsRegionPrefix": "SK"}'
 where datasource_id = (select id from oskari_statistical_datasource where locale like '%Tilastokeskus%') AND LOWER(config) LIKE '%seutukunta%';

INSERT INTO
    oskari_statistical_layer(datasource_id, layer_id, config)
VALUES(
    (SELECT id FROM oskari_statistical_datasource
        WHERE locale like '%Tilastokeskus%'),
    (SELECT id FROM oskari_maplayer WHERE type='statslayer' AND name = 'tilastointialueet:maakunta4500k'),
    '{"regionType":"MAAKUNTA, "valueProcessor": "fi.nls.oskari.control.statistics.plugins.pxweb.parser.PrefixedRegionsValueProcessor", "statsRegionPrefix": "MK""}');


CREATE TABLE cloud_file
(
    id serial NOT NULL,
    resource_id text NOT NULL,
    cc_file_id integer NOT NULL,
    CONSTRAINT cloud_file_pkey PRIMARY KEY (id),
    CONSTRAINT "cloud_file_FK_1" FOREIGN KEY (cc_file_id)
        REFERENCES cc_files (id) MATCH SIMPLE
        ON UPDATE NO ACTION ON DELETE CASCADE
)

Upgrade sql was missing the storage_backend column

CREATE TABLE cloud_file
(
    id serial NOT NULL,
    resource_id text NOT NULL,
    storage_backend text NOT NULL,
    cc_file_id integer NOT NULL,
    CONSTRAINT cloud_file_pkey PRIMARY KEY (id),
    CONSTRAINT "cloud_file_FK_1" FOREIGN KEY (cc_file_id)
        REFERENCES cc_files (id) MATCH SIMPLE
        ON UPDATE NO ACTION ON DELETE CASCADE
)


# Display all entries that have the issue
# SELECT * FROM xcolab.members_Member WHERE members_Member.status IS  NULL ;

# Display entries without a createDate and the replacement createDate (DryRun)
# SELECT T1.id_, T1.screenName, T1.createDate, T2.createDate
# FROM xcolab.members_Member T1, xcolab.members_Member T2
# WHERE T1.id_ = T2.id_ + 1 AND T1.createDate IS NULL;

# Update status fields
UPDATE xcolab.members_Member SET status=0 WHERE status IS NULL;
UPDATE xcolab.members_Member SET autoRegisteredMemberStatus=0 WHERE autoRegisteredMemberStatus IS NULL;

# Update createDate field
UPDATE xcolab.members_Member AS T1
JOIN xcolab.members_Member AS T2
    ON T1.id_-1 = T2.id_
SET T1.createDate = T2.createDate
WHERE T1.createDate IS NULL;

Remove remaining "xcolab" table name references

# Display all entries that have the issue
# SELECT * FROM xcolab.members_Member WHERE members_Member.status IS  NULL ;

# Display entries without a createDate and the replacement createDate (DryRun)
# SELECT T1.id_, T1.screenName, T1.createDate, T2.createDate
# FROM xcolab.members_Member T1, xcolab.members_Member T2
# WHERE T1.id_ = T2.id_ + 1 AND T1.createDate IS NULL;

# Update status fields
UPDATE members_Member SET status=0 WHERE status IS NULL;
UPDATE members_Member SET autoRegisteredMemberStatus=0 WHERE autoRegisteredMemberStatus IS NULL;

# Update createDate field
UPDATE members_Member AS T1
JOIN members_Member AS T2
    ON T1.id_-1 = T2.id_
SET T1.createDate = T2.createDate
WHERE T1.createDate IS NULL;


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

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

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

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

Set db default collation & charset

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

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

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

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


CREATE TABLE Users(user_id INTEGER PRIMARY KEY AUTOINCREMENT,
                   username TEXT,
                   password TEXT,
                   salt TEXT);

CREATE TABLE Schools(school_id INTEGER PRIMARY KEY AUTOINCREMENT,
                     name TEXT);

CREATE TABLE Games(game_id INTEGER PRIMARY KEY AUTOINCREMENT,
                   home_team_id INTEGER REFERENCES Schools(school_id),
                   away_team_id INTEGER REFERENCES Schools(school_id),
                   date TEXT);

CREATE TABLE Tickets(ticket_id INTEGER PRIMARY KEY AUTOINCREMENT,
                     game_id INTEGER REFERENCES Games(game_id),
                     seller_id INTEGER REFERENCES Users(user_id),
                     section INTEGER,
                     row INTEGER,
                     seat INTEGER,
                     price INTEGER,
                     sold INTEGER);

Add NOT NULL statements to table rows

CREATE TABLE Users(user_id INTEGER PRIMARY KEY AUTOINCREMENT,
                   username TEXT NOT NULL UNIQUE,
                   password TEXT NOT NULL,
                   salt TEXT);

CREATE TABLE Schools(school_id INTEGER PRIMARY KEY AUTOINCREMENT,
                     name TEXT NOT NULL UNIQUE);

CREATE TABLE Games(game_id INTEGER PRIMARY KEY AUTOINCREMENT,
                   home_team_id INTEGER NOT NULL REFERENCES Schools(school_id),
                   away_team_id INTEGER NOT NULL REFERENCES Schools(school_id),
                   date TEXT);

CREATE TABLE Tickets(ticket_id INTEGER PRIMARY KEY AUTOINCREMENT,
                     game_id INTEGER NOT NULL REFERENCES Games(game_id),
                     seller_id INTEGER NOT NULL REFERENCES Users(user_id),
                     section INTEGER,
                     row INTEGER,
                     seat INTEGER,
                     price INTEGER,
                     sold INTEGER);


alter table invoice_tracking_ids add column is_active boolean default true after record_date;
alter table invoice_tracking_ids add column updated_by varchar(50) NOT NULL after created_date;
alter table invoice_tracking_ids add column updated_date datetime NOT NULL after updated_by;
create index invoice_tracking_invoice_id_idx on invoice_tracking_ids(tenant_record_id, invoice_id);

Fix migration file to include a non null default date

alter table invoice_tracking_ids add column is_active boolean default true after record_date;
alter table invoice_tracking_ids add column updated_by varchar(50) NOT NULL after created_date;
alter table invoice_tracking_ids add column updated_date datetime NOT NULL DEFAULT '1970-01-01 00:00:00' after updated_by;
create index invoice_tracking_invoice_id_idx on invoice_tracking_ids(tenant_record_id, invoice_id);


DELETE FROM user_crispr_pairs_human;
DELETE FROM user_crispr_pairs_mouse;
DELETE FROM user_crisprs_human;
DELETE FROM user_crisprs_mouse;
DELETE FROM crispr_ots_pending;
DELETE FROM crispr_pairs_human;
DELETE FROM crispr_pairs_mouse;
DELETE FROM crispr_pairs;
DELETE FROM crispr_pair_statuses;
DELETE FROM crisprs_human;
DELETE FROM crisprs_mouse;
DELETE FROM crisprs;
DELETE FROM design_attempts;
DELETE FROM design_comments;
DELETE FROM design_comment_categories;
DELETE FROM design_oligo_loci;
DELETE FROM design_oligos;
DELETE FROM design_oligo_types;
DELETE FROM genotyping_primers;
DELETE FROM genotyping_primer_types;
DELETE FROM designs;
DELETE FROM design_types;
DELETE FROM exons;
DELETE FROM gene_design;
DELETE FROM genes;
DELETE FROM species_default_assembly;
DELETE FROM users;
DELETE FROM chromosomes;
DELETE FROM assemblies;
DELETE FROM species;

Truncate haplotype tables during unit tests

DELETE FROM user_haplotype;
DELETE FROM haplotype;
DELETE FROM user_crispr_pairs_human;
DELETE FROM user_crispr_pairs_mouse;
DELETE FROM user_crisprs_human;
DELETE FROM user_crisprs_mouse;
DELETE FROM crispr_ots_pending;
DELETE FROM crispr_pairs_human;
DELETE FROM crispr_pairs_mouse;
DELETE FROM crispr_pairs;
DELETE FROM crispr_pair_statuses;
DELETE FROM crisprs_human;
DELETE FROM crisprs_mouse;
DELETE FROM crisprs;
DELETE FROM design_attempts;
DELETE FROM design_comments;
DELETE FROM design_comment_categories;
DELETE FROM design_oligo_loci;
DELETE FROM design_oligos;
DELETE FROM design_oligo_types;
DELETE FROM genotyping_primers;
DELETE FROM genotyping_primer_types;
DELETE FROM designs;
DELETE FROM design_types;
DELETE FROM exons;
DELETE FROM gene_design;
DELETE FROM genes;
DELETE FROM species_default_assembly;
DELETE FROM users;
DELETE FROM chromosomes;
DELETE FROM assemblies;
DELETE FROM species;


ALTER TABLE _auth_provider_password ALTER COLUMN auth_data TYPE text;
ALTER TABLE _auth_provider_password RENAME COLUMN auth_data TO login_id;
ALTER TABLE _auth_provider_password ADD login_id_key text;

Add migration comments about type altering

/*
This migration script only alter auth_data type from jsonb to text,
and doesn't delete previous signup rows.
*/
ALTER TABLE _auth_provider_password ALTER COLUMN auth_data TYPE text;
ALTER TABLE _auth_provider_password RENAME COLUMN auth_data TO login_id;
ALTER TABLE _auth_provider_password ADD login_id_key text;


SELECT `ipp_group`.`id`,`ipp_group`.`name`
FROM `ipp_group`
INNER JOIN `ipp_group_join`
ON `ipp_group_join`.`group_id` = `ipp_group`.`id`
INNER JOIN `ipp_users`
ON `ipp_group_join`.`user_id` = `ipp_users`.`id`
WHERE `ipp_group_join`.`user_id` = /* Current user id */
AND `ipp_group`.`is_shared` = FALSE;

SELECT `ipp_group`.`id`,`ipp_group`.`name`
FROM `ipp_group`
INNER JOIN `ipp_group_join`
ON `ipp_group_join`.`group_id` = `ipp_group`.`id`
INNER JOIN `ipp_users`
ON `ipp_group_join`.`user_id` = `ipp_users`.`id`
WHERE `ipp_group_join`.`user_id` = /* Current user id */
AND `ipp_group`.`is_shared` = TRUE;

SELECT `ipp_document`.`group_id`,`ipp_document`.`name`,`ipp_document`.`id`
FROM `ipp_document`
INNER JOIN `ipp_users`
ON `ipp_document`.`admin_id`= `ipp_users`.`id`
WHERE `ipp_document`.`admin_id` = /*current user id*/;

Correct SQL for documents selection

SELECT `ipp_group`.`id`,`ipp_group`.`name`
FROM `ipp_group`
INNER JOIN `ipp_group_join`
ON `ipp_group_join`.`group_id` = `ipp_group`.`id`
INNER JOIN `ipp_users`
ON `ipp_group_join`.`user_id` = `ipp_users`.`id`
WHERE `ipp_group_join`.`user_id` = /* Current user id */
AND `ipp_group`.`is_shared` = FALSE;

SELECT `ipp_group`.`id`,`ipp_group`.`name`
FROM `ipp_group`
INNER JOIN `ipp_group_join`
ON `ipp_group_join`.`group_id` = `ipp_group`.`id`
INNER JOIN `ipp_users`
ON `ipp_group_join`.`user_id` = `ipp_users`.`id`
WHERE `ipp_group_join`.`user_id` = /* Current user id */
AND `ipp_group`.`is_shared` = TRUE;

SELECT `ipp_document`.`group_id`,`ipp_document`.`name`,`ipp_document`.`id`
FROM `ipp_document`
WHERE `ipp_document`.`group_id` IN(
    SELECT `ipp_group_join`.`group_id`
    FROM `ipp_group_join`
    WHERE `ipp_group_join`.`user_id`=/* Current user id */);


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;


ALTER TABLE `DITIB_PLACES` add `CREATION_TIME`     datetime DEFAULT NULL;
ALTER TABLE `DITIB_PLACES` add `MODIFICATION_TIME` datetime DEFAULT NULL;

UPDATE `DITIB_PLACES` set `CREATION_TIME` = NOW()     where `CREATION_TIME` IS NULL;
UPDATE `DITIB_PLACES` set `MODIFICATION_TIME` = NOW() where `MODIFICATION_TIME` IS NULL;

Fix broken SQL for database migration

ALTER TABLE `DITIB_PLACES` add `CREATION_TIME`     datetime DEFAULT NOW();
ALTER TABLE `DITIB_PLACES` add `MODIFICATION_TIME` datetime DEFAULT NOW();


-- Copyright [1999-2016] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--      http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.

/**
@header patch_84_85_c.sql - new columns to the epigenome table
@desc   Modify existing or add new columns to the epigenome table
*/

ALTER TABLE epigenome change efo_id ontology_accession VARCHAR(20);
ALTER TABLE epigenome add ontology ENUM('EFO','CL') after ontology_accession;
ALTER TABLE epigenome add production_name VARCHAR(120) after description;

-- patch identifier
INSERT INTO meta (species_id, meta_key, meta_value) VALUES (NULL, 'patch', 'patch_84_85_c.sql|new epigenome table columns');

Create production names from the names.

-- Copyright [1999-2016] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--      http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.

/**
@header patch_84_85_c.sql - new columns to the epigenome table
@desc   Modify existing or add new columns to the epigenome table
*/

ALTER TABLE epigenome change efo_id ontology_accession VARCHAR(20);
ALTER TABLE epigenome add ontology ENUM('EFO','CL') after ontology_accession;
ALTER TABLE epigenome add production_name VARCHAR(120) after description;

-- Create production names from the names.
--
update epigenome set production_name=name;

update epigenome set production_name = replace(production_name, ':', '_');
update epigenome set production_name = replace(production_name, '+', '');
update epigenome set production_name = replace(production_name, '-', '_');
update epigenome set production_name = replace(production_name, '.', '_');

-- patch identifier
INSERT INTO meta (species_id, meta_key, meta_value) VALUES (NULL, 'patch', 'patch_84_85_c.sql|new epigenome table columns');


Title	ISSN	eISSN
Cancer Discovery	2159-8274	2159-8290
Cancer Epidemiology, Biomarkers & Prevention	1055-9965	1538-7755
Cancer Immunology Research	x	x
Cancer Prevention Research	1940-6207	1940-6215
Cancer Research	0008-5472	1538-7445
Molecular Cancer Research	1541-7786	1557-3125
Molecular Cancer Therapeutics	1535-7163	1538-8514

Add AACR's Clinical Cancer Research metadata

Title	ISSN	eISSN
Cancer Discovery	2159-8274	2159-8290
Cancer Epidemiology, Biomarkers & Prevention	1055-9965	1538-7755
Cancer Immunology Research	x	x
Cancer Prevention Research	1940-6207	1940-6215
Cancer Research	0008-5472	1538-7445
Clinical Cancer Research	1078-0432	1557-3265
Molecular Cancer Research	1541-7786	1557-3125
Molecular Cancer Therapeutics	1535-7163	1538-8514


SELECT t1.name AS challenger, t2.name AS challengee, t1.open AS spotopen, t1.challengerspot AS challengerspot,
t1.challengeespot AS challengeespot, t1.namenumber AS namenumberone, t2.namenumber AS namenumbertwo
FROM
  (
    SELECT u1.name, c.spotId AS challengeespot, u1.spotId AS challengerspot, s.open, u1.namenumber
    FROM challenges AS c, spots AS s, users AS u1
    WHERE c.spotId = s.id AND u1.namenumber = c.usernamenumber AND c.performanceId = $1
  ) t1
LEFT JOIN
  (
    SELECT u2.name, u2.spotId, u2.namenumber
    FROM users AS u2
  ) t2
ON
  t1.challengeespot = t2.spotId
ORDER BY t1.challengerspot;

Fix sorting of challenge list query

SELECT t1.name AS challenger, t2.name AS challengee, t1.open AS spotopen, t1.challengerspot AS challengerspot,
t1.challengeespot AS challengeespot, t1.namenumber AS namenumberone, t2.namenumber AS namenumbertwo
FROM
  (
    SELECT u1.name, c.spotId AS challengeespot, u1.spotId AS challengerspot, s.open, u1.namenumber
    FROM challenges AS c, spots AS s, users AS u1
    WHERE c.spotId = s.id AND u1.namenumber = c.usernamenumber AND c.performanceId = $1
  ) t1
LEFT JOIN
  (
    SELECT u2.name, u2.spotId, u2.namenumber
    FROM users AS u2
  ) t2
ON
  t1.challengeespot = t2.spotId
ORDER BY (substring(t1.challengerspot, 0, 2), substring(t1.challengerspot, 2)::int)


CREATE OR REPLACE VIEW project_status AS
SELECT id, status
FROM project
WHERE status IS NOT NULL
GROUP BY status;

Update db view project status

CREATE OR REPLACE VIEW project_status AS
  SELECT row_number() OVER () AS id, status
  FROM project
  WHERE status IS NOT NULL
  GROUP BY status;


CREATE OR REPLACE VIEW {# geotrek.trekking #}.v_treks AS (
	SELECT e.geom, e.id, i.*
	FROM trekking_trek AS i, core_topology AS e
	WHERE i.topo_object_id = e.id
	AND e.deleted = FALSE
);

CREATE OR REPLACE VIEW {# geotrek.trekking #}.v_pois AS (
	SELECT e.geom, e.id, i.*
	FROM trekking_poi AS i, core_topology AS e
	WHERE i.topo_object_id = e.id
	AND e.deleted = FALSE
);

Add UUID to trekking views

CREATE OR REPLACE VIEW {# geotrek.trekking #}.v_treks AS (
	SELECT e.geom, e.id, e.uuid, i.*
	FROM trekking_trek AS i, core_topology AS e
	WHERE i.topo_object_id = e.id
	AND e.deleted = FALSE
);

CREATE OR REPLACE VIEW {# geotrek.trekking #}.v_pois AS (
	SELECT e.geom, e.id, e.uuid, i.*
	FROM trekking_poi AS i, core_topology AS e
	WHERE i.topo_object_id = e.id
	AND e.deleted = FALSE
);


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

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

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

Add index to temp table

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

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

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


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

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

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

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

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

Add timestamp offset fields to git hash table

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

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

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

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

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


CREATE TABLE udit_log
(
  id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(12) NOT NULL,
  recipient VARCHAR(255) NOT NULL,
  subject VARCHAR(255) NOT NULL,
  body TEXT NOT NULL,
  log_time DATETIME NOT NULL
);

Correct audit log table name

CREATE TABLE audit_log
(
  id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(12) NOT NULL,
  recipient VARCHAR(255) NOT NULL,
  subject VARCHAR(255) NOT NULL,
  body TEXT NOT NULL,
  log_time DATETIME NOT NULL
);


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

# Support multiple authentication backends

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

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

Improve back-compatibility of database evolutions

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

# Support multiple authentication backends

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

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


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

DELETE FROM t_encrypt;
DELETE FROM t_query_encrypt;
INSERT INTO t_encrypt VALUES(1, 'encryptValue');
INSERT INTO t_encrypt VALUES(4, 'encryptValue');
INSERT INTO t_query_encrypt VALUES(1, 'encryptValue', 'assistedEncryptValue');
INSERT INTO t_query_encrypt VALUES(5, 'encryptValue', 'assistedEncryptValue');

INSERT INTO t_encrypt VALUES(5, 'encryptValue');

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

DELETE FROM t_encrypt;
DELETE FROM t_query_encrypt;
INSERT INTO t_encrypt VALUES(1, 'encryptValue');
INSERT INTO t_encrypt VALUES(5, 'encryptValue');
INSERT INTO t_query_encrypt VALUES(1, 'encryptValue', 'assistedEncryptValue');
INSERT INTO t_query_encrypt VALUES(5, 'encryptValue', 'assistedEncryptValue');


INSERT INTO users (email, enabled, firstname, lastname, PASSWORD)
values('##user##@##hostname##', '1', 'Whatif', 'User', '$2a$10$IMlSuqhi3F..6V4zG/Y78.DCg2DmXT.B7JsvZVpwf5d4FiLiNQo4K');

Make the default user a whatif user.

-- create user
INSERT INTO users (email, enabled, firstname, lastname, PASSWORD)
values('##user##@##hostname##', '1', 'Whatif', 'User', '$2a$10$IMlSuqhi3F..6V4zG/Y78.DCg2DmXT.B7JsvZVpwf5d4FiLiNQo4K');
-- give the user access to whatif as a user
INSERT INTO user_apps (user_app_id, app_id, user_id)
values(1, 1, 1);
INSERT INTO user_roles (user_role_id, role_id, user_id)
values(1, 2, 1);


create user ut3_demo identified by ut3_demo quota unlimited on USERS default tablespace USERS;

grant create session, create procedure, create type, create table, create sequence, create view to ut3_demo;
grant select any dictionary to ut3_demo;

exit

Update to add trigger grant

create user ut3_demo identified by ut3_demo quota unlimited on USERS default tablespace USERS;

grant create session, create procedure,create trigger, create type, create table, create sequence, create view to ut3_demo;
grant select any dictionary to ut3_demo;

exit


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

SELECT
  receiveTimestamp, timestamp AS eventTimestamp,
  protopayload_auditlog.requestMetadata.callerIp,
  protopayload_auditlog.authenticationInfo.principalEmail,
  protopayload_auditlog.resourceName,
  protopayload_auditlog.methodName
FROM `[MY_PROJECT_ID].[MY_DATASET_ID].cloudaudit_googleapis_com_activity`
WHERE
protopayload_auditlog.methodName = "v1.compute.subnetworks.patch"
AND protopayload_auditlog.request.enableFlowLogs = "false"

Fix BigQuery SQL query for 3.02

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

SELECT
  receiveTimestamp, timestamp AS eventTimestamp,
  protopayload_auditlog.requestMetadata.callerIp,
  protopayload_auditlog.authenticationInfo.principalEmail,
  protopayload_auditlog.resourceName,
  protopayload_auditlog.methodName
FROM `[MY_PROJECT_ID].[MY_DATASET_ID].cloudaudit_googleapis_com_activity`
WHERE
protopayload_auditlog.methodName = "v1.compute.subnetworks.patch"
AND JSON_VALUE(protopayload_auditlog.requestJson, "$.logConfig.enable") = "false"


CREATE TABLE `users` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `email` VARCHAR(100) NOT NULL DEFAULT '',
  `password` VARCHAR(255) NOT NULL DEFAULT '',
  `salt` VARCHAR(255) NOT NULL DEFAULT '',
  `roles` VARCHAR(255) NOT NULL DEFAULT '',
  `name` VARCHAR(100) NOT NULL DEFAULT '',
  `time_created` INT NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `user_custom_fields` (
  user_id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  attribute VARCHAR(50) NOT NULL DEFAULT '',
  value VARCHAR(255) NOT NULL DEFAULT ''
  PRIMARY KEY (user_id, attribute)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Fix SQL definition for user_custom_fields table.

CREATE TABLE `users` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `email` VARCHAR(100) NOT NULL DEFAULT '',
  `password` VARCHAR(255) NOT NULL DEFAULT '',
  `salt` VARCHAR(255) NOT NULL DEFAULT '',
  `roles` VARCHAR(255) NOT NULL DEFAULT '',
  `name` VARCHAR(100) NOT NULL DEFAULT '',
  `time_created` INT NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `user_custom_fields` (
  user_id INT(11) UNSIGNED NOT NULL,
  attribute VARCHAR(50) NOT NULL DEFAULT '',
  value VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (user_id, attribute)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


SET SCHEMA 'cartodb';
\i scripts-available/CDB_Quota.sql
\i scripts-available/CDB_TableMetadata.sql
SET SCHEMA 'public';

Use CDB_ColumnType and CDB_ColumnNames in bash tests

SET SCHEMA 'cartodb';
\i scripts-available/CDB_Quota.sql
\i scripts-available/CDB_TableMetadata.sql
\i scripts-available/CDB_ColumnNames.sql
\i scripts-available/CDB_ColumnType.sql
SET SCHEMA 'public';


COPY (
  SELECT
    sites.abbr AS "Abbreviation",
    path AS "Old Path",
    new_url AS "Redirect URL",
    suggested_url AS "Suggested URL",
    archive_url AS "Custom Archive URL",
    CASE type WHEN 'unresolved' THEN 410 WHEN 'archive' THEN 410 WHEN 'redirect' THEN 301 END AS http_status
    FROM mappings
    INNER JOIN sites ON mappings.site_id = sites.id
    WHERE sites.global_type IS NULL
    ORDER BY sites.abbr, path
) TO STDOUT WITH DELIMITER ',' CSV HEADER;

Rearrange mappings columns into a more logical order

COPY (
  SELECT
    sites.abbr AS "Abbreviation",
    path AS "Old Path",
    CASE type WHEN 'unresolved' THEN 410 WHEN 'archive' THEN 410 WHEN 'redirect' THEN 301 END AS http_status,
    new_url AS "Redirect URL",
    archive_url AS "Custom Archive URL",
    suggested_url AS "Suggested URL"
    FROM mappings
    INNER JOIN sites ON mappings.site_id = sites.id
    WHERE sites.global_type IS NULL
    ORDER BY sites.abbr, path
) TO STDOUT WITH DELIMITER ',' CSV HEADER;


"#Update from 1.5 to 1.6 "

ALTER TABLE `projects_issues` ADD `duration` smallint(3) NOT NULL DEFAULT '100' AFTER `created_at`;
ALTER TABLE `projects` ADD `default_assignee` bigint(20) NULL DEFAULT '1';
ALTER TABLE `Issues Table` ADD `weight` bigint(20) NULL default '1';

ALTER TABLE `projects_issues`
CHANGE `created_by` `created_by` bigint(20) NOT NULL DEFAULT '1' AFTER `id`,
CHANGE `weight` `weight` bigint(20) NOT NULL DEFAULT '1' AFTER `status`;

"# Create ToDo Table "
CREATE TABLE IF NOT EXISTS `users_todos` (
  `id` bigint(20) unsigned NOT NULL auto_increment,
  `issue_id` bigint(20) default NULL,
  `user_id` bigint(20) default NULL,
  `status` tinyint(2) default '1',
  `weight` bigint(20) default 1,
  `created_at` datetime default NULL,
  `updated_at` datetime default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `tags` (`id`, `tag`, `bgcolor`, `created_at`, `updated_at`) VALUES
(9,	'status:inProgress','#FF6600',	'2016-11-10 23:12:01',	'2016-11-10 23:12:01');

Update all tables of a SQL database

"#Update from 1.5 to 1.6 "

ALTER TABLE `projects_issues` ADD `duration` smallint(3) NOT NULL DEFAULT '100' AFTER `created_at`;
ALTER TABLE `projects` ADD `default_assignee` bigint(20) NULL DEFAULT '1';
ALTER TABLE `Issues Table` ADD `weight` bigint(20) NULL default '1';

ALTER TABLE `projects_issues`
CHANGE `created_by` `created_by` bigint(20) NOT NULL DEFAULT '1' AFTER `id`,
CHANGE `weight` `weight` bigint(20) NOT NULL DEFAULT '1' AFTER `status`;

"# Create ToDo Table "
CREATE TABLE IF NOT EXISTS `users_todos` (
  `id` bigint(20) unsigned NOT NULL auto_increment,
  `issue_id` bigint(20) default NULL,
  `user_id` bigint(20) default NULL,
  `status` tinyint(2) default '1',
  `weight` bigint(20) default 1,
  `created_at` datetime default NULL,
  `updated_at` datetime default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

UPDATE tags SET id = id + 1001 WHERE id > 8;
UPDATE projects_issues_tags SET tag_id = tag_id + 1 WHERE id > 8;
INSERT INTO `tags` (`id`, `tag`, `bgcolor`, `created_at`, `updated_at`) VALUES (9,	'status:inProgress','#FF6600', NOW(), NOW() );
UPDATE tags SET id = id - 1000 WHERE id > 9;


CREATE OR REPLACE FUNCTION ts.insertaggregatechronology(_aggregatedatasetid integer,
  _agetypeid integer,
  _isdefault boolean,
  _chronologyname character varying,
  _ageboundyounger integer,
  _ageboundolder integer,
  _notes character varying)
 RETURNS TABLE(aggregatechronid integer)
 LANGUAGE sql
AS $function$
  INSERT INTO ndb.aggregatechronologies
	(aggregatedatasetid, agetypeid, isdefault, chronologyname, ageboundyounger, ageboundolder, notes)
  VALUES (_aggregatedatasetid, _agetypeid, _isdefault, _chronologyname, _ageboundyounger, _ageboundolder, _notes)
  RETURNING aggregatechronid
$function$

Insert aggregate geochron now has the proper defaults.

CREATE OR REPLACE FUNCTION ts.insertaggregatechronology(_aggregatedatasetid integer,
  _agetypeid integer,
  _isdefault boolean,
  _chronologyname character varying,
  _ageboundyounger integer,
  _ageboundolder integer,
  _notes character varying DEFAULT NULL::character varying)
 RETURNS TABLE(aggregatechronid integer)
 LANGUAGE sql
AS $function$
  INSERT INTO ndb.aggregatechronologies
	(aggregatedatasetid, agetypeid, isdefault, chronologyname, ageboundyounger, ageboundolder, notes)
  VALUES (_aggregatedatasetid, _agetypeid, _isdefault, _chronologyname, _ageboundyounger, _ageboundolder, _notes)
  RETURNING aggregatechronid
$function$


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

CREATE TABLE IF NOT EXISTS pushers2 (
    id BIGINT PRIMARY KEY,
    user_name TEXT NOT NULL,
    access_token BIGINT DEFAULT NULL,
    profile_tag VARCHAR(32) NOT NULL,
    kind VARCHAR(8) NOT NULL,
    app_id VARCHAR(64) NOT NULL,
    app_display_name VARCHAR(64) NOT NULL,
    device_display_name VARCHAR(128) NOT NULL,
    pushkey TEXT NOT NULL,
    ts BIGINT NOT NULL,
    lang VARCHAR(16),
    data TEXT,
    last_stream_ordering INTEGER,
    last_success BIGINT,
    failing_since BIGINT,
    UNIQUE (app_id, pushkey, user_name)
);

INSERT INTO pushers2 SELECT * FROM PUSHERS;

DROP TABLE PUSHERS;

ALTER TABLE pushers2 RENAME TO pushers;

Use TEXT rather than VARCHAR

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

CREATE TABLE IF NOT EXISTS pushers2 (
    id BIGINT PRIMARY KEY,
    user_name TEXT NOT NULL,
    access_token BIGINT DEFAULT NULL,
    profile_tag TEXT NOT NULL,
    kind TEXT NOT NULL,
    app_id TEXT NOT NULL,
    app_display_name TEXT NOT NULL,
    device_display_name TEXT NOT NULL,
    pushkey TEXT NOT NULL,
    ts BIGINT NOT NULL,
    lang TEXT,
    data TEXT,
    last_stream_ordering INTEGER,
    last_success BIGINT,
    failing_since BIGINT,
    UNIQUE (app_id, pushkey, user_name)
);

INSERT INTO pushers2 SELECT * FROM PUSHERS;

DROP TABLE PUSHERS;

ALTER TABLE pushers2 RENAME TO pushers;


SELECT DISTINCT
    pc.value AS practice_code,
    d.value AS email_address
FROM    redcap6170_briccsext.redcap_data d
INNER JOIN redcap6170_briccsext.redcap_data pc
    ON pc.project_id = d.project_id
    AND pc.field_name = 'practice_code'
    AND pc.record = d.record
WHERE d.project_id IN (29, 53)
    AND d.field_name IN (
        'practice_manager_email',
        'sen_part_email',
        'contact_email_add'
    )
;

Add PI to user details

SELECT DISTINCT
    pc.value AS practice_code,
    d.value AS email_address
FROM    redcap6170_briccsext.redcap_data d
INNER JOIN redcap6170_briccsext.redcap_data pc
    ON pc.project_id = d.project_id
    AND pc.field_name = 'practice_code'
    AND pc.record = d.record
WHERE d.project_id IN (29, 53)
    AND d.field_name IN (
        'practice_manager_email',
        'sen_part_email',
        'contact_email_add',
        'pi_email_add'
    )
;


/* Reinsert media to update the thumbnail_id foreign key */
"CREATE TEMPORARY TABLE " + Media::Table::Name + "_backup("
    "id_media INTEGER PRIMARY KEY AUTOINCREMENT,"
    "type INTEGER,"
    "subtype INTEGER NOT NULL DEFAULT " +
        std::to_string( static_cast<typename std::underlying_type<IMedia::SubType>::type>(
                            IMedia::SubType::Unknown ) ) + ","
    "duration INTEGER DEFAULT -1,"
    "play_count UNSIGNED INTEGER,"
    "last_played_date UNSIGNED INTEGER,"
    "real_last_played_date UNSIGNED INTEGER,"
    "insertion_date UNSIGNED INTEGER,"
    "release_date UNSIGNED INTEGER,"
    "thumbnail_id INTEGER,"
    "title TEXT COLLATE NOCASE,"
    "filename TEXT COLLATE NOCASE,"
    "is_favorite BOOLEAN NOT NULL DEFAULT 0,"
    "is_present BOOLEAN NOT NULL DEFAULT 1,"
    "device_id INTEGER,"
    "nb_playlists UNSIGNED INTEGER NOT NULL DEFAULT 0,"
    "folder_id UNSIGNED INTEGER"
")",

"INSERT INTO " + Media::Table::Name + "_backup SELECT * FROM " + Media::Table::Name,

"DROP TABLE " + Media::Table::Name,

#include "database/tables/Media_v17.sql"

"INSERT INTO " + Media::Table::Name + " SELECT * FROM " + Media::Table::Name + "_backup",
"DROP TABLE " + Media::Table::Name + "_backup",

Fix incorrect trigger due to 13 -> 14 migration

/* Reinsert media to update the thumbnail_id foreign key */
"CREATE TEMPORARY TABLE " + Media::Table::Name + "_backup("
    "id_media INTEGER PRIMARY KEY AUTOINCREMENT,"
    "type INTEGER,"
    "subtype INTEGER NOT NULL DEFAULT " +
        std::to_string( static_cast<typename std::underlying_type<IMedia::SubType>::type>(
                            IMedia::SubType::Unknown ) ) + ","
    "duration INTEGER DEFAULT -1,"
    "play_count UNSIGNED INTEGER,"
    "last_played_date UNSIGNED INTEGER,"
    "real_last_played_date UNSIGNED INTEGER,"
    "insertion_date UNSIGNED INTEGER,"
    "release_date UNSIGNED INTEGER,"
    "thumbnail_id INTEGER,"
    "title TEXT COLLATE NOCASE,"
    "filename TEXT COLLATE NOCASE,"
    "is_favorite BOOLEAN NOT NULL DEFAULT 0,"
    "is_present BOOLEAN NOT NULL DEFAULT 1,"
    "device_id INTEGER,"
    "nb_playlists UNSIGNED INTEGER NOT NULL DEFAULT 0,"
    "folder_id UNSIGNED INTEGER"
")",

"INSERT INTO " + Media::Table::Name + "_backup SELECT * FROM " + Media::Table::Name,

"DROP TABLE " + Media::Table::Name,

#include "database/tables/Media_v17.sql"

"INSERT INTO " + Media::Table::Name + " SELECT * FROM " + Media::Table::Name + "_backup",
"DROP TABLE " + Media::Table::Name + "_backup",

// This trigger was incorrectly recreated during the 13 -> 14 migration, so
// ensure it's the correct one now.
// Artists triggers are all recreated as part of the 16 -> 17 migration
"DROP TRIGGER has_track_remaining",


-- A table that will store the whole transaction log of the database.
CREATE TABLE IF NOT EXISTS txlog (
  id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
  created_at timestamptz DEFAULT current_timestamp,
  payload text
) WITH (OIDS=FALSE);

Add uuid-ossp extension to first migration.

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- A table that will store the whole transaction log of the database.
CREATE TABLE IF NOT EXISTS txlog (
  id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
  created_at timestamptz DEFAULT current_timestamp,
  payload text
) WITH (OIDS=FALSE);


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

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

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

Add missing not null props to user table fields.

CREATE TABLE IF NOT EXISTS users (
  id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
  created_at timestamptz DEFAULT current_timestamp,
  modified_at timestamptz DEFAULT current_timestamp,
  username text NOT NULL,
  email text NOT NULL,
  password text NOT NULL
) 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);


-- Maximum supported zoom level
CREATE OR REPLACE FUNCTION _CDB_MaxSupportedZoom()
RETURNS int
LANGUAGE SQL
IMMUTABLE
AS $$
  -- The maximum zoom level has to be limited for various reasons,
  -- e.g. zoom levels greater than 31 would require tile coordinates
  -- that would not fit in an INTEGER (which is signed, 32 bits long).
  -- We'll choose 20 as a limit which is safe also when the JavaScript shift
  -- operator (<<) is used for computing powers of two.
  SELECT 29;
$$;

CREATE OR REPLACE FUNCTION cartodb.CDB_ZoomFromScale(scaleDenominator numeric)
RETURNS int
LANGUAGE SQL
IMMUTABLE
AS $$
SELECT
  CASE
    -- Don't bother if the scale is larger than ~zoom level 0
    WHEN scaleDenominator > 600000000 OR scaleDenominator = 0 THEN NULL
    WHEN scaleDenominator = 0 THEN _CDB_MaxSupportedZoom()
    ELSE CAST (LEAST(ROUND(LOG(2, 559082264.028/scaleDenominator)), _CDB_MaxSupportedZoom()) AS INTEGER)
  END;
$$;

Fix zoom from scale condition for NULL result

-- Maximum supported zoom level
CREATE OR REPLACE FUNCTION _CDB_MaxSupportedZoom()
RETURNS int
LANGUAGE SQL
IMMUTABLE
AS $$
  -- The maximum zoom level has to be limited for various reasons,
  -- e.g. zoom levels greater than 31 would require tile coordinates
  -- that would not fit in an INTEGER (which is signed, 32 bits long).
  -- We'll choose 20 as a limit which is safe also when the JavaScript shift
  -- operator (<<) is used for computing powers of two.
  SELECT 29;
$$;

CREATE OR REPLACE FUNCTION cartodb.CDB_ZoomFromScale(scaleDenominator numeric)
RETURNS int
LANGUAGE SQL
IMMUTABLE
AS $$
  SELECT
    CASE
      WHEN scaleDenominator > 600000000 THEN
        -- Scale is smaller than zoom level 0
        NULL
      WHEN scaleDenominator = 0 THEN
        -- Actual zoom level would be infinite
        _CDB_MaxSupportedZoom()
      ELSE
        CAST (
          LEAST(
            ROUND(LOG(2, 559082264.028/scaleDenominator)),
            _CDB_MaxSupportedZoom()
          )
        AS INTEGER)
    END;
$$;


-- add support for java.time API
INSERT INTO Type VALUES (21, "mds.field.description.datetime", "mds.field.datetime8", "datetime", "java.time.LocalDateTime");
INSERT INTO Type VALUES (22, "mds.field.description.localDate", "mds.field.date8", "localDate", "java.time.LocalDate");

Fix for postgresql V42 migration in MDS

-- add support for java.time API
INSERT INTO "Type" VALUES (21, 'mds.field.description.datetime', 'mds.field.datetime8', 'datetime', 'java.time.LocalDateTime');
INSERT INTO "Type" VALUES (22, 'mds.field.description.localDate', 'mds.field.date8', 'localDate', 'java.time.LocalDate');


BEGIN;
ALTER TABLE subscribers RENAME TO sub;
create table subscribers (
        id              serial primary key,
        msisdn          varchar,
        name            varchar,
        authorized      smallint not null default 0,
        balance         decimal not null default 0.00,
        subscription_status     smallint not null default 0,
        subscription_date       timestamp default current_timestamp,
	location	varchar,
        created         timestamp default current_timestamp
);
INSERT INTO subscribers(id,msisdn,name,authorized,balance,subscription_status,subscription_date,created) SELECT id,msisdn,name,authorized,balance,subscription_status,subscription_date,created FROM sub;
DROP TABLE sub;
CREATE TABLE locations (
	id		serial primary key,
	name		varchar not null
);
COMMIT;

Increase counter after a succesful DB migration (11 in this case)

BEGIN;
UPDATE meta SET value='11' WHERE key='db_revision';

ALTER TABLE subscribers RENAME TO sub;
create table subscribers (
        id              serial primary key,
        msisdn          varchar,
        name            varchar,
        authorized      smallint not null default 0,
        balance         decimal not null default 0.00,
        subscription_status     smallint not null default 0,
        subscription_date       timestamp default current_timestamp,
	location	varchar,
        created         timestamp default current_timestamp
);
INSERT INTO subscribers(id,msisdn,name,authorized,balance,subscription_status,subscription_date,created) SELECT id,msisdn,name,authorized,balance,subscription_status,subscription_date,created FROM sub;
DROP TABLE sub;
CREATE TABLE locations (
	id		serial primary key,
	name		varchar not null
);
COMMIT;


DROP TABLE `test`.`person`;

CREATE TABLE `test`.`person` (
  `id` INT NULL AUTO_INCREMENT,
  `title` VARCHAR(45) NOT NULL,
  UNIQUE INDEX `id_UNIQUE` (`id` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci
COMMENT = 'test person table';

INSERT INTO `test`.`person` (`id`, `title`) VALUES ("1", "Mr Conor");

INSERT INTO `test`.`person` (`id`, `title`) VALUES ("2", "Mr John");

INSERT INTO `test`.`person` (`id`, `title`) VALUES ("3", "Joe Bloggs");

ALTER TABLE `test`.`person`
ADD COLUMN `first_name` VARCHAR(45) NULL AFTER `title`,
ADD COLUMN `surname` VARCHAR(45) NULL AFTER `first_name`,
ADD COLUMN `age` INT NULL AFTER `surname`;

UPDATE `test`.`person` SET `title`="Mr", `first_name`="Conor", `surname`="Heffron", `age`="30" WHERE `id`="1";
UPDATE `test`.`person` SET `title`="Mr", `first_name`="Joe", `surname`="Bloggs", `age`="40" WHERE `id`="2";
UPDATE `test`.`person` SET `title`="Dr", `first_name`="John", `surname`="Jones", `age`="20" WHERE `id`="3";

Update DB script to use upper case table name

DROP TABLE `test`.`PERSON`;

CREATE TABLE `test`.`PERSON` (
  `id` INT NULL AUTO_INCREMENT,
  `title` VARCHAR(45) NOT NULL,
  UNIQUE INDEX `id_UNIQUE` (`id` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci
COMMENT = 'test PERSON table';

INSERT INTO `test`.`PERSON` (`id`, `title`) VALUES ("1", "Mr Conor");

INSERT INTO `test`.`PERSON` (`id`, `title`) VALUES ("2", "Mr John");

INSERT INTO `test`.`PERSON` (`id`, `title`) VALUES ("3", "Joe Bloggs");

ALTER TABLE `test`.`PERSON`
ADD COLUMN `first_name` VARCHAR(45) NULL AFTER `title`,
ADD COLUMN `surname` VARCHAR(45) NULL AFTER `first_name`,
ADD COLUMN `age` INT NULL AFTER `surname`;

UPDATE `test`.`PERSON` SET `title`="Mr", `first_name`="Conor", `surname`="Heffron", `age`="30" WHERE `id`="1";
UPDATE `test`.`PERSON` SET `title`="Mr", `first_name`="Joe", `surname`="Bloggs", `age`="40" WHERE `id`="2";
UPDATE `test`.`PERSON` SET `title`="Dr", `first_name`="John", `surname`="Jones", `age`="20" WHERE `id`="3";


/* ALTER TABLE posts
ADD user_id INT NOT NULL;

ALTER TABLE comments
ADD user_id INT NOT NULL;

ALTER TABLE posts
ADD FOREIGN KEY (user_id) REFERENCES users(id);

ALTER TABLE comments
ADD FOREIGN KEY (user_id) REFERENCES users(id);

*/

Add user reference to post and comment


drop index ACT_IDX_HI_TASK_SCOPE on ACT_RU_TASK;
drop index ACT_IDX_HI_TASK_SUB_SCOPE on ACT_RU_TASK;
drop index ACT_IDX_HI_TASK_SCOPE_DEF on ACT_RU_TASK;

drop table if exists ACT_HI_TASKINST;

Fix mysql task service drop script

drop index ACT_IDX_HI_TASK_SCOPE on ACT_HI_TASKINST;
drop index ACT_IDX_HI_TASK_SUB_SCOPE on ACT_HI_TASKINST;
drop index ACT_IDX_HI_TASK_SCOPE_DEF on ACT_HI_TASKINST;

drop table if exists ACT_HI_TASKINST;


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

-- Create syntax for TABLE 'message'
CREATE TABLE `message` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `uuid` varchar(60) NOT NULL DEFAULT '',
  `sender` varchar(60) DEFAULT NULL,
  `message_body` varchar(255) DEFAULT '',
  `slot` int(1) DEFAULT NULL,
  `timestamp` bigint(13) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- Create syntax for TABLE 'receiver_auth'
CREATE TABLE `receiver_auth` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `uuid` varchar(60) NOT NULL DEFAULT '',
  `receiver_id` varchar(60) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- Create syntax for TABLE 'simple_id'
CREATE TABLE `simple_id` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `simple_id` varchar(11) NOT NULL DEFAULT '',
  `uuid` varchar(60) NOT NULL DEFAULT '',
  `last_update` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `simple_id` (`simple_id`),
  UNIQUE KEY `uuid` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Update db script to change timestamp to unix format(in seconds)

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

-- Create syntax for TABLE 'message'
CREATE TABLE `message` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `uuid` varchar(60) NOT NULL DEFAULT '',
  `sender` varchar(60) DEFAULT NULL,
  `message_body` varchar(255) DEFAULT '',
  `slot` int(1) DEFAULT NULL,
  `timestamp` int(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- Create syntax for TABLE 'receiver_auth'
CREATE TABLE `receiver_auth` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `uuid` varchar(60) NOT NULL DEFAULT '',
  `receiver_id` varchar(60) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- Create syntax for TABLE 'simple_id'
CREATE TABLE `simple_id` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `simple_id` varchar(11) NOT NULL DEFAULT '',
  `uuid` varchar(60) NOT NULL DEFAULT '',
  `last_update` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `simple_id` (`simple_id`),
  UNIQUE KEY `uuid` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE mq_server_msgs(
    id SERIAL NOT NULL PRIMARY KEY,
    msg_id VARCHAR(255) NOT NULL UNIQUE,
    priority INT NOT NULL,
    destination VARCHAR(255) NOT NULL,
    timestamp TIMESTAMP WITHOUT TIME ZONE NOT NULL,
    ack_timeout FLOAT NOT NULL,
    body TEXT NOT NULL
);

CREATE TABLE mq_server_ack_msgs(LIKE mq_server_msgs INCLUDING DEFAULTS);

CREATE INDEX mq_server_msgs_destination_priority_timestamp ON mq_server_msgs
       USING BTREE(priority, timestamp);

CREATE UNIQUE INDEX mq_server_ack_msgs_msg_id ON mq_server_ack_msgs USING BTREE(msg_id);

Fix index for msg table.

CREATE TABLE mq_server_msgs(
    id SERIAL NOT NULL PRIMARY KEY,
    msg_id VARCHAR(255) NOT NULL UNIQUE,
    priority INT NOT NULL,
    destination VARCHAR(255) NOT NULL,
    timestamp TIMESTAMP WITHOUT TIME ZONE NOT NULL,
    ack_timeout FLOAT NOT NULL,
    body TEXT NOT NULL
);

CREATE TABLE mq_server_ack_msgs(LIKE mq_server_msgs INCLUDING DEFAULTS);

CREATE INDEX mq_server_msgs_destination_priority_timestamp ON mq_server_msgs
       USING BTREE(destination, priority, timestamp);

CREATE UNIQUE INDEX mq_server_ack_msgs_msg_id ON mq_server_ack_msgs USING BTREE(msg_id);


CONNECT itwiki_p itwiki.labsdb;
SELECT IF( EXISTS(SELECT * FROM templatelinks WHERE tl_from=page_id AND tl_namespace=10 AND tl_title='S'),
         CONCAT('# [[', page_title, ']] - ', page_len, ' (Stub)'), CONCAT('# [[', page_title, ']] - ', page_len) )
  FROM page
  WHERE page_namespace = 0 AND page_is_redirect = 0
    AND page_len < 300
    AND page_id NOT IN ( SELECT cl_from
      FROM categorylinks
      WHERE cl_to = 'Voci_protette'
        OR cl_to LIKE 'Da_trasferire%'
        OR cl_to = 'Voci_trasferite'
        OR cl_to = 'Disambigua'
        OR cl_to LIKE 'Combinazioni_di%'
        OR cl_to LIKE 'Aiutare%'
        OR cl_to LIKE 'Liste_%'
		OR cl_to LIKE 'Decenni_%'
        OR cl_to LIKE 'Pagine_protette_per_minacce_legali'  )
  ORDER BY page_len, page_title;

Improve query Voci brevi senza avviso

CONNECT itwiki_p itwiki.labsdb;
SELECT IF( EXISTS(SELECT * FROM templatelinks WHERE tl_from=page_id AND tl_namespace=10 AND tl_title='S'),
         CONCAT('# [[', page_title, ']] - ', page_len, ' (Stub)'), CONCAT('# [[', page_title, ']] - ', page_len) )
  FROM page
  WHERE page_namespace = 0 AND page_is_redirect = 0
    AND page_len < 300
    AND page_id NOT IN ( SELECT cl_from
      FROM categorylinks
      WHERE cl_to = 'Voci_protette'
        OR cl_to LIKE 'Da_trasferire%'
        OR cl_to = 'Voci_trasferite'
        OR cl_to = 'Disambigua'
        OR cl_to LIKE 'Combinazioni_di%'
        OR cl_to LIKE 'Aiutare%'
        OR cl_to LIKE 'Liste_%'
	 OR cl_to LIKE 'Decenni_%'
	 OR cl_to LIKE 'Anni_%'
        OR cl_to LIKE 'Pagine_protette_per_minacce_legali'  )
  ORDER BY page_len, page_title;


-- SQL to show tracking days per device.
-- A relatively low number of tracking days could indicate that the bird is dead.
-- https://lifewatch-inbo.cartodb.com/viz/13fd195c-b45d-11e3-b989-0e230854a1cb/table

select
  d.bird_name,
  d.scientific_name,
  d.ring_code_color,
  min(t.date_time) as start,
  max(t.date_time) as end,
  max(t.date_time)::date - min(t.date_time)::date as days,
  d.remarks
from bird_tracking t
  left join bird_tracking_devices d
  on t.device_info_serial = d.device_info_serial
where t.userflag is false
group by
  d.bird_name,
  d.scientific_name,
  d.ring_code_color,
  d.remarks
order by days desc

Remove link that does not work

-- SQL to show tracking days per device.
-- A relatively low number of tracking days could indicate that the bird is dead.

select
  d.bird_name,
  d.scientific_name,
  d.ring_code_color,
  min(t.date_time) as start,
  max(t.date_time) as end,
  max(t.date_time)::date - min(t.date_time)::date as days,
  d.remarks
from bird_tracking t
  left join bird_tracking_devices d
  on t.device_info_serial = d.device_info_serial
where t.userflag is false
group by
  d.bird_name,
  d.scientific_name,
  d.ring_code_color,
  d.remarks
order by days desc


/* Todos os códigos das views serão adicionados aqui */
/**
 * View para selecionar a quantidade de usuários cadastrados por mês
 * @author Daniel Moreira Cardoso
 */

 CREATE VIEW `quantidade_de_usuarios_por_mes` AS
    (SELECT
        DATE_FORMAT(`usuarios`.`data_cadastro`, '%M/%Y') AS `Mês_Ano`,
        COUNT(*) AS `Quantidade de novos usuários`
    FROM
        `usuarios`
    GROUP BY `Mês_Ano`
    ORDER BY `usuarios`.`data_cadastro`);

/**
 * View para selecionar a quantidade de comentários do usuário
 * @author Gusttavo Nunes Gomes
 */
 CREATE VIEW quantidade_de_comentarios_do_usuario AS
	(SELECT
		COUNT(*) AS `Quantidade de Comentarios`,
		`usuarios`.`nome` AS `Nome Usuário`
	FROM
		((usuarios
		INNER JOIN `postagens` ON `usuarios`.`id` = `postagens`.`usuario`)
		INNER JOIN `comentarios` ON `comentarios`.`postagem` = `postagens`.`id`)
	GROUP BY `usuarios`.`id`
	ORDER BY `Quantidade de Comentarios`);

Update nos textos da view

/* Todos os códigos das views serão adicionados aqui */
/**
 * View para selecionar a quantidade de usuários cadastrados por mês
 * @author Daniel Moreira Cardoso
 */

 CREATE VIEW `quantidade_de_usuarios_por_mes` AS
    (SELECT
        DATE_FORMAT(`usuarios`.`data_cadastro`, '%M/%Y') AS `Mês_Ano`,
        COUNT(*) AS `Quantidade de novos usuários`
    FROM
        `usuarios`
    GROUP BY `Mês_Ano`
    ORDER BY `usuarios`.`data_cadastro`);

/**
 * View para selecionar a quantidade de comentários do usuário
 * @author Gusttavo Nunes Gomes
 */
 CREATE VIEW quantidade_de_comentarios_do_usuario AS
	(SELECT
		`usuarios`.`nome` AS `Usuário`,
		COUNT(*) AS `Qtde. Comentários`

	FROM
		((usuarios
		INNER JOIN `postagens` ON `usuarios`.`id` = `postagens`.`usuario`)
		INNER JOIN `comentarios` ON `comentarios`.`postagem` = `postagens`.`id`)
	GROUP BY `usuarios`.`id`
	ORDER BY `Qtde. Comentários`);


--
-- JBoss, Home of Professional Open Source.
-- Copyright 2014-2020 Red Hat, Inc., and individual contributors
-- as indicated by the @author tags.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--

--------------------------------------------------------------------------------
-- BuildEnvironment
--------------------------------------------------------------------------------
BEGIN transaction;
    ALTER TABLE buildenvironment ADD COLUMN hidden BOOLEAN;

    -- by default all existing buildenvironment are not hidden
    UPDATE buildenvironment SET hidden = false;
    ALTER TABLE buildenvironment ALTER COLUMN hidden SET NOT NULL;
COMMIT;

Update description and hidden values for BuildEnvironments

--
-- JBoss, Home of Professional Open Source.
-- Copyright 2014-2020 Red Hat, Inc., and individual contributors
-- as indicated by the @author tags.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--

--------------------------------------------------------------------------------
-- BuildEnvironment
--------------------------------------------------------------------------------
BEGIN transaction;
    ALTER TABLE buildenvironment ADD COLUMN hidden BOOLEAN;

    -- by default all existing buildenvironment are not hidden
    UPDATE buildenvironment SET hidden = false;
    ALTER TABLE buildenvironment ALTER COLUMN hidden SET NOT NULL;
COMMIT;

BEGIN transaction;
    UPDATE buildenvironment SET hidden = true WHERE systemImageRepositoryUrl LIKE 'docker-registry-default.cloud.registry.upshift.redhat.com%';
    UPDATE buildenvironment SET description = name || ' [' || systemImageId || ']';
COMMIT;


-- create text index for rdf literals
create index literals_text_index on literals(text);

-- create int index for object uri of rdf triples
create index triples_ou_index    on triples(objectUri);

-- create int index for object literal of rdf triples
create index triples_ol_index    on triples(objectLiteral);

-- create int index for [predicate,obj ur] of rdf triples
create index triples_pou_index   on triples(predicateUri, objectUri);

-- create int index for [predicate,obj literal] of rdf triples
create index triples_pol_index   on triples(predicateUri, objectLiteral);

-- create int index for [subject,predicate,obj uri] of rdf triples
create index triples_spou_index  on triples(subjectUri, predicateUri, objectUri);

-- create int index for [subject,predicate,obj literal] of rdf triples
create index triples_spol_index  on triples(subjectUri, predicateUri, objectLiteral);

-- create FTS4 virtual table to store SKOS concepts with uri/type/scheme/identifier/pref_label/alt_labels
CREATE VIRTUAL TABLE literals_fts USING fts4(id INTEGER, uri TEXT, scheme_uri TEXT, identifier TEXT, pref_label TEXT, alt_labels TEXT, text TEXT, tokenize=porter);

Revert "column type information for FTS4 literals table"

-- create text index for rdf literals
create index literals_text_index on literals(text);

-- create int index for object uri of rdf triples
create index triples_ou_index    on triples(objectUri);

-- create int index for object literal of rdf triples
create index triples_ol_index    on triples(objectLiteral);

-- create int index for [predicate,obj ur] of rdf triples
create index triples_pou_index   on triples(predicateUri, objectUri);

-- create int index for [predicate,obj literal] of rdf triples
create index triples_pol_index   on triples(predicateUri, objectLiteral);

-- create int index for [subject,predicate,obj uri] of rdf triples
create index triples_spou_index  on triples(subjectUri, predicateUri, objectUri);

-- create int index for [subject,predicate,obj literal] of rdf triples
create index triples_spol_index  on triples(subjectUri, predicateUri, objectLiteral);

-- create FTS4 virtual table to store SKOS concepts with uri/type/scheme/identifier/pref_label/alt_labels
create virtual table literals_fts USING fts4(id, uri, scheme_uri, identifier, pref_label, alt_labels, text, tokenize=porter);


# 04/30/2010

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

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

Increase size of web_form_address and web_form_address2 in campaigns, lists, in-groups to 2000 characters.

# 04/30/2010

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

ALTER TABLE osdial_campaigns MODIFY web_form_address VARCHAR(2000) DEFAULT '/osdial/agent/webform_redirect.php';##|##
 ##    Set max length on campaign web-form1 to 2000 characters.;

ALTER TABLE osdial_campaigns MODIFY web_form_address2 VARCHAR(2000) DEFAULT '/osdial/agent/webform_redirect.php';##|##
 ##    Set max length on campaign web-form2 to 2000 characters.;

ALTER TABLE osdial_lists MODIFY web_form_address VARCHAR(2000) DEFAULT '/osdial/agent/webform_redirect.php';##|##
 ##    Set max length on lists web-form1 to 2000 characters.;

ALTER TABLE osdial_lists MODIFY web_form_address2 VARCHAR(2000) DEFAULT '/osdial/agent/webform_redirect.php';##|##
 ##    Set max length on lists web-form2 to 2000 characters.;

ALTER TABLE osdial_inbound_groups MODIFY web_form_address VARCHAR(2000) DEFAULT '/osdial/agent/webform_redirect.php';##|##
 ##    Set max length on in-groups web-form1 to 2000 characters.;

ALTER TABLE osdial_inbound_groups MODIFY web_form_address2 VARCHAR(2000) DEFAULT '/osdial/agent/webform_redirect.php';##|##
 ##    Set max length on in-groups web-form2 to 2000 characters.;

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


INSERT
    INTO objects (account, id, objectType, published, updated, _json)
    SELECT
            1, id, objectType, published, updated, _json
        FROM objects_old;

CREATE INDEX ix_objects_by_just_id ON objects (id, _ID);
CREATE INDEX ix_objects_old_by_id ON objects_old (id, author, inReplyTo);

UPDATE objects SET
    author    = (
        SELECT _ID FROM objects AS a_n WHERE a_n.id=(
            SELECT author FROM objects_old WHERE objects_old.id=objects.id)),
    inReplyTo = (
        SELECT _ID from objects AS a_n WHERE a_n.id = (
            SELECT inReplyTo from objects_old where objects_old.id=objects.id));

DROP INDEX ix_objects_by_just_id;

INSERT
    INTO activities (_ID, account, id, verb, actor, object, target, published)
    SELECT
            (SELECT _ID FROM objects WHERE id=activities_old.id),       -- ID
            1,                                                          -- account
            activities.id,                                              -- id
            verb,                                                       -- verb
            (SELECT _ID FROM objects WHERE id=activities_old.actor),    -- actor
            (SELECT _ID FROM objects WHERE id=activities_old.object),   -- object
            (SELECT _ID FROM objects WHERE id=activities_old.target),   -- target
            published                                                   -- published
        FROM activities_old;

INSERT
    INTO feed_entries (account, activity)
    SELECT
            1, -- account
            (SELECT _ID FROM objects WHERE id=feed_entries_old.id)
        FROM feed_entries_old
        WHERE account=(SELECT name FROM accounts WHERE _ID=1);

Fix small SQL error in migrate_v4 script

INSERT
    INTO objects (account, id, objectType, published, updated, _json)
    SELECT
            1, id, objectType, published, updated, _json
        FROM objects_old;

CREATE INDEX ix_objects_by_just_id ON objects (id, _ID);
CREATE INDEX ix_objects_old_by_id ON objects_old (id, author, inReplyTo);

UPDATE objects SET
    author    = (
        SELECT _ID FROM objects AS a_n WHERE a_n.id=(
            SELECT author FROM objects_old WHERE objects_old.id=objects.id)),
    inReplyTo = (
        SELECT _ID from objects AS a_n WHERE a_n.id = (
            SELECT inReplyTo from objects_old where objects_old.id=objects.id));

DROP INDEX ix_objects_by_just_id;

INSERT
    INTO activities (_ID, account, id, verb, actor, object, target, published)
    SELECT
            (SELECT _ID FROM objects WHERE id=activities_old.id),       -- ID
            1,                                                          -- account
            id,                                                         -- id
            verb,                                                       -- verb
            (SELECT _ID FROM objects WHERE id=activities_old.actor),    -- actor
            (SELECT _ID FROM objects WHERE id=activities_old.object),   -- object
            (SELECT _ID FROM objects WHERE id=activities_old.target),   -- target
            published                                                   -- published
        FROM activities_old;

INSERT
    INTO feed_entries (account, activity)
    SELECT
            1, -- account
            (SELECT _ID FROM objects WHERE id=feed_entries_old.id)
        FROM feed_entries_old
        WHERE account=(SELECT name FROM accounts WHERE _ID=1);


ALTER TABLE  `contest` ADD  `visibility`  ENUM( 'Visible',  'Hidden' ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  'Hidden' AFTER `status`;

UPDATE `contest` SET `startDate` = NOW(), `endDate` = NOW() + INTERVAL 3 YEAR WHERE `status` = 'RunningContest';
UPDATE `contest` SET `startDate` = NOW() + INTERVAL 2 YEAR, `endDate` = NOW() + INTERVAL 3 YEAR WHERE `status` = 'FutureContest';
UPDATE `contest` SET `startDate` = NOW() - INTERVAL 2 YEAR, `endDate` = NOW() WHERE `status` = 'PastContest';
UPDATE `contest` SET `visibilty` = 'Visible' WHERE `status` != 'Hidden';

ALTER TABLE  `contest` CHANGE  `status`  `status` ENUM(  'Open',  'Closed' ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  'Open';

Change dbv revision file to set default status

ALTER TABLE  `contest` ADD  `visibility`  ENUM( 'Visible',  'Hidden' ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  'Hidden' AFTER `status`;

UPDATE `contest` SET `startDate` = NOW(), `endDate` = NOW() + INTERVAL 3 YEAR WHERE `status` = 'RunningContest';
UPDATE `contest` SET `startDate` = NOW() + INTERVAL 2 YEAR, `endDate` = NOW() + INTERVAL 3 YEAR WHERE `status` = 'FutureContest';
UPDATE `contest` SET `startDate` = NOW() - INTERVAL 2 YEAR, `endDate` = NOW() WHERE `status` = 'PastContest';
UPDATE `contest` SET `visibilty` = 'Visible' WHERE `status` != 'Hidden';

ALTER TABLE  `contest` CHANGE  `status`  `status` ENUM(  'Open',  'Closed' ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  'Open';

UPDATE `contest` SET `status` = 'Open';