
---- clean up all (optional)

-- DROP SCHEMA public CASCADE;
-- CREATE SCHEMA public;

-- GRANT ALL ON SCHEMA public TO postgres;
-- GRANT ALL ON SCHEMA public TO public;


---- create tables


CREATE TABLE ACC_RIGHTS
(
	"id" SERIAL NOT NULL, 
	"type" int NOT NULL, 
	"catid" int NULL, 
	"cattype" int NOT NULL, 
	"archive" int NOT NULL, 
	"username" varchar(260) NULL, 
	"rights" int NOT NULL
);
CREATE TABLE ADMIN_RIGHTS
(
	"groupname" varchar(260) NULL, 
	"type" int NULL, 
	"catid" int NULL, 
	"rightcreate" int NULL, 
	"rightdelete" int NULL, 
	"rightedit" int NULL, 
	"rightpreview" int NULL
);
CREATE TABLE ADVANCE_COMM
(
	"id" SERIAL NOT NULL, 
	"system" int NOT NULL, 
	"name" varchar(128) NOT NULL, 
	"request" varchar(3000) NOT NULL, 
	"description" varchar(3000) NULL
);
CREATE TABLE ApiUser_AttribVals
(
	"id" SERIAL NOT NULL, 
	"apiuserid" int NOT NULL, 
	"attribvalsid" int NOT NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE ApiUser_Schedules
(
	"id" SERIAL NOT NULL, 
	"apiuserid" int NOT NULL, 
	"scheduleid" int NOT NULL, 
	"tariffscaleid" int NOT NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE ApiUserHooks
(
	"id" SERIAL NOT NULL, 
	"apiuserid" int NOT NULL, 
	"url" varchar(2048) NULL, 
	"configjson" text NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE ApiUsers
(
	"id" SERIAL NOT NULL, 
	"networkid" int NULL, 
	"covenanteeid" int NULL, 
	"type" int NOT NULL, 
	"name" varchar(128) NOT NULL, 
	"details" varchar(1024) NULL, 
	"apikey" varchar(256) NOT NULL, 
	"configjson" text NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current(), 
	"phcategoryid" int NULL, 
	"deleted" int NOT NULL DEFAULT ((0)), 
	"canreadanyph" Boolean NOT NULL DEFAULT ((false))
);
CREATE TABLE ApiUsers_PlayBlocks
(
	"id" SERIAL NOT NULL, 
	"api_user_id" int NOT NULL, 
	"play_block_id" int NOT NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE aq_categories
(
	"id" SERIAL NOT NULL, 
	"standart_id" varchar(64) NULL, 
	"standart_name" varchar(256) NULL, 
	"category_id" int NULL, 
	"category_type" int NULL, 
	"recursive" Boolean NULL, 
	"enable" Boolean NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current(), 
	"standart_modify_time" bigint NULL DEFAULT ((0))
);
CREATE TABLE aq_results
(
	"id" SERIAL NOT NULL, 
	"job_id" varchar(64) NULL, 
	"standart_id" varchar(64) NULL, 
	"standart_name" varchar(256) NULL, 
	"category_id" int NULL, 
	"category_type" int NULL, 
	"ph_id" int NULL, 
	"status" int NULL, 
	"ph_stamp" bigint NULL, 
	"md5" varchar(128) NULL, 
	"result_text" text NULL, 
	"date_modify" timestamptz NULL DEFAULT (now()), 
	"standart_modify_time" bigint NULL DEFAULT ((0))
);
CREATE TABLE ATTRIB_VALS
(
	"id" SERIAL NOT NULL, 
	"name" varchar(260) NOT NULL, 
	"type" int NOT NULL DEFAULT ((1)), 
	"attr_id" int NOT NULL, 
	"deleted" int NOT NULL DEFAULT ((0)), 
	"modifydate" timestamptz NOT NULL DEFAULT (now()), 
	"radioid" int NOT NULL DEFAULT ((0)), 
	"file_path" varchar(260) NOT NULL DEFAULT (''), 
	"jm_pos" int NOT NULL DEFAULT ((-1)), 
	"ddb_owner" varchar(64) NULL, 
	"ddb_allowed" int NOT NULL DEFAULT ((0)), 
	"ddb_id" int NOT NULL DEFAULT ((0)), 
	"color" int NOT NULL DEFAULT ((16777215)), 
	"activatedate" timestamptz NOT NULL DEFAULT (now()), 
	"fornewsbrowser" int NULL, 
	"searchdepth" int NULL, 
	"tmstamp" bigint NOT NULL DEFAULT txid_current(), 
	"adddate" timestamptz NOT NULL DEFAULT (now())
);
CREATE TABLE ATTRIBS
(
	"id" SERIAL NOT NULL, 
	"name" varchar(260) NOT NULL, 
	"type" int NOT NULL DEFAULT ((1)), 
	"radioid" int NOT NULL DEFAULT ((0)), 
	"ddb_owner" varchar(64) NULL, 
	"ddb_id" int NOT NULL DEFAULT ((0)), 
	"modifydate" timestamptz NOT NULL DEFAULT (now()), 
	"fornewsbrowser" int NULL, 
	"toolbar" int NULL, 
	"nick" varchar(64) NULL, 
	"tmstamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE AUTO_MOVE
(
	"id" SERIAL NOT NULL, 
	"srccatid" int NOT NULL, 
	"srcarchive" int NOT NULL, 
	"dstcatid" int NOT NULL, 
	"dstarchive" int NOT NULL, 
	"dstdelete" int NOT NULL, 
	"keeptime" bigint NOT NULL
);
CREATE TABLE BackgroundTaskHistory
(
	"procname" varchar(64) NOT NULL, 
	"lastexec" timestamptz NOT NULL, 
	"result" int NULL
);
CREATE TABLE BROADCAST_RELEASES
(
	"id" SERIAL NOT NULL, 
	"network_id" int NOT NULL, 
	"broadcasts_id" int NOT NULL, 
	"start_datetime" timestamptz NOT NULL, 
	"duration" time NOT NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current(), 
	"from_template" Boolean NOT NULL DEFAULT ((false)), 
	"theme_text" text NULL, 
	"description_text" text NULL, 
	"deleted" int NOT NULL DEFAULT ((0))
);
CREATE TABLE BROADCAST_SIGNED_DAYS
(
	"id" SERIAL NOT NULL, 
	"network_id" int NULL, 
	"date" timestamptz NOT NULL
);
CREATE TABLE BROADCAST_TEMPLATES
(
	"id" SERIAL NOT NULL, 
	"broadcasts_id" int NOT NULL, 
	"start_date" timestamptz NOT NULL, 
	"end_date" timestamptz NULL, 
	"start_time" time NOT NULL, 
	"duration" time NOT NULL, 
	"week_day" int NULL, 
	"month_num" int NULL, 
	"month_day" int NULL, 
	"week" int NULL
);
CREATE TABLE BROADCASTS
(
	"id" SERIAL NOT NULL, 
	"network_id" int NULL, 
	"deleted" int NOT NULL, 
	"name" text NOT NULL, 
	"description" text NULL, 
	"color_rgb" int NULL, 
	"duration" time NOT NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE CAMERA_PRESETS
(
	"id" SERIAL NOT NULL, 
	"schedule_id" int NOT NULL, 
	"camera_id" varchar(256) NOT NULL, 
	"preset_node" text NOT NULL
);
CREATE TABLE CAT_AUTO_SERVICE
(
	"id" SERIAL NOT NULL, 
	"attrval_id" int NOT NULL, 
	"service_type" varchar(50) NOT NULL, 
	"params_xml" text NOT NULL
);
CREATE TABLE CAT_JNGL_BTNS
(
	"id" SERIAL NOT NULL, 
	"catid" int NOT NULL, 
	"parentid" int NOT NULL, 
	"pos" int NULL, 
	"deleted" int NULL, 
	"modifydate" timestamptz NOT NULL DEFAULT (now())
);
CREATE TABLE components
(
	"id" SERIAL NOT NULL, 
	"name" varchar(128) NOT NULL, 
	"vers" varchar(128) NULL, 
	"veri" int NULL, 
	"adddate" timestamptz NULL DEFAULT (now())
);
CREATE TABLE data_tree
(
	"id" SERIAL NOT NULL, 
	"parent_id" int NULL, 
	"str_id" varchar(128) NOT NULL, 
	"tmstamp" bigint NOT NULL DEFAULT txid_current(), 
	"xml_val" text NULL, 
	"str_val" text NULL
);
CREATE TABLE DB_IMPORT_FILTERS
(
	"id" SERIAL NOT NULL, 
	"type" int NOT NULL, 
	"name" varchar(3000) NOT NULL, 
	"value" varchar(3000) NOT NULL
);
CREATE TABLE DDB_FILES
(
	"id" SERIAL NOT NULL, 
	"ddbowner" varchar(128) NOT NULL, 
	"srcfilename" varchar(512) NOT NULL, 
	"dstfilename" varchar(512) NOT NULL, 
	"type" int NOT NULL, 
	"airtime" bigint NOT NULL, 
	"modifyft" bigint NOT NULL, 
	"checktime" bigint NULL
);
CREATE TABLE dmdb_Async_Jobs
(
	"id" SERIAL NOT NULL, 
	"content" varchar(1024) NULL, 
	"type" int NULL, 
	"state" int NULL, 
	"timestart" timestamptz NULL, 
	"timestop" timestamptz NULL, 
	"statustext" varchar(1024) NULL, 
	"apiuserid" int NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current(), 
	"result" text NULL DEFAULT (NULL)
);
CREATE TABLE dmdb_Player_Categories
(
	"id" SERIAL NOT NULL, 
	"playerid" int NULL, 
	"categoryname" varchar(1024) NULL, 
	"categorytype" int NULL, 
	"categorysortpos" int NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current(), 
	"categoryid" int NULL
);
CREATE TABLE dmdb_Player_MediaPlan
(
	"id" SERIAL NOT NULL, 
	"playerid" int NOT NULL, 
	"mediaplanid" int NOT NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE dmdb_Player_PlayerProfile
(
	"id" SERIAL NOT NULL, 
	"playerid" int NOT NULL, 
	"playerprofileid" int NOT NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE dmdb_PlayerProfile_MediaPlan
(
	"id" SERIAL NOT NULL, 
	"playerprofileid" int NOT NULL, 
	"mediaplanid" int NOT NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE dmdb_PlayerProfiles
(
	"id" SERIAL NOT NULL, 
	"apiuserid" int NULL, 
	"name" varchar(512) NULL, 
	"address" text NULL, 
	"pathtorootid" text NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current(), 
	"adddate" timestamptz NOT NULL DEFAULT (now()), 
	"modifydate" timestamptz NOT NULL DEFAULT (now()), 
	"exttype" int NOT NULL DEFAULT ((0)), 
	"extid" varchar(128) NULL
);
CREATE TABLE dmdb_Players
(
	"id" SERIAL NOT NULL, 
	"apiuserid" int NULL, 
	"scheduleid" int NULL, 
	"extplayerid" varchar(128) NULL, 
	"name" varchar(512) NULL, 
	"extname" varchar(512) NULL, 
	"description" varchar(4000) NULL, 
	"activated" int NULL DEFAULT ((0)), 
	"playbackenabled" int NULL DEFAULT ((0)), 
	"requestperiod" int NULL DEFAULT ((60)), 
	"scheduleperiodoffset" int NULL DEFAULT ((0)), 
	"schedulelivetime" int NULL DEFAULT ((1)), 
	"stamp" bigint NOT NULL DEFAULT txid_current(), 
	"remotename" varchar(512) NULL, 
	"ipaddress" varchar(16) NULL, 
	"macaddress" varchar(32) NULL, 
	"version" varchar(32) NULL, 
	"enablelog" int NULL DEFAULT ((0)), 
	"updatemode" int NULL DEFAULT ((0)), 
	"utcoffset" int NULL DEFAULT ((0)), 
	"activetimebegin" int NULL DEFAULT ((0)), 
	"activetimeend" int NULL DEFAULT ((0)), 
	"canplayvideo" Boolean NOT NULL DEFAULT ((false)), 
	"isbase" Boolean NOT NULL DEFAULT ((false)), 
	"contenttype" int NOT NULL DEFAULT ((0)), 
	"videoorientation" int NOT NULL DEFAULT ((0)), 
	"extavailablestatustimeout" int NULL, 
	"extwaitingsyncstatustimeout" int NULL, 
	"isinternetstreammode" Boolean NOT NULL DEFAULT ((false))
);
CREATE TABLE dmdb_PlayerStates
(
	"id" SERIAL NOT NULL, 
	"playerid" int NOT NULL, 
	"lastsync" timestamptz NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current(), 
	"fullloguploadtime" timestamptz NULL DEFAULT (NULL)
);
CREATE TABLE FILTERS
(
	"id" SERIAL NOT NULL, 
	"user_id" int NULL, 
	"name" text NOT NULL, 
	"filter" text NOT NULL, 
	"filtercondition" text NOT NULL, 
	"checkorder" int NULL DEFAULT ((0)), 
	"donestamp" bigint NULL DEFAULT ((0)), 
	"total" int NULL DEFAULT ((0))
);
CREATE TABLE FILTERS_STATE
(
	"id" SERIAL NOT NULL, 
	"filter_id" int NULL, 
	"user_id" int NULL, 
	"state_total" int NULL DEFAULT ((0))
);
CREATE TABLE GRID_BLOCKS
(
	"id" SERIAL NOT NULL, 
	"clock_id" int NOT NULL, 
	"play_block_id" int NOT NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE GRID_CLOCK_POS
(
	"id" SERIAL NOT NULL, 
	"day_id" int NOT NULL, 
	"clock_id" int NOT NULL, 
	"hour_num" int NOT NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE GRID_CLOCKS
(
	"id" SERIAL NOT NULL, 
	"name" varchar(128) NOT NULL, 
	"sch_id" int NULL, 
	"network_id" int NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE GRID_DAYS
(
	"id" SERIAL NOT NULL, 
	"grid_id" int NOT NULL, 
	"week_day" int NULL, 
	"month_num" int NULL, 
	"month_day" int NULL, 
	"week" int NULL DEFAULT (NULL), 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE GRIDS
(
	"id" SERIAL NOT NULL, 
	"bdate" timestamptz NULL, 
	"name" varchar(128) NOT NULL, 
	"schedule_id" int NULL, 
	"network_id" int NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current(), 
	"last_changed_dt" timestamptz NULL
);
CREATE TABLE GROUPS
(
	"id" SERIAL NOT NULL, 
	"str_id" varchar(64) NULL, 
	"name" varchar(128) NOT NULL, 
	"ad_groups" varchar(800) NULL, 
	"description" text NULL DEFAULT (NULL)
);
CREATE TABLE locked_objects
(
	"id" SERIAL NOT NULL, 
	"obj_name" varchar(1024) NULL, 
	"last_update" timestamptz NOT NULL, 
	"owner_name" varchar(255) NULL, 
	"user_val_int" int NULL
);
CREATE TABLE logger_LoudnessJournal
(
	"id" SERIAL NOT NULL, 
	"schstreamid" int NOT NULL, 
	"lufsbefore" float NULL, 
	"lufsafter" float NULL, 
	"lufsblock" float NULL, 
	"blockbegin" timestamptz NOT NULL, 
	"blockend" timestamptz NOT NULL, 
	"ismanualtime" int NULL DEFAULT ((0)), 
	"controlresult" int NULL DEFAULT ((0)), 
	"modifytime" timestamptz NULL DEFAULT (now()), 
	"errortext" text NULL, 
	"blockid" text NULL, 
	"blockplantime" timestamptz NULL
);
CREATE TABLE logger_Streams
(
	"id" SERIAL NOT NULL, 
	"name" text NOT NULL, 
	"levelcorrection" float NULL, 
	"signaldelay" int NULL, 
	"schid" int NULL, 
	"logpath" text NULL, 
	"controlenable" int NULL DEFAULT ((0))
);
CREATE TABLE MAG_CAT_SCH
(
	"id" SERIAL NOT NULL, 
	"cat_id" int NOT NULL, 
	"sch_id" int NOT NULL, 
	"plot_number" int NOT NULL, 
	"nc_root" text NULL, 
	"search_depth" int NULL, 
	"search_depth_units" int NOT NULL DEFAULT ((0)), 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE MAG_DB_PARAMS
(
	"id" SERIAL NOT NULL, 
	"type" int NOT NULL, 
	"name" varchar(3000) NOT NULL, 
	"value" varchar(3000) NOT NULL
);
CREATE TABLE mag_packets
(
	"id" SERIAL NOT NULL, 
	"name" varchar(50) NOT NULL, 
	"category_id" int NOT NULL
);
CREATE TABLE MAG_SCH_PROP
(
	"id" SERIAL NOT NULL, 
	"sch_id" int NOT NULL, 
	"nc_root" text NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE MAG_SETTINGS
(
	"id" SERIAL NOT NULL, 
	"name" varchar(256) NOT NULL, 
	"text" text NOT NULL
);
CREATE TABLE MAG_WORK
(
	"workdate" timestamptz NOT NULL, 
	"ph_id" int NOT NULL, 
	"sch_order" int NULL, 
	"attrval_id" int NOT NULL
);
CREATE TABLE MAG2_WORK
(
	"workdate" timestamptz NOT NULL, 
	"sch_id" int NOT NULL, 
	"ph_id" int NOT NULL, 
	"sch_order" int NULL, 
	"attrval_id" int NOT NULL
);
CREATE TABLE MODIFY_DATES
(
	"ph_id" int NULL, 
	"attrib_id" int NULL, 
	"attrval_id" int NULL, 
	"modifydate" timestamptz NOT NULL DEFAULT (now()), 
	"cat_jngl_btns_id" int NULL, 
	"id" SERIAL NOT NULL, 
	"filter_id" int NULL
);
CREATE TABLE MODIFY_PH
(
	"id" SERIAL NOT NULL, 
	"ph_id" int NOT NULL, 
	"tmstamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE mp_account_mediaplans
(
	"id" SERIAL NOT NULL, 
	"account_id" int NULL, 
	"mediaplan_id" int NULL
);
CREATE TABLE mp_account_services
(
	"id" SERIAL NOT NULL, 
	"account_id" int NULL, 
	"service_name" varchar(1024) NULL, 
	"service_cost" Numeric(8,2) NULL
);
CREATE TABLE mp_accounts
(
	"id" SERIAL NOT NULL, 
	"covenantee_id" int NOT NULL, 
	"organization_id" int NULL, 
	"date" timestamptz NULL, 
	"mediaplan_id" int NULL, 
	"price" Numeric(8,2) NULL, 
	"amount" int NULL, 
	"number" varchar(100) NOT NULL, 
	"barter" Boolean NULL DEFAULT ((false)), 
	"edit_type" int NOT NULL DEFAULT ((1))
);
CREATE TABLE mp_base_costs
(
	"id" SERIAL NOT NULL, 
	"tariff_scales_id" int NOT NULL, 
	"date" timestamptz NULL, 
	"day" smallint NULL, 
	"cost" Numeric(8,2) NOT NULL, 
	"hour" smallint NULL, 
	"show_type" smallint NOT NULL, 
	"tariff_type" smallint NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current(), 
	"spot_duration" int NOT NULL DEFAULT ((0)), 
	"broadcast_id" int NULL, 
	"holiday" Boolean NULL DEFAULT ((false))
);
CREATE TABLE mp_closed_days
(
	"id" SERIAL NOT NULL, 
	"shedule_id" int NOT NULL, 
	"closed_day" timestamptz NOT NULL, 
	"network_id" int NULL
);
CREATE TABLE mp_covenantees
(
	"id" SERIAL NOT NULL, 
	"users_id" int NOT NULL, 
	"name" varchar(100) NOT NULL, 
	"contacts" varchar(500) NULL, 
	"insertiontime" timestamptz NOT NULL DEFAULT (now()), 
	"modificationtime" timestamptz NOT NULL DEFAULT (now()), 
	"agency" varchar(255) NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current(), 
	"discount_type" smallint NOT NULL DEFAULT ((0)), 
	"discount_value" float NOT NULL DEFAULT ((0)), 
	"use_discount" Boolean NOT NULL DEFAULT ((false)), 
	"id_number" varchar(128) NULL
);
CREATE TABLE mp_dayparts
(
	"id" SERIAL NOT NULL, 
	"name" varchar(1000) NOT NULL, 
	"tariff_scales_id" int NOT NULL, 
	"time_start" time NULL, 
	"time_end" time NULL, 
	"block_types" int NOT NULL, 
	"week_days" int NOT NULL, 
	"hide_empty_rows" Boolean NOT NULL, 
	"hide_empty_columns" Boolean NOT NULL
);
CREATE TABLE mp_discount_types
(
	"id" int NOT NULL, 
	"name" varchar(100) NOT NULL, 
	"apply_method" smallint NOT NULL, 
	"base_discount_id" int NULL
);
CREATE TABLE mp_discount_values
(
	"id" SERIAL NOT NULL, 
	"tariff_scales_id" int NOT NULL, 
	"default_value" smallint NOT NULL, 
	"min_value" smallint NOT NULL, 
	"max_value" smallint NOT NULL, 
	"apply_method" smallint NOT NULL, 
	"name" varchar(100) NOT NULL DEFAULT (''), 
	"type_id" int NULL, 
	"apply_type" smallint NULL, 
	"combination_type" smallint NULL DEFAULT ((0)), 
	"default_value_f" float NOT NULL DEFAULT ((0)), 
	"min_value_f" float NOT NULL DEFAULT ((0)), 
	"max_value_f" float NOT NULL DEFAULT ((0)), 
	"use_in_max_discount_calculation" Boolean NULL
);
CREATE TABLE mp_mediaplan_scheds
(
	"id" SERIAL NOT NULL, 
	"mediaplan_id" int NULL, 
	"schedule_id" int NULL, 
	"tariff_scales_id" int NULL
);
CREATE TABLE mp_mediaplans
(
	"id" SERIAL NOT NULL, 
	"users_id" int NOT NULL, 
	"tariff_scales_id" int NOT NULL, 
	"covenantees_id" int NOT NULL, 
	"schedules_id" int NOT NULL, 
	"name" varchar(1024) NULL, 
	"begin_date" timestamptz NOT NULL, 
	"end_date" timestamptz NOT NULL, 
	"modify_date" timestamptz NOT NULL, 
	"cost" Numeric(8,2) NULL, 
	"releasedcost" Numeric(8,2) NULL, 
	"status" smallint NOT NULL, 
	"payment_way" smallint NULL, 
	"reserv_term" int NULL, 
	"reserv_from" timestamptz NULL, 
	"prev_status" smallint NULL, 
	"type" int NOT NULL DEFAULT ((0)), 
	"network_id" int NULL, 
	"preset_data" BYTEA NULL, 
	"description" varchar(512) NULL, 
	"settings" BYTEA NULL, 
	"organization_id" int NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current(), 
	"creation_date" timestamptz NULL, 
	"name_detailed" varchar(1024) NULL, 
	"mode" int NOT NULL DEFAULT ((0)), 
	"last_position_changed_time" timestamptz NULL, 
	"force_simplified_state_check_mode" int NOT NULL DEFAULT ((0)), 
	"ignorebymediaplaner" Boolean NOT NULL DEFAULT ((false))
);
CREATE TABLE mp_operations
(
	"id" SERIAL NOT NULL, 
	"users_id" int NOT NULL, 
	"datetime" timestamptz NOT NULL, 
	"object" varchar(100) NOT NULL, 
	"type" smallint NOT NULL, 
	"core" varchar(500) NOT NULL
);
CREATE TABLE mp_organization_attributes
(
	"id" SERIAL NOT NULL, 
	"organization_id" int NOT NULL, 
	"name" varchar(100) NOT NULL, 
	"value" varchar(500) NULL
);
CREATE TABLE mp_organizations
(
	"id" SERIAL NOT NULL, 
	"covenantees_id" int NOT NULL, 
	"name" varchar(100) NOT NULL, 
	"last_sync" timestamptz NULL
);
CREATE TABLE mp_owners_mediaplans
(
	"id" SERIAL NOT NULL, 
	"id_mediaplan" int NULL, 
	"id_user" int NULL
);
CREATE TABLE mp_payment_types
(
	"id" SERIAL NOT NULL, 
	"name" varchar(256) NULL, 
	"color" int NULL DEFAULT (NULL)
);
CREATE TABLE mp_payments
(
	"id" SERIAL NOT NULL, 
	"account_id" int NOT NULL, 
	"payment_date" timestamptz NOT NULL, 
	"price" Numeric(8,2) NOT NULL, 
	"order_number" varchar(100) NOT NULL, 
	"barter" Boolean NULL DEFAULT ((false))
);
CREATE TABLE mp_phonograms
(
	"id" SERIAL NOT NULL, 
	"ph_id" int NULL, 
	"mediaplan_id" int NULL, 
	"covenantee_id" int NULL, 
	"plan_number" smallint NOT NULL, 
	"type" smallint NOT NULL, 
	"text" varchar(1024) NULL, 
	"duration" int NULL, 
	"plan_number_pos" smallint NOT NULL, 
	"parent_id" int NULL, 
	"placement_method" int NOT NULL DEFAULT ((0)), 
	"stamp" bigint NOT NULL DEFAULT txid_current(), 
	"use_planned_duration" Boolean NULL DEFAULT ((false)), 
	"broadcast_id" int NULL, 
	"template_type" int NULL DEFAULT ((0))
);
CREATE TABLE mp_position_replacement
(
	"id" SERIAL NOT NULL, 
	"position_id" int NOT NULL, 
	"schedules_id" int NOT NULL, 
	"release_date" timestamptz NULL, 
	"placementmethod" int NOT NULL, 
	"released" Boolean NULL, 
	"is_bonus" Boolean NOT NULL, 
	"sort_position" int NOT NULL DEFAULT ((0)), 
	"discounts_enum" varchar(128) NULL
);
CREATE TABLE mp_positions
(
	"id" SERIAL NOT NULL, 
	"mediaplans_id" int NOT NULL, 
	"users_id" int NOT NULL, 
	"date" timestamptz NOT NULL, 
	"block_number" smallint NOT NULL, 
	"plan_number" smallint NOT NULL, 
	"first" Boolean NOT NULL, 
	"release_date" timestamptz NULL, 
	"version" int NOT NULL, 
	"type" int NOT NULL, 
	"position" int NOT NULL, 
	"placementmethod" int NOT NULL, 
	"released_old" Boolean NULL, 
	"released" Boolean NULL, 
	"is_bonus" Boolean NOT NULL DEFAULT ((false)), 
	"stamp" bigint NOT NULL DEFAULT txid_current(), 
	"grid_block_id" int NULL, 
	"block_time" time NULL, 
	"clock_id" int NULL, 
	"discounts_enum" varchar(128) NULL, 
	"sort_position" int NOT NULL DEFAULT ((0))
);
CREATE TABLE mp_replacement
(
	"id" SERIAL NOT NULL, 
	"schedule_id" int NOT NULL, 
	"spot_id" int NOT NULL, 
	"new_spot_id" int NOT NULL, 
	"used" Boolean NOT NULL
);
CREATE TABLE mp_reports
(
	"id" SERIAL NOT NULL, 
	"xml" text NOT NULL, 
	"xslt" text NOT NULL, 
	"type" int NULL, 
	"app_type" int NULL, 
	"is_used_app" Boolean NOT NULL DEFAULT ((false)), 
	"name" varchar(256) NULL, 
	"processor_type" int NOT NULL DEFAULT ((0)), 
	"external_processor_name" varchar(128) NULL
);
CREATE TABLE mp_running_app
(
	"mp_id" UUID NOT NULL, 
	"owner_name" varchar(255) NOT NULL, 
	"last_time_active" timestamptz NOT NULL
);
CREATE TABLE mp_schedule_tariff_scale
(
	"id" SERIAL NOT NULL, 
	"schedule_id" int NOT NULL, 
	"tariff_scale_id" int NOT NULL
);
CREATE TABLE mp_settings
(
	"id" SERIAL NOT NULL, 
	"name" varchar(1000) NOT NULL, 
	"value" BYTEA NOT NULL, 
	"enabled" Boolean NOT NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE mp_spot_types
(
	"id" SERIAL NOT NULL, 
	"show_type" int NULL, 
	"name" varchar(255) NULL, 
	"system_type" Boolean NULL DEFAULT ((false)), 
	"template" int NOT NULL DEFAULT ((0))
);
CREATE TABLE mp_step_tariffing_values
(
	"id" SERIAL NOT NULL, 
	"tariff_scales_id" int NOT NULL, 
	"min_spot_duration" smallint NULL, 
	"max_spot_duration" smallint NULL, 
	"ratio" Numeric(18,3) NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE mp_sync_events
(
	"id" SERIAL NOT NULL, 
	"mp_id" UUID NOT NULL, 
	"event_type" int NOT NULL, 
	"gen_evt_time" timestamptz NOT NULL
);
CREATE TABLE mp_tariff_scales
(
	"id" SERIAL NOT NULL, 
	"schedules_id" int NOT NULL, 
	"begin_date" timestamptz NOT NULL, 
	"type" smallint NOT NULL, 
	"max_persent" smallint NOT NULL, 
	"exchange" int NOT NULL, 
	"network_id" int NULL, 
	"name" varchar(128) NULL, 
	"end_date" timestamptz NULL, 
	"default_scale" Boolean NOT NULL DEFAULT ((false)), 
	"max_bonus_spots" varchar(16) NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current(), 
	"default_payment_type_id" int NULL, 
	"hide" Boolean NULL DEFAULT ((false))
);
CREATE TABLE mp_used_discounts
(
	"id" SERIAL NOT NULL, 
	"mediaplans_id" int NOT NULL, 
	"discount_values_id" int NOT NULL, 
	"manager_value" smallint NOT NULL, 
	"manager_value_f" float NOT NULL DEFAULT ((0)), 
	"schedule_id" int NULL, 
	"apply_type" smallint NULL, 
	"discount_enabled" Boolean NOT NULL DEFAULT ((true))
);
CREATE TABLE NETWORKS
(
	"id" SERIAL NOT NULL, 
	"name" varchar(64) NOT NULL, 
	"location" varchar(512) NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE OperationsLog
(
	"id" SERIAL NOT NULL, 
	"time" timestamptz NOT NULL DEFAULT (now()), 
	"state" int NOT NULL, 
	"resulttext" text NOT NULL
);
CREATE TABLE P_BLOCKS
(
	"id" SERIAL NOT NULL, 
	"ddbowner" varchar(260) NOT NULL, 
	"schname" varchar(260) NOT NULL, 
	"blkname" varchar(260) NOT NULL, 
	"blkdate" timestamptz NOT NULL, 
	"tmstamp" bigint NOT NULL DEFAULT txid_current(), 
	"blkmt" bigint NOT NULL, 
	"name" varchar(255) NULL, 
	"blkbinary" BYTEA NULL, 
	"blkxml" text NULL, 
	"blktype" int NULL, 
	"blklength" int NULL
);
CREATE TABLE PARAMETERS
(
	"id" SERIAL NOT NULL, 
	"type" int NOT NULL, 
	"name" varchar(3000) NOT NULL, 
	"value" varchar(3000) NOT NULL, 
	"modifydate" timestamptz NOT NULL DEFAULT (now())
);
CREATE TABLE PH
(
	"id" SERIAL NOT NULL, 
	"name" varchar(260) NOT NULL DEFAULT ('Noname'), 
	"filename" varchar(260) NOT NULL, 
	"duration" int NOT NULL DEFAULT ((0)), 
	"type" int NOT NULL DEFAULT ((1)), 
	"intro" int NOT NULL DEFAULT ((0)), 
	"outro" int NOT NULL DEFAULT ((0)), 
	"fadein" int NOT NULL DEFAULT ((0)), 
	"fadeout" int NOT NULL DEFAULT ((0)), 
	"startnext" int NOT NULL DEFAULT ((0)), 
	"ph_start" int NOT NULL DEFAULT ((0)), 
	"ph_stop" int NOT NULL DEFAULT ((0)), 
	"cmd" int NOT NULL DEFAULT ((0)), 
	"freq" int NOT NULL DEFAULT ((0)), 
	"smplsize" int NOT NULL DEFAULT ((0)), 
	"radioid" int NOT NULL DEFAULT ((0)), 
	"remotecmd" int NOT NULL DEFAULT ((0)), 
	"adddate" timestamptz NOT NULL DEFAULT (now()), 
	"lastplaytime" timestamptz NULL, 
	"modifydate" timestamptz NOT NULL DEFAULT (now()), 
	"deleted" int NOT NULL DEFAULT ((0)), 
	"jm_pos" int NOT NULL DEFAULT ((-1)), 
	"subjtext" text NULL, 
	"id_number" varchar(128) NULL, 
	"endcode" varchar(10) NULL, 
	"firstreportline" varchar(260) NULL, 
	"lastreportline" varchar(260) NULL, 
	"maxlvl" real NOT NULL DEFAULT ((0)), 
	"maxlvlok" int NOT NULL DEFAULT ((0)), 
	"gain" real NOT NULL DEFAULT ((0)), 
	"cdid" varchar(10) NULL, 
	"cdtrackid" int NOT NULL DEFAULT ((0)), 
	"album" varchar(260) NULL, 
	"songyear" int NULL, 
	"modifyft" bigint NULL, 
	"rmtlist" varchar(2048) NULL, 
	"ddb_owner" varchar(64) NULL, 
	"version" int NULL, 
	"ddb_id" int NOT NULL DEFAULT ((0)), 
	"crc32" int NOT NULL DEFAULT ((0)), 
	"sch_usedcount" int NULL, 
	"intro2" int NULL, 
	"intro3" int NULL, 
	"comment" varchar(3000) NULL, 
	"fadeintype" int NULL, 
	"fadeouttype" int NULL, 
	"mood" int NOT NULL DEFAULT ((3)), 
	"activatedate" timestamptz NOT NULL DEFAULT (now()), 
	"energy" int NULL DEFAULT ((3)), 
	"tempo" int NULL DEFAULT ((3)), 
	"texture" int NULL DEFAULT ((3)), 
	"tempo_end" int NOT NULL DEFAULT ((3)), 
	"texture_end" int NOT NULL DEFAULT ((3)), 
	"startthis" int NOT NULL DEFAULT ((0)), 
	"archive" int NOT NULL DEFAULT ((0)), 
	"nextplaytime" timestamptz NULL, 
	"usermodifytime" timestamptz NOT NULL DEFAULT (now()), 
	"dayrestrictions" BYTEA NULL, 
	"readyonair" int NOT NULL DEFAULT ((0)), 
	"headline" varchar(256) NULL, 
	"cassetestartfps" int NULL, 
	"cassetelengthfps" int NULL, 
	"backuptapename" varchar(32) NULL, 
	"backuptimecode" int NULL, 
	"keyframe" int NULL, 
	"keyicon" BYTEA NULL, 
	"tmstamp" bigint NOT NULL DEFAULT txid_current(), 
	"backuplength" int NULL, 
	"protyagfirst" int NULL, 
	"protyaglast" int NULL, 
	"leftrightch" int NULL, 
	"lccode" varchar(64) NULL, 
	"publisher" varchar(128) NULL, 
	"rds" varchar(512) NULL, 
	"cmd2" int NULL, 
	"textsizems" int NULL, 
	"phonotype" int NULL, 
	"ownername" varchar(64) NULL, 
	"ddbtmstamp" bigint NULL, 
	"nc_root" text NULL, 
	"nc_root_md5" varchar(100) NULL, 
	"loudness" float NULL DEFAULT ((0)),
	"decroid" varchar(32) NULL
);
CREATE TABLE ph_link_types
(
	"id" SERIAL NOT NULL, 
	"str_id" varchar(50) NOT NULL, 
	"name" varchar(50) NULL
);
CREATE TABLE PH_PLAY_HISTORY
(
	"id" SERIAL NOT NULL, 
	"ph_id" int NULL, 
	"playtime" timestamptz NOT NULL DEFAULT (now()), 
	"sch_id" int NULL, 
	"mp_pos_id" int NULL, 
	"mag_packet_id" int NULL, 
	"booking_id" varchar(128) NULL, 
	"block_time" timestamptz NULL, 
	"ras_guid" varchar(64) NULL, 
	"ras_block_pos" int NULL, 
	"ras_pos_in_block" int NULL, 
	"playsize" int NULL, 
	"blockid" text NULL, 
	"eleminblockid" int NULL, 
	"playerid" int NULL DEFAULT (NULL), 
	"playblockid" int NULL DEFAULT (NULL), 
	"isbackgroundvideo" Boolean NOT NULL DEFAULT ((false))
);
CREATE TABLE PH_PLAY_PLAN
(
	"id" SERIAL NOT NULL, 
	"ph_id" int NOT NULL, 
	"playtime" timestamptz NOT NULL DEFAULT (now()), 
	"sch_id" int NULL, 
	"mag_packet_id" int NULL
);
CREATE TABLE PH_TO_ATTRVALS
(
	"id" SERIAL NOT NULL, 
	"ph_id" int NOT NULL, 
	"attrval_id" int NOT NULL, 
	"jm_pos" int NOT NULL DEFAULT ((-2)), 
	"sch_order" int NULL, 
	"creationtime" timestamptz NOT NULL DEFAULT (now()), 
	"tmstamp" bigint NOT NULL DEFAULT txid_current(), 
	"mag_packet_id" int NULL
);
CREATE TABLE ph_to_ph
(
	"id" SERIAL NOT NULL, 
	"ph_id" int NOT NULL, 
	"ph_link" int NOT NULL, 
	"link_type" int NULL, 
	"order" int NOT NULL DEFAULT ((0)), 
	"key_frame_num" int NULL, 
	"key_frame_active" Boolean NOT NULL DEFAULT ((false)), 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE ph_val_reflection
(
	"id" SERIAL NOT NULL, 
	"ph_id" int NOT NULL, 
	"name" varchar(255) NOT NULL, 
	"val_str" text NULL, 
	"val_int" int NULL, 
	"val_int64" bigint NULL, 
	"val_float" float NULL, 
	"val_binary" text NULL
);
CREATE TABLE PLAY_BLOCKS
(
	"id" SERIAL NOT NULL, 
	"b_time" int NOT NULL, 
	"dur" int NOT NULL, 
	"type" int NOT NULL, 
	"name" varchar(128) NULL, 
	"blk_data" text NULL, 
	"runtime_ms" int NULL, 
	"broadcast_id" int NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE PLIST_BLOCKS
(
	"id" SERIAL NOT NULL, 
	"fileid" int NOT NULL, 
	"date" timestamptz NOT NULL, 
	"plistname" varchar(260) NULL, 
	"type" int NULL, 
	"name" varchar(260) NULL, 
	"time" int NULL, 
	"size1000" int NULL, 
	"numel" int NULL, 
	"curid" int NULL, 
	"flags" int NULL, 
	"rmtlist" varchar(2048) NULL, 
	"jnglbtn" int NULL, 
	"modifydate" timestamptz NOT NULL, 
	"ddb_fileid" int NULL, 
	"ddb_owner" varchar(64) NULL
);
CREATE TABLE PLIST_ELEMS
(
	"blockid" int NOT NULL, 
	"num" int NULL, 
	"type" int NULL, 
	"phonotype" int NULL, 
	"name" varchar(260) NULL, 
	"comment" varchar(2000) NULL, 
	"category" varchar(512) NULL, 
	"artist" varchar(512) NULL, 
	"author" varchar(512) NULL, 
	"dbid" int NULL, 
	"id_number" varchar(32) NULL, 
	"version" int NULL, 
	"radioid" int NULL, 
	"dbname" varchar(260) NULL, 
	"filename" varchar(260) NULL, 
	"rollin" int NULL, 
	"rollout" int NULL, 
	"fadein" int NULL, 
	"fadeout" int NULL, 
	"intro" int NULL, 
	"outro" int NULL, 
	"startnext" int NULL, 
	"size1000" int NULL, 
	"freq" int NULL, 
	"smplrealsize" int NULL, 
	"maxlvlok" int NULL, 
	"maxlvl" real NULL, 
	"gain" real NULL, 
	"album" varchar(260) NULL, 
	"genre" varchar(260) NULL, 
	"year" int NULL, 
	"cdid" varchar(10) NULL, 
	"cdtrackid" int NULL, 
	"cmd" int NULL, 
	"remotecmd" int NULL, 
	"endcode" varchar(10) NULL, 
	"starttime" int NULL, 
	"jnglbtn" int NULL, 
	"implastfilename" varchar(260) NULL, 
	"firstreportline" varchar(260) NULL, 
	"lastreportline" varchar(260) NULL, 
	"rmtlist" varchar(2048) NULL, 
	"gainlist" text NULL, 
	"ddb_id" int NULL, 
	"ddb_owner" varchar(64) NULL, 
	"idinblock" int NULL, 
	"intro2" int NULL, 
	"intro3" int NULL, 
	"fadeintype" int NULL, 
	"fadeouttype" int NULL, 
	"mood" int NOT NULL DEFAULT ((3)), 
	"energy" int NOT NULL DEFAULT ((3)), 
	"tempo" int NOT NULL DEFAULT ((3)), 
	"texture" int NOT NULL DEFAULT ((3)), 
	"tempo_end" int NOT NULL DEFAULT ((3)), 
	"texture_end" int NOT NULL DEFAULT ((3)), 
	"startthis" int NOT NULL DEFAULT ((0))
);
CREATE TABLE PLIST_MARKERS
(
	"plistname" varchar(260) NULL, 
	"marker" int NULL
);
CREATE TABLE PLIST_TASKS
(
	"id" SERIAL NOT NULL, 
	"id_first" int NOT NULL, 
	"id_last" int NOT NULL
);
CREATE TABLE RADIOSTATION
(
	"id" SERIAL NOT NULL, 
	"name" varchar(60) NOT NULL
);
CREATE TABLE repl_schedules
(
	"schedule_id" int NOT NULL, 
	"worker_id" int NULL, 
	"update_time" timestamptz NULL
);
CREATE TABLE repl_workers
(
	"id" SERIAL NOT NULL, 
	"workstation_id" text NULL, 
	"update_time" timestamptz NULL
);
CREATE TABLE RIGHTS
(
	"id" SERIAL NOT NULL, 
	"group_id" int NOT NULL, 
	"right_id" int NOT NULL, 
	"resource_id" varchar(1024) NULL, 
	"permission" int NOT NULL DEFAULT ((1)), 
	"resource_type" varchar(1024) NULL
);
CREATE TABLE SCH_FILES
(
	"id" SERIAL NOT NULL, 
	"blkname" varchar(260) NOT NULL, 
	"filename" varchar(260) NOT NULL, 
	"schdate" timestamptz NOT NULL
);
CREATE TABLE SCHEDULES
(
	"id" SERIAL NOT NULL, 
	"name" varchar(128) NOT NULL, 
	"path" varchar(256) NOT NULL, 
	"skel_path" varchar(256) NULL, 
	"manual_load" int NULL, 
	"disabled" int NULL, 
	"network_id" int NULL, 
	"rotate_music" int NULL, 
	"user_name" varchar(256) NULL, 
	"advanced" text NULL, 
	"main_schedule_id" int NULL DEFAULT (NULL), 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE SETTINGS
(
	"id" SERIAL NOT NULL, 
	"name" varchar(260) NOT NULL, 
	"valstr" varchar(260) NOT NULL DEFAULT (''), 
	"valint" int NOT NULL DEFAULT ((0)), 
	"valint2" int NOT NULL DEFAULT ((0))
);
CREATE TABLE SJM_BTN_TO_BTN
(
	"id" SERIAL NOT NULL, 
	"btn_id_1" int NULL, 
	"btn_id_2" int NULL, 
	"mode" int NULL
);
CREATE TABLE SJM_BTN_TO_PH
(
	"id" SERIAL NOT NULL, 
	"ph_id" int NOT NULL, 
	"btn_id" int NOT NULL, 
	"mode" int NOT NULL
);
CREATE TABLE SJM_BUTTONS
(
	"id" SERIAL NOT NULL, 
	"name" varchar(256) NULL, 
	"page_id" int NOT NULL, 
	"x" int NOT NULL, 
	"y" int NOT NULL, 
	"ex" int NOT NULL, 
	"ey" int NOT NULL, 
	"mode" int NULL, 
	"backcolor" int NULL, 
	"textcolor" int NULL, 
	"ncroot" text NULL
);
CREATE TABLE SJM_GROUP_TO_LAYOUT
(
	"id" SERIAL NOT NULL, 
	"group_id" int NOT NULL, 
	"layout_id" int NOT NULL
);
CREATE TABLE SJM_GROUPS
(
	"id" SERIAL NOT NULL, 
	"name" varchar(128) NULL
);
CREATE TABLE SJM_LAYOUTS
(
	"id" SERIAL NOT NULL, 
	"name" varchar(128) NULL, 
	"ready" int NULL, 
	"ncroot" text NULL, 
	"tmstamp" bigint NOT NULL DEFAULT txid_current(), 
	"master" Boolean NOT NULL DEFAULT ((false)), 
	"type" int NOT NULL DEFAULT ((0))
);
CREATE TABLE SJM_PAGES
(
	"id" SERIAL NOT NULL, 
	"name" varchar(128) NULL, 
	"layout_id" int NOT NULL, 
	"width" int NOT NULL, 
	"height" int NOT NULL, 
	"ready" int NULL, 
	"backcolor" int NULL, 
	"btnbackcolor" int NULL, 
	"btntextcolor" int NULL, 
	"ncroot" text NULL, 
	"tmstamp" bigint NOT NULL DEFAULT txid_current(), 
	"master_id" int NULL
);
CREATE TABLE SK_ELEM
(
	"id" SERIAL NOT NULL, 
	"name" varchar(40) NULL, 
	"duration" timestamptz NULL, 
	"type" int NULL DEFAULT ((0)), 
	"id_ph" int NULL, 
	"id_attr" int NULL, 
	"start_control" int NULL, 
	"text_control" varchar(260) NULL, 
	"short_name" varchar(2) NULL
);
CREATE TABLE SK_SK_ELEM
(
	"id" SERIAL NOT NULL, 
	"id_sk" int NULL DEFAULT ((0)), 
	"id_sk_elem" int NULL DEFAULT ((0)), 
	"duration" timestamptz NULL, 
	"number" int NULL DEFAULT ((0)), 
	"fix_time" int NULL, 
	"noearl" int NULL, 
	"nolate" int NULL, 
	"splitblock" int NULL, 
	"splitphonogram" int NULL, 
	"pause" int NULL DEFAULT ((0))
);
CREATE TABLE SKELETON
(
	"id" SERIAL NOT NULL, 
	"name" varchar(40) NULL, 
	"date_sk" timestamptz NULL DEFAULT ('1990-01-01'), 
	"day_month" int NULL DEFAULT ((0)), 
	"week" int NULL DEFAULT ((0)), 
	"odd" int NULL DEFAULT ((0)), 
	"working" int NULL DEFAULT ((0)), 
	"id_radio" int NULL DEFAULT ((0)), 
	"month" int NULL, 
	"month_month" int NULL DEFAULT ((0))
);
CREATE TABLE STORAGE
(
	"id" SERIAL NOT NULL, 
	"type" int NOT NULL, 
	"catid" int NULL, 
	"archive" int NOT NULL, 
	"path" varchar(260) NULL
);
CREATE TABLE TB_ATTRVAL
(
	"id" SERIAL NOT NULL, 
	"tbname" varchar(64) NOT NULL, 
	"btnname" varchar(64) NOT NULL, 
	"attrval_id" int NULL, 
	"attrib_id" int NULL
);
CREATE TABLE TRACT
(
	"id" SERIAL NOT NULL, 
	"version" int NOT NULL DEFAULT ((0)), 
	"critical" int NOT NULL DEFAULT ((0))
);
CREATE TABLE USER_GROUP
(
	"id" SERIAL NOT NULL, 
	"group_id" int NOT NULL, 
	"user_id" int NOT NULL
);
CREATE TABLE USERS
(
	"id" SERIAL NOT NULL, 
	"login" varchar(64) NOT NULL, 
	"password" varchar(64) NULL, 
	"fullname" varchar(128) NOT NULL, 
	"description" varchar(128) NULL, 
	"disabled" int NULL, 
	"stamp" bigint NOT NULL DEFAULT txid_current()
);
CREATE TABLE USERS_WORK
(
	"id" SERIAL NOT NULL, 
	"user_name" varchar(260) NULL, 
	"user_work" int NULL, 
	"date_work" timestamptz NULL, 
	"time_work" timestamptz NULL, 
	"temp1" int NULL, 
	"temp2" int NULL
);
CREATE TABLE VIDEO_ARC_TAPES
(
	"id" SERIAL NOT NULL, 
	"name" varchar(32) NOT NULL, 
	"starttc" int NOT NULL, 
	"firstbfsize" int NOT NULL, 
	"gcpsize" int NOT NULL, 
	"secondbfsize" int NOT NULL, 
	"bfsize" int NOT NULL, 
	"blkalignment" int NOT NULL, 
	"bfminsize" int NOT NULL, 
	"lastbfsize" int NOT NULL
);
CREATE TABLE web_states
(
	"id" SERIAL NOT NULL, 
	"user_id" int NOT NULL, 
	"type" int NOT NULL, 
	"value" text NOT NULL
);
CREATE TABLE WORKSTATION
(
	"id" SERIAL NOT NULL, 
	"workstation_id" text NULL, 
	"licence_file" text NULL, 
	"startup_path" text NULL, 
	"application_name" text NULL, 
	"update_time" timestamptz NULL, 
	"licence_type" int NULL, 
	"instance_name" text NULL, 
	"vkey_id" text NULL
);

-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
---- create all pk and unique constraint
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------

ALTER TABLE ACC_RIGHTS
    ADD CONSTRAINT PK__ACC_RIGH__3213E83F7E9D743A PRIMARY KEY ("id");
ALTER TABLE ADVANCE_COMM
    ADD CONSTRAINT PK__ADVANCE___3213E83F77226404 PRIMARY KEY ("id");
ALTER TABLE ApiUser_AttribVals
    ADD CONSTRAINT PK__ApiUser___3213E83F3F7B0989 PRIMARY KEY ("id");
ALTER TABLE ApiUser_Schedules
    ADD CONSTRAINT PK__ApiUser___3213E83FD2E1EB51 PRIMARY KEY ("id");
ALTER TABLE ApiUserHooks
    ADD CONSTRAINT PK__ApiUserH__3213E83F1D2C58BB PRIMARY KEY ("id");
ALTER TABLE ApiUsers
    ADD CONSTRAINT PK__ApiUsers__3213E83F10A904BA PRIMARY KEY ("id");
ALTER TABLE ApiUsers
    ADD CONSTRAINT UQ__ApiUsers__6AF1745327C5C309 UNIQUE ("apikey");
ALTER TABLE ApiUsers_PlayBlocks
    ADD CONSTRAINT PK__ApiUsers__3213E83FB6147083 PRIMARY KEY ("id");
ALTER TABLE aq_categories
    ADD CONSTRAINT PK__aq_categ__3213E83F500E236F PRIMARY KEY ("id");
ALTER TABLE aq_results
    ADD CONSTRAINT PK__aq_resul__3213E83F196DD782 PRIMARY KEY ("id");
ALTER TABLE ATTRIB_VALS
    ADD CONSTRAINT PK__ATTRIB_V__3213E83FC832F867 PRIMARY KEY ("id");
ALTER TABLE ATTRIBS
    ADD CONSTRAINT PK__ATTRIBS__3213E83F7E08A062 PRIMARY KEY ("id");
ALTER TABLE AUTO_MOVE
    ADD CONSTRAINT PK__AUTO_MOV__3213E83FFB7EC1E5 PRIMARY KEY ("id");
ALTER TABLE BROADCAST_RELEASES
    ADD CONSTRAINT PK__BROADCAS__3213E83FFE7C28CB PRIMARY KEY ("id");
ALTER TABLE BROADCAST_SIGNED_DAYS
    ADD CONSTRAINT PK__BROADCAS__3213E83F7437512D PRIMARY KEY ("id");
ALTER TABLE BROADCAST_TEMPLATES
    ADD CONSTRAINT PK__BROADCAS__3213E83F794EFD1F PRIMARY KEY ("id");
ALTER TABLE BROADCASTS
    ADD CONSTRAINT PK__BROADCAS__3213E83F56B1AFC4 PRIMARY KEY ("id");
ALTER TABLE CAMERA_PRESETS
    ADD CONSTRAINT PK__CAMERA_P__3213E83FF684CD2C PRIMARY KEY ("id");
ALTER TABLE data_tree
    ADD CONSTRAINT KEY_str_id_parent_id UNIQUE ("str_id", "parent_id");
ALTER TABLE data_tree
    ADD CONSTRAINT PK_data_tree_id PRIMARY KEY ("id");
ALTER TABLE DB_IMPORT_FILTERS
    ADD CONSTRAINT PK__DB_IMPOR__3213E83FC2C7504A PRIMARY KEY ("id");
ALTER TABLE DDB_FILES
    ADD CONSTRAINT PK__DDB_FILE__3213E83FCB974912 PRIMARY KEY ("id");
ALTER TABLE dmdb_Async_Jobs
    ADD CONSTRAINT PK__dmdb_Asy__3213E83F57740D4A PRIMARY KEY ("id");
ALTER TABLE dmdb_Player_Categories
    ADD CONSTRAINT PK__dmdb_Pla__3213E83F27F0D64C PRIMARY KEY ("id");
ALTER TABLE dmdb_Player_MediaPlan
    ADD CONSTRAINT PK__dmdb_Pla__3213E83F5BC73B17 PRIMARY KEY ("id");
ALTER TABLE dmdb_Player_PlayerProfile
    ADD CONSTRAINT PK__dmdb_Pla__3213E83FE3B8E167 PRIMARY KEY ("id");
ALTER TABLE dmdb_PlayerProfile_MediaPlan
    ADD CONSTRAINT PK__dmdb_Pla__3213E83F1E2B1A0B PRIMARY KEY ("id");
ALTER TABLE dmdb_PlayerProfiles
    ADD CONSTRAINT PK__dmdb_Pla__3213E83F4BC8FAA6 PRIMARY KEY ("id");
ALTER TABLE dmdb_Players
    ADD CONSTRAINT PK__dmdb_Pla__3213E83F1A0490CB PRIMARY KEY ("id");
ALTER TABLE dmdb_PlayerStates
    ADD CONSTRAINT PK__dmdb_Pla__3213E83FA21B67DF PRIMARY KEY ("id");
ALTER TABLE dmdb_PlayerStates
    ADD CONSTRAINT UQ__dmdb_Pla__2CDA01F078817F7C UNIQUE ("playerid");
ALTER TABLE FILTERS
    ADD CONSTRAINT PK__FILTERS__3213E83F2C9BC4BB PRIMARY KEY ("id");
ALTER TABLE FILTERS_STATE
    ADD CONSTRAINT PK__FILTERS___3213E83FBCAF12A2 PRIMARY KEY ("id");
ALTER TABLE GRID_BLOCKS
    ADD CONSTRAINT PK__GRID_BLO__3213E83F7A38ECF0 PRIMARY KEY ("id");
ALTER TABLE GRID_CLOCK_POS
    ADD CONSTRAINT PK__GRID_CLO__3213E83FA803E31C PRIMARY KEY ("id");
ALTER TABLE GRID_CLOCKS
    ADD CONSTRAINT PK__GRID_CLO__3213E83FF51FD693 PRIMARY KEY ("id");
ALTER TABLE GRID_DAYS
    ADD CONSTRAINT PK__GRID_DAY__3213E83FF2A6FC32 PRIMARY KEY ("id");
ALTER TABLE GRIDS
    ADD CONSTRAINT PK__GRIDS__3213E83FAC0E28ED PRIMARY KEY ("id");
ALTER TABLE GROUPS
    ADD CONSTRAINT PK__GROUPS__3213E83FC9DFBE3E PRIMARY KEY ("id");
ALTER TABLE locked_objects
    ADD CONSTRAINT PK_LOCKED_OBJECTS PRIMARY KEY ("id");
ALTER TABLE locked_objects
    ADD CONSTRAINT UK_OBJ_NAME UNIQUE ("obj_name");
ALTER TABLE logger_LoudnessJournal
    ADD CONSTRAINT PK__loudness__3214EC07770522D7 PRIMARY KEY ("id");
ALTER TABLE logger_Streams
    ADD CONSTRAINT PK__loudness__3214EC0799CB8F8B PRIMARY KEY ("id");
ALTER TABLE MAG_CAT_SCH
    ADD CONSTRAINT PK__MAG_CAT___3213E83FF8373F5D PRIMARY KEY ("id");
ALTER TABLE MAG_DB_PARAMS
    ADD CONSTRAINT PK__MAG_DB_P__3213E83FCC81A179 PRIMARY KEY ("id");
ALTER TABLE mag_packets
    ADD CONSTRAINT CheckUnicueNameAndCategory UNIQUE ("name", "category_id");
ALTER TABLE mag_packets
    ADD CONSTRAINT PK_mag_packets PRIMARY KEY ("id");
ALTER TABLE MAG_SCH_PROP
    ADD CONSTRAINT PK__MAG_SCH___3213E83F96685F54 PRIMARY KEY ("id");
ALTER TABLE MAG_SETTINGS
    ADD CONSTRAINT IX_MAG_SETTINGS UNIQUE ("name");
ALTER TABLE MODIFY_DATES
    ADD CONSTRAINT PK__MODIFY_D__3213E83FEFF6558D PRIMARY KEY ("id");
ALTER TABLE MODIFY_PH
    ADD CONSTRAINT PK__MODIFY_P__3213E83FD0D7E07E PRIMARY KEY ("id");
ALTER TABLE mp_account_mediaplans
    ADD CONSTRAINT PK_MP_ACCOUNT_MEDIAPLANS PRIMARY KEY ("id");
ALTER TABLE mp_account_services
    ADD CONSTRAINT PK_MP_ACCOUNT_SERVICES PRIMARY KEY ("id");
ALTER TABLE mp_accounts
    ADD CONSTRAINT PK_accounts PRIMARY KEY ("id");
ALTER TABLE mp_base_costs
    ADD CONSTRAINT PK_MP_BASE_COSTS PRIMARY KEY ("id");
ALTER TABLE mp_closed_days
    ADD CONSTRAINT PK_MP_CLOSED_DAYS PRIMARY KEY ("id");
ALTER TABLE mp_covenantees
    ADD CONSTRAINT PK_MP_COVENANTEES PRIMARY KEY ("id");
ALTER TABLE mp_dayparts
    ADD CONSTRAINT PK_MP_DAYPARTS PRIMARY KEY ("id");
ALTER TABLE mp_discount_types
    ADD CONSTRAINT PK_MP_DISCUONT_TYPES PRIMARY KEY ("id");
ALTER TABLE mp_discount_values
    ADD CONSTRAINT PK_MP_DISCOUNT_VALUES PRIMARY KEY ("id");
ALTER TABLE mp_mediaplan_scheds
    ADD CONSTRAINT PK_MP_MEDIAPLAN_SCHEDS PRIMARY KEY ("id");
ALTER TABLE mp_mediaplans
    ADD CONSTRAINT PK_MP_MEDIAPLANS PRIMARY KEY ("id");
ALTER TABLE mp_operations
    ADD CONSTRAINT PK_MP_OPERATIONS PRIMARY KEY ("id");
ALTER TABLE mp_organization_attributes
    ADD CONSTRAINT PK_mp_organization_attributes PRIMARY KEY ("id");
ALTER TABLE mp_organizations
    ADD CONSTRAINT PK_MP_ORGANIZATIONS PRIMARY KEY ("id");
ALTER TABLE mp_owners_mediaplans
    ADD CONSTRAINT PK_mp_owners_mediaplans PRIMARY KEY ("id");
ALTER TABLE mp_payment_types
    ADD CONSTRAINT PK__mp_payme__3213E83F3FE58A2A PRIMARY KEY ("id");
ALTER TABLE mp_payments
    ADD CONSTRAINT PK_payments PRIMARY KEY ("id");
ALTER TABLE mp_phonograms
    ADD CONSTRAINT PK_MP_PHONOGRAMS PRIMARY KEY ("id");
ALTER TABLE mp_position_replacement
    ADD CONSTRAINT PK_MP_POSITION_REPLACEMENT PRIMARY KEY ("id");
ALTER TABLE mp_positions
    ADD CONSTRAINT PK_MP_POSITIONS PRIMARY KEY ("id");
ALTER TABLE mp_replacement
    ADD CONSTRAINT PK__mp_repla__3213E83F9833886F PRIMARY KEY ("id");
ALTER TABLE mp_reports
    ADD CONSTRAINT PK_MP_REPORTS PRIMARY KEY ("id");
ALTER TABLE mp_running_app
    ADD CONSTRAINT PK_MP_RUNNING_APP PRIMARY KEY ("mp_id");
ALTER TABLE mp_schedule_tariff_scale
    ADD CONSTRAINT PK_MP_SCHEDULE_TARIFF_SCALE PRIMARY KEY ("id");
ALTER TABLE mp_settings
    ADD CONSTRAINT PK_MP_SETTINGS_EXT PRIMARY KEY ("id");
ALTER TABLE mp_spot_types
    ADD CONSTRAINT PK_MP_SPOT_TYPES PRIMARY KEY ("id");
ALTER TABLE mp_step_tariffing_values
    ADD CONSTRAINT PK_MP_STEP_TARIFFING_VALUES PRIMARY KEY ("id");
ALTER TABLE mp_sync_events
    ADD CONSTRAINT PK_MP_SYNC_EVENTS PRIMARY KEY ("id");
ALTER TABLE mp_tariff_scales
    ADD CONSTRAINT PK_MP_TARIFF_SCALES PRIMARY KEY ("id");
ALTER TABLE mp_used_discounts
    ADD CONSTRAINT PK_MP_USED_DISCOUNTS PRIMARY KEY ("id");
ALTER TABLE NETWORKS
    ADD CONSTRAINT PK__NETWORKS__3213E83F39D4B2EA PRIMARY KEY ("id");
ALTER TABLE NETWORKS
    ADD CONSTRAINT UQ__NETWORKS__NAME UNIQUE ("name");
ALTER TABLE OperationsLog
    ADD CONSTRAINT PK_OperationsLog PRIMARY KEY ("id");
ALTER TABLE P_BLOCKS
    ADD CONSTRAINT P_BLOCKS_UNIQUE_BlkDate_BlkName UNIQUE ("schname", "blkdate", "blkname");
ALTER TABLE P_BLOCKS
    ADD CONSTRAINT PK__P_BLOCKS__3213E83F64C07FDC PRIMARY KEY ("id");
ALTER TABLE PARAMETERS
    ADD CONSTRAINT PK__PARAMETE__3213E83FE7D304BC PRIMARY KEY ("id");
ALTER TABLE PH
    ADD CONSTRAINT PK__PH__3213E83F1C21C400 PRIMARY KEY ("id");
ALTER TABLE ph_link_types
    ADD CONSTRAINT PK_ph_link_types PRIMARY KEY ("id");
ALTER TABLE ph_link_types
    ADD CONSTRAINT UQ__ph_link___3B994169B74B5E05 UNIQUE ("str_id");
ALTER TABLE PH_PLAY_HISTORY
    ADD CONSTRAINT PK__PH_PLAY___3213E83F1FA4F024 PRIMARY KEY ("id");
ALTER TABLE PH_PLAY_PLAN
    ADD CONSTRAINT PK__PH_PLAY___3213E83F87B5BBF5 PRIMARY KEY ("id");
ALTER TABLE PH_TO_ATTRVALS
    ADD CONSTRAINT PK__PH_TO_AT__3213E83F65166DC2 PRIMARY KEY ("id");
ALTER TABLE ph_to_ph
    ADD CONSTRAINT PK_ph_to_ph PRIMARY KEY ("id");
ALTER TABLE ph_val_reflection
    ADD CONSTRAINT PK_ph_val_reflection_id PRIMARY KEY ("id");
ALTER TABLE PLAY_BLOCKS
    ADD CONSTRAINT PK__PLAY_BLO__3213E83F91975DE6 PRIMARY KEY ("id");
ALTER TABLE RADIOSTATION
    ADD CONSTRAINT PK__RADIOSTA__3213E83F05E676B3 PRIMARY KEY ("id");
ALTER TABLE repl_schedules
    ADD CONSTRAINT PK_repl_schedules PRIMARY KEY ("schedule_id");
ALTER TABLE repl_workers
    ADD CONSTRAINT PK_repl_workers PRIMARY KEY ("id");
ALTER TABLE RIGHTS
    ADD CONSTRAINT PK__RIGHTS__3213E83F939715EA PRIMARY KEY ("id");
ALTER TABLE SCH_FILES
    ADD CONSTRAINT PK__SCH_FILE__3213E83F203E42F7 PRIMARY KEY ("id");
ALTER TABLE SCHEDULES
    ADD CONSTRAINT IX_sch_bname UNIQUE ("name");
ALTER TABLE SCHEDULES
    ADD CONSTRAINT PK__SCHEDULE__3213E83F1FE162B2 PRIMARY KEY ("id");
ALTER TABLE SJM_BTN_TO_BTN
    ADD CONSTRAINT PK__SJM_BTN___3213E83FD6EA68C6 PRIMARY KEY ("id");
ALTER TABLE SJM_BTN_TO_PH
    ADD CONSTRAINT PK__SJM_BTN___3213E83F5E1E07FF PRIMARY KEY ("id");
ALTER TABLE SJM_BUTTONS
    ADD CONSTRAINT PK__SJM_BUTT__3213E83F7B880340 PRIMARY KEY ("id");
ALTER TABLE SJM_GROUP_TO_LAYOUT
    ADD CONSTRAINT PK__SJM_GROU__3213E83F620C9F7F PRIMARY KEY ("id");
ALTER TABLE SJM_GROUPS
    ADD CONSTRAINT PK__SJM_GROU__3213E83F35A4AC7E PRIMARY KEY ("id");
ALTER TABLE SJM_LAYOUTS
    ADD CONSTRAINT PK__SJM_LAYO__3213E83F02F3002D PRIMARY KEY ("id");
ALTER TABLE SJM_PAGES
    ADD CONSTRAINT PK__SJM_PAGE__3213E83F2DAE3C19 PRIMARY KEY ("id");
ALTER TABLE SK_ELEM
    ADD CONSTRAINT PK__SK_ELEM__3213E83F35FA4C96 PRIMARY KEY ("id");
ALTER TABLE SK_SK_ELEM
    ADD CONSTRAINT PK__SK_SK_EL__3213E83F43C00224 PRIMARY KEY ("id");
ALTER TABLE SKELETON
    ADD CONSTRAINT PK__SKELETON__3213E83F152FEE46 PRIMARY KEY ("id");
ALTER TABLE STORAGE
    ADD CONSTRAINT PK__STORAGE__3213E83FD4F4E2F0 PRIMARY KEY ("id");
ALTER TABLE TB_ATTRVAL
    ADD CONSTRAINT PK__TB_ATTRV__3213E83FD133C4F4 PRIMARY KEY ("id");
ALTER TABLE TRACT
    ADD CONSTRAINT PK__TRACT__3213E83F830803C7 PRIMARY KEY ("id");
ALTER TABLE USER_GROUP
    ADD CONSTRAINT PK__USER_GRO__3213E83F5F8318F5 PRIMARY KEY ("id");
ALTER TABLE USERS
    ADD CONSTRAINT IX_users UNIQUE ("login");
ALTER TABLE USERS
    ADD CONSTRAINT PK__USERS__3213E83FB256D38C PRIMARY KEY ("id");
ALTER TABLE USERS_WORK
    ADD CONSTRAINT PK__USERS_WO__3213E83F7B06A0CA PRIMARY KEY ("id");
ALTER TABLE VIDEO_ARC_TAPES
    ADD CONSTRAINT PK__VIDEO_AR__3213E83F9FFC7CFA PRIMARY KEY ("id");
ALTER TABLE VIDEO_ARC_TAPES
    ADD CONSTRAINT UQ__VIDEO_AR__NAME UNIQUE ("name");
ALTER TABLE web_states
    ADD CONSTRAINT PK__web_stat__3213E83F7FAAD823 PRIMARY KEY ("id");
ALTER TABLE WORKSTATION
    ADD CONSTRAINT PK__WORKSTAT__3214EC274BE895FF PRIMARY KEY ("id");
 
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
---- reset pk sequenses
-------------------------------------------------------------------------------

CREATE OR REPLACE FUNCTION pg_temp.restartIdSequence(table_name text, seq_name text)
    RETURNS bigint AS
$func$
DECLARE
    max_id int = NULL;
BEGIN
    EXECUTE ('select max(id) from ' || table_name) INTO max_id;
    IF max_id IS NOT NULL
    THEN
        max_id := max_id + 1;
        EXECUTE ('ALTER SEQUENCE ' || seq_name || ' RESTART with ' || max_id);
    END IF;
    RETURN max_id;
END
$func$ LANGUAGE plpgsql;

DO
$$
    DECLARE
        rec record;
    BEGIN
        FOR rec IN
            SELECT t.table_name AS table_name
            FROM information_schema.tables t
                     INNER JOIN information_schema.columns c ON c.table_name = t.table_name
                AND c.table_schema = t.table_schema
            WHERE t.table_name NOT LIKE 'pg\_%'
              AND t.table_schema = 'public'
              AND c.column_name = 'id'
              AND t.table_name != 'mp_discount_types'
            ORDER BY t.table_name
            LOOP
                --EXECUTE ('ALTER SEQUENCE ' || rec.table_name || '_id_seq RESTART');
                PERFORM pg_temp.restartIdSequence(rec.table_name, rec.table_name || '_id_seq');
            END LOOP;
    END
$$;

-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
---- create all foreign keys
-------------------------------------------------------------------------------

ALTER TABLE FILTERS_STATE
    ADD CONSTRAINT FK__FILTERS_S__filte__062DE679 FOREIGN KEY ("filter_id") REFERENCES FILTERS ("id") ON DELETE CASCADE;
ALTER TABLE FILTERS_STATE
    ADD CONSTRAINT FK__FILTERS_S__user___07220AB2 FOREIGN KEY ("user_id") REFERENCES USERS ("id");
ALTER TABLE web_states
    ADD CONSTRAINT FK__web_state__user___09FE775D FOREIGN KEY ("user_id") REFERENCES USERS ("id") ON DELETE CASCADE;
ALTER TABLE mp_mediaplan_scheds
    ADD CONSTRAINT FK_MP_MEDIAPLAN_SCHEDS_14_MP_MEDIAPLANS FOREIGN KEY ("mediaplan_id") REFERENCES mp_mediaplans ("id") ON DELETE CASCADE;
ALTER TABLE mp_base_costs
    ADD CONSTRAINT FK_MP_BASE__18_MP_TARIF FOREIGN KEY ("tariff_scales_id") REFERENCES mp_tariff_scales ("id") ON DELETE CASCADE;
ALTER TABLE mp_covenantees
    ADD CONSTRAINT FK_MP_COVEN_1_USERS FOREIGN KEY ("users_id") REFERENCES USERS ("id");
ALTER TABLE mp_discount_values
    ADD CONSTRAINT FK_MP_DISCO_10_MP_TARIF FOREIGN KEY ("tariff_scales_id") REFERENCES mp_tariff_scales ("id") ON DELETE CASCADE;
ALTER TABLE ApiUserHooks
    ADD CONSTRAINT FK__ApiUserHo__apiUs__0FB750B3 FOREIGN KEY ("apiuserid") REFERENCES ApiUsers ("id") ON DELETE CASCADE;
ALTER TABLE mp_mediaplans
    ADD CONSTRAINT FK_MP_MEDIA_3_MP_COVEN FOREIGN KEY ("covenantees_id") REFERENCES mp_covenantees ("id") ON DELETE CASCADE;
ALTER TABLE mp_mediaplans
    ADD CONSTRAINT FK_MP_MEDIA_8_MP_TARIF FOREIGN KEY ("tariff_scales_id") REFERENCES mp_tariff_scales ("id");
ALTER TABLE ApiUser_Schedules
    ADD CONSTRAINT FK__ApiUser_S__apiUs__1293BD5E FOREIGN KEY ("apiuserid") REFERENCES ApiUsers ("id") ON DELETE CASCADE;
ALTER TABLE mp_mediaplans
    ADD CONSTRAINT FK_MP_MEDIA_LAST_USERS FOREIGN KEY ("users_id") REFERENCES USERS ("id");
ALTER TABLE ApiUser_Schedules
    ADD CONSTRAINT FK__ApiUser_S__sched__1387E197 FOREIGN KEY ("scheduleid") REFERENCES SCHEDULES ("id") ON DELETE CASCADE;
ALTER TABLE mp_operations
    ADD CONSTRAINT FK_MP_OPERA_16_USERS FOREIGN KEY ("users_id") REFERENCES USERS ("id");
ALTER TABLE ApiUser_Schedules
    ADD CONSTRAINT FK__ApiUser_S__tarif__147C05D0 FOREIGN KEY ("tariffscaleid") REFERENCES mp_tariff_scales ("id") ON DELETE CASCADE;
ALTER TABLE mp_organizations
    ADD CONSTRAINT FK_MP_ORGAN_2_MP_COVEN FOREIGN KEY ("covenantees_id") REFERENCES mp_covenantees ("id") ON DELETE CASCADE;
ALTER TABLE mp_sync_events
    ADD CONSTRAINT FK_MP_SYNC_EVENTS_VS_MP_RUNNING_APP FOREIGN KEY ("mp_id") REFERENCES mp_running_app ("mp_id") ON DELETE CASCADE;
ALTER TABLE mp_phonograms
    ADD CONSTRAINT FK_MP_PHONO_13_MP_MEDIA FOREIGN KEY ("mediaplan_id") REFERENCES mp_mediaplans ("id") ON DELETE CASCADE;
ALTER TABLE mp_phonograms
    ADD CONSTRAINT FK_MP_PHONO_15_PH FOREIGN KEY ("ph_id") REFERENCES PH ("id");
ALTER TABLE ApiUsers_PlayBlocks
    ADD CONSTRAINT FK__ApiUsers___api_u__1758727B FOREIGN KEY ("api_user_id") REFERENCES ApiUsers ("id") ON DELETE CASCADE;
ALTER TABLE mp_positions
    ADD CONSTRAINT FK_MP_POSIT_5_MP_MEDIA FOREIGN KEY ("mediaplans_id") REFERENCES mp_mediaplans ("id") ON DELETE CASCADE;
ALTER TABLE ATTRIB_VALS
    ADD CONSTRAINT FK__ATTRIB_VA__attr___17F790F9 FOREIGN KEY ("attr_id") REFERENCES ATTRIBS ("id") ON DELETE CASCADE;
ALTER TABLE ApiUsers_PlayBlocks
    ADD CONSTRAINT FK__ApiUsers___play___184C96B4 FOREIGN KEY ("play_block_id") REFERENCES PLAY_BLOCKS ("id") ON DELETE CASCADE;
ALTER TABLE mp_positions
    ADD CONSTRAINT FK_MP_POSIT_OWNER_USERS FOREIGN KEY ("users_id") REFERENCES USERS ("id");
ALTER TABLE SKELETON
    ADD CONSTRAINT FK__SKELETON__id_rad__19DFD96B FOREIGN KEY ("id_radio") REFERENCES RADIOSTATION ("id") ON DELETE CASCADE;
ALTER TABLE mp_used_discounts
    ADD CONSTRAINT FK_MP_USED__11_MP_MEDIA FOREIGN KEY ("mediaplans_id") REFERENCES mp_mediaplans ("id") ON DELETE CASCADE;
ALTER TABLE ACC_RIGHTS
    ADD CONSTRAINT FK__ACC_RIGHT__CatId__1AD3FDA4 FOREIGN KEY ("catid") REFERENCES ATTRIB_VALS ("id") ON DELETE CASCADE;
ALTER TABLE mp_used_discounts
    ADD CONSTRAINT FK_MP_USED__12_MP_DISCO FOREIGN KEY ("discount_values_id") REFERENCES mp_discount_values ("id") ON DELETE CASCADE;
ALTER TABLE MODIFY_DATES
    ADD CONSTRAINT FK__MODIFY_DA__attrv__1BC821DD FOREIGN KEY ("attrval_id") REFERENCES ATTRIB_VALS ("id") ON DELETE CASCADE;
ALTER TABLE MODIFY_DATES
    ADD CONSTRAINT FK__MODIFY_DA__ph_id__1CBC4616 FOREIGN KEY ("ph_id") REFERENCES PH ("id") ON DELETE CASCADE;
ALTER TABLE PH_TO_ATTRVALS
    ADD CONSTRAINT FK__PH_TO_ATT__attrv__1DB06A4F FOREIGN KEY ("attrval_id") REFERENCES ATTRIB_VALS ("id") ON DELETE CASCADE;
ALTER TABLE ApiUser_AttribVals
    ADD CONSTRAINT FK__ApiUser_A__apiUs__1E05700A FOREIGN KEY ("apiuserid") REFERENCES ApiUsers ("id") ON DELETE CASCADE;
ALTER TABLE PH_TO_ATTRVALS
    ADD CONSTRAINT FK__PH_TO_ATT__ph_id__1EA48E88 FOREIGN KEY ("ph_id") REFERENCES PH ("id") ON DELETE CASCADE;
ALTER TABLE ApiUser_AttribVals
    ADD CONSTRAINT FK__ApiUser_A__attri__1EF99443 FOREIGN KEY ("attribvalsid") REFERENCES ATTRIB_VALS ("id") ON DELETE CASCADE;
ALTER TABLE mag_packets
    ADD CONSTRAINT FK_mag_packets_ATTRIB_VALS FOREIGN KEY ("category_id") REFERENCES ATTRIB_VALS ("id") ON DELETE CASCADE;
ALTER TABLE SK_ELEM
    ADD CONSTRAINT FK__SK_ELEM__id_attr__1F98B2C1 FOREIGN KEY ("id_attr") REFERENCES ATTRIB_VALS ("id") ON DELETE CASCADE;
ALTER TABLE STORAGE
    ADD CONSTRAINT FK__STORAGE__CatId__208CD6FA FOREIGN KEY ("catid") REFERENCES ATTRIB_VALS ("id") ON DELETE CASCADE;
ALTER TABLE SK_SK_ELEM
    ADD CONSTRAINT FK__SK_SK_ELE__id_sk__2180FB33 FOREIGN KEY ("id_sk_elem") REFERENCES SK_ELEM ("id") ON DELETE CASCADE;
ALTER TABLE SK_SK_ELEM
    ADD CONSTRAINT FK__SK_SK_ELE__id_sk__22751F6C FOREIGN KEY ("id_sk") REFERENCES SKELETON ("id") ON DELETE CASCADE;
ALTER TABLE repl_schedules
    ADD CONSTRAINT FK_repl_workers FOREIGN KEY ("worker_id") REFERENCES repl_workers ("id");
ALTER TABLE repl_schedules
    ADD CONSTRAINT FK_repl_schedules FOREIGN KEY ("schedule_id") REFERENCES SCHEDULES ("id") ON DELETE CASCADE;
ALTER TABLE PH_PLAY_PLAN
    ADD CONSTRAINT FK__PH_PLAY_PLAN_mag_packets FOREIGN KEY ("mag_packet_id") REFERENCES mag_packets ("id");
ALTER TABLE ph_to_ph
    ADD CONSTRAINT FK_ph_to_ph_PH FOREIGN KEY ("ph_id") REFERENCES PH ("id");
ALTER TABLE mp_account_services
    ADD CONSTRAINT PK_MP_ACCOUNT_SERVICES_MP_ACCOUNTS FOREIGN KEY ("account_id") REFERENCES mp_accounts ("id") ON DELETE CASCADE;
ALTER TABLE mp_account_mediaplans
    ADD CONSTRAINT PK_MP_ACCOUNT_MEDIAPLANS_MP_ACCOUNTS FOREIGN KEY ("account_id") REFERENCES mp_accounts ("id") ON DELETE CASCADE;
ALTER TABLE mp_account_mediaplans
    ADD CONSTRAINT PK_MP_ACCOUNT_MEDIAPLANS_MP_MEDIAPLANS FOREIGN KEY ("mediaplan_id") REFERENCES mp_mediaplans ("id");
ALTER TABLE SJM_GROUP_TO_LAYOUT
    ADD CONSTRAINT FK__SJM_GROUP__group__2BC97F7C FOREIGN KEY ("group_id") REFERENCES SJM_GROUPS ("id") ON DELETE CASCADE;
ALTER TABLE SJM_GROUP_TO_LAYOUT
    ADD CONSTRAINT FK__SJM_GROUP__layou__2CBDA3B5 FOREIGN KEY ("layout_id") REFERENCES SJM_LAYOUTS ("id") ON DELETE CASCADE;
ALTER TABLE SJM_PAGES
    ADD CONSTRAINT FK__SJM_PAGES__layou__2F9A1060 FOREIGN KEY ("layout_id") REFERENCES SJM_LAYOUTS ("id") ON DELETE CASCADE;
ALTER TABLE mp_owners_mediaplans
    ADD CONSTRAINT FK_mp_owners_mediaplans_mp_mediaplans FOREIGN KEY ("id_mediaplan") REFERENCES mp_mediaplans ("id") ON DELETE CASCADE;
ALTER TABLE mp_owners_mediaplans
    ADD CONSTRAINT FK_mp_owners_mediaplans_USERS FOREIGN KEY ("id_user") REFERENCES USERS ("id");
ALTER TABLE SJM_BUTTONS
    ADD CONSTRAINT FK__SJM_BUTTO__page___32767D0B FOREIGN KEY ("page_id") REFERENCES SJM_PAGES ("id") ON DELETE CASCADE;
ALTER TABLE mp_positions
    ADD CONSTRAINT FK_mp_positions_GRID_BLOCKS FOREIGN KEY ("grid_block_id") REFERENCES GRID_BLOCKS ("id");
ALTER TABLE SJM_BTN_TO_PH
    ADD CONSTRAINT FK__SJM_BTN_T__ph_id__3552E9B6 FOREIGN KEY ("ph_id") REFERENCES PH ("id") ON DELETE CASCADE;
ALTER TABLE SJM_BTN_TO_PH
    ADD CONSTRAINT FK__SJM_BTN_T__btn_i__36470DEF FOREIGN KEY ("btn_id") REFERENCES SJM_BUTTONS ("id") ON DELETE CASCADE;
ALTER TABLE mp_mediaplan_scheds
    ADD CONSTRAINT FK_mp_mediaplan_scheds_mp_tariff_scales FOREIGN KEY ("tariff_scales_id") REFERENCES mp_tariff_scales ("id");
ALTER TABLE SJM_BTN_TO_BTN
    ADD CONSTRAINT FK__SJM_BTN_T__btn_i__39237A9A FOREIGN KEY ("btn_id_1") REFERENCES SJM_BUTTONS ("id");
ALTER TABLE mp_used_discounts
    ADD CONSTRAINT FK_mp_used_discounts_schedules FOREIGN KEY ("schedule_id") REFERENCES SCHEDULES ("id");
ALTER TABLE aq_categories
    ADD CONSTRAINT FK_aq_categories_ATTRIB_VALS FOREIGN KEY ("category_id") REFERENCES ATTRIB_VALS ("id") ON DELETE CASCADE;
ALTER TABLE SJM_BTN_TO_BTN
    ADD CONSTRAINT FK__SJM_BTN_T__btn_i__3A179ED3 FOREIGN KEY ("btn_id_2") REFERENCES SJM_BUTTONS ("id");
ALTER TABLE aq_results
    ADD CONSTRAINT FK_aq_results_ATTRIB_VALS FOREIGN KEY ("category_id") REFERENCES ATTRIB_VALS ("id") ON DELETE CASCADE;
ALTER TABLE aq_results
    ADD CONSTRAINT FK_aq_results_PH FOREIGN KEY ("ph_id") REFERENCES PH ("id") ON DELETE CASCADE;
ALTER TABLE TB_ATTRVAL
    ADD CONSTRAINT FK__TB_ATTRVA__attrv__3C34F16F FOREIGN KEY ("attrval_id") REFERENCES ATTRIB_VALS ("id") ON DELETE CASCADE;
ALTER TABLE MODIFY_PH
    ADD CONSTRAINT FK__MODIFY_PH__ph_id__3F9B6DFF FOREIGN KEY ("ph_id") REFERENCES PH ("id") ON DELETE CASCADE;
ALTER TABLE mp_discount_values
    ADD CONSTRAINT FK__mp_discou__type___41B8C09B FOREIGN KEY ("type_id") REFERENCES mp_discount_types ("id");
ALTER TABLE mp_schedule_tariff_scale
    ADD CONSTRAINT FK_MP_SCHEDULE_TARIFF_SCALE_SCHEDULE FOREIGN KEY ("schedule_id") REFERENCES SCHEDULES ("id") ON DELETE CASCADE;
ALTER TABLE PH_PLAY_HISTORY
    ADD CONSTRAINT FK__PH_PLAY_H__ph_id__43D61337 FOREIGN KEY ("ph_id") REFERENCES PH ("id") ON DELETE CASCADE;
ALTER TABLE mp_schedule_tariff_scale
    ADD CONSTRAINT FK_MP_SCHEDULE_TARIFF_SCALE_MP_TARIFF_SCALES FOREIGN KEY ("tariff_scale_id") REFERENCES mp_tariff_scales ("id") ON DELETE CASCADE;
ALTER TABLE PH_PLAY_PLAN
    ADD CONSTRAINT FK__PH_PLAY_P__ph_id__47A6A41B FOREIGN KEY ("ph_id") REFERENCES PH ("id") ON DELETE CASCADE;
ALTER TABLE mp_phonograms
    ADD CONSTRAINT PK_MP_PHONOGRAMS_BROADCASTS FOREIGN KEY ("broadcast_id") REFERENCES BROADCASTS ("id");
ALTER TABLE mp_base_costs
    ADD CONSTRAINT PK_MP_BASE_COST_BROADCASTS FOREIGN KEY ("broadcast_id") REFERENCES BROADCASTS ("id");
ALTER TABLE logger_LoudnessJournal
    ADD CONSTRAINT FK__loudness___SchSt__4B0D20AB FOREIGN KEY ("schstreamid") REFERENCES logger_Streams ("id");
ALTER TABLE MAG_CAT_SCH
    ADD CONSTRAINT FK__MAG_CAT_S__cat_i__4C364F0E FOREIGN KEY ("cat_id") REFERENCES ATTRIB_VALS ("id") ON DELETE CASCADE;
ALTER TABLE MAG_CAT_SCH
    ADD CONSTRAINT FK__MAG_CAT_S__sch_i__4D2A7347 FOREIGN KEY ("sch_id") REFERENCES SCHEDULES ("id") ON DELETE CASCADE;
ALTER TABLE logger_Streams
    ADD CONSTRAINT FK__logger_St__SchId__50C5FA01 FOREIGN KEY ("schid") REFERENCES SCHEDULES ("id") ON DELETE CASCADE;
ALTER TABLE MAG_SCH_PROP
    ADD CONSTRAINT FK__MAG_SCH_P__sch_i__50FB042B FOREIGN KEY ("sch_id") REFERENCES SCHEDULES ("id") ON DELETE CASCADE;
ALTER TABLE dmdb_Players
    ADD CONSTRAINT FK__dmdb_Play__apiUs__52793849 FOREIGN KEY ("apiuserid") REFERENCES ApiUsers ("id");
ALTER TABLE SJM_PAGES
    ADD CONSTRAINT FK_SJM_PAGES_SJM_PAGES FOREIGN KEY ("master_id") REFERENCES SJM_PAGES ("id");
ALTER TABLE dmdb_Players
    ADD CONSTRAINT FK__dmdb_Play__sched__536D5C82 FOREIGN KEY ("scheduleid") REFERENCES SCHEDULES ("id") ON DELETE CASCADE;
ALTER TABLE mp_step_tariffing_values
    ADD CONSTRAINT FK_MP_STEP_TARIFFING_VALUES_14_MP_TARIFF_SCALES FOREIGN KEY ("tariff_scales_id") REFERENCES mp_tariff_scales ("id") ON DELETE CASCADE;
ALTER TABLE RIGHTS
    ADD CONSTRAINT FK__RIGHTS__group_id__55F4C372 FOREIGN KEY ("group_id") REFERENCES GROUPS ("id") ON DELETE CASCADE;
ALTER TABLE USER_GROUP
    ADD CONSTRAINT FK__USER_GROU__group__58D1301D FOREIGN KEY ("group_id") REFERENCES GROUPS ("id") ON DELETE CASCADE;
ALTER TABLE USER_GROUP
    ADD CONSTRAINT FK__USER_GROU__user___59C55456 FOREIGN KEY ("user_id") REFERENCES USERS ("id") ON DELETE CASCADE;
ALTER TABLE CAMERA_PRESETS
    ADD CONSTRAINT FK__CAMERA_PR__sched__5A4F643B FOREIGN KEY ("schedule_id") REFERENCES SCHEDULES ("id") ON DELETE CASCADE;
ALTER TABLE SCHEDULES
    ADD CONSTRAINT FK_SCHEDULES_NETWORK_ID_NETWORKS_ID FOREIGN KEY ("network_id") REFERENCES NETWORKS ("id");
ALTER TABLE GRIDS
    ADD CONSTRAINT FK_GRIDS_NETWORK_ID_NETWORKS_ID FOREIGN KEY ("network_id") REFERENCES NETWORKS ("id") ON DELETE CASCADE;
ALTER TABLE dmdb_PlayerStates
    ADD CONSTRAINT FK__dmdb_Play__playe__5C02A283 FOREIGN KEY ("playerid") REFERENCES dmdb_Players ("id") ON DELETE CASCADE;
ALTER TABLE CAT_AUTO_SERVICE
    ADD CONSTRAINT FK_CAT_AUTO_SERVICE_ATTRIB_VALS FOREIGN KEY ("attrval_id") REFERENCES ATTRIB_VALS ("id") ON DELETE CASCADE;
ALTER TABLE GRID_CLOCKS
    ADD CONSTRAINT FK_GRID_CLOCKS_NETWORK_ID_NETWORKS_ID FOREIGN KEY ("network_id") REFERENCES NETWORKS ("id");
ALTER TABLE GRID_CLOCKS
    ADD CONSTRAINT FK_GRID_CLOCKS_SCH_ID_SCHEDULES_ID FOREIGN KEY ("sch_id") REFERENCES SCHEDULES ("id");
ALTER TABLE GRIDS
    ADD CONSTRAINT FK_GRIDS_SCHEDULE_ID_SCHEDULES_ID FOREIGN KEY ("schedule_id") REFERENCES SCHEDULES ("id");
ALTER TABLE dmdb_PlayerProfiles
    ADD CONSTRAINT FK__dmdb_Play__apiUs__5EDF0F2E FOREIGN KEY ("apiuserid") REFERENCES ApiUsers ("id");
ALTER TABLE dmdb_Player_PlayerProfile
    ADD CONSTRAINT FK__dmdb_Play__playe__61BB7BD9 FOREIGN KEY ("playerid") REFERENCES dmdb_Players ("id") ON DELETE CASCADE;
ALTER TABLE mp_mediaplans
    ADD CONSTRAINT FK_MP_MEDIA_4_NETWORK FOREIGN KEY ("network_id") REFERENCES NETWORKS ("id");
ALTER TABLE GRID_DAYS
    ADD CONSTRAINT FK__GRID_DAYS__grid___625A9A57 FOREIGN KEY ("grid_id") REFERENCES GRIDS ("id") ON DELETE CASCADE;
ALTER TABLE dmdb_Player_PlayerProfile
    ADD CONSTRAINT FK__dmdb_Play__playe__62AFA012 FOREIGN KEY ("playerprofileid") REFERENCES dmdb_PlayerProfiles ("id") ON DELETE CASCADE;
ALTER TABLE mp_closed_days
    ADD CONSTRAINT FK_MP_CLOSED_DAYS_12_NETWORK FOREIGN KEY ("network_id") REFERENCES NETWORKS ("id");
ALTER TABLE mp_tariff_scales
    ADD CONSTRAINT FK_MP_TARIF_7_NETWORK FOREIGN KEY ("network_id") REFERENCES NETWORKS ("id");
ALTER TABLE BROADCASTS
    ADD CONSTRAINT FK__BROADCAST__netwo__64CCF2AE FOREIGN KEY ("network_id") REFERENCES NETWORKS ("id");
ALTER TABLE mp_replacement
    ADD CONSTRAINT FK_MP_REPLACEMENT_SCHEDULES FOREIGN KEY ("schedule_id") REFERENCES SCHEDULES ("id") ON DELETE CASCADE;
ALTER TABLE dmdb_Player_MediaPlan
    ADD CONSTRAINT FK__dmdb_Play__playe__658C0CBD FOREIGN KEY ("playerid") REFERENCES dmdb_Players ("id") ON DELETE CASCADE;
ALTER TABLE mp_replacement
    ADD CONSTRAINT FK_MP_REPLACEMENT_MP_PHONOGRAMS_1 FOREIGN KEY ("spot_id") REFERENCES mp_phonograms ("id") ON DELETE CASCADE;
ALTER TABLE dmdb_Player_MediaPlan
    ADD CONSTRAINT FK__dmdb_Play__media__668030F6 FOREIGN KEY ("mediaplanid") REFERENCES mp_mediaplans ("id") ON DELETE CASCADE;
ALTER TABLE mp_replacement
    ADD CONSTRAINT FK_MP_REPLACEMENT_MP_PHONOGRAMS_2 FOREIGN KEY ("new_spot_id") REFERENCES mp_phonograms ("id");
ALTER TABLE GRID_CLOCK_POS
    ADD CONSTRAINT FK__GRID_CLOC__day_i__681373AD FOREIGN KEY ("day_id") REFERENCES GRID_DAYS ("id") ON DELETE CASCADE;
ALTER TABLE GRID_CLOCK_POS
    ADD CONSTRAINT FK__GRID_CLOC__clock__690797E6 FOREIGN KEY ("clock_id") REFERENCES GRID_CLOCKS ("id") ON DELETE CASCADE;
ALTER TABLE dmdb_PlayerProfile_MediaPlan
    ADD CONSTRAINT FK__dmdb_Play__playe__695C9DA1 FOREIGN KEY ("playerprofileid") REFERENCES dmdb_PlayerProfiles ("id") ON DELETE CASCADE;
ALTER TABLE dmdb_PlayerProfile_MediaPlan
    ADD CONSTRAINT FK__dmdb_Play__media__6A50C1DA FOREIGN KEY ("mediaplanid") REFERENCES mp_mediaplans ("id") ON DELETE CASCADE;
ALTER TABLE mp_position_replacement
    ADD CONSTRAINT FK_MP_POSIT_REPL_MP_POSIT FOREIGN KEY ("position_id") REFERENCES mp_positions ("id") ON DELETE CASCADE;
ALTER TABLE GRID_BLOCKS
    ADD CONSTRAINT FK__GRID_BLOC__clock__6DCC4D03 FOREIGN KEY ("clock_id") REFERENCES GRID_CLOCKS ("id") ON DELETE CASCADE;
ALTER TABLE GRID_BLOCKS
    ADD CONSTRAINT FK__GRID_BLOC__play___6EC0713C FOREIGN KEY ("play_block_id") REFERENCES PLAY_BLOCKS ("id") ON DELETE CASCADE;
ALTER TABLE data_tree
    ADD CONSTRAINT FK_data_tree_id_parent_id FOREIGN KEY ("parent_id") REFERENCES data_tree ("id");
ALTER TABLE BROADCAST_TEMPLATES
    ADD CONSTRAINT FK__BROADCAST__broad__7226EDCC FOREIGN KEY ("broadcasts_id") REFERENCES BROADCASTS ("id") ON DELETE CASCADE;
ALTER TABLE BROADCAST_RELEASES
    ADD CONSTRAINT FK__BROADCAST__netwo__75035A77 FOREIGN KEY ("network_id") REFERENCES NETWORKS ("id");
ALTER TABLE dmdb_Player_Categories
    ADD CONSTRAINT FK__dmdb_Play__playe__75C27486 FOREIGN KEY ("playerid") REFERENCES dmdb_Players ("id") ON DELETE CASCADE;
ALTER TABLE BROADCAST_RELEASES
    ADD CONSTRAINT FK__BROADCAST__broad__75F77EB0 FOREIGN KEY ("broadcasts_id") REFERENCES BROADCASTS ("id") ON DELETE CASCADE;
ALTER TABLE ph_to_ph
    ADD CONSTRAINT FK_ph_to_ph_link FOREIGN KEY ("ph_link") REFERENCES PH ("id");
ALTER TABLE ph_to_ph
    ADD CONSTRAINT FK_ph_to_ph_link_type FOREIGN KEY ("link_type") REFERENCES ph_link_types ("id") ON DELETE CASCADE;
ALTER TABLE dmdb_Async_Jobs
    ADD CONSTRAINT FK_dmdb_Async_Jobs_ApiUsers FOREIGN KEY ("apiuserid") REFERENCES ApiUsers ("id") ON DELETE CASCADE;
ALTER TABLE BROADCAST_SIGNED_DAYS
    ADD CONSTRAINT FK__BROADCAST__netwo__78D3EB5B FOREIGN KEY ("network_id") REFERENCES NETWORKS ("id");
ALTER TABLE ph_val_reflection
    ADD CONSTRAINT FK_ph_val_reflection_ph_id FOREIGN KEY ("ph_id") REFERENCES PH ("id") ON DELETE CASCADE;
ALTER TABLE FILTERS
    ADD CONSTRAINT FK__FILTERS__user_id__7E8CC4B1 FOREIGN KEY ("user_id") REFERENCES USERS ("id") ON DELETE CASCADE;
  

-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
----  create all non clustered and filter indexes
-------------------------------------------------------------------------------

CREATE INDEX idx_IX_ApiUser_AttribVals_timestamp ON ApiUser_AttribVals ("stamp" ASC);
CREATE INDEX idx_IX_ApiUser_Schedules_timestamp ON ApiUser_Schedules ("stamp" ASC);
CREATE INDEX idx_IX_ApiUserHooks_timestamp ON ApiUserHooks ("stamp" ASC);
CREATE INDEX idx_IX_ApiUsers_timestamp ON ApiUsers ("stamp" ASC);
CREATE INDEX idx_IX_ApiUsers_PlayBlock_timestamp ON ApiUsers_PlayBlocks ("stamp" ASC);
CREATE INDEX idx_id ON ATTRIB_VALS ("id" ASC);
-- CREATE  INDEX idx_id ON ATTRIBS("id" ASC);
CREATE INDEX idx_id_1 ON ATTRIBS ("id" ASC);
CREATE INDEX idx_IX_dmdb_Async_Jobs_timestamp ON dmdb_Async_Jobs ("stamp" ASC);
CREATE INDEX idx_IX_dmdb_Player_Categories_timestamp ON dmdb_Player_Categories ("stamp" ASC);
CREATE INDEX idx_IX_dmdb_Player_MediaPlan_timestamp ON dmdb_Player_MediaPlan ("stamp" ASC);
CREATE INDEX idx_IX_dmdb_Player_PlayerProfile_timestamp ON dmdb_Player_PlayerProfile ("stamp" ASC);
CREATE INDEX idx_IX_dmdb_PlayerProfile_MediaPlan_timestamp ON dmdb_PlayerProfile_MediaPlan ("stamp" ASC);
CREATE INDEX idx_IX_dmdb_PlayerProfiles_timestamp ON dmdb_PlayerProfiles ("stamp" ASC);
CREATE INDEX idx_IX_dmdb_Players_timestamp ON dmdb_Players ("stamp" ASC);
CREATE INDEX idx_IX_dmdb_PlayerStates_timestamp ON dmdb_PlayerStates ("stamp" ASC);
CREATE INDEX idx_IX_GRID_BLOCKS_timestamp ON GRID_BLOCKS ("stamp" ASC);
CREATE INDEX idx_IX_GRID_CLOCK_POS_timestamp ON GRID_CLOCK_POS ("stamp" ASC);
CREATE INDEX idx_IX_GRID_CLOCKS_timestamp ON GRID_CLOCKS ("stamp" ASC);
CREATE INDEX idx_IX_GRID_DAYS_timestamp ON GRID_DAYS ("stamp" ASC);
CREATE INDEX idx_IX_GRIDS_timestamp ON GRIDS ("stamp" ASC);
CREATE INDEX idx_indx_WorkDate ON MAG_WORK ("workdate" ASC);
CREATE INDEX idx_MODIFY_PH_PH_ID ON MODIFY_PH ("ph_id" ASC);
CREATE INDEX idx_IX_mp_base_costs_timestamp ON mp_base_costs ("stamp" ASC);
CREATE INDEX idx_x18_FK ON mp_base_costs ("tariff_scales_id" ASC);
-- CREATE UNIQUE  INDEX idx_covenantee_id_number_uniq ON mp_covenantees("id_number" ASC)  where (mp_covenantees.ID_Number IS NOT NULL);
CREATE UNIQUE INDEX idx_covenantee_id_number_uniq ON mp_covenantees ("id_number" ASC) WHERE (mp_covenantees."id_number" IS NOT NULL);
CREATE INDEX idx_IX_mp_covenantees_timestamp ON mp_covenantees ("stamp" ASC);
CREATE INDEX idx_x1_FK ON mp_covenantees ("users_id" ASC);
CREATE INDEX idx_FK_MP_DISCOUNT_VALUES_VS_MP_TYPE_ID ON mp_discount_values ("type_id" ASC);
CREATE INDEX idx_x10_FK ON mp_discount_values ("tariff_scales_id" ASC);
CREATE INDEX idx_FK_MP_PAYMENTS_VS_MP_ACCOUNTS ON mp_mediaplan_scheds ("mediaplan_id" ASC);
CREATE INDEX idx_IX_mp_mediaplans_timestamp ON mp_mediaplans ("stamp" ASC);
CREATE INDEX idx_last_user_FK ON mp_mediaplans ("users_id" ASC);
CREATE INDEX idx_x3_FK ON mp_mediaplans ("covenantees_id" ASC);
CREATE INDEX idx_x4_FK ON mp_mediaplans ("schedules_id" ASC);
CREATE INDEX idx_x8_FK ON mp_mediaplans ("tariff_scales_id" ASC);
CREATE INDEX idx_x16_FK ON mp_operations ("users_id" ASC);
CREATE INDEX idx_x2_FK ON mp_organizations ("covenantees_id" ASC);
-- CREATE  INDEX idx_FK_MP_PAYMENTS_VS_MP_ACCOUNTS ON mp_payments("account_id" ASC);
CREATE INDEX idx_FK_MP_PAYMENTS_VS_MP_ACCOUNTS_1 ON mp_payments ("account_id" ASC);
CREATE INDEX idx_IX_mp_phonograms_timestamp ON mp_phonograms ("stamp" ASC);
CREATE INDEX idx_x13_FK ON mp_phonograms ("mediaplan_id" ASC);
CREATE INDEX idx_x15_FK ON mp_phonograms ("ph_id" ASC);
CREATE INDEX idx_FK_MP_POSITION_REPLACEMENT_VS_MP_POSITION ON mp_position_replacement ("position_id" ASC);
CREATE INDEX idx_IX_mp_positions_block_number ON mp_positions ("block_number" ASC);
CREATE INDEX idx_IX_mp_positions_date ON mp_positions ("date" ASC);
CREATE INDEX idx_IX_mp_positions_timestamp ON mp_positions ("stamp" ASC);
CREATE INDEX idx_owner_FK ON mp_positions ("users_id" ASC);
CREATE INDEX idx_x5_FK ON mp_positions ("mediaplans_id" ASC);
CREATE INDEX idx_IX_mp_settings_timestamp ON mp_settings ("stamp" ASC);
CREATE INDEX idx_IX_mp_step_tariffing_values_timestamp ON mp_step_tariffing_values ("stamp" ASC);
CREATE INDEX idx_IX_mp_tariff_scales_timestamp ON mp_tariff_scales ("stamp" ASC);
CREATE INDEX idx_x7_FK ON mp_tariff_scales ("schedules_id" ASC);
CREATE INDEX idx_FK_MP_USED_DISCOUNTS_VS_MP_DISCOUNT_VALUES ON mp_used_discounts ("discount_values_id" ASC);
CREATE INDEX idx_x11_FK ON mp_used_discounts ("mediaplans_id" ASC);
CREATE INDEX idx_IX_NETWORKS_timestamp ON NETWORKS ("stamp" ASC);
-- CREATE  INDEX idx_id ON PH("id" ASC);
CREATE INDEX idx_id_2 ON PH ("id" ASC);
CREATE INDEX idx_IX_PH_timestamp ON PH ("tmstamp" ASC);
CREATE INDEX idx_PlayTime ON PH_PLAY_HISTORY ("playtime" ASC);
-- CREATE  INDEX idx_PlayTime ON PH_PLAY_PLAN("playtime" ASC);
CREATE INDEX idx_PlayTime_1 ON PH_PLAY_PLAN ("playtime" ASC);
CREATE INDEX idx_attrval_id ON PH_TO_ATTRVALS ("attrval_id" ASC);
-- CREATE  INDEX idx_id ON PH_TO_ATTRVALS("id" ASC);
CREATE INDEX idx_id_3 ON PH_TO_ATTRVALS ("id" ASC);
CREATE INDEX idx_ph_id ON PH_TO_ATTRVALS ("ph_id" ASC);
CREATE INDEX idx_ph_val_reflection_name ON ph_val_reflection ("name" ASC);
CREATE INDEX idx_IX_PLAY_BLOCKS_timestamp ON PLAY_BLOCKS ("stamp" ASC);
CREATE INDEX idx_IX_SCHEDULES_timestamp ON SCHEDULES ("stamp" ASC);
CREATE INDEX idx_IX_USERS_timestamp ON USERS ("stamp" ASC);


-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
---- create stamp/tmstamp/modifydate triggers
-------------------------------------------------------------------------------

-- Declare functions
CREATE OR REPLACE FUNCTION upd_stamp_column()
    RETURNS TRIGGER AS
$$
BEGIN
    new.stamp = TXID_CURRENT();
    RETURN new;
END;
$$ LANGUAGE 'plpgsql';

CREATE OR REPLACE FUNCTION upd_tmstamp_column()
    RETURNS TRIGGER AS
$$
BEGIN
    new.tmstamp = TXID_CURRENT();
    RETURN new;
END;
$$ LANGUAGE 'plpgsql';

CREATE OR REPLACE FUNCTION upd_tmstamp_modifydate_columns()
    RETURNS TRIGGER AS
$$
BEGIN
    new.tmstamp = TXID_CURRENT();
    new.modifydate = now();
    RETURN new;
END;
$$ LANGUAGE 'plpgsql';

CREATE OR REPLACE FUNCTION upd_modifydate_column()
    RETURNS TRIGGER AS
$$
BEGIN
    new.modifydate = now();
    RETURN new;
END;
$$ LANGUAGE 'plpgsql';


-- Create triggers
DROP TRIGGER IF EXISTS t_update_mp_tariff_scales_stamp_column
    ON mp_tariff_scales;
CREATE TRIGGER t_update_mp_tariff_scales_stamp_column
    BEFORE UPDATE
    ON mp_tariff_scales
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_apiusers_stamp_column
    ON apiusers;
CREATE TRIGGER t_update_apiusers_stamp_column
    BEFORE UPDATE
    ON apiusers
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_apiuserhooks_stamp_column
    ON apiuserhooks;
CREATE TRIGGER t_update_apiuserhooks_stamp_column
    BEFORE UPDATE
    ON apiuserhooks
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_mp_settings_stamp_column
    ON mp_settings;
CREATE TRIGGER t_update_mp_settings_stamp_column
    BEFORE UPDATE
    ON mp_settings
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_apiuser_schedules_stamp_column
    ON apiuser_schedules;
CREATE TRIGGER t_update_apiuser_schedules_stamp_column
    BEFORE UPDATE
    ON apiuser_schedules
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_apiusers_playblocks_stamp_column
    ON apiusers_playblocks;
CREATE TRIGGER t_update_apiusers_playblocks_stamp_column
    BEFORE UPDATE
    ON apiusers_playblocks
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_apiuser_attribvals_stamp_column
    ON apiuser_attribvals;
CREATE TRIGGER t_update_apiuser_attribvals_stamp_column
    BEFORE UPDATE
    ON apiuser_attribvals
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_attribs_tmstamp_column
    ON attribs;
CREATE TRIGGER t_update_attribs_tmstamp_column
    BEFORE UPDATE
    ON attribs
    FOR EACH ROW
EXECUTE PROCEDURE upd_tmstamp_column();

DROP TRIGGER IF EXISTS t_update_sjm_layouts_tmstamp_column
    ON sjm_layouts;
CREATE TRIGGER t_update_sjm_layouts_tmstamp_column
    BEFORE UPDATE
    ON sjm_layouts
    FOR EACH ROW
EXECUTE PROCEDURE upd_tmstamp_column();

DROP TRIGGER IF EXISTS t_update_ph_tmstamp_column
    ON ph;
CREATE TRIGGER t_update_ph_tmstamp_column
    BEFORE UPDATE
    ON ph
    FOR EACH ROW
EXECUTE PROCEDURE upd_tmstamp_column();

DROP TRIGGER IF EXISTS t_update_sjm_pages_tmstamp_column
    ON sjm_pages;
CREATE TRIGGER t_update_sjm_pages_tmstamp_column
    BEFORE UPDATE
    ON sjm_pages
    FOR EACH ROW
EXECUTE PROCEDURE upd_tmstamp_column();

DROP TRIGGER IF EXISTS t_update_attrib_vals_tmstamp_column
    ON attrib_vals;
CREATE TRIGGER t_update_attrib_vals_tmstamp_column
    BEFORE UPDATE
    ON attrib_vals
    FOR EACH ROW
EXECUTE PROCEDURE upd_tmstamp_column();

DROP TRIGGER IF EXISTS t_update_aq_categories_stamp_column
    ON aq_categories;
CREATE TRIGGER t_update_aq_categories_stamp_column
    BEFORE UPDATE
    ON aq_categories
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_ph_to_attrvals_tmstamp_column
    ON ph_to_attrvals;
CREATE TRIGGER t_update_ph_to_attrvals_tmstamp_column
    BEFORE UPDATE
    ON ph_to_attrvals
    FOR EACH ROW
EXECUTE PROCEDURE upd_tmstamp_column();

DROP TRIGGER IF EXISTS t_update_modify_ph_tmstamp_column
    ON modify_ph;
CREATE TRIGGER t_update_modify_ph_tmstamp_column
    BEFORE UPDATE
    ON modify_ph
    FOR EACH ROW
EXECUTE PROCEDURE upd_tmstamp_column();

DROP TRIGGER IF EXISTS t_update_mag_cat_sch_stamp_column
    ON mag_cat_sch;
CREATE TRIGGER t_update_mag_cat_sch_stamp_column
    BEFORE UPDATE
    ON mag_cat_sch
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_p_blocks_tmstamp_column
    ON p_blocks;
CREATE TRIGGER t_update_p_blocks_tmstamp_column
    BEFORE UPDATE
    ON p_blocks
    FOR EACH ROW
EXECUTE PROCEDURE upd_tmstamp_column();

DROP TRIGGER IF EXISTS t_update_mag_sch_prop_stamp_column
    ON mag_sch_prop;
CREATE TRIGGER t_update_mag_sch_prop_stamp_column
    BEFORE UPDATE
    ON mag_sch_prop
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_users_stamp_column
    ON users;
CREATE TRIGGER t_update_users_stamp_column
    BEFORE UPDATE
    ON users
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_dmdb_players_stamp_column
    ON dmdb_players;
CREATE TRIGGER t_update_dmdb_players_stamp_column
    BEFORE UPDATE
    ON dmdb_players
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_mp_step_tariffing_values_stamp_column
    ON mp_step_tariffing_values;
CREATE TRIGGER t_update_mp_step_tariffing_values_stamp_column
    BEFORE UPDATE
    ON mp_step_tariffing_values
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_networks_stamp_column
    ON networks;
CREATE TRIGGER t_update_networks_stamp_column
    BEFORE UPDATE
    ON networks
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_dmdb_playerstates_stamp_column
    ON dmdb_playerstates;
CREATE TRIGGER t_update_dmdb_playerstates_stamp_column
    BEFORE UPDATE
    ON dmdb_playerstates
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_schedules_stamp_column
    ON schedules;
CREATE TRIGGER t_update_schedules_stamp_column
    BEFORE UPDATE
    ON schedules
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_dmdb_playerprofiles_stamp_column
    ON dmdb_playerprofiles;
CREATE TRIGGER t_update_dmdb_playerprofiles_stamp_column
    BEFORE UPDATE
    ON dmdb_playerprofiles
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_grids_stamp_column
    ON grids;
CREATE TRIGGER t_update_grids_stamp_column
    BEFORE UPDATE
    ON grids
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_dmdb_player_playerprofile_stamp_column
    ON dmdb_player_playerprofile;
CREATE TRIGGER t_update_dmdb_player_playerprofile_stamp_column
    BEFORE UPDATE
    ON dmdb_player_playerprofile
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_grid_days_stamp_column
    ON grid_days;
CREATE TRIGGER t_update_grid_days_stamp_column
    BEFORE UPDATE
    ON grid_days
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_broadcasts_stamp_column
    ON broadcasts;
CREATE TRIGGER t_update_broadcasts_stamp_column
    BEFORE UPDATE
    ON broadcasts
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_grid_clocks_stamp_column
    ON grid_clocks;
CREATE TRIGGER t_update_grid_clocks_stamp_column
    BEFORE UPDATE
    ON grid_clocks
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_dmdb_player_mediaplan_stamp_column
    ON dmdb_player_mediaplan;
CREATE TRIGGER t_update_dmdb_player_mediaplan_stamp_column
    BEFORE UPDATE
    ON dmdb_player_mediaplan
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_grid_clock_pos_stamp_column
    ON grid_clock_pos;
CREATE TRIGGER t_update_grid_clock_pos_stamp_column
    BEFORE UPDATE
    ON grid_clock_pos
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_dmdb_playerprofile_mediaplan_stamp_column
    ON dmdb_playerprofile_mediaplan;
CREATE TRIGGER t_update_dmdb_playerprofile_mediaplan_stamp_column
    BEFORE UPDATE
    ON dmdb_playerprofile_mediaplan
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_play_blocks_stamp_column
    ON play_blocks;
CREATE TRIGGER t_update_play_blocks_stamp_column
    BEFORE UPDATE
    ON play_blocks
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_grid_blocks_stamp_column
    ON grid_blocks;
CREATE TRIGGER t_update_grid_blocks_stamp_column
    BEFORE UPDATE
    ON grid_blocks
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_data_tree_tmstamp_column
    ON data_tree;
CREATE TRIGGER t_update_data_tree_tmstamp_column
    BEFORE UPDATE
    ON data_tree
    FOR EACH ROW
EXECUTE PROCEDURE upd_tmstamp_column();

DROP TRIGGER IF EXISTS t_update_mp_base_costs_stamp_column
    ON mp_base_costs;
CREATE TRIGGER t_update_mp_base_costs_stamp_column
    BEFORE UPDATE
    ON mp_base_costs
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_mp_covenantees_stamp_column
    ON mp_covenantees;
CREATE TRIGGER t_update_mp_covenantees_stamp_column
    BEFORE UPDATE
    ON mp_covenantees
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_broadcast_releases_stamp_column
    ON broadcast_releases;
CREATE TRIGGER t_update_broadcast_releases_stamp_column
    BEFORE UPDATE
    ON broadcast_releases
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_dmdb_player_categories_stamp_column
    ON dmdb_player_categories;
CREATE TRIGGER t_update_dmdb_player_categories_stamp_column
    BEFORE UPDATE
    ON dmdb_player_categories
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_ph_to_ph_stamp_column
    ON ph_to_ph;
CREATE TRIGGER t_update_ph_to_ph_stamp_column
    BEFORE UPDATE
    ON ph_to_ph
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_dmdb_async_jobs_stamp_column
    ON dmdb_async_jobs;
CREATE TRIGGER t_update_dmdb_async_jobs_stamp_column
    BEFORE UPDATE
    ON dmdb_async_jobs
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_mp_mediaplans_stamp_column
    ON mp_mediaplans;
CREATE TRIGGER t_update_mp_mediaplans_stamp_column
    BEFORE UPDATE
    ON mp_mediaplans
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_mp_phonograms_stamp_column
    ON mp_phonograms;
CREATE TRIGGER t_update_mp_phonograms_stamp_column
    BEFORE UPDATE
    ON mp_phonograms
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();

DROP TRIGGER IF EXISTS t_update_mp_positions_stamp_column
    ON mp_positions;
CREATE TRIGGER t_update_mp_positions_stamp_column
    BEFORE UPDATE
    ON mp_positions
    FOR EACH ROW
EXECUTE PROCEDURE upd_stamp_column();


-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
---- create modify_dates triggers
-------------------------------------------------------------------------------

-------------------- ATTRIB_VALS: 
-- ModifyAttrVal
CREATE OR REPLACE FUNCTION ModifyAttrValFunc() RETURNS TRIGGER AS
$$
BEGIN
    INSERT INTO modify_dates (attrval_id) VALUES (new.id);
    RETURN new;
END;
$$ LANGUAGE 'plpgsql';

DROP TRIGGER IF EXISTS ModifyAttrVal
    ON attrib_vals;
CREATE TRIGGER ModifyAttrVal
    AFTER INSERT OR UPDATE
    ON attrib_vals
    FOR EACH ROW
EXECUTE PROCEDURE ModifyAttrValFunc();


-------------------- ATTRIBS: 
-- ModifyAttribs
CREATE OR REPLACE FUNCTION ModifyAttribsFunc() RETURNS TRIGGER AS
$$
BEGIN
    INSERT INTO modify_dates (attrib_id) VALUES (new.id);
    RETURN new;
END;
$$ LANGUAGE 'plpgsql';

DROP TRIGGER IF EXISTS ModifyAttribs
    ON attribs;
CREATE TRIGGER ModifyAttribs
    AFTER INSERT OR UPDATE
    ON attribs
    FOR EACH ROW
EXECUTE PROCEDURE ModifyAttribsFunc();


-------------------- CAT_JNGL_BTNS: 
-- OnModifyCatJnglBtns
CREATE OR REPLACE FUNCTION OnModifyCatJnglBtnsFunc() RETURNS TRIGGER AS
$$
BEGIN
    INSERT INTO modify_dates (cat_jngl_btns_id) VALUES (new.id);
    RETURN new;
END;
$$ LANGUAGE 'plpgsql';

DROP TRIGGER IF EXISTS OnModifyCatJnglBtns
    ON cat_jngl_btns;
CREATE TRIGGER OnModifyCatJnglBtns
    AFTER INSERT OR UPDATE
    ON cat_jngl_btns
    FOR EACH ROW
EXECUTE PROCEDURE OnModifyCatJnglBtnsFunc();


-------------------- PH_TO_ATTRVALS: 
-- OnPhToAttrVals
CREATE OR REPLACE FUNCTION OnPhToAttrValsFunc() RETURNS TRIGGER AS
$$
BEGIN
    INSERT INTO modify_dates (attrval_id) VALUES (new.attrval_id);
    IF (new.attrval_id != old.attrval_id)
    THEN
        INSERT INTO modify_dates (attrval_id) VALUES (old.attrval_id);
    END IF;

    INSERT INTO modify_dates (ph_id) VALUES (new.ph_id);
    IF (new.ph_id != old.ph_id)
    THEN
        INSERT INTO modify_dates (ph_id) VALUES (old.ph_id);
    END IF;

    UPDATE modify_ph SET ph_id=ph_id WHERE ph_id = old.ph_id;

    IF (old.ph_id != NULL)
    THEN
        INSERT INTO modify_ph (ph_id)
        SELECT old.ph_id
        WHERE NOT EXISTS(SELECT modify_ph.ph_id FROM modify_ph);
    END IF;

    RETURN new;
END;
$$ LANGUAGE 'plpgsql';

DROP TRIGGER IF EXISTS OnPhToAttrVals
    ON ph_to_attrvals;
CREATE TRIGGER OnPhToAttrVals
    AFTER INSERT OR DELETE OR UPDATE
    ON ph_to_attrvals
    FOR EACH ROW
EXECUTE PROCEDURE OnPhToAttrValsFunc();


-------------------- FILTERS: 
-- InsertOrModifyFilter
CREATE OR REPLACE FUNCTION InsertOrModifyFilterFunc() RETURNS TRIGGER AS
$$
BEGIN
    INSERT INTO modify_dates (filter_id) VALUES (new.id);
    RETURN new;
END;
$$ LANGUAGE 'plpgsql';

DROP TRIGGER IF EXISTS InsertOrModifyFilter
    ON filters;
CREATE TRIGGER InsertOrModifyFilter
    AFTER INSERT OR UPDATE
    ON filters
    FOR EACH ROW
EXECUTE PROCEDURE InsertOrModifyFilterFunc();

-- DeleteFilter
CREATE OR REPLACE FUNCTION DeleteFilterFunc() RETURNS TRIGGER AS
$$
BEGIN
    INSERT INTO modify_dates (filter_id) VALUES (old.id);
    RETURN new;
END;
$$ LANGUAGE 'plpgsql';

DROP TRIGGER IF EXISTS DeleteFilter
    ON filters;
CREATE TRIGGER DeleteFilter
    AFTER DELETE
    ON filters
    FOR EACH ROW
EXECUTE PROCEDURE DeleteFilterFunc();


-------------------- PH_TO_PH: 
-- OnPhToPhFunc;
CREATE OR REPLACE FUNCTION OnPhToPhFunc() RETURNS TRIGGER AS
$$
BEGIN
    INSERT INTO MODIFY_DATES (ph_id) VALUES (new.ph_id);
    INSERT INTO MODIFY_DATES (ph_id) VALUES (old.ph_id);
    RETURN new;
END;
$$ LANGUAGE 'plpgsql';

DROP TRIGGER IF EXISTS OnPhToPh
    ON ph_to_ph;
CREATE TRIGGER OnPhToPh
    AFTER INSERT OR DELETE
    ON ph_to_ph
    FOR EACH ROW
EXECUTE PROCEDURE OnPhToPhFunc();


-------------------- PH: 
-- InsertPH
CREATE OR REPLACE FUNCTION InsertPHFunc() RETURNS TRIGGER AS
$$
BEGIN
    INSERT INTO modify_dates (ph_id) VALUES (new.id);
    RETURN new;
END;
$$ LANGUAGE 'plpgsql';

DROP TRIGGER IF EXISTS InsertPH
    ON ph;
CREATE TRIGGER InsertPH
    AFTER INSERT
    ON ph
    FOR EACH ROW
EXECUTE PROCEDURE InsertPHFunc();

-- ModifyPH
CREATE OR REPLACE FUNCTION ModifyPHFunc() RETURNS TRIGGER AS
$$
BEGIN
    UPDATE ph SET modifydate=NOW() WHERE id = new.id;
    INSERT INTO modify_dates (ph_id) VALUES (new.id);

    IF (new.archive != old.archive)
    THEN
        INSERT INTO MODIFY_DATES (attrval_id)
        SELECT attrval_id
        FROM ph_to_attrvals
        WHERE ph_id = new.id
          AND attrval_id IS NOT NULL;
    END IF;

    RETURN new;
END;
$$ LANGUAGE 'plpgsql';

DROP TRIGGER IF EXISTS ModifyPH
    ON ph;
CREATE TRIGGER ModifyPH
    -- игнорируем изменение lastplaytime и modifydate, надо поискать лучшие варианты
    AFTER UPDATE OF "id", "name", "filename", "duration", "type", "intro", "outro", "fadein", "fadeout",
        "startnext", "ph_start", "ph_stop", "cmd", "freq", "smplsize", "radioid", "remotecmd", "adddate",
        "deleted", "jm_pos", "subjtext", "id_number", "endcode", "firstreportline", "lastreportline",
        "maxlvl", "maxlvlok", "gain", "cdid", "cdtrackid", "album", "songyear", "modifyft", "rmtlist",
        "ddb_owner", "version", "ddb_id", "crc32", "sch_usedcount", "intro2", "intro3", "comment",
        "fadeintype", "fadeouttype", "mood", "activatedate", "energy", "tempo", "texture", "tempo_end",
        "texture_end", "startthis", "archive", "nextplaytime", "usermodifytime", "dayrestrictions",
        "readyonair", "headline", "cassetestartfps", "cassetelengthfps", "backuptapename", "backuptimecode",
        "keyframe", "keyicon", "tmstamp", "backuplength", "protyagfirst", "protyaglast", "leftrightch",
        "lccode", "publisher", "rds", "cmd2", "textsizems", "phonotype", "ownername", "ddbtmstamp",
        "nc_root", "nc_root_md5", "loudness"
    ON ph
    FOR EACH ROW
EXECUTE PROCEDURE ModifyPHFunc();

-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
---- prepare TEST_NEW_2 stored procedure
-------------------------------------------------------------------------------

CREATE OR REPLACE FUNCTION InlineMaxBigint(
    p1 bigint,
    p2 bigint
) RETURNS bigint
AS
$func$
BEGIN
    RETURN CASE
               WHEN @p1 IS NULL AND @p2 IS NOT NULL THEN @p2
               WHEN @p2 IS NULL AND @p1 IS NOT NULL THEN @p1
               WHEN @p1 > @p2 THEN @p1
               ELSE @p2 END;
END
$func$ LANGUAGE plpgsql;


-- возвращает миксимальный modify_dates.id, но не более 500 от p_id
CREATE OR REPLACE FUNCTION GetNextModifyDatesLastId(p_id int)
    RETURNS int AS
$func$
DECLARE
    max_id int;
BEGIN
    max_id := (SELECT MAX(id) FROM modify_dates);

    IF (p_id >= 0 AND max_id > p_id + 500)
    THEN
        max_id := p_id + 500;
    END IF;

    RETURN (max_id);
END;
$func$ LANGUAGE plpgsql;


-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
---- schedule_blocks
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------


CREATE TABLE schedule_blocks
        (
            id SERIAL NOT NULL PRIMARY KEY,
            schedule_id INT,
			blkdate timestamp,
			tmstamp bigint NOT NULL DEFAULT txid_current(),
			blk_json text,
			blk_type INT,
			blk_pattern_id INT default null,
			deleted boolean default false,
			blk_elems INT default null
        );
		
CREATE TABLE schedule_patterns
        (
            id SERIAL NOT NULL PRIMARY KEY,
            schedule_id INT,
			name text,
			start_date timestamp,
			end_date timestamp,
			month_num INT,
			week_num INT,
			day_of_week_num INT,
			day_num INT,
			tmstamp bigint NOT NULL DEFAULT txid_current()
        );

 CREATE TABLE settings_map
        (
            pkey text NOT NULL PRIMARY KEY,
			pvalue_bin bytea NULL,
			pvalue_txt text NULL,
			tmstamp bigint NOT NULL DEFAULT txid_current(),
			type INT
        );

ALTER TABLE schedule_blocks
    ADD CONSTRAINT FK_SCHEDULE_BLOCKS_SCHEDULES FOREIGN KEY ("schedule_id") REFERENCES schedules ("id") ON DELETE CASCADE;
	
ALTER TABLE schedule_blocks 
	ADD CONSTRAINT FK_SCHEDULE_BLOCKS_SCHEDULE_PATTERNS FOREIGN KEY ("blk_pattern_id") REFERENCES schedule_patterns("id") ON DELETE CASCADE;
	
ALTER TABLE schedule_patterns 
	ADD CONSTRAINT FK_SCHEDULE_PATTERNS_SCHEDULES FOREIGN KEY ("schedule_id") REFERENCES schedules(id);

DROP TRIGGER IF EXISTS t_update_schedule_blocks_tmstamp_column
    ON schedule_blocks;
CREATE TRIGGER t_update_schedule_blocks_tmstamp_column
    BEFORE UPDATE
    ON schedule_blocks
    FOR EACH ROW
EXECUTE PROCEDURE upd_tmstamp_column();

DROP TRIGGER IF EXISTS t_update_schedule_patterns_tmstamp_column
    ON schedule_patterns;
CREATE TRIGGER t_update_schedule_patterns_tmstamp_column
    BEFORE UPDATE
    ON schedule_patterns
    FOR EACH ROW
EXECUTE PROCEDURE upd_tmstamp_column();

DROP TRIGGER IF EXISTS t_update_settings_map_tmstamp_column
    ON settings_map;
CREATE TRIGGER t_update_settings_map_tmstamp_column
    BEFORE UPDATE
    ON settings_map
    FOR EACH ROW
EXECUTE PROCEDURE upd_tmstamp_column();

-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
---- insert defaults
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------


-------------------------------------------------------------------------------

INSERT INTO ATTRIBS (Name,Type,NICK) VALUES ('Categories',	0, 'CATEGORY');
INSERT INTO ATTRIBS (Name,Type,NICK) VALUES ('Artists',	0, 'ARTIST');
INSERT INTO ATTRIBS (Name,Type,NICK) VALUES ('Authors',	0, 'AUTHOR');

INSERT INTO ATTRIBS (Name,Type,NICK) VALUES ('Vocal',	2, 'VOCAL');--id=4
INSERT INTO ATTRIBS (Name,Type,NICK) VALUES ('Vocal',	3, 'VOCAL');--id=5
INSERT INTO ATTRIBS (Name,Type,NICK) VALUES ('Vocal',	1, 'VOCAL');--id=6
INSERT INTO ATTRIBS (Name,Type,NICK) VALUES ('Activity',	1, 'ACTIVITY');


INSERT INTO ATTRIB_VALS (Name,Type,attr_id) VALUES ('Male',	2, 4);
INSERT INTO ATTRIB_VALS (Name,Type,attr_id) VALUES ('Female',	2, 4);
INSERT INTO ATTRIB_VALS (Name,Type,attr_id) VALUES ('Duet',	2, 4);
INSERT INTO ATTRIB_VALS (Name,Type,attr_id) VALUES ('Chorus',	2, 4);
INSERT INTO ATTRIB_VALS (Name,Type,attr_id) VALUES ('Instrumental',	2, 4);

INSERT INTO ATTRIB_VALS (Name,Type,attr_id) VALUES ('Male',	3, 5);
INSERT INTO ATTRIB_VALS (Name,Type,attr_id) VALUES ('Female',	3, 5);
INSERT INTO ATTRIB_VALS (Name,Type,attr_id) VALUES ('Duet',	3, 5);
INSERT INTO ATTRIB_VALS (Name,Type,attr_id) VALUES ('Chorus',	3, 5);
INSERT INTO ATTRIB_VALS (Name,Type,attr_id) VALUES ('Instrumental',	3, 5);

INSERT INTO ATTRIB_VALS (Name,Type,attr_id) VALUES ('Male',	1, 6);
INSERT INTO ATTRIB_VALS (Name,Type,attr_id) VALUES ('Female',	1, 6);
INSERT INTO ATTRIB_VALS (Name,Type,attr_id) VALUES ('Duet',	1, 5);
INSERT INTO ATTRIB_VALS (Name,Type,attr_id) VALUES ('Chorus',	1, 6);
INSERT INTO ATTRIB_VALS (Name,Type,attr_id) VALUES ('Instrumental',	1, 6);

-------------------------------------------------------------------------------

INSERT INTO TRACT (Version) VALUES(1000);
INSERT INTO TRACT (Version) VALUES(1100);
INSERT INTO TRACT (Version) VALUES(1200);
INSERT INTO TRACT (Version) VALUES(1210);
INSERT INTO TRACT (Version) VALUES(1220);
INSERT INTO TRACT (Version) VALUES(1300);
INSERT INTO TRACT (Version) VALUES(1310);
INSERT INTO TRACT (Version) VALUES(1320);
INSERT INTO TRACT (Version) VALUES(1400);
INSERT INTO TRACT (Version) VALUES(1410);
INSERT INTO TRACT (Version) VALUES(1420);
INSERT INTO TRACT (Version) VALUES(1430);
INSERT INTO TRACT (Version) VALUES(1500);
INSERT INTO TRACT (Version) VALUES(1510);
INSERT INTO TRACT (Version) VALUES(1520);
INSERT INTO TRACT (Version) VALUES(1600);
INSERT INTO TRACT (Version) VALUES(1610);
INSERT INTO TRACT (Version) VALUES(1620);
INSERT INTO TRACT (Version) VALUES(1630);
INSERT INTO TRACT (Version) VALUES(1640);
INSERT INTO TRACT (Version) VALUES(1650);
INSERT INTO TRACT (Version) VALUES(1660);
INSERT INTO TRACT (Version) VALUES(1670);
INSERT INTO TRACT (Version) VALUES(1680);
INSERT INTO TRACT (Version) VALUES(1700);
INSERT INTO TRACT (Version) VALUES(1710);
INSERT INTO TRACT (Version) VALUES(1720);
INSERT INTO TRACT (Version) VALUES(1730);
INSERT INTO TRACT (Version) VALUES(1740);
INSERT INTO TRACT (Version) VALUES(1750);
INSERT INTO TRACT (Version) VALUES(1760);
INSERT INTO TRACT (Version) VALUES(1770);
INSERT INTO TRACT (Version) VALUES(1780);
INSERT INTO TRACT (Version) VALUES(1781);
INSERT INTO TRACT (Version) VALUES(1782);
INSERT INTO TRACT (Version) VALUES(1783);
INSERT INTO TRACT (Version) VALUES(1790);
INSERT INTO TRACT (Version) VALUES(1800);
INSERT INTO TRACT (Version) VALUES(1810);
INSERT INTO TRACT (Version) VALUES(1820);
INSERT INTO TRACT (Version) VALUES(1830);
INSERT INTO TRACT (Version) VALUES(1840);
INSERT INTO TRACT (Version) VALUES(1850);
INSERT INTO TRACT (Version) VALUES(1860);
INSERT INTO TRACT (Version) VALUES(1870);
INSERT INTO TRACT (Version) VALUES(1880);
INSERT INTO TRACT (Version) VALUES(1890);
INSERT INTO TRACT (Version) VALUES(1900);
INSERT INTO TRACT (Version) VALUES(1910);
INSERT INTO TRACT (Version) VALUES(1920);
INSERT INTO TRACT (Version) VALUES(1930);
INSERT INTO TRACT (Version) VALUES(1940);
INSERT INTO TRACT (Version) VALUES(1950);
INSERT INTO TRACT (Version) VALUES(1960);
INSERT INTO TRACT (Version) VALUES(1970);
INSERT INTO TRACT (Version) VALUES(1990);
INSERT INTO TRACT (Version) VALUES(2000);
INSERT INTO TRACT (Version) VALUES(2010);
INSERT INTO TRACT (Version) VALUES(2020);
INSERT INTO TRACT (Version) VALUES(2030);
INSERT INTO TRACT (Version) VALUES(2040);
INSERT INTO TRACT (Version) VALUES(2050);
INSERT INTO TRACT (Version) VALUES(2060);
INSERT INTO TRACT (Version) VALUES(2070);
INSERT INTO TRACT (Version) VALUES(2080);
INSERT INTO TRACT (Version) VALUES(2090);
INSERT INTO TRACT (Version) VALUES(2100);
INSERT INTO TRACT (Version) VALUES(2110);
INSERT INTO TRACT (Version) VALUES(2120);
INSERT INTO TRACT (Version) VALUES(2130);
INSERT INTO TRACT (Version) VALUES(2140);
INSERT INTO TRACT (Version) VALUES(2150);
INSERT INTO TRACT (Version) VALUES(2170);
INSERT INTO TRACT (Version) VALUES(2190);
INSERT INTO TRACT (Version) VALUES(2200);
INSERT INTO TRACT (Version) VALUES(2210);
INSERT INTO TRACT (Version) VALUES(2220);
INSERT INTO TRACT (Version) VALUES(2230);
INSERT INTO TRACT (Version) VALUES(2240);
INSERT INTO TRACT (Version) VALUES(2250);
INSERT INTO TRACT (Version) VALUES(2260);
INSERT INTO TRACT (Version) VALUES(2270);
INSERT INTO TRACT (Version) VALUES(2280);
INSERT INTO TRACT (Version) VALUES(2290);
INSERT INTO TRACT (Version) VALUES(2300);
INSERT INTO TRACT (Version) VALUES(2310);
INSERT INTO TRACT (Version) VALUES(2320);
INSERT INTO TRACT (Version) VALUES(2330);
INSERT INTO TRACT (Version) VALUES(2340);
INSERT INTO TRACT (Version) VALUES(2350);
INSERT INTO TRACT (Version) VALUES(2360);
INSERT INTO TRACT (Version) VALUES(2365);
INSERT INTO TRACT (Version) VALUES(2370);
INSERT INTO TRACT (Version) VALUES(2380);
INSERT INTO TRACT (Version) VALUES(2390);
INSERT INTO TRACT (Version) VALUES(2400);
INSERT INTO TRACT (Version) VALUES(2410);
INSERT INTO TRACT (Version) VALUES(2420);
INSERT INTO TRACT (Version) VALUES(2430);
INSERT INTO TRACT (Version) VALUES(2440);
INSERT INTO TRACT (Version) VALUES(2450);
INSERT INTO TRACT (Version) VALUES(2460);
INSERT INTO TRACT (Version) VALUES(2470);
INSERT INTO TRACT (Version) VALUES(2480);
INSERT INTO TRACT (Version) VALUES(2490);
INSERT INTO TRACT (Version) VALUES(2500);
INSERT INTO TRACT (Version) VALUES(2510);
INSERT INTO TRACT (Version) VALUES(2520);
INSERT INTO TRACT (Version) VALUES(2530);
INSERT INTO TRACT (Version) VALUES(2540);
INSERT INTO TRACT (Version) VALUES(2550);
INSERT INTO TRACT (Version) VALUES(2560);
INSERT INTO TRACT (Version) VALUES(2570);
INSERT INTO TRACT (Version) VALUES(2580);
INSERT INTO TRACT (Version) VALUES(2590);
INSERT INTO TRACT (Version) VALUES(2600);
INSERT INTO TRACT (Version) VALUES(2610);
INSERT INTO TRACT (Version) VALUES(2620);
INSERT INTO TRACT (Version) VALUES(2630);
INSERT INTO TRACT (Version) VALUES(2640);
INSERT INTO TRACT (Version) VALUES(2650);
INSERT INTO TRACT (Version) VALUES(2660);
INSERT INTO TRACT (Version) VALUES(2670);
INSERT INTO TRACT (Version) VALUES(2680);
INSERT INTO TRACT (Version) VALUES(2690);
INSERT INTO TRACT (Version) VALUES(2700);
INSERT INTO TRACT (Version) VALUES(2710);
INSERT INTO TRACT (Version) VALUES(2720);
INSERT INTO TRACT (Version) VALUES(2730);
INSERT INTO TRACT (Version) VALUES(2740);
INSERT INTO TRACT (Version) VALUES(2750);
INSERT INTO TRACT (Version) VALUES(2751);
INSERT INTO TRACT (Version) VALUES(2752);
INSERT INTO TRACT (Version) VALUES(2753);
INSERT INTO TRACT (Version) VALUES(2800);
INSERT INTO TRACT (Version) VALUES(2810);
INSERT INTO TRACT (Version) VALUES(2820);
INSERT INTO TRACT (Version) VALUES(2821);
INSERT INTO TRACT (Version) VALUES(2830);
INSERT INTO TRACT (Version) VALUES(2831);
INSERT INTO TRACT (Version) VALUES(2832);
INSERT INTO TRACT (Version) VALUES(2840);
INSERT INTO TRACT (Version) VALUES(2850);

-------------------------------------------------------------------------------

INSERT INTO components(name, veri) VALUES('Components.AddDate column', 1);
INSERT INTO components(name, veri) VALUES('Nullable PH.LastPlayTime', 1);
INSERT INTO components(name, veri) VALUES('PH.Triggers.ModifyPH', 2);
INSERT INTO components(name, veri) VALUES('Blocks binary', 2);
INSERT INTO components(name, veri) VALUES('SP.RunBackgroundTask', 1);
INSERT INTO components(name, veri) VALUES('SP.MdbBackgroundTask', 1);
INSERT INTO components(name, veri) VALUES('SP.MdbClean', 1);
INSERT INTO components(name, veri) VALUES('InlineMinMax', 1);
INSERT INTO components(name, veri) VALUES('PH.Loudness', 1);
INSERT INTO components(name, veri) VALUES('TEST_NEW_2 PH.Loudness', 1);
INSERT INTO components(name, veri) VALUES('TEST_NEW_V2 PH.Loudness', 1);
INSERT INTO components(name, veri) VALUES('PH.Loudness', 2);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 10);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 20);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 30);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 40);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 50);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 60);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 70);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 80);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 90);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 100);
INSERT INTO components(name, veri) VALUES('MAG.Packets', 1);
INSERT INTO components(name, veri) VALUES('TEST_NEW_2 PH_TO_ATTRVALS.mag_packet_id', 1);
INSERT INTO components(name, veri) VALUES('TEST_NEW_V2 PH_TO_ATTRVALS.mag_packet_id', 1);
INSERT INTO components(name, veri) VALUES('PH_PLAY_HISTORY.mag_packet_id', 1);
INSERT INTO components(name, veri) VALUES('SP.RunBackgroundTask', 2);
INSERT INTO components(name, veri) VALUES('PH.ClearPhToPhTrigger', 1);
INSERT INTO components(name, veri) VALUES('UnicodeDB', 1);
INSERT INTO components(name, veri) VALUES('PH.ID_Number.128', 1);
INSERT INTO components(name, veri) VALUES('PH_PLAY_HISTORY.booking_id.128', 1);
INSERT INTO components(name, veri) VALUES('PH_PLAY_HISTORY.booking_id.128', 2);
INSERT INTO components(name, veri) VALUES('OperationsLog', 1);
INSERT INTO components(name, veri) VALUES('OperationsLog', 2);
INSERT INTO components(name, veri) VALUES('OperationsLog', 3);
INSERT INTO components(name, veri) VALUES('PH_PLAY_HISTORY.PlaySize', 1);
INSERT INTO components(name, veri) VALUES('PH.Publisher.128', 1);
INSERT INTO components(name, veri) VALUES('TF.ufnGetPhIdentities', 1);
INSERT INTO components(name, veri) VALUES('PH_PLAY_HISTORY', 1);
INSERT INTO components(name, veri) VALUES('SP.MdbClean', 2);
INSERT INTO components(name, veri) VALUES('TEST_NEW_2 PH_TO_ATTRVALS.mag_packet_id', 2);
INSERT INTO components(name, veri) VALUES('TEST_NEW_V2 PH_TO_ATTRVALS.mag_packet_id', 2);
INSERT INTO components(name, veri) VALUES('MODIFY_PH', 1);
INSERT INTO components(name, veri) VALUES('TEST_NEW_2.MODIFY_PH', 1);
INSERT INTO components(name, veri) VALUES('TEST_NEW_V2.MODIFY_PH', 1);
INSERT INTO components(name, veri) VALUES('TEST_NEW_2.DdbTmStamp', 1);
INSERT INTO components(name, veri) VALUES('TEST_NEW_V2.DdbTmStamp', 1);
INSERT INTO components(name, veri) VALUES('LoudnessJournal', 1);
INSERT INTO components(name, veri) VALUES('LoudnessJournal', 2);
INSERT INTO components(name, veri) VALUES('LoudnessJournal', 3);
INSERT INTO components(name, veri) VALUES('LoudnessJournal', 4);
INSERT INTO components(name, veri) VALUES('PH_PLAY_HISTORY', 2);
INSERT INTO components(name, veri) VALUES('SP.MdbClean', 3);
INSERT INTO components(name, veri) VALUES('SJM_STRUCTURE', 1);
INSERT INTO components(name, veri) VALUES('LICENCE', 1);
INSERT INTO components(name, veri) VALUES('GRIDS', 1);
INSERT INTO components(name, veri) VALUES('SJM_STRUCTURE', 2);
INSERT INTO components(name, veri) VALUES('LICENCE', 2);
INSERT INTO components(name, veri) VALUES('SCHEDULES', 1);
INSERT INTO components(name, veri) VALUES('CAMERA_CONTROL_SYSTEM', 1);
INSERT INTO components(name, veri) VALUES('MDB_CAT_AUTO_SERVICE', 1);
INSERT INTO components(name, veri) VALUES('SP.MdbClean', 4);
INSERT INTO components(name, veri) VALUES('BROADCASTS', 1);
INSERT INTO components(name, veri) VALUES('BROADCASTS', 2);
INSERT INTO components(name, veri) VALUES('PH_PLAY_HISTORY.mag_packet_id', 2);
INSERT INTO components(name, veri) VALUES('LICENCE', 3);
INSERT INTO components(name, veri) VALUES('TEXT_FILTERS', 1);
INSERT INTO components(name, veri) VALUES('FILTERS.Triggers.ModifyFilters', 1);
INSERT INTO components(name, veri) VALUES('PROCEDURE.TEST_NEW_2', 1);
INSERT INTO components(name, veri) VALUES('SP.RunBackgroundTask', 3);
INSERT INTO components(name, veri) VALUES('TEXT_FILTERS', 2);
INSERT INTO components(name, veri) VALUES('MODIFY_PH', 2);
INSERT INTO components(name, veri) VALUES('locked_objects', 1);
INSERT INTO components(name, veri) VALUES('DigispotAPI', 1);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 1);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 2);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 3);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 4);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 5);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 6);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 7);
INSERT INTO components(name, veri) VALUES('BROADCASTS', 3);
INSERT INTO components(name, veri) VALUES('BROADCASTS', 4);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 8);
INSERT INTO components(name, veri) VALUES('replication_workers', 2);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 110);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 120);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 130);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 140);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 150);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 160);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 170);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 180);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 190);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 200);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 210);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 220);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 230);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 240);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 250);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 260);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 270);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 290);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 295);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 300);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 310);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 320);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 330);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 340);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 350);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 360);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 370);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 380);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 390);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 400);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 410);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 420);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 430);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 440);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 450);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 460);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 470);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 480);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 490);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 500);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 510);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 520);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 530);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 540);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 550);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 560);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 570);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 580);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 590);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 600);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 610);
INSERT INTO components(name, veri) VALUES('MediaPlannerComponent', 620);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 10);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 20);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 30);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 40);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 50);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 60);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 70);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 80);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 90);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 100);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 110);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 120);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 130);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 140);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 150);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 160);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 170);
INSERT INTO components(name, veri) VALUES('AudioQuality', 1);
INSERT INTO components(name, veri) VALUES('AudioQuality', 2);
INSERT INTO components(name, veri) VALUES('AudioQuality', 3);
INSERT INTO components(name, veri) VALUES('MediaIntegrationApi', 180);
INSERT INTO components(name, veri) VALUES('DecroAutomatComponent', 1);
INSERT INTO components(name, veri) VALUES('DecroAutomatComponent', 2);
INSERT INTO components(name, veri) VALUES('DecroAutomatComponent', 3);
INSERT INTO components(name, veri) VALUES('DigispotDbService', 1);
INSERT INTO components(name, veri) VALUES('DigispotDbService', 2);
INSERT INTO components(name, veri) VALUES('DigispotDbService', 3);
INSERT INTO components(name, veri) VALUES('DigispotDbService', 4);
INSERT INTO components(name, veri) VALUES('DigispotDbService', 5);

-------------------------------------------------------------------------------

INSERT INTO ph_link_types(str_id, name) VALUES ('Picture', 'Picture');

-------------------------------------------------------------------------------

INSERT INTO mp_discount_types (id, name, apply_method, base_discount_id) VALUES (1, 'Скидка1', 0, 1);
INSERT INTO mp_discount_types (id, name, apply_method, base_discount_id) VALUES (2, 'Скидка2', 0, 2);
INSERT INTO mp_discount_types (id, name, apply_method, base_discount_id) VALUES (3, 'Скидка3', 1, 3);
INSERT INTO mp_discount_types (id, name, apply_method, base_discount_id) VALUES (4, 'Скидка4', 1, 4);
INSERT INTO mp_discount_types (id, name, apply_method, base_discount_id) VALUES (6, 'Скидка5', 0, 6);
INSERT INTO mp_discount_types (id, name, apply_method, base_discount_id) VALUES (7, 'Скидка6', 0, 7);
INSERT INTO mp_discount_types (id, name, apply_method, base_discount_id) VALUES (8, 'Скидка7', 0, 8);
INSERT INTO mp_discount_types (id, name, apply_method, base_discount_id) VALUES (9, 'Скидка для бонусного проката', 0, 9);
INSERT INTO mp_discount_types (id, name, apply_method, base_discount_id) VALUES (10, 'Скидка контрагента', 0, 10);


-------------------------------------------------------------------------------

INSERT INTO mp_spot_types (show_type, name, system_type,  template) VALUES(0, 'Прокат ролика в блоке', true, 0);
INSERT INTO mp_spot_types (show_type, name, system_type,  template) VALUES(1, 'Спонсорcкий прокат', true, 1);
INSERT INTO mp_spot_types (show_type, name, system_type,  template) VALUES(2, 'Прямое включение', true, 2);

-------------------------------------------------------------------------------

INSERT INTO BackgroundTaskHistory (ProcName, LastExec) VALUES ('MdbClean', '2023-08-26 03:00:00.000');

-------------------------------------------------------------------------------

INSERT INTO PARAMETERS (Type, Name, Value) VALUES (0, 'MdbClean.Interval', 168);

-------------------------------------------------------------------------------
