• This repository has been archived on 04/Jun/2024
  • Stars
    star
    247
  • Rank 164,117 (Top 4 %)
  • Language
    JavaScript
  • Created about 10 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Native (C/C++) bindings to PostgreSQL with sync and async options.

node-pg-native

Build Status

High performance native bindings between node.js and PostgreSQL via libpq with a simple API.

install

You need PostgreSQL client libraries & tools installed. An easy way to check is to type pg_config. If pg_config is in your path, you should be good to go. If it's not in your path you'll need to consult operating specific instructions on how to go about getting it there.

Some ways I've done it in the past:

  • On macOS: brew install libpq
  • On Ubuntu/Debian: apt-get install libpq-dev g++ make
  • On RHEL/CentOS: yum install postgresql-devel
  • On Windows:
  1. Install Visual Studio C++ (successfully built with Express 2010). Express is free.
  2. Install PostgreSQL (http://www.postgresql.org/download/windows/)
  3. Add your Postgre Installation's bin folder to the system path (i.e. C:\Program Files\PostgreSQL\9.3\bin).
  4. Make sure that both libpq.dll and pg_config.exe are in that folder.

Afterwards pg_config should be in your path. Then...

$ npm i pg-native

use

async

var Client = require('pg-native')

var client = new Client();
client.connect(function(err) {
  if(err) throw err

  //text queries
  client.query('SELECT NOW() AS the_date', function(err, rows) {
    if(err) throw err

    console.log(rows[0].the_date) //Tue Sep 16 2014 23:42:39 GMT-0400 (EDT)

    //parameterized statements
    client.query('SELECT $1::text as twitter_handle', ['@briancarlson'], function(err, rows) {
      if(err) throw err

      console.log(rows[0].twitter_handle) //@briancarlson
    })

    //prepared statements
    client.prepare('get_twitter', 'SELECT $1::text as twitter_handle', 1, function(err) {
      if(err) throw err

      //execute the prepared, named statement
      client.execute('get_twitter', ['@briancarlson'], function(err, rows) {
        if(err) throw err

        console.log(rows[0].twitter_handle) //@briancarlson

        //execute the prepared, named statement again
        client.execute('get_twitter', ['@realcarrotfacts'], function(err, rows) {
          if(err) throw err

          console.log(rows[0].twitter_handle) //@realcarrotfacts
          
          client.end(function() {
            console.log('ended')
          })
        })
      })
    })
  })
})

sync

Because pg-native is bound to libpq it is able to provide sync operations for both connecting and queries. This is a bad idea in non-blocking systems like web servers, but is exteremly convienent in scripts and bootstrapping applications - much the same way fs.readFileSync comes in handy.

var Client = require('pg-native')

var client = new Client()
client.connectSync()

//text queries
var rows = client.querySync('SELECT NOW() AS the_date')
console.log(rows[0].the_date) //Tue Sep 16 2014 23:42:39 GMT-0400 (EDT)

//parameterized queries
var rows = client.querySync('SELECT $1::text as twitter_handle', ['@briancarlson'])
console.log(rows[0].twitter_handle) //@briancarlson

//prepared statements
client.prepareSync('get_twitter', 'SELECT $1::text as twitter_handle', 1)

var rows = client.executeSync('get_twitter', ['@briancarlson'])
console.log(rows[0].twitter_handle) //@briancarlson

var rows = client.executeSync('get_twitter', ['@realcarrotfacts'])
console.log(rows[0].twitter_handle) //@realcarrotfacts

api

constructor

  • constructor Client()

Constructs and returns a new Client instance

async functions

  • client.connect(<params:string>, callback:function(err:Error))

Connect to a PostgreSQL backend server.

params is optional and is in any format accepted by libpq. The connection string is passed as is to libpq, so any format supported by libpq will be supported here. Likewise, any format unsupported by libpq will not work. If no parameters are supplied libpq will use environment variables to connect.

Returns an Error to the callback if the connection was unsuccessful. callback is required.

example
var client = new Client()
client.connect(function(err) {
  if(err) throw err
  
  console.log('connected!')
})

var client2 = new Client()
client2.connect('postgresql://user:password@host:5432/database?param=value', function(err) {
  if(err) throw err
  
  console.log('connected with connection string!')
})
  • client.query(queryText:string, <values:string[]>, callback:Function(err:Error, rows:Object[]))

Execute a query with the text of queryText and optional parameters specified in the values array. All values are passed to the PostgreSQL backend server and executed as a parameterized statement. The callback is required and is called with an Error object in the event of a query error, otherwise it is passed an array of result objects. Each element in this array is a dictionary of results with keys for column names and their values as the values for those columns.

example
var client = new Client()
client.connect(function(err) {
  if (err) throw err
  
  client.query('SELECT NOW()', function(err, rows) {
    if (err) throw err
    
    console.log(rows) // [{ "now": "Tue Sep 16 2014 23:42:39 GMT-0400 (EDT)" }]
    
    client.query('SELECT $1::text as name', ['Brian'], function(err, rows) {
      if (err) throw err
      
      console.log(rows) // [{ "name": "Brian" }]
      
      client.end()
    })
  })
})
  • client.prepare(statementName:string, queryText:string, nParams:int, callback:Function(err:Error))

Prepares a named statement for later execution. You must supply the name of the statement via statementName, the command to prepare via queryText and the number of parameters in queryText via nParams. Calls the callback with an Error if there was an error.

example
var client = new Client()
client.connect(function(err) {
  if(err) throw err
  
  client.prepare('prepared_statement', 'SELECT $1::text as name', 1, function(err) {
    if(err) throw err
    
    console.log('statement prepared')
    client.end()
  })
  
})
  • client.execute(statementName:string, <values:string[]>, callback:Function(err:err, rows:Object[]))

Executes a previously prepared statement on this client with the name of statementName, passing it the optional array of query parameters as a values array. The callback is mandatory and is called with and Error if the execution failed, or with the same array of results as would be passed to the callback of a client.query result.

example
var client = new Client()
client.connect(function(err) {
  if(err) throw err
  
  client.prepare('i_like_beans', 'SELECT $1::text as beans', 1, function(err) {
    if(err) throw err
    
    client.execute('i_like_beans', ['Brak'], function(err, rows) {
      if(err) throw err
      
      console.log(rows) // [{ "i_like_beans": "Brak" }]
      client.end()
    })
  })
})
  • client.end(<callback:Function()>

Ends the connection. Calls the optional callback when the connection is terminated.

example
var client = new Client()
client.connect(function(err) {
  if(err) throw err
  client.end(function() {
    console.log('client ended') // client ended
  })
})
  • client.cancel(callback:function(err))

Cancels the active query on the client. Callback receives an error if there was an error sending the cancel request.

example
var client = new Client()
client.connectSync()
//sleep for 100 seconds
client.query('select pg_sleep(100)', function(err) {
  console.log(err) // [Error: ERROR: canceling statement due to user request]
})
client.cancel(function(err) {
  console.log('cancel dispatched')
})

sync functions

  • client.connectSync(params:string)

Connect to a PostgreSQL backend server. Params is in any format accepted by libpq. Throws an Error if the connection was unsuccessful.

  • client.querySync(queryText:string, <values:string[]>) -> results:Object[]

Executes a query with a text of queryText and optional parameters as values. Uses a parameterized query if values are supplied. Throws an Error if the query fails, otherwise returns an array of results.

  • client.prepareSync(statementName:string, queryText:string, nParams:int)

Prepares a name statement with name of statementName and a query text of queryText. You must specify the number of params in the query with the nParams argument. Throws an Error if the statement is un-preparable, otherwise returns an array of results.

  • client.executeSync(statementName:string, <values:string[]>) -> results:Object[]

Executes a previously prepared statement on this client with the name of statementName, passing it the optional array of query paramters as a values array. Throws an Error if the execution fails, otherwas returns an array of results.

testing

$ npm test

To run the tests you need a PostgreSQL backend reachable by typing psql with no connection parameters in your terminal. The tests use environment variables to connect to the backend.

An example of supplying a specific host the tests:

$ PGHOST=blabla.mydatabasehost.com npm test

license

The MIT License (MIT)

Copyright (c) 2014 Brian M. Carlson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

node-postgres

PostgreSQL client for node.js.
JavaScript
12,166
star
2

node-sql

SQL generation for node.js
JavaScript
1,048
star
3

node-pg-copy-streams

COPY FROM / COPY TO for node-postgres. Stream from one database to another, and stuff.
JavaScript
331
star
4

node-pg-query-stream

Query results from node-postgres as a readable (object) stream
JavaScript
311
star
5

node-pg-types

Type parsing for node-postgres
JavaScript
270
star
6

node-forky

Forky manages your cluster module stuff for you so you don't have to pull your hair out.
JavaScript
254
star
7

node-pg-pool

A connection pool for node-postgres
JavaScript
180
star
8

jade-mode

Emacs major mode for jade template highlighting
Emacs Lisp
156
star
9

node-domain-middleware

Middleware to attach your express app's request & response to a domain. No more process.uncaughtException nonsense.
JavaScript
120
star
10

node-libpq

Simple, low level native bindings to PostgreSQL's libpq from node.js
JavaScript
112
star
11

node-postgres-docs

Documentation for node-postgres
JavaScript
97
star
12

node-pg-query

Simple helper to run queries with node-postgres
JavaScript
79
star
13

node-pg-cursor

Query cursor extension for node-postgres
JavaScript
78
star
14

node-okay

bubble errors back up your big ol' nested callback chain
JavaScript
69
star
15

node-postgres-pure

node-postgres without any of the C/C++ stuff
JavaScript
59
star
16

node-pdf-text

extract text from a pdf as an array of text blocks
JavaScript
46
star
17

node-omf

ORANGE MOCHA FRAPPUCCINO
JavaScript
40
star
18

node-relational

ORM with an emphasis on the O, the R, and the M.
CoffeeScript
37
star
19

node-nsqueue

node.js client for nsq
JavaScript
23
star
20

node-agi

node.js AGI (Asterisk Gateway Interface)
JavaScript
21
star
21

stylus-blueprint

Blueprint ported to stylus
JavaScript
17
star
22

node-deprecate

Mark a method as deprecated by printing a warning to the console the first time it's called
JavaScript
14
star
23

node-hacker-news-parser

Parses the insanely shitty html of hacker news comments into JSON
JavaScript
13
star
24

node-buffer-writer

A very fast buffer writer with expandable memory to reduce memory use
JavaScript
12
star
25

node-heroku-env

Because sometimes I wanna connect my local box to heroku postgres.
JavaScript
11
star
26

node-auto-deploy

my little auto-deploy script
JavaScript
11
star
27

node-querybox

A little helper to run queries stored in .sql files
JavaScript
10
star
28

node-packet-reader

JavaScript
10
star
29

indexeddb-performance-demo

Demo of simultaneous read/write speed vs. read only speed of indexeddb
JavaScript
8
star
30

node-ami

Asterisk AMI client for node.js
JavaScript
7
star
31

keeper

ORM for node.js
JavaScript
7
star
32

hipchat-eraser

Erase your 1 on 1 HipChat history
JavaScript
7
star
33

node-proxynova

node.js interface to the proxynova.com proxy list
JavaScript
6
star
34

vim-config

mah vim config
Vim Script
6
star
35

postgres-session

node-postgres backed session store for node.js express (connect middleware)
JavaScript
5
star
36

node-pg-parse-float

Add parse-float functionality back to node-postgres
JavaScript
5
star
37

upstart-scripts

Place to keep various upstart scripts so I stop forgetting how to make them
5
star
38

node-pg-pipe

Very efficient row by row streaming between PostgreSQL tables. Uses libpq.
JavaScript
4
star
39

node-pg-writable

Create a writable stream which very quickly writes an array of values to a table in postgres
JavaScript
4
star
40

fluxed

tiny flux implementation
JavaScript
3
star
41

bencher

node.js benchmarking & performance analysis utilities
JavaScript
3
star
42

node-array-reader

Search forwards and backwards in an array of strings
JavaScript
3
star
43

hyperterm-focus-reporting

Adds focus reporting to hyperterm for tmux & vim support
JavaScript
3
star
44

json-with-typed-arrays

JSON stringify/parse with typed array support
JavaScript
2
star
45

react-starter

Because setting this stuff up is a nightmare
JavaScript
2
star
46

node-kafka-protocol

JavaScript
2
star
47

node-logged

Simple logging for node.js
JavaScript
2
star
48

deadblackhearts.com

Band Website
Ruby
2
star
49

tailed

`tail -f` for node.js
JavaScript
2
star
50

node-pg-stream

A readable stream (objectmode) that gives you postgres rows
JavaScript
2
star
51

drain

A testing helper for node.js async code
2
star
52

unit.js

unit testing for javascript
JavaScript
2
star
53

node-ansible-tower-client

Simple client to ansible tower to run a job based on a template name
JavaScript
2
star
54

node-gelf-encode

Encode GELF json to proper GELF binary
JavaScript
1
star
55

myiptables

My iptables configuration file
1
star
56

memory-socket

In-memory node.js socket for use in testing
JavaScript
1
star
57

wasm-hello-world

HTML
1
star
58

git-nits

Some bits and bops I use to help me suck less at git
Shell
1
star
59

node-pg-copy-table

Copy tables from one database to another with streams and queries
JavaScript
1
star
60

node-dogpile

Dogpile cache an expensive async function
JavaScript
1
star
61

node-level-readable

Fast, efficient leveldb readable stream over the network
JavaScript
1
star
62

node-postgres-bench

Benchmark old & new node postgres
JavaScript
1
star
63

brianc.github.com

stuff stuff. gimme some stuff.
1
star
64

install-scripts

install scripts for cloud servers because chef is like whaaaa??
Shell
1
star
65

node-gelf-parser

Parse GELF binary using a through-stream
JavaScript
1
star
66

express-skeleton

Skeleton app for express with jade & sass
JavaScript
1
star
67

node-buffer-slice

slice a buffer into an array of sub-buffers
JavaScript
1
star
68

dotfiles

Mah .files
Lua
1
star
69

test-dir

Require directories full of files for testing.
JavaScript
1
star
70

proxied

A stream http proxy server with http request pause() support
CoffeeScript
1
star
71

pdbh

private.deadblackhearts.com
JavaScript
1
star
72

xo

kiss hug - exceptionally tiny event-bus framework
CoffeeScript
1
star
73

node-make-emitter

event emitter constructor factory
JavaScript
1
star
74

node-httper

Little wrapper around request to make consuming an external service a bit easier.
JavaScript
1
star
75

mvp.py

mvp.py
Python
1
star
76

node-pg-bench

node-postgres benchmarking utility
JavaScript
1
star