
CREATE DATABASE IF NOT EXISTS parts;

GRANT ALL PRIVILEGES ON parts.* TO 'teddy'@'%';
FLUSH PRIVILEGES;

USE parts;

-- Permanent Temp Tables
DROP TABLE IF EXISTS parts.tmp_DOG_Calc_User;
-- DROP TABLE IF EXISTS parts.tmp_core_Msg_Error;
DROP TABLE IF EXISTS parts.tmp_DOG_User;
DROP TABLE IF EXISTS parts.tmp_DOG_User_Role_Link;


-- Permanent Tables
DROP TABLE IF EXISTS parts.DOG_Dog_Drive_Link_Temp;
DROP TABLE IF EXISTS parts.DOG_Dog_Drive_Link_Audit;
DROP TABLE IF EXISTS parts.DOG_Dog_Drive_Link;

DROP TABLE IF EXISTS parts.DOG_Drive_Temp;
DROP TABLE IF EXISTS parts.DOG_Drive_Audit;
DROP TABLE IF EXISTS parts.DOG_Drive;

DROP TABLE IF EXISTS parts.DOG_Command_Button_Link_Temp;
DROP TABLE IF EXISTS parts.DOG_Command_Button_Link_Audit;
DROP TABLE IF EXISTS parts.DOG_Command_Button_Link;

DROP TABLE IF EXISTS parts.DOG_Button_Icon_Temp;
DROP TABLE IF EXISTS parts.DOG_Button_Icon_Audit;
DROP TABLE IF EXISTS parts.DOG_Button_Icon;

DROP TABLE IF EXISTS parts.DOG_Image_Temp;
DROP TABLE IF EXISTS parts.DOG_Image_Audit;
DROP TABLE IF EXISTS parts.DOG_Image;

DROP TABLE IF EXISTS parts.DOG_Button_Shape_Temp;
DROP TABLE IF EXISTS parts.DOG_Button_Shape_Audit;
DROP TABLE IF EXISTS parts.DOG_Button_Shape;

DROP TABLE IF EXISTS parts.DOG_Colour_Temp;
DROP TABLE IF EXISTS parts.DOG_Colour_Audit;
DROP TABLE IF EXISTS parts.DOG_Colour;

DROP TABLE IF EXISTS parts.DOG_Location_Link_Temp;
DROP TABLE IF EXISTS parts.DOG_Location_Link_Audit;
DROP TABLE IF EXISTS parts.DOG_Location_Link;

DROP TABLE IF EXISTS parts.DOG_Location_Temp;
DROP TABLE IF EXISTS parts.DOG_Location_Audit;
DROP TABLE IF EXISTS parts.DOG_Location;

DROP TABLE IF EXISTS parts.DOG_Personal_Best_Temp;
DROP TABLE IF EXISTS parts.DOG_Personal_Best_Audit;
DROP TABLE IF EXISTS parts.DOG_Personal_Best;

DROP TABLE IF EXISTS parts.DOG_Dog_Command_Link_Temp;
DROP TABLE IF EXISTS parts.DOG_Dog_Command_Link_Audit;
DROP TABLE IF EXISTS parts.DOG_Dog_Command_Link;

DROP TABLE IF EXISTS parts.DOG_Command_Temp;
DROP TABLE IF EXISTS parts.DOG_Command_Audit;
DROP TABLE IF EXISTS parts.DOG_Command;

DROP TABLE IF EXISTS parts.DOG_Command_Category_Temp;
DROP TABLE IF EXISTS parts.DOG_Command_Category_Audit;
DROP TABLE IF EXISTS parts.DOG_Command_Category;

DROP TABLE IF EXISTS parts.DOG_Obedience_Level_Temp;
DROP TABLE IF EXISTS parts.DOG_Obedience_Level_Audit;
DROP TABLE IF EXISTS parts.DOG_Obedience_Level;

DROP TABLE IF EXISTS parts.DOG_Understanding_Level_Temp;
DROP TABLE IF EXISTS parts.DOG_Understanding_Level_Audit;
DROP TABLE IF EXISTS parts.DOG_Understanding_Level;

DROP TABLE IF EXISTS parts.DOG_Competency_Level_Temp;
DROP TABLE IF EXISTS parts.DOG_Competency_Level_Audit;
DROP TABLE IF EXISTS parts.DOG_Competency_Level;

DROP TABLE IF EXISTS parts.DOG_Dog_Breed_Link_Temp;
DROP TABLE IF EXISTS parts.DOG_Dog_Breed_Link_Audit;
DROP TABLE IF EXISTS parts.DOG_Dog_Breed_Link;

DROP TABLE IF EXISTS parts.DOG_Breed_Temp;
DROP TABLE IF EXISTS parts.DOG_Breed_Audit;
DROP TABLE IF EXISTS parts.DOG_Breed;

DROP TABLE IF EXISTS parts.DOG_Dog_Temp;
DROP TABLE IF EXISTS parts.DOG_Dog_Audit;
DROP TABLE IF EXISTS parts.DOG_Dog;

DROP TABLE IF EXISTS parts.DOG_Dog_Change_Set;

DROP TABLE IF EXISTS parts.DOG_Calc_User_Temp;

DROP TABLE IF EXISTS parts.DOG_User_Role_Link_Audit;
DROP TABLE IF EXISTS parts.DOG_User_Role_Link;

DROP TABLE IF EXISTS parts.DOG_Role_Permission_Link_Audit;
DROP TABLE IF EXISTS parts.DOG_Role_Permission_Link;

DROP TABLE IF EXISTS parts.DOG_Role_Audit;
DROP TABLE IF EXISTS parts.DOG_Role;

DROP TABLE IF EXISTS parts.DOG_User_Temp;
DROP TABLE IF EXISTS parts.DOG_User_Audit;
DROP TABLE IF EXISTS parts.DOG_User;

DROP TABLE IF EXISTS parts.DOG_Permission_Audit;
DROP TABLE IF EXISTS parts.DOG_Permission;

DROP TABLE IF EXISTS parts.DOG_Permission_Group_Audit;
DROP TABLE IF EXISTS parts.DOG_Permission_Group;

DROP TABLE IF EXISTS parts.DOG_Access_Level_Audit;
DROP TABLE IF EXISTS parts.DOG_Access_Level;

DROP TABLE IF EXISTS parts.DOG_User_Change_Set;

/*
DROP TABLE IF EXISTS parts.CORE_Split_Key_Value_Pair_Csv_Temp;
DROP TABLE IF EXISTS parts.CORE_Split_Temp;

*/
DROP TABLE IF EXISTS parts.CORE_File_Type;
DROP TABLE IF EXISTS parts.CORE_Msg_Error_Type;

-- Stored Procedures
DROP PROCEDURE IF EXISTS parts.p_DOG_test_get_many_dog_command;
DROP PROCEDURE IF EXISTS parts.p_DOG_test_get_many_command;
DROP PROCEDURE IF EXISTS parts.p_DOG_get_many_command;
DROP PROCEDURE IF EXISTS parts.p_DOG_test_save_command;
DROP PROCEDURE IF EXISTS parts.p_DOG_save_command;

DROP PROCEDURE IF EXISTS parts.p_DOG_clear_calc_user;
DROP PROCEDURE IF EXISTS parts.p_DOG_calc_user;

/*
DROP PROCEDURE IF EXISTS parts.p_core_clear_split_key_value_pair_csv;
DROP PROCEDURE IF EXISTS parts.p_core_split_key_value_pair_csv;
DROP PROCEDURE IF EXISTS parts.p_core_clear_split;
DROP PROCEDURE IF EXISTS parts.p_core_split;
DROP PROCEDURE IF EXISTS parts.p_clear_split_key_value_pair_csv;
DROP PROCEDURE IF EXISTS parts.p_split_key_value_pair_csv;
DROP PROCEDURE IF EXISTS parts.p_clear_split;
DROP PROCEDURE IF EXISTS parts.p_split;

DROP PROCEDURE IF EXISTS parts.p_core_debug_timing_reporting;
DROP PROCEDURE IF EXISTS parts.p_debug_timing_reporting;
DROP PROCEDURE IF EXISTS parts.p_core_validate_guid;
DROP PROCEDURE IF EXISTS parts.p_core_validate_guid_test;
*/
USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'CORE_Msg_Error_Type'
;

CREATE TABLE IF NOT EXISTS parts.CORE_Msg_Error_Type (
	  id_type INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, code VARCHAR(100) NOT NULL
	, name VARCHAR(500) NOT NULL
	, description VARCHAR(1000)
    , is_breaking_error BIT NOT NULL
    , background_colour VARCHAR(32) NOT NULL DEFAULT '#111111'
    , text_colour VARCHAR(32) NOT NULL DEFAULT '#110000'
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'CORE_File_Type'
;

CREATE TABLE IF NOT EXISTS parts.CORE_File_Type (
	  id_file_type INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, code VARCHAR(100) NOT NULL
    , name VARCHAR(250) NOT NULL
    , is_image BIT NOT NULL DEFAULT 0
    , active BIT NOT NULL DEFAULT 1
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'CORE_Split_Temp'
;

CREATE TABLE IF NOT EXISTS parts.CORE_Split_Temp (
	  guid BINARY(36) NOT NULL
    , display_order INT NOT NULL
	, substring VARCHAR(4000) NOT NULL
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'CORE_Split_Key_Value_Pair_Csv_Temp'
;

CREATE TABLE IF NOT EXISTS parts.CORE_Split_Key_Value_Pair_Csv_Temp (
	  guid BINARY(36) NOT NULL
    , id INT NOT NULL
	, key_column VARCHAR(4000) NULL
    , value_column VARCHAR(4000) NULL
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_User_Change_Set'
;

CREATE TABLE IF NOT EXISTS parts.DOG_User_Change_Set (
	  id_change_set INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , comment VARCHAR(500)
    , updated_last_on DATETIME
    , id_user_updated_last_by INT
);
USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Access_Level'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Access_Level (
      id_access_level INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , code VARCHAR(100)
    , name VARCHAR(250)
    , priority INT NOT NULL
    , display_order INT NOT NULL
    , active BIT NOT NULL DEFAULT 1
);



USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Permission_Group'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Permission_Group (
      id_group INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , code VARCHAR(100)
    , name VARCHAR(250)
    , display_order INT NOT NULL
    , active BIT NOT NULL DEFAULT 1
);
USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Permission'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Permission (
      id_permission INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , code VARCHAR(100)
    , name VARCHAR(250)
    , id_permission_group INT NOT NULL
    , CONSTRAINT FK_DOG_Permission_id_permission_group
		FOREIGN KEY (id_permission_group)
        REFERENCES parts.DOG_Permission_Group(id_group)
    , id_access_level_required INT NOT NULL
    , CONSTRAINT FK_DOG_Permission_id_access_level_required
		FOREIGN KEY (id_access_level_required)
        REFERENCES parts.DOG_Access_Level(id_access_level)
    , display_order INT NOT NULL
    , active BIT NOT NULL DEFAULT 1
);
USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_User'
;

CREATE TABLE IF NOT EXISTS parts.DOG_User (
      id_user INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , id_user_auth0 VARCHAR(200)
    , firstname VARCHAR(250)
    , surname VARCHAR(250)
    , email VARCHAR(254)
    , is_email_verified BIT NOT NULL DEFAULT 0
    , is_super_user BIT NOT NULL DEFAULT 0
    , active BIT NOT NULL DEFAULT 1
    , created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_User_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
    , id_change_set INT
    , CONSTRAINT FK_DOG_User_id_change_set
		FOREIGN KEY (id_change_set)
        REFERENCES parts.DOG_User_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_User_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_User_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , id_user INT NOT NULL
    , CONSTRAINT FK_DOG_User_Audit_id_user
		FOREIGN KEY (id_user)
        REFERENCES parts.DOG_User(id_user)
    , name_field VARCHAR(100) NOT NULL
    , value_prev VARCHAR(500)
    , value_new VARCHAR(500)
    , id_change_set INT NOT NULL
    , CONSTRAINT FK_DOG_User_Audit_id_change_set
		FOREIGN KEY (id_change_set)
        REFERENCES parts.DOG_User_Change_Set(id_change_set)
);
USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_User_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_User_Temp (
      id_temp INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , id_user INT NOT NULL
    , id_user_auth0 VARCHAR(200)
    , firstname VARCHAR(250)
    , surname VARCHAR(250)
    , email VARCHAR(254)
    , is_email_verified BIT
    , is_super_user BIT
    , active BIT
    , guid BINARY(36) NOT NULL
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Role'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Role (
      id_role INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , code VARCHAR(100)
    , name VARCHAR(250)
    , display_order INT NOT NULL
    , active BIT NOT NULL DEFAULT 1
    , created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Role_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
    , id_change_set INT
    , CONSTRAINT FK_DOG_Role_id_change_set
		FOREIGN KEY (id_change_set) 
        REFERENCES parts.DOG_User_Change_Set(id_change_set)
);
USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Role_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Role_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , id_role INT NOT NULL
    , CONSTRAINT FK_DOG_Role_Audit_id_role
		FOREIGN KEY (id_role)
        REFERENCES parts.DOG_Role(id_role)
    , name_field VARCHAR(100) NOT NULL
    , value_prev VARCHAR(500)
    , value_new VARCHAR(500)
    , id_change_set INT NOT NULL
    , CONSTRAINT FK_DOG_Role_Audit_id_change_set
		FOREIGN KEY (id_change_set)
        REFERENCES parts.DOG_User_Change_Set(id_change_set)
);
USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Role_Permission_Link'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Role_Permission_Link (
      id_link INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , id_role INT NOT NULL
    , CONSTRAINT FK_DOG_Role_Permission_Link_id_role
		FOREIGN KEY (id_role)
        REFERENCES parts.DOG_Role(id_role)
    , id_permission INT NOT NULL
    , CONSTRAINT FK_DOG_Role_Permission_Link_id_permission
		FOREIGN KEY (id_permission)
        REFERENCES parts.DOG_Permission(id_permission)
    , id_access_level INT NOT NULL
    , CONSTRAINT FK_DOG_Role_Permission_Link_id_access_level
		FOREIGN KEY (id_access_level)
        REFERENCES parts.DOG_Access_Level(id_access_level)
    , active BIT NOT NULL DEFAULT 1
    , created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Role_Permission_Link_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
    , id_change_set INT
    , CONSTRAINT FK_DOG_Role_Permission_Link_id_change_set
		FOREIGN KEY (id_change_set)
        REFERENCES parts.DOG_User_Change_Set(id_change_set)
);
USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Role_Permission_Link_Audit';

CREATE TABLE IF NOT EXISTS parts.DOG_Role_Permission_Link_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , id_link INT NOT NULL
    , CONSTRAINT FK_DOG_Role_Permission_Link_Audit_id_link
		FOREIGN KEY (id_link)
        REFERENCES parts.DOG_Role_Permission_Link(id_link)
    , name_field VARCHAR(100) NOT NULL
    , value_prev VARCHAR(500)
    , value_new VARCHAR(500)
    , id_change_set INT NOT NULL
    , CONSTRAINT FK_DOG_Role_Permission_Link_Audit_id_change_set
		FOREIGN KEY (id_change_set)
        REFERENCES parts.DOG_User_Change_Set(id_change_set)
);
USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_User_Role_Link'
;

CREATE TABLE IF NOT EXISTS parts.DOG_User_Role_Link (
      id_link INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , id_user INT NOT NULL
    , CONSTRAINT FK_DOG_User_Role_Link_id_user
		FOREIGN KEY (id_user)
        REFERENCES parts.DOG_User(id_user)
    , id_role INT NOT NULL
    , CONSTRAINT FK_DOG_User_Role_Link_id_role
		FOREIGN KEY (id_role)
        REFERENCES parts.DOG_Role(id_role)
    , active BIT NOT NULL DEFAULT 1
    , created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_User_Role_Link_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
    , id_change_set INT
    , CONSTRAINT FK_DOG_User_Role_Link_id_change_set
		FOREIGN KEY (id_change_set)
        REFERENCES parts.DOG_User_Change_Set(id_change_set)
);
USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_User_Role_Link_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_User_Role_Link_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , id_link INT NOT NULL
    , CONSTRAINT FK_DOG_User_Role_Link_Audit_id_link
		FOREIGN KEY (id_link)
        REFERENCES parts.DOG_User_Role_Link(id_link)
    , name_field VARCHAR(100) NOT NULL
    , value_prev VARCHAR(500)
    , value_new VARCHAR(500)
    , id_change_set INT NOT NULL
    , CONSTRAINT FK_DOG_User_Role_Link_Audit_id_change_set
		FOREIGN KEY (id_change_set)
        REFERENCES parts.DOG_User_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Calc_User_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Calc_User_Temp (
	  guid BINARY(36) NOT NULL
	, id_user INT
	, id_permission_required INT NOT NULL
	, CONSTRAINT FK_DOG_Calc_User_Temp_id_permission_required
		FOREIGN KEY (id_permission_required)
		REFERENCES parts.DOG_Permission (id_permission)
	, priority_access_level_required INT NOT NULL
	, is_super_user BIT
	, priority_access_level_user INT
	, has_access BIT
);
USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Dog_Change_Set'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Dog_Change_Set (
	  id_change_set INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, comment VARCHAR(500)
	, updated_last_on DATETIME
    , id_user_updated_last_by INT
    , CONSTRAINT FK_DOG_Role_id_user_updated_last_by
        FOREIGN KEY (id_user_updated_last_by)
        REFERENCES parts.DOG_User(id_user)
);
USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Dog'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Dog (
	  id_dog INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , name VARCHAR(250) NOT NULL
	, appearance VARCHAR(1000)
    , mass_kg DECIMAL(7, 3)
    , notes TEXT
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Dog_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Dog_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Dog_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Dog_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_dog INT NOT NULL
	, CONSTRAINT FK_DOG_Dog_Audit_id_dog
		FOREIGN KEY (id_dog)
		REFERENCES parts.DOG_Dog(id_dog)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Dog_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Dog_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Dog_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
	, id_dog INT
	, name VARCHAR(250)
	, appearance VARCHAR(1000)
    , mass_kg DECIMAL(7, 3)
	, notes TEXT
	, active BIT
    , guid BINARY(36)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Breed'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Breed (
	  id_breed INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , code VARCHAR(100) NOT NULL
    , name VARCHAR(250) NOT NULL
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Breed_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Breed_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Breed_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Breed_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_breed INT NOT NULL
	, CONSTRAINT FK_DOG_Breed_Audit_id_breed
		FOREIGN KEY (id_breed)
		REFERENCES parts.DOG_Breed(id_breed)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Breed_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Breed_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Breed_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
	, id_breed INT
    , code VARCHAR(100)
	, name VARCHAR(250)
	, active BIT
    , guid BINARY(36)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Dog_Breed_Link'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Dog_Breed_Link (
	  id_link INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_dog INT NOT NULL
    , CONSTRAINT FK_DOG_Dog_Breed_Link_id_dog
		FOREIGN KEY (id_dog)
        REFERENCES parts.DOG_Dog(id_dog)
	, id_breed INT NOT NULL
    , CONSTRAINT FK_DOG_Dog_Breed_Link_id_breed
		FOREIGN KEY (id_breed)
        REFERENCES parts.DOG_Breed(id_breed)
    , lineage_ratio DECIMAL(5, 4) NOT NULL
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Dog_Breed_Link_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Dog_Breed_Link_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Dog_Breed_Link_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Dog_Breed_Link_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_link INT NOT NULL
	, CONSTRAINT FK_DOG_Dog_Breed_Link_Audit_id_link
		FOREIGN KEY (id_link)
		REFERENCES parts.DOG_Dog_Breed_Link(id_link)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Dog_Breed_Link_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Dog_Breed_Link_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Dog_Breed_Link_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
    , id_link INT
	, id_dog INT
	, id_breed INT
	, lineage_ratio DECIMAL(5, 4)
	, active BIT
    , guid BINARY(36)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Understanding_Level'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Understanding_Level (
	  id_understanding_level INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , code VARCHAR(100) NOT NULL
    , name VARCHAR(250) NOT NULL
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Understanding_Level_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Understanding_Level_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Understanding_Level_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Understanding_Level_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_understanding_level INT NOT NULL
	, CONSTRAINT FK_DOG_Understanding_Level_Audit_id_understanding_level
		FOREIGN KEY (id_understanding_level)
		REFERENCES parts.DOG_Understanding_Level(id_understanding_level)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Understanding_Level_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Understanding_Level_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Understanding_Level_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
    , id_understanding_level INT  
    , code VARCHAR(100)
    , name VARCHAR(250)
	, active BIT
    , guid BINARY(36)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Obedience_Level'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Obedience_Level (
	  id_obedience_level INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , code VARCHAR(100) NOT NULL
    , name VARCHAR(250) NOT NULL
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Obedience_Level_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Obedience_Level_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Obedience_Level_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Obedience_Level_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_obedience_level INT NOT NULL
	, CONSTRAINT FK_DOG_Obedience_Level_Audit_id_obedience_level
		FOREIGN KEY (id_obedience_level)
		REFERENCES parts.DOG_Obedience_Level(id_obedience_level)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Obedience_Level_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Obedience_Level_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Obedience_Level_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
    , id_obedience_level INT  
    , code VARCHAR(100)
    , name VARCHAR(250)
	, active BIT
    , guid BINARY(36)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Command_Category'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Command_Category (
	  id_command_category INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , code VARCHAR(100) NOT NULL
    , name VARCHAR(250) NOT NULL
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Command_Category_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Command_Category_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Command_Category_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Command_Category_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_command_category INT NOT NULL
	, CONSTRAINT FK_DOG_Command_Category_Audit_id_command_category
		FOREIGN KEY (id_command_category)
		REFERENCES parts.DOG_Command_Category(id_command_category)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Command_Category_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Command_Category_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Command_Category_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
	, id_command_category INT
	, code VARCHAR(100)
	, name VARCHAR(250)
	, active BIT
    , guid BINARY(36)
);
USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Command'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Command (
	  id_command INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_command_category INT NOT NULL
    , CONSTRAINT FK_DOG_Command_id_command_category
		FOREIGN KEY (id_command_category)
        REFERENCES parts.DOG_Command_Category(id_command_category)
    , name VARCHAR(250) NOT NULL
	, hand_signal_default_description TEXT
    , can_have_button BIT NOT NULL DEFAULT 0
	, notes TEXT
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Command_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Command_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Command_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Command_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_command INT NOT NULL
	, CONSTRAINT FK_DOG_Command_Audit_id_command
		FOREIGN KEY (id_command)
		REFERENCES parts.DOG_Command(id_command)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Command_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Command_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Command_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
	, id_command INT
	, id_command_category INT
	, name VARCHAR(250)
	, hand_signal_default_description TEXT
    , can_have_button BIT
	, notes TEXT
	, active BIT
    , guid BINARY(36)

    , name_command_category VARCHAR(250)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Dog_Command_Link'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Dog_Command_Link (
	  id_link INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_dog INT NOT NULL
    , CONSTRAINT FK_DOG_Dog_Command_Link_id_dog
		FOREIGN KEY (id_dog)
        REFERENCES parts.DOG_Dog(id_dog)
	, id_command INT NOT NULL
    , CONSTRAINT FK_DOG_Dog_Command_Link_id_command
		FOREIGN KEY (id_command)
        REFERENCES parts.DOG_Command(id_command)
	, id_understanding_level INT NOT NULL
    , CONSTRAINT FK_DOG_Dog_Command_Link_id_understanding_level
		FOREIGN KEY (id_understanding_level)
        REFERENCES parts.DOG_Understanding_Level(id_understanding_level)
	, id_obedience_level INT NOT NULL
    , CONSTRAINT FK_DOG_Dog_Command_Link_id_obedience_level
		FOREIGN KEY (id_obedience_level)
        REFERENCES parts.DOG_Obedience_Level(id_obedience_level)
    , hand_signal_description TEXT
	, notes TEXT
--  , has_button BIT NOT NULL DEFAULT 0
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Dog_Command_Link_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Dog_Command_Link_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Dog_Command_Link_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Dog_Command_Link_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_link INT NOT NULL
	, CONSTRAINT FK_DOG_Dog_Command_Link_Audit_id_link
		FOREIGN KEY (id_link)
		REFERENCES parts.DOG_Dog_Command_Link(id_link)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Dog_Command_Link_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Dog_Command_Link_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Dog_Command_Link_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
	, id_link INT
	, id_dog INT
	, id_command INT
	, id_understanding_level INT
	, id_obedience_level INT
    , hand_signal_description TEXT
	, notes TEXT
--  , has_button BIT
	, active BIT
    , guid BINARY(36)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Personal_Best'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Personal_Best (
	  id_personal_best INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_dog_command_link INT NOT NULL
    , CONSTRAINT FK_DOG_Personal_Best_id_dog_command_link
		FOREIGN KEY (id_dog_command_link)
        REFERENCES parts.DOG_Dog_Command_Link(id_link)
	, is_achieved_using_button BIT NOT NULL DEFAULT 0
	, situation TEXT NOT NULL
    , duration_seconds INT
    , quantity INT
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Personal_Best_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Personal_Best_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Personal_Best_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Personal_Best_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_personal_best INT NOT NULL
	, CONSTRAINT FK_DOG_Personal_Best_Audit_id_personal_best
		FOREIGN KEY (id_personal_best)
		REFERENCES parts.DOG_Personal_Best(id_personal_best)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Personal_Best_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Personal_Best_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Personal_Best_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
	, id_personal_best INT
	, id_dog_command_link INT
	, is_achieved_using_button BIT
	, situation TEXT
    , duration_seconds INT
    , quantity INT
	, active BIT
    , guid BINARY(36)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Location'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Location (
	  id_location INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , code VARCHAR(100) NOT NULL
    , name VARCHAR(250) NOT NULL
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Location_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Location_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Location_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Location_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_location INT NOT NULL
	, CONSTRAINT FK_DOG_Location_Audit_id_location
		FOREIGN KEY (id_location)
		REFERENCES parts.DOG_Location(id_location)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Location_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Location_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Location_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
    , id_location INT
    , code VARCHAR(100)
    , name VARCHAR(250)
	, active BIT
    , guid BINARY(36)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Location_Link'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Location_Link (
	  id_link INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , id_location_parent INT
    , CONSTRAINT FK_DOG_Location_Link_id_location_parent
        FOREIGN KEY (id_location_parent)
        REFERENCES parts.DOG_Location(id_location)
    , id_location_child INT
    , CONSTRAINT FK_DOG_Location_Link_id_location_child
        FOREIGN KEY (id_location_child)
        REFERENCES parts.DOG_Location(id_location)
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Location_Link_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Location_Link_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Location_Link_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Location_Link_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_link INT NOT NULL
	, CONSTRAINT FK_DOG_Location_Link_Audit_id_link
		FOREIGN KEY (id_link)
		REFERENCES parts.DOG_Location_Link(id_link)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Location_Link_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Location_Link_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Location_Link_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
    , id_link INT
    , id_location_parent INT
    , id_location_child INT
	, active BIT
    , guid BINARY(36)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Colour'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Colour (
	  id_colour INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , code VARCHAR(100) NOT NULL
    , name VARCHAR(250) NOT NULL
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Colour_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Colour_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Colour_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Colour_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_colour INT NOT NULL
	, CONSTRAINT FK_DOG_Colour_Audit_id_colour
		FOREIGN KEY (id_colour)
		REFERENCES parts.DOG_Colour(id_colour)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Colour_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Colour_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Colour_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
    , id_colour INT
    , code VARCHAR(100)
    , name VARCHAR(250)
	, active BIT
    , guid BINARY(36)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Button_Shape'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Button_Shape (
	  id_button_shape INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , code VARCHAR(100) NOT NULL
    , name VARCHAR(250) NOT NULL
    , description TEXT
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Button_Shape_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Button_Shape_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Button_Shape_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Button_Shape_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_button_shape INT NOT NULL
	, CONSTRAINT FK_DOG_Button_Shape_Audit_id_button_shape
		FOREIGN KEY (id_button_shape)
		REFERENCES parts.DOG_Button_Shape(id_button_shape)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Button_Shape_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Button_Shape_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Button_Shape_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
    , id_button_shape INT
    , code VARCHAR(100)
    , name VARCHAR(250)
    , description TEXT
	, active BIT
    , guid BINARY(36)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Image'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Image (
	  id_image INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , id_file_type INT NOT NULL
    , CONSTRAINT FK_DOG_Image_id_file_type
        FOREIGN KEY (id_file_type)
        REFERENCES parts.CORE_File_Type(id_file_type)
    , id_dog INT
    , CONSTRAINT FK_DOG_Image_id_dog
        FOREIGN KEY (id_dog)
        REFERENCES parts.DOG_Dog(id_dog)
    , path VARCHAR(1024) NOT NULL
    , display_order INT
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Image_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Image_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Image_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Image_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_image INT NOT NULL
	, CONSTRAINT FK_DOG_Image_Audit_id_image
		FOREIGN KEY (id_image)
		REFERENCES parts.DOG_Image(id_image)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Image_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Image_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Image_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
    , id_image INT
    , id_file_type INT NOT NULL
    , id_dog INT
    , path VARCHAR(1024) NOT NULL
    , display_order INT
	, active BIT
    , guid BINARY(36)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Button_Icon'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Button_Icon (
	  id_button_icon INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , id_image INT
    , CONSTRAINT FK_DOG_Button_Icon_id_image
        FOREIGN KEY (id_image)
        REFERENCES parts.DOG_Image(id_image)
    , code VARCHAR(100) NOT NULL
    , name VARCHAR(250) NOT NULL
    , description TEXT
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Button_Icon_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Button_Icon_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Button_Icon_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Button_Icon_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_button_icon INT NOT NULL
	, CONSTRAINT FK_DOG_Button_Icon_Audit_id_button_icon
		FOREIGN KEY (id_button_icon)
		REFERENCES parts.DOG_Button_Icon(id_button_icon)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Button_Icon_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Button_Icon_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Button_Icon_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
	, id_button_icon INT
    , id_image INT
    , code VARCHAR(100)
    , name VARCHAR(250)
    , description TEXT
	, active BIT
    , guid BINARY(36)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Command_Button_Link'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Command_Button_Link (
	  id_link INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_command INT NOT NULL
    , CONSTRAINT FK_DOG_Command_Button_Link_id_command
		FOREIGN KEY (id_command)
        REFERENCES parts.DOG_Command(id_command)
	, id_button_shape INT NOT NULL
    , CONSTRAINT FK_DOG_Command_Button_Link_id_button_shape
		FOREIGN KEY (id_button_shape)
        REFERENCES parts.DOG_Button_Shape(id_button_shape)
	, id_button_colour INT NOT NULL
    , CONSTRAINT FK_DOG_Command_Button_Link_id_button_colour
		FOREIGN KEY (id_button_colour)
        REFERENCES parts.DOG_Colour(id_colour)
	, id_button_icon INT
    , CONSTRAINT FK_DOG_Command_Button_Link_id_button_icon
		FOREIGN KEY (id_button_icon)
        REFERENCES parts.DOG_Button_Icon(id_button_icon)
	, id_location INT NOT NULL
    , CONSTRAINT FK_DOG_Command_Button_Link_id_location
		FOREIGN KEY (id_location)
        REFERENCES parts.DOG_Location(id_location)
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Command_Button_Link_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Command_Button_Link_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Command_Button_Link_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Command_Button_Link_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_link INT NOT NULL
	, CONSTRAINT FK_DOG_Command_Button_Link_Audit_id_link
		FOREIGN KEY (id_link)
		REFERENCES parts.DOG_Command_Button_Link(id_link)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Command_Button_Link_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Command_Button_Link_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Command_Button_Link_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
	, id_link INT
	, id_command INT
	, id_button_shape INT
	, id_button_colour INT
	, id_button_icon INT
	, id_location INT
    , has_button BIT
	, active BIT
    , guid BINARY(36)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Drive'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Drive (
	  id_drive INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    , code VARCHAR(100) NOT NULL
    , name VARCHAR(250) NOT NULL
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Drive_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Drive_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Drive_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Drive_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_drive INT NOT NULL
	, CONSTRAINT FK_DOG_Drive_Audit_id_drive
		FOREIGN KEY (id_drive)
		REFERENCES parts.DOG_Drive(id_drive)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Drive_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Drive_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Drive_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
	, id_drive INT
    , code VARCHAR(100)
    , name VARCHAR(250)
	, active BIT
    , guid BINARY(36)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Dog_Drive_Link'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Dog_Drive_Link (
	  id_link INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_dog INT NOT NULL
    , CONSTRAINT FK_DOG_Dog_Drive_Link_id_dog
		FOREIGN KEY (id_dog)
        REFERENCES parts.DOG_Dog(id_dog)
	, id_drive INT NOT NULL
    , CONSTRAINT FK_DOG_Dog_Drive_Link_id_drive
		FOREIGN KEY (id_drive)
        REFERENCES parts.DOG_Drive(id_drive)
    , dominance_ratio DECIMAL(5, 4)
    , active BIT NOT NULL DEFAULT 1
	, created_on DATETIME
    , id_user_created_by INT
    , CONSTRAINT FK_DOG_Dog_Drive_Link_id_user_created_by
        FOREIGN KEY (id_user_created_by)
        REFERENCES parts.DOG_User(id_user)
	, id_change_set INT
	, CONSTRAINT FK_DOG_Dog_Drive_Link_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Dog_Drive_Link_Audit'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Dog_Drive_Link_Audit (
	  id_audit INT NOT NULL AUTO_INCREMENT PRIMARY KEY
	, id_link INT NOT NULL
	, CONSTRAINT FK_DOG_Dog_Drive_Link_Audit_id_link
		FOREIGN KEY (id_link)
		REFERENCES parts.DOG_Dog_Drive_Link(id_link)
	, name_field VARCHAR(100) NOT NULL
	, value_prev TEXT
	, value_new TEXT
	, id_change_set INT NOT NULL
	, CONSTRAINT FK_DOG_Dog_Drive_Link_Audit_id_change_set
		FOREIGN KEY (id_change_set) 
		REFERENCES parts.DOG_Dog_Change_Set(id_change_set)
);

USE parts;

SELECT CONCAT('WARNING: Table ', TABLE_SCHEMA, '.', TABLE_NAME, ' already exists.') AS msg_warning 
FROM INFORMATION_SCHEMA.TABLES 
WHERE 
        TABLE_SCHEMA = 'parts' 
    AND TABLE_NAME = 'DOG_Dog_Drive_Link_Temp'
;

CREATE TABLE IF NOT EXISTS parts.DOG_Dog_Drive_Link_Temp (
	  id_temp INT NOT NULL PRIMARY KEY AUTO_INCREMENT
	, id_link INT
	, id_dog INT
	, id_drive INT
	, dominance_ratio DECIMAL(5, 4)
	, active BIT
    , guid BINARY(36)
);
USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_User_Change_Set;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_User_Change_Set
BEFORE INSERT ON parts.DOG_User_Change_Set
FOR EACH ROW
BEGIN
	IF NEW.updated_last_on <=> NULL THEN
		SET NEW.updated_last_on = NOW();
	END IF;
END //
DELIMITER ;


DELIMITER //
CREATE TRIGGER parts.before_update_DOG_User_Change_Set
BEFORE UPDATE ON parts.DOG_User_Change_Set
FOR EACH ROW
BEGIN
	IF NOT EXISTS(SELECT * FROM parts.DOG_User WHERE id_user = NEW.id_user_updated_last_by) THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New Updated-Last-By User ID must be provided.';
	END IF;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_User;
DROP TRIGGER IF EXISTS parts.before_update_DOG_User;


DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_User
BEFORE INSERT ON parts.DOG_User
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;


DELIMITER //
CREATE TRIGGER parts.before_update_DOG_User
BEFORE UPDATE ON parts.DOG_User
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_User_Audit (
		id_user,
        name_field,
        value_prev,
        value_new,
        id_change_set
    )
    -- Changed id_user_auth0
	SELECT NEW.id_user, 'id_user_auth0', OLD.id_user_auth0, NEW.id_user_auth0, NEW.id_change_set
		WHERE NOT (OLD.id_user_auth0 <=> NEW.id_user_auth0)
	UNION
    -- Changed firstname
	SELECT NEW.id_user, 'firstname', OLD.firstname, NEW.firstname, NEW.id_change_set
		WHERE NOT (OLD.firstname <=> NEW.firstname)
	UNION
    -- Changed surname
	SELECT NEW.id_user, 'surname', OLD.surname, NEW.surname, NEW.id_change_set
		WHERE NOT (OLD.surname <=> NEW.surname)
	UNION 
	-- Changed email
	SELECT NEW.id_user, 'email', OLD.email, NEW.email, NEW.id_change_set
		WHERE NOT (OLD.email <=> NEW.email)
	UNION
	-- Changed is_email_verified
	SELECT NEW.id_user, 'is_email_verified', CONVERT(CONVERT(OLD.is_email_verified, SIGNED), CHAR), CONVERT(CONVERT(NEW.is_email_verified, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.is_email_verified <=> NEW.is_email_verified)
	UNION
	-- Changed is_super_user
	SELECT NEW.id_user, 'is_super_user', CONVERT(CONVERT(OLD.is_super_user, SIGNED), CHAR), CONVERT(CONVERT(NEW.is_super_user, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.is_super_user <=> NEW.is_super_user)
	UNION
    -- Changed active
	SELECT NEW.id_user, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;
USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Role;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Role;


DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Role
BEFORE INSERT ON parts.DOG_Role
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;


DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Role
BEFORE UPDATE ON parts.DOG_Role
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Role_Audit (
		id_role,
        name_field,
        value_prev,
        value_new,
        id_change_set
    )
    -- Changed code
	SELECT NEW.id_role, 'code', OLD.code, NEW.code, NEW.id_change_set
		WHERE NOT OLD.code <=> NEW.code
	UNION
	-- Changed name
	SELECT NEW.id_role, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT OLD.name <=> NEW.name
	UNION
	-- Changed active
	SELECT NEW.id_role, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    UNION
    -- Changed display_order
	SELECT NEW.id_role, 'display_order', CONVERT(OLD.display_order, CHAR), CONVERT(NEW.display_order, CHAR), NEW.id_change_set
		WHERE NOT OLD.display_order <=> NEW.display_order
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Role_Permission_Link;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Role_Permission_Link;


DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Role_Permission_Link
BEFORE INSERT ON parts.DOG_Role_Permission_Link
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;


DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Role_Permission_Link
BEFORE UPDATE ON parts.DOG_Role_Permission_Link
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Role_Permission_Link_Audit (
		id_link,
        name_field,
        value_prev,
        value_new,
        id_change_set
    )
    -- Changed id_role
	SELECT NEW.id_link, 'id_role', CONVERT(OLD.id_role, CHAR), CONVERT(NEW.id_role, CHAR), NEW.id_change_set
		WHERE NOT OLD.id_role <=> NEW.id_role
	UNION
	-- Changed id_permission
	SELECT NEW.id_link, 'id_permission', CONVERT(OLD.id_permission, CHAR), CONVERT(NEW.id_permission, CHAR), NEW.id_change_set
		WHERE NOT OLD.id_permission <=> NEW.id_permission
    UNION
    -- Changed id_access_level
	SELECT NEW.id_link, 'id_access_level', CONVERT(OLD.id_access_level, CHAR), CONVERT(NEW.id_access_level, CHAR), NEW.id_change_set
		WHERE NOT OLD.id_access_level <=> NEW.id_access_level
	UNION
	-- Changed active
	SELECT NEW.id_link, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_User_Role_Link;
DROP TRIGGER IF EXISTS parts.before_update_DOG_User_Role_Link;


DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_User_Role_Link
BEFORE INSERT ON parts.DOG_User_Role_Link
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;


DELIMITER //
CREATE TRIGGER parts.before_update_DOG_User_Role_Link
BEFORE UPDATE ON parts.DOG_User_Role_Link
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_User_Role_Link_Audit (
		id_link,
        name_field,
        value_prev,
        value_new,
        id_change_set
    )
	-- Changed id_user
	SELECT NEW.id_link, 'id_user', CONVERT(OLD.id_user, CHAR), CONVERT(NEW.id_user, CHAR), NEW.id_change_set
		WHERE NOT OLD.id_user <=> NEW.id_user
    UNION
    -- Changed id_role
	SELECT NEW.id_link, 'id_role', CONVERT(OLD.id_role, CHAR), CONVERT(NEW.id_role, CHAR), NEW.id_change_set
		WHERE NOT OLD.id_role <=> NEW.id_role
	UNION
	-- Changed active
	SELECT NEW.id_link, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Dog_Change_Set;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Dog_Change_Set
BEFORE INSERT ON parts.DOG_Dog_Change_Set
FOR EACH ROW
BEGIN
	IF NEW.updated_last_on <=> NULL THEN
		SET NEW.updated_last_on = NOW();
	END IF;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Dog;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Dog;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Dog
BEFORE INSERT ON parts.DOG_Dog
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Dog
BEFORE UPDATE ON parts.DOG_Dog
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Dog_Audit (
		  id_dog
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
    -- Changed name
	SELECT NEW.id_dog, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT OLD.name <=> NEW.name
    UNION
    -- Changed appearance
	SELECT NEW.id_dog, 'appearance', OLD.appearance, NEW.appearance, NEW.id_change_set
		WHERE NOT OLD.appearance <=> NEW.appearance
	UNION
	-- Changed mass_kg
	SELECT NEW.id_dog, 'mass_kg', CONVERT(OLD.mass_kg, CHAR), CONVERT(NEW.mass_kg, CHAR), NEW.id_change_set
		WHERE NOT (OLD.mass_kg <=> NEW.mass_kg)
	UNION
	-- Changed active
	SELECT NEW.id_dog, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Breed;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Breed;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Breed
BEFORE INSERT ON parts.DOG_Breed
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Breed
BEFORE UPDATE ON parts.DOG_Breed
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Breed_Audit (
		  id_breed
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
    -- Changed code
	SELECT NEW.id_breed, 'code', OLD.code, NEW.code, NEW.id_change_set
		WHERE NOT OLD.code <=> NEW.code
    UNION
    -- Changed name
	SELECT NEW.id_breed, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT OLD.name <=> NEW.name
    UNION
	-- Changed active
	SELECT NEW.id_breed, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Dog_Breed_Link;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Dog_Breed_Link;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Dog_Breed_Link
BEFORE INSERT ON parts.DOG_Dog_Breed_Link
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Dog_Breed_Link
BEFORE UPDATE ON parts.DOG_Dog_Breed_Link
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Dog_Breed_Link_Audit (
		  id_link
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_dog
	SELECT NEW.id_link, 'id_dog', CONVERT(OLD.id_dog, CHAR), CONVERT(NEW.id_dog, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_dog <=> NEW.id_dog)
    UNION
	-- Changed id_breed
	SELECT NEW.id_link, 'id_breed', CONVERT(OLD.id_breed, CHAR), CONVERT(NEW.id_breed, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_breed <=> NEW.id_breed)
    UNION
	-- Changed lineage_ratio
	SELECT NEW.id_link, 'lineage_ratio', CONVERT(OLD.lineage_ratio, CHAR), CONVERT(NEW.lineage_ratio, CHAR), NEW.id_change_set
		WHERE NOT (OLD.lineage_ratio <=> NEW.lineage_ratio)
    UNION
	-- Changed active
	SELECT NEW.id_link, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Understanding_Level;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Understanding_Level;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Understanding_Level
BEFORE INSERT ON parts.DOG_Understanding_Level
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Understanding_Level
BEFORE UPDATE ON parts.DOG_Understanding_Level
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Understanding_Level_Audit (
		  id_understanding_level
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
    -- Changed code
	SELECT NEW.id_understanding_level, 'code', OLD.code, NEW.code, NEW.id_change_set
		WHERE NOT OLD.code <=> NEW.code
	UNION
    -- Changed name
	SELECT NEW.id_understanding_level, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT OLD.name <=> NEW.name
    UNION
	-- Changed active
	SELECT NEW.id_understanding_level, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Obedience_Level;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Obedience_Level;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Obedience_Level
BEFORE INSERT ON parts.DOG_Obedience_Level
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Obedience_Level
BEFORE UPDATE ON parts.DOG_Obedience_Level
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Obedience_Level_Audit (
		  id_obedience_level
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
    -- Changed code
	SELECT NEW.id_obedience_level, 'code', OLD.code, NEW.code, NEW.id_change_set
		WHERE NOT OLD.code <=> NEW.code
	UNION
    -- Changed name
	SELECT NEW.id_obedience_level, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT OLD.name <=> NEW.name
    UNION
	-- Changed active
	SELECT NEW.id_obedience_level, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Command_Category;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Command_Category;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Command_Category
BEFORE INSERT ON parts.DOG_Command_Category
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Command_Category
BEFORE UPDATE ON parts.DOG_Command_Category
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Command_Category_Audit (
		  id_command_category
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
    -- Changed code
	SELECT NEW.id_command_category, 'code', OLD.code, NEW.code, NEW.id_change_set
		WHERE NOT OLD.code <=> NEW.code
	UNION
    -- Changed name
	SELECT NEW.id_command_category, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT OLD.name <=> NEW.name
    UNION
	-- Changed active
	SELECT NEW.id_command_category, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Command;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Command;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Command
BEFORE INSERT ON parts.DOG_Command
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Command
BEFORE UPDATE ON parts.DOG_Command
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Command_Audit (
		  id_command
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_command_category
	SELECT NEW.id_command, 'id_command_category', CONVERT(OLD.id_command_category, CHAR), CONVERT(NEW.id_command_category, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_command_category <=> NEW.id_command_category)
	UNION
    -- Changed name
	SELECT NEW.id_command, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT OLD.name <=> NEW.name
	UNION
    -- Changed hand_signal_default_description
	SELECT NEW.id_command, 'hand_signal_default_description', OLD.hand_signal_default_description, NEW.hand_signal_default_description, NEW.id_change_set
		WHERE NOT OLD.hand_signal_default_description <=> NEW.hand_signal_default_description
	UNION
	-- Changed can_have_button
	SELECT NEW.id_command, 'can_have_button', CONVERT(CONVERT(OLD.can_have_button, SIGNED), CHAR), CONVERT(CONVERT(NEW.can_have_button, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.can_have_button <=> NEW.can_have_button)
	UNION
    -- Changed notes
	SELECT NEW.id_command, 'notes', OLD.notes, NEW.notes, NEW.id_change_set
		WHERE NOT OLD.notes <=> NEW.notes
	UNION
	-- Changed active
	SELECT NEW.id_command, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Dog_Command_Link;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Dog_Command_Link;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Dog_Command_Link
BEFORE INSERT ON parts.DOG_Dog_Command_Link
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Dog_Command_Link
BEFORE UPDATE ON parts.DOG_Dog_Command_Link
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Dog_Command_Link_Audit (
		  id_link
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_dog
	SELECT NEW.id_link, 'id_dog', CONVERT(OLD.id_dog, CHAR), CONVERT(NEW.id_dog, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_dog <=> NEW.id_dog)
	UNION
	-- Changed id_command
	SELECT NEW.id_link, 'id_command', CONVERT(OLD.id_command, CHAR), CONVERT(NEW.id_command, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_command <=> NEW.id_command)
	UNION
	-- Changed id_understanding_level
	SELECT NEW.id_link, 'id_understanding_level', CONVERT(OLD.id_understanding_level, CHAR), CONVERT(NEW.id_understanding_level, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_understanding_level <=> NEW.id_understanding_level)
	UNION
	-- Changed id_obedience_level
	SELECT NEW.id_link, 'id_obedience_level', CONVERT(OLD.id_obedience_level, CHAR), CONVERT(NEW.id_obedience_level, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_obedience_level <=> NEW.id_obedience_level)
	UNION
    -- Changed hand_signal_description
	SELECT NEW.id_link, 'hand_signal_description', OLD.hand_signal_description, NEW.hand_signal_description, NEW.id_change_set
		WHERE NOT OLD.hand_signal_description <=> NEW.hand_signal_description
	UNION
    -- Changed notes
	SELECT NEW.id_link, 'notes', OLD.notes, NEW.notes, NEW.id_change_set
		WHERE NOT OLD.notes <=> NEW.notes
	UNION
    /*
	-- Changed has_button
	SELECT NEW.id_link, 'has_button', CONVERT(CONVERT(OLD.has_button, SIGNED), CHAR), CONVERT(CONVERT(NEW.has_button, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.has_button <=> NEW.has_button)
	UNION
	*/
    -- Changed active
	SELECT NEW.id_link, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Personal_Best;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Personal_Best;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Personal_Best
BEFORE INSERT ON parts.DOG_Personal_Best
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Personal_Best
BEFORE UPDATE ON parts.DOG_Personal_Best
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Personal_Best_Audit (
		  id_personal_best
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_dog_command_link
	SELECT NEW.id_personal_best, 'id_dog_command_link', CONVERT(OLD.id_dog_command_link, CHAR), CONVERT(NEW.id_dog_command_link, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_dog_command_link <=> NEW.id_dog_command_link)
	UNION
    -- Changed is_achieved_using_button
	SELECT NEW.id_personal_best, 'is_achieved_using_button', CONVERT(CONVERT(OLD.is_achieved_using_button, SIGNED), CHAR), CONVERT(CONVERT(NEW.is_achieved_using_button, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.is_achieved_using_button <=> NEW.is_achieved_using_button)
	UNION
    -- Changed situation
	SELECT NEW.id_personal_best, 'situation', OLD.situation, NEW.situation, NEW.id_change_set
		WHERE NOT OLD.situation <=> NEW.situation
	UNION
	-- Changed quantity
	SELECT NEW.id_personal_best, 'quantity', CONVERT(OLD.quantity, CHAR), CONVERT(NEW.quantity, CHAR), NEW.id_change_set
		WHERE NOT (OLD.quantity <=> NEW.quantity)
	UNION
	-- Changed duration_seconds
	SELECT NEW.id_personal_best, 'duration_seconds', CONVERT(OLD.duration_seconds, CHAR), CONVERT(NEW.duration_seconds, CHAR), NEW.id_change_set
		WHERE NOT (OLD.duration_seconds <=> NEW.duration_seconds)
	UNION
    -- Changed active
	SELECT NEW.id_personal_best, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Location;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Location;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Location
BEFORE INSERT ON parts.DOG_Location
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Location
BEFORE UPDATE ON parts.DOG_Location
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Location_Audit (
		  id_location
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed code
	SELECT NEW.id_location, 'code', OLD.code, NEW.code, NEW.id_change_set
		WHERE NOT (OLD.code <=> NEW.code)
	UNION
	-- Changed name
	SELECT NEW.id_location, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT (OLD.name <=> NEW.name)
	UNION
	-- Changed active
	SELECT NEW.id_location, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Location_Link;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Location_Link;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Location_Link
BEFORE INSERT ON parts.DOG_Location_Link
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Location_Link
BEFORE UPDATE ON parts.DOG_Location_Link
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Location_Link_Audit (
		  id_link
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_location_parent
	SELECT NEW.id_link, 'id_location_parent', CONVERT(OLD.id_location_parent, CHAR), CONVERT(NEW.id_location_parent, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_location_parent <=> NEW.id_location_parent)
	UNION
	-- Changed id_location_child
	SELECT NEW.id_link, 'id_location_child', CONVERT(OLD.id_location_child, CHAR), CONVERT(NEW.id_location_child, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_location_child <=> NEW.id_location_child)
	UNION
	-- Changed active
	SELECT NEW.id_link, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Colour;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Colour;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Colour
BEFORE INSERT ON parts.DOG_Colour
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Colour
BEFORE UPDATE ON parts.DOG_Colour
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Colour_Audit (
		  id_colour
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed code
	SELECT NEW.id_colour, 'code', OLD.code, NEW.code, NEW.id_change_set
		WHERE NOT (OLD.code <=> NEW.code)
	UNION
	-- Changed name
	SELECT NEW.id_colour, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT (OLD.name <=> NEW.name)
	UNION
	-- Changed active
	SELECT NEW.id_colour, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Button_Shape;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Button_Shape;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Button_Shape
BEFORE INSERT ON parts.DOG_Button_Shape
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Button_Shape
BEFORE UPDATE ON parts.DOG_Button_Shape
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Button_Shape_Audit (
		  id_button_shape
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed code
	SELECT NEW.id_button_shape, 'code', OLD.code, NEW.code, NEW.id_change_set
		WHERE NOT (OLD.code <=> NEW.code)
	UNION
	-- Changed name
	SELECT NEW.id_button_shape, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT (OLD.name <=> NEW.name)
	UNION
	-- Changed description
	SELECT NEW.id_button_shape, 'description', OLD.description, NEW.description, NEW.id_change_set
		WHERE NOT (OLD.description <=> NEW.description)
	UNION
	-- Changed active
	SELECT NEW.id_button_shape, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Image;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Image;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Image
BEFORE INSERT ON parts.DOG_Image
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Image
BEFORE UPDATE ON parts.DOG_Image
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Image_Audit (
		  id_image
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_file_type
	SELECT NEW.id_image, 'id_file_type', CONVERT(OLD.id_file_type, CHAR), CONVERT(NEW.id_file_type, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_file_type <=> NEW.id_file_type)
	UNION
	-- Changed id_dog
	SELECT NEW.id_image, 'id_dog', CONVERT(OLD.id_dog, CHAR), CONVERT(NEW.id_dog, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_dog <=> NEW.id_dog)
	UNION
	-- Changed path
	SELECT NEW.id_image, 'path', OLD.path, NEW.path, NEW.id_change_set
		WHERE NOT (OLD.path <=> NEW.path)
	UNION
	-- Changed display_order
	SELECT NEW.id_image, 'display_order', CONVERT(OLD.display_order, CHAR), CONVERT(NEW.display_order, CHAR), NEW.id_change_set
		WHERE NOT (OLD.display_order <=> NEW.display_order)
	UNION
	-- Changed active
	SELECT NEW.id_image, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Button_Icon;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Button_Icon;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Button_Icon
BEFORE INSERT ON parts.DOG_Button_Icon
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Button_Icon
BEFORE UPDATE ON parts.DOG_Button_Icon
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Button_Icon_Audit (
		  id_button_icon
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_image
	SELECT NEW.id_button_icon, 'id_image', CONVERT(OLD.id_image, CHAR), CONVERT(NEW.id_image, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_image <=> NEW.id_image)
	UNION
	-- Changed code
	SELECT NEW.id_button_icon, 'code', OLD.code, NEW.code, NEW.id_change_set
		WHERE NOT (OLD.code <=> NEW.code)
	UNION
	-- Changed name
	SELECT NEW.id_button_icon, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT (OLD.name <=> NEW.name)
	UNION
	-- Changed description
	SELECT NEW.id_button_icon, 'description', OLD.description, NEW.description, NEW.id_change_set
		WHERE NOT (OLD.description <=> NEW.description)
	UNION
	-- Changed active
	SELECT NEW.id_button_icon, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Command_Button_Link;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Command_Button_Link;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Command_Button_Link
BEFORE INSERT ON parts.DOG_Command_Button_Link
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Command_Button_Link
BEFORE UPDATE ON parts.DOG_Command_Button_Link
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Command_Button_Link_Audit (
		  id_link
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_command
	SELECT NEW.id_link, 'id_command', CONVERT(OLD.id_command, CHAR), CONVERT(NEW.id_command, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_command <=> NEW.id_command)
	UNION
	-- Changed id_button_shape
	SELECT NEW.id_link, 'id_button_shape', CONVERT(OLD.id_button_shape, CHAR), CONVERT(NEW.id_button_shape, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_button_shape <=> NEW.id_button_shape)
	UNION
	-- Changed id_button_colour
	SELECT NEW.id_link, 'id_button_colour', CONVERT(OLD.id_button_colour, CHAR), CONVERT(NEW.id_button_colour, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_button_colour <=> NEW.id_button_colour)
	UNION
	-- Changed id_button_icon
	SELECT NEW.id_link, 'id_button_icon', CONVERT(OLD.id_button_icon, CHAR), CONVERT(NEW.id_button_icon, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_button_icon <=> NEW.id_button_icon)
	UNION
	-- Changed id_location
	SELECT NEW.id_link, 'id_location', CONVERT(OLD.id_location, CHAR), CONVERT(NEW.id_location, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_location <=> NEW.id_location)
	UNION
	-- Changed active
	SELECT NEW.id_link, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Drive;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Drive;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Drive
BEFORE INSERT ON parts.DOG_Drive
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Drive
BEFORE UPDATE ON parts.DOG_Drive
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Drive_Audit (
		  id_drive
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed code
	SELECT NEW.id_drive, 'code', OLD.code, NEW.code, NEW.id_change_set
		WHERE NOT (OLD.code <=> NEW.code)
	UNION
	-- Changed name
	SELECT NEW.id_drive, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT (OLD.name <=> NEW.name)
	UNION
	-- Changed active
	SELECT NEW.id_drive, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Dog_Drive_Link;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Dog_Drive_Link;

DELIMITER //
CREATE TRIGGER parts.before_insert_DOG_Dog_Drive_Link
BEFORE INSERT ON parts.DOG_Dog_Drive_Link
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Dog_Drive_Link
BEFORE UPDATE ON parts.DOG_Dog_Drive_Link
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO parts.DOG_Dog_Drive_Link_Audit (
		  id_link
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_dog
	SELECT NEW.id_link, 'id_dog', CONVERT(OLD.id_dog, CHAR), CONVERT(NEW.id_dog, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_dog <=> NEW.id_dog)
	UNION
	-- Changed id_drive
	SELECT NEW.id_link, 'id_drive', CONVERT(OLD.id_drive, CHAR), CONVERT(NEW.id_drive, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_drive <=> NEW.id_drive)
	UNION
	-- Changed dominance_ratio
	SELECT NEW.id_link, 'dominance_ratio', CONVERT(OLD.dominance_ratio, CHAR), CONVERT(NEW.dominance_ratio, CHAR), NEW.id_change_set
		WHERE NOT (OLD.dominance_ratio <=> NEW.dominance_ratio)
	UNION
	-- Changed active
	SELECT NEW.id_link, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;

USE parts;

DROP PROCEDURE IF EXISTS parts.p_core_validate_guid;
DROP PROCEDURE IF EXISTS parts.p_core_validate_guid_test;

DELIMITER //
CREATE PROCEDURE parts.p_core_validate_guid (
	IN a_guid BINARY(36)
)
BEGIN
    IF ISNULL(a_guid) THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'GUID is required.'
        ;
	END IF;
END //
DELIMITER ;


DELIMITER //
CREATE PROCEDURE parts.p_core_validate_guid_test ()
BEGIN
    CALL parts.p_core_validate_guid ( 'nips' );
	CALL parts.p_core_validate_guid ( NULL );
END //
DELIMITER ;

-- CALL parts.p_core_validate_guid_test();
USE parts;

DROP PROCEDURE IF EXISTS parts.p_core_debug_timing_reporting;

DELIMITER //
CREATE PROCEDURE parts.p_core_debug_timing_reporting (
	IN a_time_start TIMESTAMP(6)
)
BEGIN
/*
	PROCEDURE parts.p_core_debug_timing_reporting
	Shared method timing reporting
*/
    DECLARE v_time_end TIMESTAMP(6);

	SET v_time_end := CURRENT_TIMESTAMP(6);
	SELECT
		a_time_start
		, UNIX_TIMESTAMP(a_time_start)
		, MICROSECOND(a_time_start) / 1000
		, v_time_end
		, UNIX_TIMESTAMP(v_time_end)
		, MICROSECOND(v_time_end) / 1000
		, v_time_end - a_time_start AS timestamp_delta
		, UNIX_TIMESTAMP(v_time_end - a_time_start) AS UNIX_TIMESTAMP_timestamp_delta
		, MICROSECOND(v_time_end - a_time_start) AS MICROSECOND_timestamp_delta
		-- , TIME_FORMAT(TIMEDIFF(v_time_end, a_time_start), '%H:%i:%s') AS time_difference
		, CONCAT(
			TIME_FORMAT(TIMEDIFF(v_time_end, a_time_start), '%H hours, %i minutes, %s seconds'),
			', ',
			TIMESTAMPDIFF(MICROSECOND, a_time_start, v_time_end) % 1000000 / 1000, ' milliseconds'
		) AS time_difference
	;
	
END //
DELIMITER ;

/*
CALL parts.p_core_debug_timing_reporting (
	CURRENT_TIMESTAMP(6)
);
*/
USE parts;

DROP PROCEDURE IF EXISTS parts.p_core_split;

DELIMITER //
CREATE PROCEDURE parts.p_core_split (
	  IN a_guid BINARY(36)
	, IN a_string LONGTEXT
	, IN a_separator VARCHAR(1000)
    -- IN a_allow_empty BIT
    , IN a_debug BIT
)
BEGIN
    DECLARE v_has_string BIT;
    DECLARE v_has_separator BIT;
    DECLARE v_i_separator INT;
    DECLARE v_i_start INT;
    DECLARE v_i_end INT;
    DECLARE v_current_item VARCHAR(4000);
    DECLARE v_time_start TIMESTAMP(6);
    
    SET v_time_start := CURRENT_TIMESTAMP(6);
    SET a_string := IFNULL(a_string, '');
    SET a_separator := IFNULL(a_separator, '');
    SET a_debug := IFNULL(a_debug, 0);
    
    IF a_debug = 1 THEN
		SELECT
              a_guid
            , a_string
            , a_separator
            , a_debug
		;
    END IF;
    
    CALL parts.p_core_validate_guid ( a_guid );
    
    DROP TABLE IF EXISTS tmp_Split_Split;
    
    CREATE TEMPORARY TABLE tmp_Split_Split (
        display_order INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
		substring VARCHAR(4000) NOT NULL
    );
    
    SET v_has_string = CASE WHEN a_string = '' THEN 0 ELSE 1 END;
    SET v_has_separator = CASE WHEN a_separator = '' THEN 0 ELSE 1 END;
    
    IF v_has_string THEN

		SET v_i_start = 1;
		SET v_i_end = LOCATE(',', a_string);

		WHILE v_i_end > 0 DO
			SET v_current_item = SUBSTRING(a_string, v_i_start, v_i_end - v_i_start);
			INSERT INTO tmp_Split_Split (substring) VALUES (v_current_item);

			SET v_i_start = v_i_end + 1;
			SET v_i_end = LOCATE(',', a_string, v_i_start);
		END WHILE;

		SET v_current_item = SUBSTRING(a_string, v_i_start);
		INSERT INTO tmp_Split_Split (substring) VALUES (TRIM(v_current_item));
	END IF;

	IF EXISTS (SELECT * FROM tmp_Split_Split LIMIT 1) THEN
		START TRANSACTION;
			INSERT INTO parts.CORE_Split_Temp (
                  guid
                , display_order
                , substring
			)
            SELECT
				  a_guid
				, display_order
                , substring
			FROM tmp_Split_Split
            ;
		COMMIT;
    END IF;
    
    DROP TABLE IF EXISTS tmp_Split_Split;
    
    IF a_debug = 1 THEN
		CALL parts.p_core_debug_timing_reporting ( v_time_start );
    END IF;
END //
DELIMITER ;


/*
CALL parts.p_core_split (
	  'nips'
	, 'noods, cheese ' -- a_string
	, ',' -- a_separator
	-- '0', -- a_allow_empty
    , 1
);

SELECT *
FROM parts.CORE_Split_Temp
WHERE GUID = 'nips';

CALL parts.p_core_clear_split_temp( 'nips' );
*/

USE parts;

DROP PROCEDURE IF EXISTS parts.p_core_clear_split;


DELIMITER //
CREATE PROCEDURE parts.p_core_clear_split (
	IN a_guid BINARY(36)
)
BEGIN
	CALL parts.p_core_validate_guid( a_guid );

	START TRANSACTION; 
	
	-- DROP TABLE IF EXISTS 
    DELETE FROM parts.CORE_Split_Temp
    WHERE GUID = a_guid
    ;
	
	COMMIT;
END //
DELIMITER ;

/*

CALL parts.p_core_clear_split ( 'nips' );


*/

USE parts;

DROP PROCEDURE IF EXISTS parts.p_core_split_key_value_pair_csv;

DELIMITER //
CREATE PROCEDURE parts.p_core_split_key_value_pair_csv (
	IN a_guid BINARY(36)
	, IN a_string LONGTEXT
    , IN a_debug BIT
)
BEGIN
    DECLARE v_has_string BIT;
    DECLARE v_current_item VARCHAR(4000);
    DECLARE v_time_start TIMESTAMP(6);
    
    SET v_time_start := CURRENT_TIMESTAMP(6);
    SET a_string := IFNULL(a_string, '');
    SET a_debug := IFNULL(a_debug, 0);
    
    SET v_has_string = CASE WHEN a_string = '' THEN 0 ELSE 1 END;
    
    IF a_debug = 1 THEN
		SELECT
			a_guid
            , a_string
            , a_debug
		;
    END IF;
    
    CALL parts.p_core_validate_guid ( a_guid );
    
    DROP TABLE IF EXISTS tmp_Input_Split_Key_Value_Pair_Csv;
    DROP TABLE IF EXISTS tmp_Split_Split_Key_Value_Pair_Csv;

    CREATE TEMPORARY TABLE tmp_Input_Split_Key_Value_Pair_Csv (
        input_string TEXT
    );

    CREATE TEMPORARY TABLE tmp_Split_Split_Key_Value_Pair_Csv (
        id INT AUTO_INCREMENT PRIMARY KEY
        , key_column VARCHAR(4000)
        , value_column VARCHAR(4000)
    );

    INSERT INTO tmp_Input_Split_Key_Value_Pair_Csv (
        input_string
    ) 
    VALUES (
        a_string
    );

    INSERT INTO tmp_Split_Split_Key_Value_Pair_Csv (key_column, value_column)
    SELECT 
        SUBSTRING_INDEX(SUBSTRING_INDEX(t.pair, ':', 1), ',', -1) AS key_column,
        SUBSTRING_INDEX(t.pair, ':', -1) AS value_column
    FROM (
        SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(input_string, ',', n), ',', -1) pair
        FROM temp_input
        CROSS JOIN (
            SELECT a.N + b.N * 10 + 1 n
            FROM (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
            CROSS JOIN (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
            ORDER BY n
        ) numbers
        WHERE n <= 1 + (LENGTH(input_string) - LENGTH(REPLACE(input_string, ',', '')))
    ) t;

	IF EXISTS (SELECT * FROM tmp_Split_Split_Key_Value_Pair_Csv LIMIT 1) THEN
		START TRANSACTION;
			INSERT INTO parts.CORE_Split_Key_Value_Pair_Csv_Temp (
				guid
				, id
                , key_column
                , value_column
			)
            SELECT
				a_guid
				, id
                , key_column
                , value_column
			FROM tmp_Split_Split_Key_Value_Pair_Csv
            ;
		COMMIT;
    END IF;
    
    DROP TEMPORARY TABLE IF EXISTS tmp_Input_Split_Key_Value_Pair_Csv;
    DROP TEMPORARY TABLE IF EXISTS tmp_Split_Split_Key_Value_Pair_Csv;
    
    IF a_debug = 1 THEN
		CALL parts.p_core_debug_timing_reporting ( v_time_start );
    END IF;
END //
DELIMITER ;


/*
CALL parts.p_core_split_key_value_pair_csv (
	'nipsnipsnipsnipsnipsnipsnipsnipsnips'
	, '1:100,2:200,3:300,4:400' -- a_string
    , 1
);

SELECT *
FROM parts.CORE_Split_key_value_pair_csv_Temp
WHERE GUID = 'nipsnipsnipsnipsnipsnipsnipsnipsnips';

CALL parts.p_core_clear_split_key_value_pair_csv_temp( 'nipsnipsnipsnipsnipsnipsnipsnipsnips' );
*/

USE parts;

DROP PROCEDURE IF EXISTS parts.p_core_clear_split_key_value_pair_csv;


DELIMITER //
CREATE PROCEDURE parts.p_core_clear_split_key_value_pair_csv (
	IN a_guid BINARY(36)
)
BEGIN
	CALL parts.p_core_validate_guid( a_guid );

	START TRANSACTION; 
	
	-- DROP TABLE IF EXISTS 
    DELETE FROM parts.CORE_Split_Key_Value_Pair_Csv_Temp
    WHERE GUID = a_guid
    ;
	
	COMMIT;
END //
DELIMITER ;

/*

CALL parts.p_core_clear_split_key_value_pair_csv ( 'nips' );


*/

USE parts;

DROP PROCEDURE IF EXISTS parts.p_DOG_user_eval;
DROP PROCEDURE IF EXISTS parts.p_DOG_calc_user;

DELIMITER //
CREATE PROCEDURE parts.p_DOG_calc_user (
	  IN a_guid BINARY(36)
    , IN a_ids_user TEXT
    , IN a_get_inactive_user BIT
    , IN a_ids_permission VARCHAR(4000)
    , IN a_debug BIT
)
BEGIN
    DECLARE v_has_filter_permission BIT;
    DECLARE v_has_filter_user BIT;
    DECLARE v_id_permission INT;
    DECLARE v_time_start TIMESTAMP(6);
	DECLARE v_ids_row_delete VARCHAR(500);
    DECLARE v_code_type_error_bad_data VARCHAR(200);
    DECLARE v_id_type_error_bad_data INT;
    DECLARE v_code_error_permission VARCHAR(200);
    DECLARE v_id_permission_required INT;
    DECLARE v_priority_access_level_required INT;
    DECLARE v_priority_access_level_view INT;
    
    SET v_time_start := CURRENT_TIMESTAMP(6);
    SET v_code_type_error_bad_data := (SELECT code FROM parts.CORE_Msg_Error_Type WHERE code = 'BAD_DATA');
    SET v_id_type_error_bad_data := (SELECT id_type FROM parts.CORE_Msg_Error_Type WHERE code = v_code_type_error_bad_data);
    SET v_code_error_permission := (SELECT code FROM parts.CORE_Msg_Error_Type WHERE id_type = 2);
    SET v_priority_access_level_view := (SELECT priority FROM parts.DOG_Access_Level WHERE code = 'VIEW' LIMIT 1);
    
    CALL parts.p_core_validate_guid ( a_guid );
    SET a_ids_user := TRIM(IFNULL(a_ids_user, ''));
    SET a_get_inactive_user := IFNULL(a_get_inactive_user, 0);
    SET a_ids_permission := TRIM(IFNULL(a_ids_permission, ''));
    SET a_debug := IFNULL(a_debug, 0);
    
    IF a_debug = 1 THEN
		SELECT
			  a_guid
            , a_ids_user
            , a_get_inactive_user
            , a_ids_permission
            , a_debug
		;
    END IF;
    
	DROP TABLE IF EXISTS tmp_Calc_User;
	DROP TABLE IF EXISTS tmp_User_Calc_User;
	DROP TABLE IF EXISTS tmp_Split_Calc_User;
    
	CREATE TEMPORARY TABLE tmp_Calc_User (
		  id_row INT PRIMARY KEY AUTO_INCREMENT NOT NULL
		, id_user INT NULL
		, id_permission_required INT NOT NULL
		, priority_access_level_required INT NOT NULL
        , is_super_user BIT NULL
		, priority_access_level_user INT NULL
		, has_access BIT
	);

	CREATE TEMPORARY TABLE tmp_User_Calc_User (
		id_user INT NOT NULL
        , is_super_user BIT NOT NULL
        -- , id_access_level INT
        , priority_access_level INT NOT NULL
	);
    
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Msg_Error_Calc_User (
		  display_order INT NOT NULL PRIMARY KEY AUTO_INCREMENT
		, id_type INT NULL
        , code VARCHAR(100) NOT NULL
        , msg VARCHAR(4000) NOT NULL
	);
    
    CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Split_Calc_User (
		substring VARCHAR(4000) NOT NULL
        , as_int INT NULL
	);
    DELETE FROM tmp_Split_Calc_User;
	
    SET v_has_filter_user = CASE WHEN a_ids_user = '' THEN 0 ELSE 1 END;
	SET a_ids_permission = REPLACE(a_ids_permission, '|', ',');
    SET v_has_filter_permission = CASE WHEN a_ids_permission = '' THEN 0 ELSE 1 END;
    -- SET v_id_access_level_view = (SELECT id_access_level FROM parts.DOG_Access_Level WHERE code = 'VIEW' LIMIT 1);


    -- Permission IDs
	IF NOT v_has_filter_permission THEN
        INSERT INTO tmp_Msg_Error_Calc_User (
              id_type
            , code
            , msg
        )
        SELECT
              v_id_type_error_bad_data
            , v_code_type_error_bad_data
            , 'Permission ID required.'
        ;
    ELSE
		CALL parts.p_core_split(a_guid, a_ids_permission, ',', a_debug);
		
		INSERT INTO tmp_Split_Calc_User (
			  substring
			, as_int
		)
		SELECT 
			  substring
			, CONVERT(substring, DECIMAL(10,0)) AS as_int
		FROM parts.CORE_Split_Temp
		WHERE 
                GUID = a_guid
			AND NOT ISNULL(substring)
			AND substring != ''
		;
		
		CALL parts.p_core_clear_split( a_guid );
		
		-- Invalid or inactive
		IF EXISTS (
            SELECT PERM.id_permission 
            FROM tmp_Split_Calc_User t_S 
            LEFT JOIN parts.DOG_Permission PERM ON t_S.as_int = PERM.id_permission 
            WHERE 
                    ISNULL(t_S.as_int) 
                OR  ISNULL(PERM.id_permission) 
                OR  PERM.active = 0
        ) THEN
			INSERT INTO tmp_Msg_Error_Calc_User (
				  id_type
				, code
				, msg
			)
			SELECT
				  v_id_type_error_bad_data
				, v_code_type_error_bad_data
				, CONCAT('Invalid or inactive permission IDs: ', IFNULL(GROUP_CONCAT(t_S.substring SEPARATOR ', '), 'NULL'))
			FROM tmp_Split_Calc_User t_S
			LEFT JOIN parts.DOG_Permission PERM ON t_S.as_int = PERM.id_permission 
			WHERE 
				    ISNULL(t_S.as_int)
				OR  ISNULL(PERM.id_permission)
				OR  PERM.active = 0
			;
		ELSE 
            SELECT
                  PERM.id_permission
                , PERM.id_access_level_required
            INTO 
                  v_id_permission_required
                , v_priority_access_level_required
            FROM tmp_Split_Calc_User t_S 
            LEFT JOIN parts.DOG_Permission PERM ON t_S.as_int = PERM.id_permission 
            INNER JOIN parts.DOG_Access_Level AL ON PERM.id_access_level_required = AL.id_access_level
            ORDER BY AL.priority ASC
            LIMIT 1
            ;

            IF ISNULL(v_id_permission_required) THEN
                INSERT INTO tmp_Msg_Error_Calc_User (
                    id_type
                    , code
                    , msg
                )
                SELECT
                    v_id_type_error_bad_data
                    , v_code_type_error_bad_data
                    , 'Valid Permission ID required.'
                ;
            END IF;
		END IF;
	END IF;
    DELETE FROM tmp_Split_Calc_User;
    
	-- Users
	CALL parts.p_core_split(a_guid, a_ids_user, ',', a_debug);
	
	INSERT INTO tmp_Split_Calc_User (
		  substring
		, as_int
	)
	SELECT 
		substring
		, CONVERT(substring, DECIMAL(10,0)) AS as_int
	FROM parts.CORE_Split_Temp
	WHERE 
            GUID = a_guid
		AND NOT ISNULL(substring)
		AND substring != ''
	;
	
	CALL parts.p_core_clear_split( a_guid );
	
	-- Invalid or inactive
	IF EXISTS (SELECT U.id_user FROM tmp_Split_Calc_User t_S LEFT JOIN parts.DOG_User U ON t_S.as_int = U.id_user WHERE ISNULL(t_S.as_int) OR ISNULL(U.id_user) OR (a_get_inactive_user = 0 AND U.active = 0)) THEN
		INSERT INTO tmp_Msg_Error_Calc_User (
			  id_type
			, code
			, msg
		)
		SELECT
			  v_id_type_error_bad_data
			, v_code_type_error_bad_data
			, CONCAT('Invalid or inactive user IDs: ', IFNULL(GROUP_CONCAT(t_S.substring SEPARATOR ', '), 'NULL'))
		FROM tmp_Split_Calc_User t_S
		LEFT JOIN parts.DOG_User U ON t_S.as_int = U.id_user 
		WHERE 
			    ISNULL(t_S.as_int) 
			OR  ISNULL(U.id_user)
			OR  (
				    a_get_inactive_user = 0
                AND U.active = 0
			)
		;
	ELSE
		IF NOT EXISTS (SELECT * FROM tmp_Split_Calc_User) THEN
			INSERT INTO tmp_Split_Calc_User (substring, as_int)
			VALUES ( '', NULL );
		END IF;
		
		IF a_debug = 1 THEN
			SELECT *
			FROM tmp_Split_Calc_User;
		END IF;
		
        INSERT INTO tmp_User_Calc_User (
			  id_user
            , is_super_user
            , priority_access_level
		)
        SELECT
			  U.id_user
            , IFNULL(U.is_super_user, 0) AS is_super_user
            , IFNULL(MIN(AL_U.priority), v_priority_access_level_view) AS priority_access_level
		FROM tmp_Split_Calc_User t_S
        INNER JOIN parts.DOG_User U ON t_S.as_int = U.id_user
		LEFT JOIN parts.DOG_User_Role_Link URL
			ON U.id_user = URL.id_user
			AND URL.active
		LEFT JOIN parts.DOG_Role_Permission_Link RPL
			ON URL.id_role = RPL.id_role
			AND RPL.active
		LEFT JOIN parts.DOG_Access_Level AL_U
			ON RPL.id_access_level = AL_U.id_access_level
			AND AL_U.active
		GROUP BY U.id_user
        ;
        			
		INSERT INTO tmp_Calc_User (
			  id_user
			, id_permission_required
			, priority_access_level_required
			, priority_access_level_user
			, is_super_user
		)
		SELECT 
			  t_UCU.id_user
			, v_id_permission_required
			, v_priority_access_level_required
			, t_UCU.priority_access_level AS priority_access_level_user
			, t_UCU.is_super_user AS is_super_user
		FROM tmp_User_Calc_User t_UCU
        ;
	END IF;    
    DELETE FROM tmp_Split_Calc_User;

    
    -- Calculated fields
	UPDATE tmp_Calc_User t_CU
	SET
		  t_CU.has_access = (
                (t_CU.is_super_user = 1)
            OR  (t_CU.priority_access_level_user <= t_CU.priority_access_level_required)
        )
	;
    
    -- Export data to staging table
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error_Calc_User) THEN
        START TRANSACTION;
			INSERT INTO parts.DOG_Calc_User_Temp (
				  guid
				, id_user
				, id_permission_required
				, priority_access_level_required
				, priority_access_level_user
				, is_super_user
				, has_access
			)
			SELECT
				  a_guid
				, t_CU.id_user
				, t_CU.id_permission_required
				, t_CU.priority_access_level_required
				, t_CU.priority_access_level_user
				, t_CU.is_super_user
                , t_CU.has_access
			FROM tmp_Calc_User t_CU
			;
		COMMIT;
    END IF;
    
    IF a_debug = 1 THEN
		SELECT * FROM tmp_Msg_Error_Calc_User;
		SELECT * FROM tmp_Calc_User;
        SELECT * FROM tmp_User_Calc_User;
		SELECT * FROM parts.DOG_Calc_User_Temp WHERE GUID = a_guid;
		CALL parts.p_DOG_clear_calc_user ( a_guid, a_debug );
    END IF;
    
    -- Clean up
	DROP TABLE IF EXISTS tmp_Calc_User;
	DROP TABLE IF EXISTS tmp_User_Calc_User;
    DELETE FROM tmp_Split_Calc_User;
    
    IF a_debug = 1 THEN
        CALL parts.p_debug_timing_reporting( v_time_start );
    END IF;
END //
DELIMITER ;

/*

CALL parts.p_DOG_calc_user (
	'chips                               '  -- a_guid
	, 1										-- a_ids_user
	, 0										-- a_get_inactive_user
	, '2'									-- a_ids_permission
	, '1'									-- a_ids_access_level
    , 0										-- a_debug
);
CALL parts.p_DOG_calc_user (
	'chips                               '  -- a_guid
	, 1 									-- a_ids_user
	, 0 									-- a_get_inactive_user
	, '2'									-- a_ids_permission
	, '1'									-- a_ids_access_level
    , 0										-- a_debug
);
*/
USE parts;

DROP PROCEDURE IF EXISTS parts.p_DOG_clear_calc_user;

DELIMITER //
CREATE PROCEDURE parts.p_DOG_clear_calc_user (
	  IN a_guid BINARY(36)
    , IN a_debug BIT
)
BEGIN
	DECLARE v_time_start TIMESTAMP(6);
    SET v_time_start := CURRENT_TIMESTAMP(6);
    
    CALL parts.p_core_validate_guid ( a_guid );
    
	START TRANSACTION;
		
		DELETE FROM parts.DOG_Calc_User_Temp
		WHERE GUID = a_guid
		;
	
	COMMIT;
    
    IF a_debug = 1 THEN
		CALL parts.p_debug_timing_reporting( v_time_start );
    END IF;
END //
DELIMITER ;

/*

CALL parts.p_DOG_clear_calc_user (
	'chips                               ' -- a_guid
    , 1 -- debug
);

SELECT *
FROM parts.DOG_Calc_User_Temp
WHERE GUID = 'chips                               '
;

*/

USE parts;

DROP PROCEDURE IF EXISTS parts.p_DOG_save_command;

DELIMITER //
CREATE PROCEDURE parts.p_DOG_save_command (
    IN a_comment VARCHAR(500),
	IN a_guid BINARY(36),
    IN a_id_user INT,
    IN a_debug BIT
)
BEGIN
	DECLARE v_code_type_error_bad_data VARCHAR(100);
    DECLARE v_id_type_error_bad_data INT;
    DECLARE v_id_permission_dog_admin INT;
    DECLARE v_id_permission_dog_new INT;
    DECLARE v_id_change_set INT;
    DECLARE v_time_start TIMESTAMP(6);
    DECLARE v_can_admin BIT;
    DECLARE v_can_create BIT;
    
    DECLARE exit handler for SQLEXCEPTION
    BEGIN
        GET DIAGNOSTICS CONDITION 1
            @sqlstate = RETURNED_SQLSTATE
            , @errno = MYSQL_ERRNO
            , @text = MESSAGE_TEXT
		;
        
        ROLLBACK;
        
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Msg_Error (
			  id_error INT NOT NULL PRIMARY KEY AUTO_INCREMENT
			, id_type INT NULL
			, code VARCHAR(100)
			, msg VARCHAR(4000) NOT NULL
		);

        INSERT INTO tmp_Msg_Error (
			  id_type
			, code
            , msg
		)
        SELECT 
			  MET.id_type
            , @errno
            , @text
		FROM parts.CORE_Msg_Error_Type MET
        WHERE MET.code = 'MYSQL_ERROR'
		;

        SELECT 
            t_ERROR.id_error
            , t_ERROR.id_type
            , t_ERROR.code
            , ERROR_TYPE.name
            , ERROR_TYPE.description
            , ERROR_TYPE.is_breaking_error
            , ERROR_TYPE.background_colour
            , ERROR_TYPE.text_colour
            , t_ERROR.msg
        FROM tmp_Msg_Error t_ERROR
        INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type
        ;

		DROP TABLE IF EXISTS tmp_Msg_Error;
    END;
    
    SET v_time_start := CURRENT_TIMESTAMP(6);
    SET v_code_type_error_bad_data := 'BAD_DATA';
    SET v_id_type_error_bad_data := (SELECT ERROR_TYPE.id_type FROM parts.CORE_Msg_Error_Type ERROR_TYPE WHERE ERROR_TYPE.code = v_code_type_error_bad_data LIMIT 1);
    SET v_id_permission_dog_admin := (SELECT PERMISSION.id_permission FROM parts.DOG_Permission PERMISSION WHERE PERMISSION.code = 'DOG_ADMIN' LIMIT 1);
    SET v_id_permission_dog_new := (SELECT PERMISSION.id_permission FROM parts.DOG_Permission PERMISSION WHERE PERMISSION.code = 'DOG_CREATE' LIMIT 1);
    
    CALL parts.p_core_validate_guid ( a_guid );
    
    DROP TABLE IF EXISTS tmp_Command;
    
    CREATE TEMPORARY TABLE tmp_Command (
          id_command INT
        , id_command_category INT
        , name VARCHAR(250)
        , hand_signal_default_description TEXT
        , can_have_button BIT
        , notes TEXT
        , active BIT
        , is_new BIT
        , name_error VARCHAR(250)

        , name_command_category VARCHAR(250)
    );
        
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Msg_Error (
		  id_error INT NOT NULL PRIMARY KEY AUTO_INCREMENT
		, id_type INT NULL
        , code VARCHAR(100)
        , msg VARCHAR(4000) NOT NULL
	);
        
    
    -- Get data from Temp table
    INSERT INTO tmp_Command (
		  id_command
        , id_command_category
        , name
        , hand_signal_default_description
        , can_have_button
        , notes
        , active
        , is_new

        , name_command_category
	)
    SELECT 
		  COMMAND_T.id_command AS id_command
        , COMMAND_T.id_command_category AS id_command_category
        , COALESCE(COMMAND_T.name, COMMAND.name) AS name
        , COALESCE(COMMAND_T.hand_signal_default_description, COMMAND.hand_signal_default_description) AS hand_signal_default_description
        , COALESCE(COMMAND_T.can_have_button, COMMAND.can_have_button) AS can_have_button
        , COALESCE(COMMAND_T.notes, COMMAND.notes) AS notes
        , COALESCE(COMMAND_T.active, COMMAND.active, 1) AS active
        , CASE WHEN IFNULL(COMMAND_T.id_command, 0) < 1 THEN 1 ELSE 0 END AS is_new

        , COMMAND_T.name_command_category AS name_command_category 
	FROM parts.DOG_Command_Temp COMMAND_T
    LEFT JOIN parts.DOG_Command COMMAND ON COMMAND_T.id_command = COMMAND.id_command
    WHERE COMMAND_T.guid = a_guid
    ;

    UPDATE tmp_Command t_COMMAND
    SET name_error = COALESCE(t_COMMAND.name, t_COMMAND.notes, t_COMMAND.name_command_category, '(No Command)')
    ;

    -- Find missing id_command_category by name_command_category
    UPDATE tmp_Command t_COMMAND
    INNER JOIN parts.DOG_Command_Category COMMAND_CATEGORY ON t_COMMAND.name_command_category = COMMAND_CATEGORY.name
    SET t_COMMAND.id_command_category = COMMAND_CATEGORY.id_command_category
    WHERE t_COMMAND.id_command_category IS NULL
    ;
    
    IF EXISTS (
        SELECT * 
        FROM tmp_Command t_COMMAND 
        WHERE ISNULL(t_COMMAND.id_command_category) 
        LIMIT 1
    ) THEN
		INSERT INTO tmp_Msg_Error (
			  id_type
			, code
			, msg
		)
		SELECT
			  v_id_type_error_bad_data
			, v_code_type_error_bad_data
			, CONCAT('The following Command(s) do not have a Category: ', GROUP_CONCAT(t_COMMAND.name_error SEPARATOR ', ')) AS msg
		FROM tmp_Command t_COMMAND
		WHERE t_COMMAND.id_command_category IS NULL
		;
    END IF;
    
    -- Validation
    -- Missing mandatory fields
    -- id_command_category
    IF EXISTS (SELECT * FROM tmp_Command t_COMMAND WHERE ISNULL(t_COMMAND.id_command_category) LIMIT 1) THEN
		INSERT INTO tmp_Msg_Error (
			  id_type
			, code
			, msg
		)
		SELECT
			  v_id_type_error_bad_data
			, v_code_type_error_bad_data
			, CONCAT('The following Command(s) do not have a Category: ', GROUP_CONCAT(t_COMMAND.name_error SEPARATOR ', ')) AS msg
		FROM tmp_Command t_COMMAND
		WHERE ISNULL(t_COMMAND.id_command_category)
		;
    END IF;
    -- name
    IF EXISTS (SELECT * FROM tmp_Command t_COMMAND WHERE ISNULL(t_COMMAND.name) LIMIT 1) THEN
		INSERT INTO tmp_Msg_Error (
			  id_type
			, code
			, msg
		)
		SELECT
			  v_id_type_error_bad_data
			, v_code_type_error_bad_data
			, CONCAT('The following Command(s) do not have a Name: ', GROUP_CONCAT(t_COMMAND.name_error SEPARATOR ', ')) AS msg
		FROM tmp_Command t_COMMAND
		WHERE ISNULL(t_COMMAND.name)
		;
    END IF;
    -- can_have_button
    IF EXISTS (SELECT * FROM tmp_Command t_COMMAND WHERE ISNULL(t_COMMAND.can_have_button) LIMIT 1) THEN
		INSERT INTO tmp_Msg_Error (
			  id_type
			, code
			, msg
		)
		SELECT
			  v_id_type_error_bad_data
			, v_code_type_error_bad_data
			, CONCAT('The following Command(s) do not have a Can-Have-Button: ', GROUP_CONCAT(t_COMMAND.name_error SEPARATOR ', ')) AS msg
		FROM tmp_Command t_COMMAND
		WHERE ISNULL(t_COMMAND.can_have_button)
		;
    END IF;
    
    -- Permissions
    IF a_debug = 1 THEN
		SELECT 
			  a_guid
			, a_id_user
			, FALSE -- a_get_inactive_user
			, v_id_permission_dog_admin
			, v_id_permission_dog_new
			, 0 -- a_debug
        ;
    END IF;
    
	CALL parts.p_DOG_calc_user(
          a_guid
        , a_id_user
        , FALSE -- a_get_inactive_user
        , v_id_permission_dog_admin
        , 0 -- a_debug
    );
	
    SELECT
          IFNULL(CU_T.has_access, 0)
    INTO
          v_can_admin
    FROM parts.DOG_Calc_User_Temp CU_T
    WHERE CU_T.GUID = a_guid
    LIMIT 1
    ;
	
	CALL parts.p_DOG_clear_calc_user(
		  a_guid
        , 0 -- a_debug
	);
    
	CALL parts.p_DOG_calc_user(
          a_guid
        , a_id_user
        , FALSE -- a_get_inactive_user
        , v_id_permission_dog_new
        , 0 -- a_debug
    );
	
    SELECT
          IFNULL(CU_T.has_access, 0)
    INTO
          v_can_create
    FROM parts.DOG_Calc_User_Temp CU_T
    WHERE CU_T.GUID = a_guid
    LIMIT 1
    ;
	
	CALL parts.p_DOG_clear_calc_user(
		  a_guid
        , 0 -- a_debug
	);
    
    IF (v_can_create = 0 AND EXISTS(SELECT * FROM tmp_Command WHERE is_new = 1)) THEN
		DELETE t_ME
        FROM tmp_Msg_Error t_ME
        WHERE t_ME.id_type <> v_id_type_error_no_permission
        ;
		INSERT INTO tmp_Msg_Error (
			  id_type
            , code
			, msg
		)
		VALUES (
			  v_id_type_error_no_permission
            , v_code_type_error_no_permission
			, 'You do not have permission to create new Commands.'
		)
        ;
    END IF;
    
    IF (v_can_admin = 0 AND EXISTS(SELECT * FROM tmp_Command WHERE is_new = 0)) THEN
		DELETE t_ME
        FROM tmp_Msg_Error t_ME
        WHERE t_ME.id_type <> v_id_type_error_no_permission
        ;
		INSERT INTO tmp_Msg_Error (
			  id_type
            , code
			, msg
		)
		VALUES (
			  v_id_type_error_no_permission
            , v_code_type_error_no_permission
			, 'You do not have permission to admin Commands.'
		)
        ;
    END IF;
    
    IF EXISTS (SELECT * FROM tmp_Msg_Error t_ERROR INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type WHERE ERROR_TYPE.is_breaking_error = 1 LIMIT 1) THEN
    	IF a_debug = 1 THEN
	    	SELECT * from tmp_Command;
	    END IF;

        DELETE FROM tmp_Command;
    END IF;

    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error t_ERROR INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type WHERE ERROR_TYPE.is_breaking_error = 1 LIMIT 1) THEN
		START TRANSACTION;
		
			INSERT INTO parts.DOG_Dog_Change_Set ( 
                  comment
                , id_user_updated_last_by
                , updated_last_on
            )
			VALUES ( 
                  a_comment
                , a_id_user
                , v_time_start
            )
			;
			
			SET v_id_change_set := LAST_INSERT_ID();
			
			UPDATE parts.DOG_Command COMMAND
			INNER JOIN tmp_Command t_COMMAND 
				ON  COMMAND.id_command = t_COMMAND.id_command
				AND t_COMMAND.is_new = 0
			SET 
				  COMMAND.id_command_category = t_COMMAND.id_command_category
				, COMMAND.name = t_COMMAND.name
				, COMMAND.hand_signal_default_description = t_COMMAND.hand_signal_default_description
				, COMMAND.can_have_button = t_COMMAND.can_have_button
                , COMMAND.notes = t_COMMAND.notes
				, COMMAND.active = t_COMMAND.active
				, COMMAND.id_change_set = v_id_change_set
			;
			
			INSERT INTO parts.DOG_Command (
				  id_command_category
				, name
				, hand_signal_default_description
				, can_have_button
                , notes
				, active
				, id_user_created_by
				, created_on
			)
			SELECT
				  t_COMMAND.id_command_category         AS id_command_category
				, t_COMMAND.name                        AS name
				, t_COMMAND.hand_signal_default_description     AS hand_signal_default_description
				, t_COMMAND.can_have_button             AS can_have_button
                , t_COMMAND.notes                       AS notes
				, t_COMMAND.active                      AS active
				, a_id_user                             AS created_by
				, v_time_start                          AS created_on
			FROM tmp_Command t_COMMAND
			WHERE 
				    t_COMMAND.is_new = 1
				AND t_COMMAND.active = 1
			;
			
		COMMIT;
    END IF;
	
	START TRANSACTION;

		DELETE FROM parts.DOG_Command_Temp
		WHERE GUID = a_guid
        ;
		
	COMMIT;
    
    -- Errors
    SELECT 
          t_ERROR.id_error
		, t_ERROR.id_type
        , t_ERROR.code
        , ERROR_TYPE.name
        , ERROR_TYPE.description
        , ERROR_TYPE.is_breaking_error
        , ERROR_TYPE.background_colour
        , ERROR_TYPE.text_colour
		, t_ERROR.msg
    FROM tmp_Msg_Error t_ERROR
	INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type
	;
    
	IF a_debug = 1 THEN
		SELECT * from tmp_Command;
	END IF;

    DROP TEMPORARY TABLE tmp_Command;
    DROP TEMPORARY TABLE tmp_Msg_Error;
    
	IF a_debug = 1 THEN
		CALL parts.p_core_debug_timing_reporting ( v_time_start );
	END IF;
END //
DELIMITER ;



/*


select 
	*
    -- COUNT(*)
-- delete
from parts.DOG_Command_Temp
;
select COUNT(*)
from parts.DOG_Command_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from parts.DOG_Command
;
select COUNT(*)
from parts.DOG_Command
;


CALL parts.p_DOG_save_command (
	'nipples'
    , (SELECT GUID FROM parts.DOG_Command_Temp COMMAND_TEMP ORDER BY id_temp DESC LIMIT 1)
    , 1
    , 1
);


select 
	*
    -- COUNT(*)
-- delete
from parts.DOG_Command_Temp
;
select COUNT(*)
from parts.DOG_Command_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from parts.DOG_Command
;
select COUNT(*)
from parts.DOG_Command
;

*/
USE parts;

DROP PROCEDURE IF EXISTS parts.p_DOG_test_save_command;


DELIMITER //
CREATE PROCEDURE parts.p_DOG_test_save_command ()
BEGIN
	
	DECLARE v_guid BINARY(36);
	DECLARE v_time_start TIMESTAMP(6);
    
    SET v_time_start := CURRENT_TIMESTAMP(6);
	SET v_guid := 'nipple_ripple_chipple_spittle_pickle'; -- 123456789012345678901234567890123456

    SELECT 'Start of Test';

	SELECT *
	FROM parts.DOG_Command
	;
	SELECT *
	FROM parts.DOG_Command_Temp
	;

	START TRANSACTION;
		
		INSERT INTO parts.DOG_Command_Temp (
			  id_command
            , email
            , name_contact
            , name_company
            , message
            , guid
            , active
		)
        /*
		VALUES (
			  -1 -- id_command
			, 'edward.middletonsmith@gmail.com' -- email
			, 'Teddy' -- name_contact
			, 'PARTS Ltd' -- name_company
			, 'Sa dude' -- message
			, v_guid
		)
        */
		VALUES (
			  -1 -- id_command
			, 'edward.middletonsmith@gmail.com' -- email
			, 'Teddy' -- name_contact
			, 'PARTS Ltd' -- name_company
			, 'hegrodorf is good' -- message
			, v_guid
            , 1 -- active
		)
        ;
		
	COMMIT;
    
	SELECT *
	FROM parts.DOG_Command_Temp
	-- WHERE GUID = v_guid
    ;
    
    CALL parts.p_DOG_save_command ( 
		  'Test save Command' -- comment
        , v_guid -- guid
        , 3 -- 1 -- id_user
		, 1 -- debug
    );
    
	SELECT *
	FROM parts.DOG_Command
	;
	SELECT *
	FROM parts.DOG_Command_Temp
	;
    
	CALL parts.p_debug_timing_reporting ( v_time_start );
END //
DELIMITER ;


/*
SELECT 'Before Test';
SELECT *
FROM parts.DOG_Command
;
SELECT *
FROM parts.DOG_Command_Temp
;


CALL parts.p_DOG_test_save_command ();

SELECT 'After Test';
SELECT *
FROM parts.DOG_Command
;
SELECT *
FROM parts.DOG_Command_Temp
;

DELETE FROM parts.DOG_Command_Temp;

DROP TABLE IF EXISTS tmp_Msg_Error;


*/
 
USE parts;

DROP PROCEDURE IF EXISTS parts.p_DOG_get_many_dog_command;

DELIMITER //
CREATE PROCEDURE parts.p_DOG_get_many_dog_command (
	  IN a_id_user INT
    , IN a_get_all_dog BIT
	, IN a_get_inactive_dog BIT
	, IN a_ids_dog TEXT
    , IN a_get_all_command BIT
	, IN a_get_inactive_command BIT
	, IN a_ids_command TEXT
    , IN a_get_all_understanding_level BIT
	, IN a_get_inactive_understanding_level BIT
	, IN a_ids_understanding_level TEXT
    , IN a_get_all_obedience_level BIT
	, IN a_get_inactive_obedience_level BIT
	, IN a_ids_obedience_level TEXT
    , IN a_debug BIT
)
BEGIN
    DECLARE v_code_type_error_bad_data VARCHAR(100);
    DECLARE v_code_type_error_no_permission VARCHAR(100);
    DECLARE v_id_type_error_bad_data INT;
    DECLARE v_id_type_error_no_permission INT;
    DECLARE v_has_filter_command BIT;
    DECLARE v_has_filter_dog BIT;
    DECLARE v_has_filter_obedience_level BIT;
    DECLARE v_has_filter_understanding_level BIT;
    DECLARE v_guid BINARY(36);
    DECLARE v_id_permission_dog_view INT;
    DECLARE v_id_minimum INT;
    DECLARE v_time_start TIMESTAMP(6);
    DECLARE v_can_view BIT;
    
    DECLARE exit handler for SQLEXCEPTION
    BEGIN
        GET DIAGNOSTICS CONDITION 1
            @sqlstate = RETURNED_SQLSTATE
            , @errno = MYSQL_ERRNO
            , @text = MESSAGE_TEXT
		;
        
        ROLLBACK;
        
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Msg_Error (
			  id_error INT NOT NULL PRIMARY KEY AUTO_INCREMENT
			, id_type INT NULL
			, code VARCHAR(100) NOT NULL
			, msg VARCHAR(4000) NOT NULL
		);

        INSERT INTO tmp_Msg_Error (
			  id_type
            , code
            , msg
		)
        SELECT 
			  MET.id_type
            , @errno
            , @text
		FROM parts.CORE_Msg_Error_Type MET
        WHERE MET.code = 'MYSQL_ERROR'
		;
        
        SELECT 
            t_ERROR.id_error
            , t_ERROR.id_type
            , t_ERROR.code
            , ERROR_TYPE.name
            , ERROR_TYPE.description
            , ERROR_TYPE.is_breaking_error
            , ERROR_TYPE.background_colour
            , ERROR_TYPE.text_colour
            , t_ERROR.msg
        FROM tmp_Msg_Error t_ERROR
        INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type
        ;
        
		DROP TABLE IF EXISTS tmp_Msg_Error;
    END;

    SET v_time_start := CURRENT_TIMESTAMP(6);
    SET v_guid := UUID();
    SET v_code_type_error_bad_data := 'BAD_DATA';
    SET v_code_type_error_no_permission := 'NO_PERMISSION';
    SET v_id_type_error_bad_data := (SELECT ERROR_TYPE.id_type FROM parts.CORE_Msg_Error_Type ERROR_TYPE WHERE ERROR_TYPE.code = v_code_type_error_bad_data LIMIT 1);
    SET v_id_type_error_no_permission := (SELECT ERROR_TYPE.id_type FROM parts.CORE_Msg_Error_Type ERROR_TYPE WHERE ERROR_TYPE.code = v_code_type_error_no_permission LIMIT 1);
    SET v_id_permission_dog_view := (SELECT PERMISSION.id_permission FROM parts.DOG_Permission PERMISSION WHERE PERMISSION.code = 'DOG_VIEW' LIMIT 1);
    
    SET a_id_user := IFNULL(a_id_user, 0);
    SET a_get_all_dog := IFNULL(a_get_all_dog, 0);
    SET a_get_inactive_dog := IFNULL(a_get_inactive_dog, 0);
    SET a_ids_dog := TRIM(IFNULL(a_ids_dog, ''));
    SET a_get_all_command := IFNULL(a_get_all_command, 0);
    SET a_get_inactive_command := IFNULL(a_get_inactive_command, 0);
    SET a_ids_command := TRIM(IFNULL(a_ids_command, ''));
    SET a_get_all_understanding_level := IFNULL(a_get_all_understanding_level, 0);
    SET a_get_inactive_understanding_level := IFNULL(a_get_inactive_understanding_level, 0);
    SET a_ids_understanding_level := TRIM(IFNULL(a_ids_understanding_level, ''));
    SET a_get_all_obedience_level := IFNULL(a_get_all_obedience_level, 0);
    SET a_get_inactive_obedience_level := IFNULL(a_get_inactive_obedience_level, 0);
    SET a_ids_obedience_level := TRIM(IFNULL(a_ids_obedience_level, ''));
    SET a_debug := IFNULL(a_debug, 0);
    
    IF a_debug = 1 THEN
		SELECT 
			  a_id_user
            , a_get_all_dog
            , a_get_inactive_dog
            , a_ids_dog
            , a_get_all_command
            , a_get_inactive_command
            , a_ids_command
            , a_get_all_understanding_level
            , a_get_inactive_understanding_level
            , a_ids_understanding_level
            , a_get_all_obedience_level
            , a_get_inactive_obedience_level
            , a_ids_obedience_level
            , a_debug
		;

        SELECT
              v_id_type_error_bad_data
            , v_id_type_error_no_permission
            , v_guid
            , v_id_permission_dog_view
            , v_time_start
        ;
    END IF;

    DROP TEMPORARY TABLE IF EXISTS tmp_Split;
    DROP TEMPORARY TABLE IF EXISTS tmp_Msg_Error;
    DROP TEMPORARY TABLE IF EXISTS tmp_Obedience_Level;
    DROP TEMPORARY TABLE IF EXISTS tmp_Understanding_Level;
    DROP TEMPORARY TABLE IF EXISTS tmp_Command;
    DROP TEMPORARY TABLE IF EXISTS tmp_Dog;
    
    CREATE TEMPORARY TABLE tmp_Dog (
		  id_dog INT NOT NULL
        , name VARCHAR(250)
    );
    
    CREATE TEMPORARY TABLE tmp_Command (
		  id_command INT NOT NULL
    --  , code VARCHAR(100)
        , name VARCHAR(250)
    );
    
    CREATE TEMPORARY TABLE tmp_Understanding_Level (
		  id_understanding_level INT NOT NULL
        , code VARCHAR(100)
        , name VARCHAR(250)
    );
    
    CREATE TEMPORARY TABLE tmp_Obedience_Level (
		  id_obedience_level INT NOT NULL
        , code VARCHAR(100)
        , name VARCHAR(250)
    );
    
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Msg_Error (
          id_error INT NOT NULL PRIMARY KEY AUTO_INCREMENT
		, id_type INT NULL
		, code VARCHAR(100) NOT NULL
        , msg VARCHAR(4000) NOT NULL
	);
    
    CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Split (
		  substring VARCHAR(4000) NOT NULL
        , as_int INT NULL
	);
    DELETE FROM tmp_Split;
    
    CALL parts.p_core_validate_guid ( v_guid );
    
    SET v_has_filter_dog = CASE WHEN a_ids_dog = '' THEN 0 ELSE 1 END;
    SET v_has_filter_command = CASE WHEN a_ids_command = '' THEN 0 ELSE 1 END;
    SET v_has_filter_understanding_level = CASE WHEN a_ids_understanding_level = '' THEN 0 ELSE 1 END;
    SET v_has_filter_obedience_level = CASE WHEN a_ids_obedience_level = '' THEN 0 ELSE 1 END;

    -- Dogs
    IF v_has_filter_dog = 1 THEN
		CALL parts.p_split(v_guid, a_ids_dog, ',', a_debug);
		
		INSERT INTO tmp_Split (
			  substring
			, as_int
		)
		SELECT 
			  SPLIT_T.substring
			, CONVERT(SPLIT_T.substring, DECIMAL(10,0)) AS as_int
		FROM parts.CORE_Split_Temp SPLIT_T
		WHERE 
                SPLIT_T.GUID = v_guid
			AND IFNULL(SPLIT_T.substring, '') <> ''
		;
		
		CALL parts.p_clear_split_temp( v_guid );
	END IF;
    
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error t_ERROR INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type WHERE ERROR_TYPE.is_breaking_error = 1 LIMIT 1) THEN
		IF EXISTS (
			SELECT * 
            FROM tmp_Split t_SPLIT 
            LEFT JOIN parts.DOG_Dog DOG ON t_SPLIT.as_int = DOG.id_dog 
			WHERE 
				    ISNULL(t_SPLIT.as_int) 
                OR  ISNULL(DOG.id_dog)
				OR  (
					DOG.active = 0
					AND a_get_inactive_dog = 0
				)
		) THEN
			INSERT INTO tmp_Msg_Error (
				  id_type
		        , code
				, msg
			)
			SELECT
				  v_id_type_error_bad_data
                , v_code_type_error_bad_data
				, CONCAT('Invalid or inactive Dog IDs: ', IFNULL(GROUP_CONCAT(t_SPLIT.substring SEPARATOR ', '), 'NULL'))
			FROM tmp_Split t_SPLIT
			LEFT JOIN parts.DOG_Dog DOG ON t_SPLIT.as_int = DOG.id_dog
			WHERE 
				    ISNULL(t_SPLIT.as_int) 
				OR  ISNULL(DOG.id_dog)
				OR  (
					DOG.active = 0
					AND a_get_inactive_dog = 0
				)
			;
		ELSE
			INSERT INTO tmp_Dog (
				  id_dog
                , name
			)
			SELECT 
				  DOG.id_dog
                , DOG.name
			FROM tmp_Split t_SPLIT
			RIGHT JOIN parts.DOG_Dog DOG ON t_SPLIT.as_int = DOG.id_dog
			WHERE 
                (
					    a_get_all_dog = 1
					OR  (
						    v_has_filter_dog = 1
						AND NOT ISNULL(t_SPLIT.as_int)
					)
				)
				AND (
					    a_get_inactive_dog = 1
					OR  DOG.active = 1
				)
			;
		END IF;
	END IF;
    
    DELETE FROM tmp_Split;
    
    -- Commands
    IF v_has_filter_command = 1 THEN
		CALL parts.p_split(v_guid, a_ids_command, ',', a_debug);
		
		INSERT INTO tmp_Split (
			  substring
			, as_int
		)
		SELECT 
			  substring
			, CONVERT(substring, DECIMAL(10,0)) AS as_int
		FROM parts.CORE_Split_Temp
		WHERE 
                GUID = v_guid
			AND NOT ISNULL(substring)
			AND substring <> ''
		;
		
		CALL parts.p_clear_split_temp( v_guid );
	END IF;
    
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error t_ERROR INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type WHERE ERROR_TYPE.is_breaking_error = 1 LIMIT 1) THEN
		IF EXISTS (
			SELECT * 
            FROM tmp_Split t_SPLIT 
            LEFT JOIN parts.DOG_Command COMMAND ON t_SPLIT.as_int = COMMAND.id_command 
			WHERE 
				    ISNULL(t_SPLIT.as_int) 
                OR  ISNULL(COMMAND.id_command)
				OR  (
					COMMAND.active = 0
					AND a_get_inactive_command = 0
				)
		) THEN
			INSERT INTO tmp_Msg_Error (
				  id_type
		        , code
				, msg
			)
			SELECT
				  v_id_type_error_bad_data
                , v_code_type_error_bad_data
				, CONCAT('Invalid or inactive Command IDs: ', IFNULL(GROUP_CONCAT(t_SPLIT.substring SEPARATOR ', '), 'NULL'))
			FROM tmp_Split t_SPLIT
			LEFT JOIN parts.DOG_Command COMMAND ON t_SPLIT.as_int = COMMAND.id_command
			WHERE 
				    ISNULL(t_SPLIT.as_int) 
				OR  ISNULL(COMMAND.id_command)
				OR  (
					COMMAND.active = 0
					AND a_get_inactive_command = 0
				)
			;
		ELSE
			INSERT INTO tmp_Command (
				  id_command
                , name
			)
			SELECT 
				  COMMAND.id_command
            --  , COMMAND.code
                , COMMAND.name
			FROM tmp_Split t_SPLIT
			RIGHT JOIN parts.DOG_Command COMMAND ON t_SPLIT.as_int = COMMAND.id_command
			WHERE 
                (
					    a_get_all_command = 1
					OR  (
						    v_has_filter_command = 1
						AND NOT ISNULL(t_SPLIT.as_int)
					)
				)
				AND (
					    a_get_inactive_command = 1
					OR  COMMAND.active = 1
				)
			;
		END IF;
	END IF;
    
    DELETE FROM tmp_Split;
    
    -- Understanding Levels
    IF v_has_filter_understanding_level = 1 THEN
		CALL parts.p_split(v_guid, a_ids_understanding_level, ',', a_debug);
		
		INSERT INTO tmp_Split (
			  substring
			, as_int
		)
		SELECT 
			  substring
			, CONVERT(substring, DECIMAL(10,0)) AS as_int
		FROM parts.CORE_Split_Temp
		WHERE 
                GUID = v_guid
			AND NOT ISNULL(substring)
			AND substring <> ''
		;
		
		CALL parts.p_clear_split_temp( v_guid );
	END IF;
    
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error t_ERROR INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type WHERE ERROR_TYPE.is_breaking_error = 1 LIMIT 1) THEN
		IF EXISTS (
			SELECT * 
            FROM tmp_Split t_SPLIT 
            LEFT JOIN parts.DOG_Understanding_Level UNDERSTANDING_LEVEL ON t_SPLIT.as_int = UNDERSTANDING_LEVEL.id_understanding_level 
			WHERE 
				    ISNULL(t_SPLIT.as_int) 
                OR  ISNULL(UNDERSTANDING_LEVEL.id_understanding_level)
				OR  (
					UNDERSTANDING_LEVEL.active = 0
					AND a_get_inactive_understanding_level = 0
				)
		) THEN
			INSERT INTO tmp_Msg_Error (
				  id_type
				, code
                , msg
			)
			SELECT
				  v_id_type_error_bad_data
                , v_code_type_error_bad_data
				, CONCAT('Invalid or inactive Understanding Level IDs: ', IFNULL(GROUP_CONCAT(t_SPLIT.substring SEPARATOR ', '), 'NULL'))
			FROM tmp_Split t_SPLIT
			LEFT JOIN parts.DOG_Understanding_Level UNDERSTANDING_LEVEL ON t_SPLIT.as_int = UNDERSTANDING_LEVEL.id_understanding_level
			WHERE 
				    ISNULL(t_SPLIT.as_int) 
				OR  ISNULL(UNDERSTANDING_LEVEL.id_understanding_level)
				OR  (
					UNDERSTANDING_LEVEL.active = 0
					AND a_get_inactive_understanding_level = 0
				)
			;
		ELSE
			INSERT INTO tmp_Understanding_Level (
				  id_understanding_level
                , code
                , name
			)
			SELECT 
				  UNDERSTANDING_LEVEL.id_understanding_level
                , UNDERSTANDING_LEVEL.code
                , UNDERSTANDING_LEVEL.name
			FROM tmp_Split t_SPLIT
			RIGHT JOIN parts.DOG_Understanding_Level UNDERSTANDING_LEVEL ON t_SPLIT.as_int = UNDERSTANDING_LEVEL.id_understanding_level
			WHERE 
                (
					    a_get_all_understanding_level = 1
					OR  (
						    v_has_filter_understanding_level = 1
						AND NOT ISNULL(t_SPLIT.as_int)
					)
				)
				AND (
					    a_get_inactive_understanding_level = 1
					OR  UNDERSTANDING_LEVEL.active = 1
				)
			;
		END IF;
	END IF;
    
    DELETE FROM tmp_Split;
    
    -- Obedience Levels
    IF v_has_filter_obedience_level = 1 THEN
		CALL parts.p_split(v_guid, a_ids_obedience_level, ',', a_debug);
		
		INSERT INTO tmp_Split (
			  substring
			, as_int
		)
		SELECT 
			  substring
			, CONVERT(substring, DECIMAL(10,0)) AS as_int
		FROM parts.CORE_Split_Temp
		WHERE 
                GUID = v_guid
			AND NOT ISNULL(substring)
			AND substring <> ''
		;
		
		CALL parts.p_clear_split_temp( v_guid );
	END IF;
    
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error t_ERROR INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type WHERE ERROR_TYPE.is_breaking_error = 1 LIMIT 1) THEN
		IF EXISTS (
			SELECT * 
            FROM tmp_Split t_SPLIT 
            LEFT JOIN parts.DOG_Obedience_Level OBEDIENCE_LEVEL ON t_SPLIT.as_int = OBEDIENCE_LEVEL.id_obedience_level 
			WHERE 
				    ISNULL(t_SPLIT.as_int) 
                OR  ISNULL(OBEDIENCE_LEVEL.id_obedience_level)
				OR  (
					OBEDIENCE_LEVEL.active = 0
					AND a_get_inactive_obedience_level = 0
				)
		) THEN
			INSERT INTO tmp_Msg_Error (
				  id_type
				, code
                , msg
			)
			SELECT
				  v_id_type_error_bad_data
                , v_code_type_error_bad_data
				, CONCAT('Invalid or inactive Obedience Level IDs: ', IFNULL(GROUP_CONCAT(t_SPLIT.substring SEPARATOR ', '), 'NULL'))
			FROM tmp_Split t_SPLIT
			LEFT JOIN parts.DOG_Obedience_Level OBEDIENCE_LEVEL ON t_SPLIT.as_int = OBEDIENCE_LEVEL.id_obedience_level
			WHERE 
				    ISNULL(t_SPLIT.as_int) 
				OR  ISNULL(OBEDIENCE_LEVEL.id_obedience_level)
				OR  (
					OBEDIENCE_LEVEL.active = 0
					AND a_get_inactive_obedience_level = 0
				)
			;
		ELSE
			INSERT INTO tmp_Obedience_Level (
				  id_obedience_level
                , code
                , name
			)
			SELECT 
				  OBEDIENCE_LEVEL.id_obedience_level
                , OBEDIENCE_LEVEL.code
                , OBEDIENCE_LEVEL.name
			FROM tmp_Split t_SPLIT
			RIGHT JOIN parts.DOG_Obedience_Level OBEDIENCE_LEVEL ON t_SPLIT.as_int = OBEDIENCE_LEVEL.id_obedience_level
			WHERE 
                (
					    a_get_all_obedience_level = 1
					OR  (
						    v_has_filter_obedience_level = 1
						AND NOT ISNULL(t_SPLIT.as_int)
					)
				)
				AND (
					    a_get_inactive_obedience_level = 1
					OR  OBEDIENCE_LEVEL.active = 1
				)
			;
		END IF;
	END IF;
    
    DELETE FROM tmp_Split;
    

    -- Permissions
    IF a_debug = 1 THEN
		SELECT 
			  v_guid
			, a_id_user
			, FALSE -- a_get_inactive_user
			, v_id_permission_dog_view
			, 0 -- a_debug
        ;
    END IF;
    
	CALL parts.p_DOG_calc_user(
          v_guid
        , a_id_user
        , FALSE -- a_get_inactive_user
        , v_id_permission_dog_view
        , 0 -- a_debug
    );
	
    SELECT
          IFNULL(CALC_USER_T.has_access, 0)
    INTO
          v_can_view
    FROM parts.DOG_Calc_User_Temp CALC_USER_T
    WHERE CALC_USER_T.GUID = v_guid
    LIMIT 1
    ;
    
    IF a_debug = 1 THEN
        SELECT v_can_view;
    END IF;
    
    IF (v_can_view = 0) THEN
		DELETE t_ME
        FROM tmp_Msg_Error t_ME
        WHERE t_ME.id_type <> v_id_type_error_no_permission
        ;
		INSERT INTO tmp_Msg_Error (
			  id_type
			, code
            , msg
		)
		VALUES (
			  v_id_type_error_no_permission
            , v_code_type_error_no_permission
			, 'You do not have permission to view Commands.'
		)
        ;
    END IF;
	
	CALL parts.p_DOG_clear_calc_user(
		v_guid
        , 0 -- a_debug
	);
    
    IF EXISTS(SELECT * FROM tmp_Msg_Error t_ERROR INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type WHERE ERROR_TYPE.is_breaking_error = 1 LIMIT 1) THEN
        IF a_debug = 1 THEN
            SELECT * FROM tmp_Dog;
            SELECT * FROM tmp_Command;
            SELECT * FROM tmp_Obedience_Level;
        END IF;

        DELETE FROM tmp_Dog;
        DELETE FROM tmp_Command;
        SELECT * FROM tmp_Understanding_Level;
        DELETE FROM tmp_Obedience_Level;
    END IF;

    -- Outputs
    -- Commands
    SELECT 
          DOG_COMMAND_LINK.id_link AS id_dog_command_link
        , t_DOG.id_dog
        , t_DOG.name
        , t_COMMAND.id_command
    --  , t_COMMAND.code
        , t_COMMAND.name
        , t_UNDERSTANDING_LEVEL.id_understanding_level
        , t_UNDERSTANDING_LEVEL.code AS code_understanding_level
        , t_UNDERSTANDING_LEVEL.name AS name_understanding_level
        , t_OBEDIENCE_LEVEL.id_obedience_level
        , t_OBEDIENCE_LEVEL.code AS code_obedience_level
        , t_OBEDIENCE_LEVEL.name AS name_obedience_level
        , DOG_COMMAND_LINK.active
    FROM parts.DOG_Dog_Command_Link DOG_COMMAND_LINK
    INNER JOIN tmp_Dog t_DOG ON DOG_COMMAND_LINK.id_dog = t_DOG.id_dog
    INNER JOIN tmp_Command t_COMMAND ON DOG_COMMAND_LINK.id_command = t_COMMAND.id_command
    INNER JOIN tmp_Understanding_Level t_UNDERSTANDING_LEVEL ON DOG_COMMAND_LINK.id_understanding_level = t_UNDERSTANDING_LEVEL.id_understanding_level
    INNER JOIN tmp_Obedience_Level t_OBEDIENCE_LEVEL ON DOG_COMMAND_LINK.id_obedience_level = t_OBEDIENCE_LEVEL.id_obedience_level
	;
    
    -- Errors
    SELECT 
          t_ERROR.id_error
		, t_ERROR.id_type
        , t_ERROR.code
        , ERROR_TYPE.name
        , ERROR_TYPE.description
        , ERROR_TYPE.is_breaking_error
        , ERROR_TYPE.background_colour
        , ERROR_TYPE.text_colour
		, t_ERROR.msg
    FROM tmp_Msg_Error t_ERROR
	INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type
	;
    
    IF a_debug = 1 AND v_can_view = 1 THEN
        SELECT * FROM tmp_Dog;
        SELECT * FROM tmp_Command;
        SELECT * FROM tmp_Understanding_Level;
        SELECT * FROM tmp_Obedience_Level;
    END IF;
    
    DROP TEMPORARY TABLE IF EXISTS tmp_Split;
    DROP TEMPORARY TABLE IF EXISTS tmp_Msg_Error;
    DROP TEMPORARY TABLE IF EXISTS tmp_Obedience_Level;
    DROP TEMPORARY TABLE IF EXISTS tmp_Understanding_Level;
    DROP TEMPORARY TABLE IF EXISTS tmp_Command;
    DROP TEMPORARY TABLE IF EXISTS tmp_Dog;
    
    IF a_debug = 1 THEN
		CALL parts.p_core_debug_timing_reporting ( v_time_start );
    END IF;
END //
DELIMITER ;


/*

CALL parts.p_DOG_get_many_dog_command (
	  1 -- 'auth0|6582b95c895d09a70ba10fef',	-- a_id_user
    , 1                                     	-- a_get_all_dog
	, 0                                     	-- a_get_inactive_dog
	, ''                                    	-- a_ids_dog
    , 1                                     	-- a_get_all_command
	, 0                                     	-- a_get_inactive_command
	, ''                                    	-- a_ids_command
    , 1                                     	-- a_get_all_understanding_level
	, 0                                     	-- a_get_inactive_understanding_level
	, ''                                    	-- a_ids_understanding_level
    , 1                                     	-- a_get_all_obedience_level
	, 0                                     	-- a_get_inactive_obedience_level
	, ''                                    	-- a_ids_obedience_level
    , 1                                     	-- a_debug
);

*/
USE parts;


-- Error Message Types
/* Existing table */
INSERT INTO parts.CORE_Msg_Error_Type (
	  code
    , name
    , description
    , is_breaking_error
)
VALUES 
	(
          'BAD_DATA'
        , 'Invalid data'
        , 'Rubbish data'
        , 1
    )
	, (
          'NO_PERMISSION'
        , 'No permission'
        , 'Not authorised'
        , 1
    )
    , (
          'MYSQL_ERROR'
        , 'MySQL error'
        , 'MySQL execution error.'
        , 1
    )
    , (
          'WARNING'
        , 'Warning'
        , 'Non-breaking error.'
        , 0
    )
;

INSERT INTO parts.CORE_File_Type (
      code
    , name
    , is_image
)
VALUES
      (
          'JPG'
        , 'JPG'
        , 1
    )
;

-- Access Levels
INSERT INTO parts.DOG_Access_Level (
	  display_order
    , code
    , name
    , priority
)
VALUES 
	(
          1
        , 'VIEW'
        , 'View'
        , 3
    )
	, (
          2
        , 'EDIT'
        , 'Edit'
        , 2
    )
	, (
          3
        , 'ADMIN'
        , 'Admin'
        , 1
    )
;

-- Permission Groups
INSERT INTO parts.DOG_Permission_Group (
	display_order
    , code
    , name
)
VALUES 
	(
          0
        , 'DOG'
        , 'Dog'
    )
	, (
          1
        , 'USER'
        , 'Admin User'
    )
;

-- Permissions
INSERT INTO parts.DOG_Permission (
	  display_order
    , code
    , name
    , id_permission_group
    , id_access_level_required
)
VALUES 
	(
          1
        , 'DOG_VIEW'
        , 'View Dog'
        , 1
        , 3
    )
	, (
          1
        , 'DOG_ADMIN'
        , 'Admin Dog'
        , 1
        , 3
    )
	, (
          1
        , 'DOG_CREATE'
        , 'Create Dog'
        , 1
        , 1
    )
;

-- Users
INSERT INTO parts.DOG_User (
	  id_user_auth0
	, firstname
    , surname
	, email
	, is_super_user
    , active
)
VALUES 
	(
		  'auth0|6582b95c895d09a70ba10fef' -- id_user_auth0
		, 'Teddy' -- firstname
        , 'Middleton-Smith' -- surname
        , 'edward.middletonsmith@gmail.com' -- email
        , 1 -- is_super_user
		, 1 -- active
	)
    , (
		'auth0|672659014296b7f94a9bab45' -- id_user_auth0
		, 'Tierney' -- firstname
		, 'Gullen' -- surname
		, 'tierneybailey13@gmail.com' -- email
		, 1 -- is_super_user
		, 1 -- active
	)
    , (
          NULL -- id_user_auth0
        , 'Command Bot' -- firstname
        , 'Bot' -- surname
        , 'teddy@partsltd.co.uk' -- email
        , 0 -- is_super_user
        , 1 -- active
    )
;

-- Roles
INSERT INTO parts.DOG_Role (
	  display_order
	, code
	, name
    , id_user_created_by
)
VALUES 
	  (
          1
        , 'MANAGER'
        , 'Manager'
        , 1
    )
	, (
          2
        , 'USER'
        , 'User'
        , 1
    )
;

-- Role Permission link
INSERT INTO parts.DOG_Role_Permission_Link (
	  id_role
    , id_permission
    , id_access_level
    , id_user_created_by
)
VALUES 
	  (
          1
        , 1
        , 3
        , 1
    )
	, (
          1
        , 2
        , 3
        , 1
    )
	, (
          1
        , 3
        , 3
        , 1
    )
	, (
          2
        , 1
        , 1
        , 1
    )
	, (
          2
        , 2
        , 1
        , 1
    )
	, (
          2
        , 3
        , 1
        , 1
    )
;

-- User Role link
INSERT INTO parts.DOG_User_Role_Link (
	  id_user
    , id_role
    , id_user_created_by
)
VALUES 
	(
          1
        , 1
        , 1
    )
	, (
          2
        , 2
        , 1
    )
	, (
          3
        , 2
        , 1
    )
;

-- Project-specific tables
INSERT INTO parts.DOG_Dog (
      name
    , appearance
    , mass_kg
)
VALUES 
      (
          'Molly'
        , 'Cute'
        , 20
    )
;

INSERT INTO parts.DOG_Breed (
      code
    , name
)
VALUES 
      (
          'BORDER_COLLIE'
        , 'Border Collie'
    )
;

INSERT INTO parts.DOG_Dog_Breed_Link (
      id_dog
    , id_breed
    , lineage_ratio
)
VALUES 
      (
          1
        , 1
        , 1
    )
;

INSERT INTO parts.DOG_Understanding_Level (
      code
    , name
)
VALUES 
      (
          'UNKNOWN'
        , 'Not known'
    )
    , (
          'INTRODUCED'
        , 'Has been introduced'
    )
    , (
          'RECOGNISES_COMBINED_VISUAL_AND_VERBAL_SIGNAL'
        , 'Combined visual and verbal signal recognised'
    )
    , (
          'RECOGNISES_VISUAL_SIGNAL'
        , 'Visual signal alone recognised'
    )
    , (
          'RECOGNISES_VERBAL_SIGNAL'
        , 'Verbal signal alone recognised'
    )
    , (
          'UNDERSTOOD'
        , 'Understood'
    )
;

INSERT INTO parts.DOG_Obedience_Level (
      code
    , name
)
VALUES 
      (
          'REFUSAL'
        , 'Refuses to obey'
    )
    , (
          'ON_HER_TERMS'
        , 'Might obey if she feels like it'
    )
    , (
          'OBEYS_UNDISTRACTED'
        , 'Obeys without distractions'
    )
    , (
          'OBEYS_MILDLY_DISTRACTED'
        , 'Obeys when mildly distracted'
    )
    , (
          'OBEYS_PERFECTLY'
        , 'Obeys in all situations'
    )
;

INSERT INTO parts.DOG_Command_Category (
      code
    , name
)
VALUES 
      (
          'ACTIVITIES'
        , 'Activities'
    )
    , (
          'BASIC_OBEDIENCE'
        , 'Basic obedience'
    )
    , (
          'BEHAVIOUR_MODIFICATION'
        , 'Behaviour modification'
    )
    , (
          'BODY_PARTS'
        , 'Body parts'
    )
    , (
          'CLOTHING_AND_EQUIPMENT'
        , 'Clothing and equipment'
    )
    , (
          'COMPARISON'
        , 'Comparison'
    )
    , (
          'ADJECTIVES'
        , 'Compliments and insults (adjectives)'
    )
    , (
          'EMOTIONAL_STATE'
        , 'Emotional state'
    )
    , (
          'ENVIRONMENT'
        , 'Environment'
    )
    , (
          'ESSENTIAL_NEEDS'
        , 'Essential needs'
    )
    , (
          'IMPULSE_CONTROL'
        , 'Impulse control'
    )
    , (
          'LOCATION'
        , 'Location'
    )
    , (
          'MANNERS'
        , 'Manners'
    )
    , (
          'MEALTIME'
        , 'Mealtime'
    )
    , (
          'PARTY_TRICK'
        , 'Party trick'
    )
    , (
          'PEOPLE'
        , 'People'
    )
    , (
          'PLAY'
        , 'Play'
    )
    , (
          'POSITION'
        , 'Position'
    )
    , (
          'QUESTIONS'
        , 'Questions'
    )
    , (
          'SERVICE'
        , 'Service'
    )
    , (
          'TIME_AND_SCHEDULING'
        , 'Time and scheduling'
    )
    , (
          'UTILITY'
        , 'Utility'
    )
;

/*
INSERT INTO parts.DOG_Command (
      code
    , name
)
VALUES 
      (
          'lick'
        , 'nips'
    )
;
*/

/*
INSERT INTO parts.DOG_Dog_Command_Link (
      id_dog
    , id_command
    , id_understanding_level
    , id_obedience_level
    , notes
)
VALUES 
      (
          'lick'
        , 'nips'
    )
;
*/

INSERT INTO parts.DOG_Location (
      code
    , name
)
VALUES 
      (
          'LOUNGE'
        , 'Lounge'
    )
;

/*
INSERT INTO parts.DOG_Location_Link (
      id_location_parent
    , id_location_child
)
VALUES 
      (
          1
        , 2
    )
;
*/

INSERT INTO parts.DOG_Colour (
      code
    , name
)
VALUES 
      (
          'RED'
        , 'Red'
    )
    , (
          'GREEN'
        , 'Green'
    )
;

INSERT INTO parts.DOG_Button_Shape (
      code
    , name
    , description
)
VALUES 
      (
          'ROUND'
        , 'Round'
        , 'Cylindrical'
    )
    , (
          'HEXAGONAL'
        , 'Hexagonal'
        , 'Hexagonal prism'
    )
;

/*
INSERT INTO parts.DOG_Image (
      id_file_type
    , id_dog
    , path
    , display_order
)
VALUES 
      (
          1
        , 1
        , NULL
        , NULL
    )
;
*/

/*
INSERT INTO parts.DOG_Button_Icon (
      id_image
    , code
    , name
    , description
)
VALUES 
      (
          1
        , NULL
    )
;
*/

/*
INSERT INTO parts.DOG_Command_Button_Link (
      id_command
    , id_button_shape
    , id_button_colour
    , id_button_icon
    , id_location
)
VALUES 
      (
          1     -- AS id_command
        , 1     -- AS id_button_shape
        , 1     -- AS id_button_colour
        , NULL  -- AS id_button_icon
        , 1     -- AS id_location
    )
;
*/

INSERT INTO parts.DOG_Drive (
      code
    , name
)
VALUES 
      (
          'PREY'
        , 'Prey'
    )
    , (
          'PACK'
        , 'Pack'
    )
;

INSERT INTO parts.DOG_Dog_Drive_Link (
      id_dog
    , id_drive
    , dominance_ratio
)
VALUES 
      (
          1
        , 1
        , 0.5
    )
    , (
          1
        , 2
        , 0.5
    )
;



/*
 Post Excel-insert:


SELECT *
FROM demo.DOG_Dog;

/ *
SELECT *
FROM demo.DOG_Command;
* /

SELECT *
-- DELETE
FROM demo.DOG_Understanding_Level;

SELECT *
-- DELETE
FROM demo.DOG_Obedience_Level;

/ *
INSERT INTO demo.DOG_Dog_Command_Link (
      id_dog
    , id_command
    , id_understanding_level
    , id_obedience_level
    , notes
)
SELECT
	  DOG.id_dog
    , COMMAND.id_command
    , 
FROM demo.DOG_Dog DOG
CROSS JOIN demo.DOG_Command COMMAND
WHERE DOG.name = 'Molly'

* /

*/

-- Core tables
-- Error Message type
SELECT * FROM parts.CORE_Msg_Error_Type;


-- Common project tables
-- User Change Sets
SELECT * FROM parts.DOG_User_Change_Set;

-- Access Levels
SELECT * FROM parts.DOG_Access_Level;

-- Permission Groups
SELECT * FROM parts.DOG_Permission_Group;

-- Permissions
SELECT * FROM parts.DOG_Permission;

-- Users
SELECT * FROM parts.DOG_User;
SELECT * FROM parts.DOG_User_Audit;

-- Roles
SELECT * FROM parts.DOG_Role;
SELECT * FROM parts.DOG_Role_Audit;

-- Role Permission link
SELECT * FROM parts.DOG_Role_Permission_Link;
SELECT * FROM parts.DOG_Role_Permission_Link_Audit;

-- User Role link
SELECT * FROM parts.DOG_User_Role_Link;
SELECT * FROM parts.DOG_User_Role_Link_Audit;


-- Project-specific tables
-- Command Change Sets
SELECT * FROM parts.DOG_Dog_Change_Set;

-- Commands
SELECT * FROM parts.DOG_Dog;
SELECT * FROM parts.DOG_Dog_Audit;
SELECT * FROM parts.DOG_Dog_Temp;

SELECT * FROM parts.DOG_Breed;
SELECT * FROM parts.DOG_Breed_Audit;
SELECT * FROM parts.DOG_Breed_Temp;

SELECT * FROM parts.DOG_Dog_Breed_Link;
SELECT * FROM parts.DOG_Dog_Breed_Link_Audit;
SELECT * FROM parts.DOG_Dog_Breed_Link_Temp;

SELECT * FROM parts.DOG_Obedience_Level;
SELECT * FROM parts.DOG_Obedience_Level_Audit;
SELECT * FROM parts.DOG_Obedience_Level_Temp;

SELECT * FROM parts.DOG_Command_Category;
SELECT * FROM parts.DOG_Command_Category_Audit;
SELECT * FROM parts.DOG_Command_Category_Temp;

SELECT * FROM parts.DOG_Command;
SELECT * FROM parts.DOG_Command_Audit;
SELECT * FROM parts.DOG_Command_Temp;

SELECT * FROM parts.DOG_Dog_Command_Link;
SELECT * FROM parts.DOG_Dog_Command_Link_Audit;
SELECT * FROM parts.DOG_Dog_Command_Link_Temp;

SELECT * FROM parts.DOG_Location;
SELECT * FROM parts.DOG_Location_Audit;
SELECT * FROM parts.DOG_Location_Temp;

SELECT * FROM parts.DOG_Location_Link;
SELECT * FROM parts.DOG_Location_Link_Audit;
SELECT * FROM parts.DOG_Location_Link_Temp;

SELECT * FROM parts.DOG_Colour;
SELECT * FROM parts.DOG_Colour_Audit;
SELECT * FROM parts.DOG_Colour_Temp;

SELECT * FROM parts.DOG_Button_Shape;
SELECT * FROM parts.DOG_Button_Shape_Audit;
SELECT * FROM parts.DOG_Button_Shape_Temp;

SELECT * FROM parts.DOG_Image;
SELECT * FROM parts.DOG_Image_Audit;
SELECT * FROM parts.DOG_Image_Temp;

SELECT * FROM parts.DOG_Button_Icon;
SELECT * FROM parts.DOG_Button_Icon_Audit;
SELECT * FROM parts.DOG_Button_Icon_Temp;

SELECT * FROM parts.DOG_Command_Button_Link;
SELECT * FROM parts.DOG_Command_Button_Link_Audit;
SELECT * FROM parts.DOG_Command_Button_Link_Temp;

SELECT * FROM parts.DOG_Drive;
SELECT * FROM parts.DOG_Drive_Audit;
SELECT * FROM parts.DOG_Drive_Temp;

SELECT * FROM parts.DOG_Dog_Drive_Link;
SELECT * FROM parts.DOG_Dog_Drive_Link_Audit;
SELECT * FROM parts.DOG_Dog_Drive_Link_Temp;

