PostgreSQL
 SQL >> Database >  >> RDS >> PostgreSQL

Scrivere una funzione PL/pgSQL che restituisce righe da una vista dinamica

Qualcosa del genere dovrebbe funzionare:

CREATE OR REPLACE FUNCTION tt_query(orig_name regclass, data_tt timestamp) RETURNS SETOF record AS $func$ BEGIN EXECUTE 'CREATE OR REPLACE TEMP VIEW tmp as select * from ' || orig_name || ' where trigger_changed >' || quote_literal(data_tt) || ' ORDER BY trigger_changed DESC'; -- altro lavoro sulla vista tmp -- restituisci le righe della vista temp RETURN QUERY SELECT * FROM tmp; END $func$ LANGUAGE plpgsql; 
  • Il tipo di identificatore di oggetto regclass protegge automaticamente dalla SQL injection.
  • Evita la vecchia sintassi var ALIAS for $1 e dichiara invece i nomi dei parametri.
  • Eviterei la parola quasi riservata temp come identificatore e userei tmp.
  • RETURN QUERY restituisce un insieme, ma poiché stai restituendo record anonimi, Postgres richiede una lista di definizione delle colonne a ogni chiamata, cosa piuttosto scomoda.
SELECT * FROM tt_query('tbl_name', '2014-02-15 12:00') AS f(col1 int, col2 text, ...);

Approccio migliore: se il tipo di ritorno varia in base alla tabella, dichiara il parametro come polimorfico e lascia che Postgres deduca il tipo di riga della tabella:

CREATE OR REPLACE FUNCTION tt_query(orig_name anyelement, data_tt timestamp) RETURNS SETOF anyelement AS $func$ BEGIN EXECUTE format('CREATE OR REPLACE TEMP VIEW tmp AS SELECT * FROM %s WHERE trigger_changed > %L ORDER BY trigger_changed DESC' ,pg_typeof(orig_name) ,data_tt); RETURN QUERY SELECT * FROM tmp; END $func$ LANGUAGE plpgsql; 

Chiamala semplicemente:

SELECT * FROM tt_query(NULL::tbl_name, '2014-02-15 12:00'); 

Qui format() gestisce la costruzione sicura e ordinata delle stringhe con %s e %L.