Connection

Ryun Shofner edited this page May 5, 2016 · 9 revisions

Connection is a 1 to 1 mapping to the postgres client/server messaging protocol.

Connection is used internally by the Client.

Not necessary/recommended to directly instantiate this object under normal scenarios

Technically, you can do anything you want with PostgreSQL using the connection object if you required special lower level access. Let me know if you do use it directly as maybe what you're doing could be wrapped up in the Client api. I studied the protocol for a while implementing this and the documentation is pretty solid. If you're already familiar you should be right at home. Have fun looking up the oids for the datatypes in your bound queries

There are a few minor variations from the protocol:

  • The connection only supports 'text' mode right now.
  • Renamed 'passwordMessage' to 'password'
  • Renamed 'startupMessage' to 'startup'
  • Renamed 'errorResponse' to 'error'
  • Renamed 'noticeResponse' to 'notice'

The reason for the renamings is 90% of the message names in the protocol do no contain "message" "request" "response" or anything similar, and I feel it's a bit redundant to send a "passwordMessage message." But then again...I do say ATM machine.

Anyways...using a connection directly is a pretty verbose and cumbersome affair. Here's an example of executing a PostgreSQL-compliant prepared query using the Connection api directly.

note: this works and is taken directly from an integration test; however, it doesn't include error handling

    var con = new Connection({stream: new net.Stream()});

    con.connect('5432','localhost');

    con.once('connect', function() {

      con.startup({
        user: username,
        database: database
      });

      con.once('readyForQuery', function() {

        con.query('create temp table ids(id integer)');

        con.once('readyForQuery', function() {

          con.query('insert into ids(id) values(1); insert into ids(id) values(2);');

          con.once('readyForQuery', function() {

            con.parse({
              text: 'select * from ids'
            });
            con.flush();

            con.once('parseComplete', function() {
              con.bind();
              con.flush();
            });

            con.once('bindComplete', function() {
              con.execute();
              con.flush();
            });

            con.once('commandComplete', function() {
              con.sync();
            });

            con.once('readyForQuery', function() {
              con.end();
            });
          });
        });
      });
    });

◄ Back (API - pg.pools) Next (Prepared Statements) ►