Skip to content

Instantly share code, notes, and snippets.

@viphat
Created November 15, 2017 02:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viphat/f96d47db1a2990a3e7b1a749799b0750 to your computer and use it in GitHub Desktop.
Save viphat/f96d47db1a2990a3e7b1a749799b0750 to your computer and use it in GitHub Desktop.
Postgres Function with Parameters
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';
@viphat
Copy link
Author

viphat commented Nov 15, 2017

sql = """
  SELECT * FROM vessels_arrival_departure_time(
    ARRAY[#{imos.map { |e| "'" + e.to_s + "'" }.join(',')}],
    #{timestamp.nil? ? 'NULL' : '\'' + timestamp + '\''},
    #{port_locode.nil? ? 'NULL' : '\'' + port_locode + '\''})
"""
ActiveRecord::Base.connection.execute(sql)

response =
  _get_port_vessels.map do |record|
    {
      imo: record['imo'],
      mmsi: record['mmsi'],
      vessel_name: record['vessel_name'],
      voyage_number: record['voyage_number'],
      port_locode: record['locode'],
      event_name: record['event_name'],
      event_time: record['event_time']
    }
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment