Created
November 15, 2017 02:31
-
-
Save viphat/f96d47db1a2990a3e7b1a749799b0750 to your computer and use it in GitHub Desktop.
Postgres Function with Parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION vessels_arrival_departure_time(imos text[], | |
since timestamp without time zone default null, | |
port_locode text default null) | |
RETURNS TABLE(port_vessels_id int, imo varchar, mmsi varchar, | |
vessel_name varchar, voyage_number jsonb, | |
port_locode varchar, event_name varchar, | |
event_time timestamp without time zone | |
) AS $$ | |
SELECT pv.id, v.imo, v.mmsi, | |
v.name, bs.voyage_number, | |
p.locode, | |
CASE WHEN pv.nav_status_code = 85 THEN 'VA' | |
WHEN pv.nav_status_code = 86 THEN 'VD' | |
END, | |
pv.last_position_updated_at | |
FROM port_vessels AS pv | |
JOIN vessels as v ON pv.vessel_id = v.id | |
JOIN ports as p ON pv.port_id = p.id | |
JOIN berth_shifts as bs ON pv.berth_shift_id = bs.id | |
WHERE v.imo = ANY($1) | |
AND ($2 IS NULL OR pv.last_position_updated_at > $2) | |
AND ($3 IS NULL OR p.locode = $3) | |
$$ LANGUAGE sql; | |
SELECT 'DROP FUNCTION ' || oid::regprocedure | |
FROM pg_proc | |
WHERE proname = 'vessels_arrival_departure_time' | |
AND pg_function_is_visible(oid); | |
DROP FUNCTION vessels_arrival_departure_time(text[], timestamp without time zone, text) | |
SELECT * FROM vessels_arrival_departure_time(ARRAY['9436290', '9306835'], '2017-10-10T00:00:00Z', 'ESBIO') | |
SELECT * FROM vessels_arrival_departure_time( | |
ARRAY['9436290','9306835'], | |
'2017-10-10T00:01:00Z', | |
NULL) | |
CREATE VIEW custom_port_vessels AS | |
SELECT pv.id, v.imo, v.mmsi, | |
v.name, bs.voyage_number, | |
p.locode, | |
CASE WHEN pv.nav_status_code = 85 THEN 'VA' | |
WHEN pv.nav_status_code = 86 THEN 'VD' | |
END, | |
pv.last_position_updated_at | |
FROM port_vessels AS pv | |
JOIN vessels as v ON pv.vessel_id = v.id | |
JOIN ports as p ON pv.port_id = p.id | |
JOIN berth_shifts as bs ON pv.berth_shift_id = bs.id; | |
SELECT * FROM custom_port_vessels WHERE imo = '9355331'; | |
Author
viphat
commented
Nov 15, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment