CREATE OR REPLACE FUNCTION departure_part (par_stop_id text, t_schema text, is_tmp boolean DEFAULT false)
    RETURNS integer
    LANGUAGE plpgsql
AS $function$
    declare txt_sql text;
    declare master_table_name text;
begin
    txt_sql = 'SET search_path TO ' || t_schema || ';';

    if is_tmp = true then
        txt_sql = txt_sql ||' ALTER TABLE IF EXISTS ropidgtfs_departures_' || trim(par_stop_id) || ' RENAME TO ropidgtfs_departures_' || trim(par_stop_id) || '_drop;';
        master_table_name = 'ropidgtfs_departures_tmp';
    else
        master_table_name = 'ropidgtfs_departures';
    end if;

    txt_sql = txt_sql || ' CREATE TABLE IF NOT EXISTS ropidgtfs_departures_' || trim(par_stop_id);
    txt_sql = txt_sql || ' PARTITION OF ' || master_table_name || ' FOR VALUES IN (''' || trim(par_stop_id) || ''')';
    execute txt_sql;
return 0;
end;
$function$
;

DROP TABLE IF EXISTS ropidgtfs_departures_actual;
DROP TABLE IF EXISTS ropidgtfs_departures;
CREATE TABLE ropidgtfs_departures (
	stop_sequence smallint NOT NULL,
	stop_headsign varchar(70) NULL,
	pickup_type char(1) NULL,
	drop_off_type char(1) NULL,
	arrival_time varchar(20) NULL,
	arrival_datetime timestamptz NULL,
	departure_time varchar(20) NULL,
	departure_datetime timestamptz NULL,
	stop_id varchar(25) NOT NULL,
	stop_name varchar(100) NULL,
	platform_code varchar(10) NULL,
	wheelchair_boarding smallint NULL,
	min_stop_sequence smallint NULL,
	max_stop_sequence smallint NULL,
	trip_id varchar(50) NOT NULL,
	trip_headsign varchar(100) NOT NULL,
	trip_short_name varchar(30) NULL,
	wheelchair_accessible smallint NULL,
	service_id varchar(30) NULL,
	"date" date NULL,
	route_short_name varchar(50) NULL,
	route_type char(1) NULL,
	route_id varchar(20) NULL,
	is_night char(1) NULL,
	is_regional char(1) NULL,
	is_substitute_transport char(1) NULL,
	next_stop_sequence smallint NULL,
	next_stop_id varchar(30) NULL,
	last_stop_sequence smallint NULL,
	last_stop_id varchar(30) NULL,
	part_index varchar(4) NOT NULL
) partition by list(part_index);

CREATE INDEX ropidgtfs_departures_stop_idx ON ropidgtfs_departures USING btree (stop_id);
CREATE INDEX ropidgtfs_departures_part_index_idx ON ropidgtfs_departures USING btree (part_index);
CREATE UNIQUE INDEX ropidgtfs_departures_unique_idx ON ropidgtfs_departures USING btree (part_index, service_id, date, trip_id, stop_sequence);
