Return id if a row exists, INSERT otherwise

node.js, postgresql, sql, sql-insert

Solution

I would suggest doing the checking on the database side and just returning the id to nodejs.

Example:

CREATE OR REPLACE FUNCTION foo(p_param1 tableFoo.attr1%TYPE, p_param2 tableFoo.attr1%TYPE) RETURNS tableFoo.id%TYPE AS $$
  DECLARE
  v_id tableFoo.pk%TYPE;
  BEGIN
    SELECT id
    INTO v_id
    FROM tableFoo
    WHERE attr1 = p_param1
    AND attr2 = p_param2;

    IF v_id IS NULL THEN
      INSERT INTO tableFoo(id, attr1, attr2) VALUES (DEFAULT, p_param1, p_param2)
      RETURNING id INTO v_id;
    END IF;

    RETURN v_id:

  END;
$$ LANGUAGE plpgsql;

And than on the Node.js-side (i'm using node-postgres in this example):

var pg = require('pg');
pg.connect('someConnectionString', function(connErr, client){

  //do some errorchecking here

  client.query('SELECT id FROM foo($1, $2);', ['foo', 'bar'], function(queryErr, result){

    //errorchecking

    var id = result.rows[0].id;      

  };

});

Problem

I'm writing a function in node.js to query a PostgreSQL table. If the row exists, I want to return the id column from the row. If it doesn't exist, I want to insert it and return the id (`insert into ... returning id`). I've been trying variations of `case` and `if else` statements and can't seem to get it to work.

Original source

Related problems