CREATE OR REPLACE FUNCTION dfms.upsert_ncm_execution(p_schema_name text, p_fleet_id INTEGER, p_ncm_number INTEGER, p_version text, p_hostname text, p_process_id INTEGER, p_execution_id INTEGER)
RETURNS INTEGER AS
$BODY$
DECLARE
record_found BOOLEAN;
execution_id INTEGER;
BEGIN
EXECUTE 'SELECT count(*) FROM ' || p_schema_name || '.ncm_executions WHERE fleet_id = $1 AND ncm_number = $2' INTO record_found USING p_fleet_id, p_ncm_number;
IF record_found THEN
EXECUTE 'UPDATE ' || p_schema_name || '.ncm_executions SET execution_id = execution_id + 1 WHERE fleet_id = $1 AND ncm_number = $2' USING p_fleet_id, p_ncm_number;
ELSE
BEGIN
EXECUTE 'INSERT INTO ' || p_schema_name || '.ncm_executions(fleet_id, ncm_number, version, hostname, process_id, execution_id) VALUES($1, $2, $3, $4, $5, $6)' USING p_fleet_id, p_ncm_number, p_version, p_hostname, p_process_id, p_execution_id;
EXCEPTION WHEN unique_violation THEN
-- do nothing
END;
END IF;
EXECUTE 'SELECT execution_id FROM ' || p_schema_name || '.ncm_executions WHERE fleet_id = $1 AND ncm_number = $2' INTO execution_id USING p_fleet_id, p_ncm_number;
RETURN execution_id;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
|