Return id if a row exists, INSERT otherwise

前端 未结 4 1962
盖世英雄少女心
盖世英雄少女心 2021-01-04 11:41

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 inser

4条回答
  •  独厮守ぢ
    2021-01-04 12:40

    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;      
    
      };
    
    });
    

提交回复
热议问题