1

I am writing a unit test for my PostgreSQL functionality. This starts with inserting data in the database and then calling a certain function. However, because I use auto-incrementing IDs, I cannot know what parameter to put in my function call.

I want to be able to do something like this:

INSERT INTO myTable ...;

SELECT id FROM myTable INTO l_id;

SELECT my_function(l_id);

Updates

  • I am using an SQL script, not PL/pgSQL
  • In MySQL I can do this: SELECT @id:=itemid FROM myTable;, then later on, I can use @id anywhere I like.
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195

3 Answers3

1

INSERT in Postgres returns an OID, which you can get in a number of ways

  • Using the returning clause in normal SQL, e.g.

INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets') RETURNING did;

  • using the GET DIAGNOSTICS api in PL-PGSQL

  • using the return function in a helper library (syntax depending on library).

In your case, you could do something like

with res as (
INSERT INTO my_table (id, ...) VALUES(x,..)
RETURNING id)
SELECT my_function(res.id);
Stev_k
  • 2,118
  • 3
  • 22
  • 36
1
DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp ;
SET search_path=tmp;

CREATE TABLE mytab
    ( id INTEGER NOT NULL PRIMARY KEY
    );
INSERT INTO mytab (id) SELECT gs FROM generate_series(1,10) gs;

CREATE OR REPLACE FUNCTION tmp.myfunc ( _int  integer )
RETURNS text AS
$func$

DECLARE ret text;

BEGIN
    ret = 'OMG_' || _int::text;
RETURN ret;
END;
$func$
LANGUAGE 'plpgsql'
    ;

SELECT myfunc(1);

SELECT myfunc(mt.id)
FROM mytab mt
    ;

Also, for smaller things you could use psql's \gset command : (link to documentation)

wildplasser
  • 43,142
  • 8
  • 66
  • 109
0

Here I found mentioning of the DO block, which seems to work as a anonymous function. I fixed it like this:

INSERT ...

DO $$
DECLARE
    l_id integer;
BEGIN
    SELECT id FROM table INTO l_id;
    SELECT myFunction(l_id);
END$$;
Community
  • 1
  • 1
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195