Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgres composite type on node-postgres

Say I have the following postgreSQL composite type:

CREATE TYPE myType AS(
  id  bigint,
  name  text,
);

and a stored procedure that excepts that type:

CREATE FUNCTION myFunction(mt myType){
//do some stuff
}

I would like to call this procedure from Node-js using node-postgres module.

var pg = require('pg');
var connectionString = "connection string";
pg.connect(connectionString, function(err, client, done) {
   client.query('SELECT myFunction($1)', [some value],   
      function(err, result) {
      // do stuff
      done();
    });
});

How do i create such a type in JS? Is there a way to pass a type from Node to a Postgres stored procedure?

like image 659
Yaki Klein Avatar asked Mar 29 '15 19:03

Yaki Klein


People also ask

How to create composite type in PostgreSQL?

Constructing Composite Values. To write a composite value as a literal constant, enclose the field values within parentheses and separate them by commas. You can put double quotes around any field value, and must do so if it contains commas or parentheses. (More details appear below.)

What is composite key in PostgreSQL?

A composite key in SQL can be defined as a combination of multiple columns, and these columns are used to identify all the rows that are involved uniquely. Even though a single column can't identify any row uniquely, a combination of over one column can uniquely identify any record.

What is a node in PostgreSQL?

Essentially, node-postgres is a collection of Node. js modules for interfacing with a PostgreSQL database. Among the many features node-postgres supports include callbacks, promises, async/await, connection pooling, prepared statements, cursors, rich type parsing, and C/C++ bindings.


1 Answers

After some more work i found a solution to this problem.

var pg = require('pg');
var connectionString = "connection string";

var myType = [
  12345,
  'you'
];
pg.connect(connectionString, function(err, client, done) {
   client.query('SELECT myFunction($1::myType)', 
     ['(' + myType.join(',') + ')' ],   
     function(err, result) {
      // do stuff
    done();
   });
});

The join will return this: 12345,you. When adding the bracts it will create a string that will look like this '(12345,'you')', in the Postgres DB it will get cast to myType.

like image 125
Yaki Klein Avatar answered Nov 15 '22 05:11

Yaki Klein