6

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?

Yaki Klein
  • 3,978
  • 3
  • 37
  • 34

2 Answers2

4

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.

Yaki Klein
  • 3,978
  • 3
  • 37
  • 34
  • 1
    nice question. I wrote same kind of example to post it but I saw your question and got it all – Nulik Jan 28 '17 at 17:03
0

If you are looking for another potential solution to the issue of passing in data combined in types, consider using json. Since json is easily handled in Javascript (and many other languages), it is easy enough to handle.

Tycholiz
  • 1,102
  • 4
  • 17
  • 33