Downgrade to prettier@1.x to support node@8.x

This commit is contained in:
Brian M. Carlson 2020-04-10 11:15:42 -05:00
parent c13cf81ee8
commit 6353affeca
137 changed files with 1564 additions and 1417 deletions

View File

@ -1,6 +0,0 @@
{
"semi": false,
"printWidth": 120,
"trailingComma": "es5",
"singleQuote": true
}

View File

@ -23,6 +23,13 @@
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^3.1.2",
"lerna": "^3.19.0",
"prettier": "^2.0.4"
"prettier": "1.19.1"
},
"prettier": {
"semi": false,
"printWidth": 120,
"arrowParens": "always",
"trailingComma": "es5",
"singleQuote": true
}
}

View File

@ -25,18 +25,18 @@ function Cursor(text, values, config) {
util.inherits(Cursor, EventEmitter)
Cursor.prototype._ifNoData = function () {
Cursor.prototype._ifNoData = function() {
this.state = 'idle'
this._shiftQueue()
}
Cursor.prototype._rowDescription = function () {
Cursor.prototype._rowDescription = function() {
if (this.connection) {
this.connection.removeListener('noData', this._ifNoData)
}
}
Cursor.prototype.submit = function (connection) {
Cursor.prototype.submit = function(connection) {
this.connection = connection
this._portal = 'C_' + nextUniqueID++
@ -75,13 +75,13 @@ Cursor.prototype.submit = function (connection) {
con.once('rowDescription', this._rowDescription)
}
Cursor.prototype._shiftQueue = function () {
Cursor.prototype._shiftQueue = function() {
if (this._queue.length) {
this._getRows.apply(this, this._queue.shift())
}
}
Cursor.prototype._closePortal = function () {
Cursor.prototype._closePortal = function() {
// because we opened a named portal to stream results
// we need to close the same named portal. Leaving a named portal
// open can lock tables for modification if inside a transaction.
@ -90,19 +90,19 @@ Cursor.prototype._closePortal = function () {
this.connection.sync()
}
Cursor.prototype.handleRowDescription = function (msg) {
Cursor.prototype.handleRowDescription = function(msg) {
this._result.addFields(msg.fields)
this.state = 'idle'
this._shiftQueue()
}
Cursor.prototype.handleDataRow = function (msg) {
Cursor.prototype.handleDataRow = function(msg) {
const row = this._result.parseRow(msg.fields)
this.emit('row', row, this._result)
this._rows.push(row)
}
Cursor.prototype._sendRows = function () {
Cursor.prototype._sendRows = function() {
this.state = 'idle'
setImmediate(() => {
const cb = this._cb
@ -118,26 +118,26 @@ Cursor.prototype._sendRows = function () {
})
}
Cursor.prototype.handleCommandComplete = function (msg) {
Cursor.prototype.handleCommandComplete = function(msg) {
this._result.addCommandComplete(msg)
this._closePortal()
}
Cursor.prototype.handlePortalSuspended = function () {
Cursor.prototype.handlePortalSuspended = function() {
this._sendRows()
}
Cursor.prototype.handleReadyForQuery = function () {
Cursor.prototype.handleReadyForQuery = function() {
this._sendRows()
this.state = 'done'
this.emit('end', this._result)
}
Cursor.prototype.handleEmptyQuery = function () {
Cursor.prototype.handleEmptyQuery = function() {
this.connection.sync()
}
Cursor.prototype.handleError = function (msg) {
Cursor.prototype.handleError = function(msg) {
this.connection.removeListener('noData', this._ifNoData)
this.connection.removeListener('rowDescription', this._rowDescription)
this.state = 'error'
@ -159,7 +159,7 @@ Cursor.prototype.handleError = function (msg) {
this.connection.sync()
}
Cursor.prototype._getRows = function (rows, cb) {
Cursor.prototype._getRows = function(rows, cb) {
this.state = 'busy'
this._cb = cb
this._rows = []
@ -173,7 +173,7 @@ Cursor.prototype._getRows = function (rows, cb) {
// users really shouldn't be calling 'end' here and terminating a connection to postgres
// via the low level connection.end api
Cursor.prototype.end = util.deprecate(function (cb) {
Cursor.prototype.end = util.deprecate(function(cb) {
if (this.state !== 'initialized') {
this.connection.sync()
}
@ -181,7 +181,7 @@ Cursor.prototype.end = util.deprecate(function (cb) {
this.connection.end()
}, 'Cursor.end is deprecated. Call end on the client itself to end a connection to the database.')
Cursor.prototype.close = function (cb) {
Cursor.prototype.close = function(cb) {
if (!this.connection || this.state === 'done') {
if (cb) {
return setImmediate(cb)
@ -192,13 +192,13 @@ Cursor.prototype.close = function (cb) {
this._closePortal()
this.state = 'done'
if (cb) {
this.connection.once('readyForQuery', function () {
this.connection.once('readyForQuery', function() {
cb()
})
}
}
Cursor.prototype.read = function (rows, cb) {
Cursor.prototype.read = function(rows, cb) {
if (this.state === 'idle') {
return this._getRows(rows, cb)
}

View File

@ -3,51 +3,51 @@ const Cursor = require('../')
const pg = require('pg')
const text = 'SELECT generate_series as num FROM generate_series(0, 50)'
describe('close', function () {
beforeEach(function (done) {
describe('close', function() {
beforeEach(function(done) {
const client = (this.client = new pg.Client())
client.connect(done)
})
this.afterEach(function (done) {
this.afterEach(function(done) {
this.client.end(done)
})
it('can close a finished cursor without a callback', function (done) {
it('can close a finished cursor without a callback', function(done) {
const cursor = new Cursor(text)
this.client.query(cursor)
this.client.query('SELECT NOW()', done)
cursor.read(100, function (err) {
cursor.read(100, function(err) {
assert.ifError(err)
cursor.close()
})
})
it('closes cursor early', function (done) {
it('closes cursor early', function(done) {
const cursor = new Cursor(text)
this.client.query(cursor)
this.client.query('SELECT NOW()', done)
cursor.read(25, function (err) {
cursor.read(25, function(err) {
assert.ifError(err)
cursor.close()
})
})
it('works with callback style', function (done) {
it('works with callback style', function(done) {
const cursor = new Cursor(text)
const client = this.client
client.query(cursor)
cursor.read(25, function (err, rows) {
cursor.read(25, function(err, rows) {
assert.ifError(err)
assert.strictEqual(rows.length, 25)
cursor.close(function (err) {
cursor.close(function(err) {
assert.ifError(err)
client.query('SELECT NOW()', done)
})
})
})
it('is a no-op to "close" the cursor before submitting it', function (done) {
it('is a no-op to "close" the cursor before submitting it', function(done) {
const cursor = new Cursor(text)
cursor.close(done)
})

View File

@ -5,14 +5,14 @@ const pg = require('pg')
const text = 'SELECT generate_series as num FROM generate_series(0, 4)'
describe('error handling', function () {
it('can continue after error', function (done) {
describe('error handling', function() {
it('can continue after error', function(done) {
const client = new pg.Client()
client.connect()
const cursor = client.query(new Cursor('asdfdffsdf'))
cursor.read(1, function (err) {
cursor.read(1, function(err) {
assert(err)
client.query('SELECT NOW()', function (err) {
client.query('SELECT NOW()', function(err) {
assert.ifError(err)
client.end()
done()
@ -27,11 +27,11 @@ describe('read callback does not fire sync', () => {
client.connect()
const cursor = client.query(new Cursor('asdfdffsdf'))
let after = false
cursor.read(1, function (err) {
cursor.read(1, function(err) {
assert(err, 'error should be returned')
assert.strictEqual(after, true, 'should not call read sync')
after = false
cursor.read(1, function (err) {
cursor.read(1, function(err) {
assert(err, 'error should be returned')
assert.strictEqual(after, true, 'should not call read sync')
client.end()
@ -47,13 +47,13 @@ describe('read callback does not fire sync', () => {
client.connect()
const cursor = client.query(new Cursor('SELECT NOW()'))
let after = false
cursor.read(1, function (err) {
cursor.read(1, function(err) {
assert(!err)
assert.strictEqual(after, true, 'should not call read sync')
cursor.read(1, function (err) {
cursor.read(1, function(err) {
assert(!err)
after = false
cursor.read(1, function (err) {
cursor.read(1, function(err) {
assert(!err)
assert.strictEqual(after, true, 'should not call read sync')
client.end()
@ -66,16 +66,16 @@ describe('read callback does not fire sync', () => {
})
})
describe('proper cleanup', function () {
it('can issue multiple cursors on one client', function (done) {
describe('proper cleanup', function() {
it('can issue multiple cursors on one client', function(done) {
const client = new pg.Client()
client.connect()
const cursor1 = client.query(new Cursor(text))
cursor1.read(8, function (err, rows) {
cursor1.read(8, function(err, rows) {
assert.ifError(err)
assert.strictEqual(rows.length, 5)
const cursor2 = client.query(new Cursor(text))
cursor2.read(8, function (err, rows) {
cursor2.read(8, function(err, rows) {
assert.ifError(err)
assert.strictEqual(rows.length, 5)
client.end()

View File

@ -4,58 +4,58 @@ const pg = require('pg')
const text = 'SELECT generate_series as num FROM generate_series(0, 5)'
describe('cursor', function () {
beforeEach(function (done) {
describe('cursor', function() {
beforeEach(function(done) {
const client = (this.client = new pg.Client())
client.connect(done)
this.pgCursor = function (text, values) {
this.pgCursor = function(text, values) {
return client.query(new Cursor(text, values || []))
}
})
afterEach(function () {
afterEach(function() {
this.client.end()
})
it('fetch 6 when asking for 10', function (done) {
it('fetch 6 when asking for 10', function(done) {
const cursor = this.pgCursor(text)
cursor.read(10, function (err, res) {
cursor.read(10, function(err, res) {
assert.ifError(err)
assert.strictEqual(res.length, 6)
done()
})
})
it('end before reading to end', function (done) {
it('end before reading to end', function(done) {
const cursor = this.pgCursor(text)
cursor.read(3, function (err, res) {
cursor.read(3, function(err, res) {
assert.ifError(err)
assert.strictEqual(res.length, 3)
done()
})
})
it('callback with error', function (done) {
it('callback with error', function(done) {
const cursor = this.pgCursor('select asdfasdf')
cursor.read(1, function (err) {
cursor.read(1, function(err) {
assert(err)
done()
})
})
it('read a partial chunk of data', function (done) {
it('read a partial chunk of data', function(done) {
const cursor = this.pgCursor(text)
cursor.read(2, function (err, res) {
cursor.read(2, function(err, res) {
assert.ifError(err)
assert.strictEqual(res.length, 2)
cursor.read(3, function (err, res) {
cursor.read(3, function(err, res) {
assert(!err)
assert.strictEqual(res.length, 3)
cursor.read(1, function (err, res) {
cursor.read(1, function(err, res) {
assert(!err)
assert.strictEqual(res.length, 1)
cursor.read(1, function (err, res) {
cursor.read(1, function(err, res) {
assert(!err)
assert.ifError(err)
assert.strictEqual(res.length, 0)
@ -66,14 +66,14 @@ describe('cursor', function () {
})
})
it('read return length 0 past the end', function (done) {
it('read return length 0 past the end', function(done) {
const cursor = this.pgCursor(text)
cursor.read(2, function (err) {
cursor.read(2, function(err) {
assert(!err)
cursor.read(100, function (err, res) {
cursor.read(100, function(err, res) {
assert(!err)
assert.strictEqual(res.length, 4)
cursor.read(100, function (err, res) {
cursor.read(100, function(err, res) {
assert(!err)
assert.strictEqual(res.length, 0)
done()
@ -82,14 +82,14 @@ describe('cursor', function () {
})
})
it('read huge result', function (done) {
it('read huge result', function(done) {
this.timeout(10000)
const text = 'SELECT generate_series as num FROM generate_series(0, 100000)'
const values = []
const cursor = this.pgCursor(text, values)
let count = 0
const read = function () {
cursor.read(100, function (err, rows) {
const read = function() {
cursor.read(100, function(err, rows) {
if (err) return done(err)
if (!rows.length) {
assert.strictEqual(count, 100001)
@ -105,14 +105,14 @@ describe('cursor', function () {
read()
})
it('normalizes parameter values', function (done) {
it('normalizes parameter values', function(done) {
const text = 'SELECT $1::json me'
const values = [{ name: 'brian' }]
const cursor = this.pgCursor(text, values)
cursor.read(1, function (err, rows) {
cursor.read(1, function(err, rows) {
if (err) return done(err)
assert.strictEqual(rows[0].me.name, 'brian')
cursor.read(1, function (err, rows) {
cursor.read(1, function(err, rows) {
assert(!err)
assert.strictEqual(rows.length, 0)
done()
@ -120,9 +120,9 @@ describe('cursor', function () {
})
})
it('returns result along with rows', function (done) {
it('returns result along with rows', function(done) {
const cursor = this.pgCursor(text)
cursor.read(1, function (err, rows, result) {
cursor.read(1, function(err, rows, result) {
assert.ifError(err)
assert.strictEqual(rows.length, 1)
assert.strictEqual(rows, result.rows)
@ -134,7 +134,7 @@ describe('cursor', function () {
})
})
it('emits row events', function (done) {
it('emits row events', function(done) {
const cursor = this.pgCursor(text)
cursor.read(10)
cursor.on('row', (row, result) => result.addRow(row))
@ -144,7 +144,7 @@ describe('cursor', function () {
})
})
it('emits row events when cursor is closed manually', function (done) {
it('emits row events when cursor is closed manually', function(done) {
const cursor = this.pgCursor(text)
cursor.on('row', (row, result) => result.addRow(row))
cursor.on('end', (result) => {
@ -155,21 +155,21 @@ describe('cursor', function () {
cursor.read(3, () => cursor.close())
})
it('emits error events', function (done) {
it('emits error events', function(done) {
const cursor = this.pgCursor('select asdfasdf')
cursor.on('error', function (err) {
cursor.on('error', function(err) {
assert(err)
done()
})
})
it('returns rowCount on insert', function (done) {
it('returns rowCount on insert', function(done) {
const pgCursor = this.pgCursor
this.client
.query('CREATE TEMPORARY TABLE pg_cursor_test (foo VARCHAR(1), bar VARCHAR(1))')
.then(function () {
.then(function() {
const cursor = pgCursor('insert into pg_cursor_test values($1, $2)', ['a', 'b'])
cursor.read(1, function (err, rows, result) {
cursor.read(1, function(err, rows, result) {
assert.ifError(err)
assert.strictEqual(rows.length, 0)
assert.strictEqual(result.rowCount, 1)

View File

@ -2,30 +2,30 @@ const assert = require('assert')
const pg = require('pg')
const Cursor = require('../')
describe('queries with no data', function () {
beforeEach(function (done) {
describe('queries with no data', function() {
beforeEach(function(done) {
const client = (this.client = new pg.Client())
client.connect(done)
})
afterEach(function () {
afterEach(function() {
this.client.end()
})
it('handles queries that return no data', function (done) {
it('handles queries that return no data', function(done) {
const cursor = new Cursor('CREATE TEMPORARY TABLE whatwhat (thing int)')
this.client.query(cursor)
cursor.read(100, function (err, rows) {
cursor.read(100, function(err, rows) {
assert.ifError(err)
assert.strictEqual(rows.length, 0)
done()
})
})
it('handles empty query', function (done) {
it('handles empty query', function(done) {
let cursor = new Cursor('-- this is a comment')
cursor = this.client.query(cursor)
cursor.read(100, function (err, rows) {
cursor.read(100, function(err, rows) {
assert.ifError(err)
assert.strictEqual(rows.length, 0)
done()

View File

@ -31,16 +31,16 @@ function poolQueryPromise(pool, readRowCount) {
})
}
describe('pool', function () {
beforeEach(function () {
describe('pool', function() {
beforeEach(function() {
this.pool = new pg.Pool({ max: 1 })
})
afterEach(function () {
afterEach(function() {
this.pool.end()
})
it('closes cursor early, single pool query', function (done) {
it('closes cursor early, single pool query', function(done) {
poolQueryPromise(this.pool, 25)
.then(() => done())
.catch((err) => {
@ -49,7 +49,7 @@ describe('pool', function () {
})
})
it('closes cursor early, saturated pool', function (done) {
it('closes cursor early, saturated pool', function(done) {
const promises = []
for (let i = 0; i < 10; i++) {
promises.push(poolQueryPromise(this.pool, 25))
@ -62,7 +62,7 @@ describe('pool', function () {
})
})
it('closes exhausted cursor, single pool query', function (done) {
it('closes exhausted cursor, single pool query', function(done) {
poolQueryPromise(this.pool, 100)
.then(() => done())
.catch((err) => {
@ -71,7 +71,7 @@ describe('pool', function () {
})
})
it('closes exhausted cursor, saturated pool', function (done) {
it('closes exhausted cursor, saturated pool', function(done) {
const promises = []
for (let i = 0; i < 10; i++) {
promises.push(poolQueryPromise(this.pool, 100))
@ -84,16 +84,16 @@ describe('pool', function () {
})
})
it('can close multiple times on a pool', async function () {
it('can close multiple times on a pool', async function() {
const pool = new pg.Pool({ max: 1 })
const run = async () => {
const cursor = new Cursor(text)
const client = await pool.connect()
client.query(cursor)
await new Promise((resolve) => {
cursor.read(25, function (err) {
cursor.read(25, function(err) {
assert.ifError(err)
cursor.close(function (err) {
cursor.close(function(err) {
assert.ifError(err)
client.release()
resolve()

View File

@ -1,7 +1,7 @@
'use strict'
const EventEmitter = require('events').EventEmitter
const NOOP = function () {}
const NOOP = function() {}
const removeWhere = (list, predicate) => {
const i = list.findIndex(predicate)
@ -33,10 +33,10 @@ function promisify(Promise, callback) {
}
let rej
let res
const cb = function (err, client) {
const cb = function(err, client) {
err ? rej(err) : res(client)
}
const result = new Promise(function (resolve, reject) {
const result = new Promise(function(resolve, reject) {
res = resolve
rej = reject
})
@ -76,7 +76,7 @@ class Pool extends EventEmitter {
this.options.max = this.options.max || this.options.poolSize || 10
this.options.maxUses = this.options.maxUses || Infinity
this.log = this.options.log || function () {}
this.log = this.options.log || function() {}
this.Client = this.options.Client || Client || require('pg').Client
this.Promise = this.options.Promise || global.Promise
@ -321,7 +321,7 @@ class Pool extends EventEmitter {
// guard clause against passing a function as the first parameter
if (typeof text === 'function') {
const response = promisify(this.Promise, text)
setImmediate(function () {
setImmediate(function() {
return response.callback(new Error('Passing a function as the first parameter to pool.query is not supported'))
})
return response.result

View File

@ -13,10 +13,10 @@ const checkType = (promise) => {
return promise.catch((e) => undefined)
}
describe('Bring your own promise', function () {
describe('Bring your own promise', function() {
it(
'uses supplied promise for operations',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool({ Promise: BluebirdPromise })
const client1 = yield checkType(pool.connect())
client1.release()
@ -30,7 +30,7 @@ describe('Bring your own promise', function () {
it(
'uses promises in errors',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool({ Promise: BluebirdPromise, port: 48484 })
yield checkType(pool.connect())
yield checkType(pool.end())

View File

@ -3,25 +3,25 @@ const describe = require('mocha').describe
const it = require('mocha').it
const Pool = require('../')
describe('Connection strings', function () {
it('pool delegates connectionString property to client', function (done) {
describe('Connection strings', function() {
it('pool delegates connectionString property to client', function(done) {
const connectionString = 'postgres://foo:bar@baz:1234/xur'
const pool = new Pool({
// use a fake client so we can check we're passed the connectionString
Client: function (args) {
Client: function(args) {
expect(args.connectionString).to.equal(connectionString)
return {
connect: function (cb) {
connect: function(cb) {
cb(new Error('testing'))
},
on: function () {},
on: function() {},
}
},
connectionString: connectionString,
})
pool.connect(function (err, client) {
pool.connect(function(err, client) {
expect(err).to.not.be(undefined)
done()
})

View File

@ -54,7 +54,7 @@ describe('connection timeout', () => {
it(
'should handle multiple timeouts',
co.wrap(
function* () {
function*() {
const errors = []
const pool = new Pool({ connectionTimeoutMillis: 1, port: this.port, host: 'localhost' })
for (var i = 0; i < 15; i++) {
@ -142,7 +142,7 @@ describe('connection timeout', () => {
const orgConnect = Client.prototype.connect
let called = false
Client.prototype.connect = function (cb) {
Client.prototype.connect = function(cb) {
// Simulate a failure on first call
if (!called) {
called = true
@ -179,7 +179,7 @@ describe('connection timeout', () => {
let connection = 0
Client.prototype.connect = function (cb) {
Client.prototype.connect = function(cb) {
// Simulate a failure on first call
if (connection === 0) {
connection++

View File

@ -19,7 +19,7 @@ describe('pool ending', () => {
it(
'ends with clients',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool()
const res = yield pool.query('SELECT $1::text as name', ['brianc'])
expect(res.rows[0].name).to.equal('brianc')
@ -29,7 +29,7 @@ describe('pool ending', () => {
it(
'allows client to finish',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool()
const query = pool.query('SELECT $1::text as name', ['brianc'])
yield pool.end()

View File

@ -8,20 +8,20 @@ const it = require('mocha').it
const Pool = require('../')
describe('pool error handling', function () {
it('Should complete these queries without dying', function (done) {
describe('pool error handling', function() {
it('Should complete these queries without dying', function(done) {
const pool = new Pool()
let errors = 0
let shouldGet = 0
function runErrorQuery() {
shouldGet++
return new Promise(function (resolve, reject) {
return new Promise(function(resolve, reject) {
pool
.query("SELECT 'asd'+1 ")
.then(function (res) {
.then(function(res) {
reject(res) // this should always error
})
.catch(function (err) {
.catch(function(err) {
errors++
resolve(err)
})
@ -31,7 +31,7 @@ describe('pool error handling', function () {
for (let i = 0; i < 5; i++) {
ps.push(runErrorQuery())
}
Promise.all(ps).then(function () {
Promise.all(ps).then(function() {
expect(shouldGet).to.eql(errors)
pool.end(done)
})
@ -40,7 +40,7 @@ describe('pool error handling', function () {
describe('calling release more than once', () => {
it(
'should throw each time',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool()
const client = yield pool.connect()
client.release()
@ -50,10 +50,10 @@ describe('pool error handling', function () {
})
)
it('should throw each time with callbacks', function (done) {
it('should throw each time with callbacks', function(done) {
const pool = new Pool()
pool.connect(function (err, client, clientDone) {
pool.connect(function(err, client, clientDone) {
expect(err).not.to.be.an(Error)
clientDone()
@ -66,7 +66,7 @@ describe('pool error handling', function () {
})
describe('calling connect after end', () => {
it('should return an error', function* () {
it('should return an error', function*() {
const pool = new Pool()
const res = yield pool.query('SELECT $1::text as name', ['hi'])
expect(res.rows[0].name).to.equal('hi')
@ -113,7 +113,7 @@ describe('pool error handling', function () {
describe('error from idle client', () => {
it(
'removes client from pool',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool()
const client = yield pool.connect()
expect(pool.totalCount).to.equal(1)
@ -148,7 +148,7 @@ describe('pool error handling', function () {
describe('error from in-use client', () => {
it(
'keeps the client in the pool',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool()
const client = yield pool.connect()
expect(pool.totalCount).to.equal(1)
@ -195,7 +195,7 @@ describe('pool error handling', function () {
describe('pool with lots of errors', () => {
it(
'continues to work and provide new clients',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool({ max: 1 })
const errors = []
for (var i = 0; i < 20; i++) {

View File

@ -6,15 +6,15 @@ const describe = require('mocha').describe
const it = require('mocha').it
const Pool = require('../')
describe('events', function () {
it('emits connect before callback', function (done) {
describe('events', function() {
it('emits connect before callback', function(done) {
const pool = new Pool()
let emittedClient = false
pool.on('connect', function (client) {
pool.on('connect', function(client) {
emittedClient = client
})
pool.connect(function (err, client, release) {
pool.connect(function(err, client, release) {
if (err) return done(err)
release()
pool.end()
@ -23,52 +23,52 @@ describe('events', function () {
})
})
it('emits "connect" only with a successful connection', function () {
it('emits "connect" only with a successful connection', function() {
const pool = new Pool({
// This client will always fail to connect
Client: mockClient({
connect: function (cb) {
connect: function(cb) {
process.nextTick(() => {
cb(new Error('bad news'))
})
},
}),
})
pool.on('connect', function () {
pool.on('connect', function() {
throw new Error('should never get here')
})
return pool.connect().catch((e) => expect(e.message).to.equal('bad news'))
})
it('emits acquire every time a client is acquired', function (done) {
it('emits acquire every time a client is acquired', function(done) {
const pool = new Pool()
let acquireCount = 0
pool.on('acquire', function (client) {
pool.on('acquire', function(client) {
expect(client).to.be.ok()
acquireCount++
})
for (let i = 0; i < 10; i++) {
pool.connect(function (err, client, release) {
pool.connect(function(err, client, release) {
if (err) return done(err)
release()
})
pool.query('SELECT now()')
}
setTimeout(function () {
setTimeout(function() {
expect(acquireCount).to.be(20)
pool.end(done)
}, 100)
})
it('emits error and client if an idle client in the pool hits an error', function (done) {
it('emits error and client if an idle client in the pool hits an error', function(done) {
const pool = new Pool()
pool.connect(function (err, client) {
pool.connect(function(err, client) {
expect(err).to.equal(undefined)
client.release()
setImmediate(function () {
setImmediate(function() {
client.emit('error', new Error('problem'))
})
pool.once('error', function (err, errClient) {
pool.once('error', function(err, errClient) {
expect(err.message).to.equal('problem')
expect(errClient).to.equal(client)
done()
@ -78,7 +78,7 @@ describe('events', function () {
})
function mockClient(methods) {
return function () {
return function() {
const client = new EventEmitter()
Object.assign(client, methods)
return client

View File

@ -22,7 +22,7 @@ describe('idle timeout', () => {
it(
'times out and removes clients when others are also removed',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool({ idleTimeoutMillis: 10 })
const clientA = yield pool.connect()
const clientB = yield pool.connect()
@ -49,7 +49,7 @@ describe('idle timeout', () => {
it(
'can remove idle clients and recreate them',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool({ idleTimeoutMillis: 1 })
const results = []
for (var i = 0; i < 20; i++) {
@ -67,7 +67,7 @@ describe('idle timeout', () => {
it(
'does not time out clients which are used',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool({ idleTimeoutMillis: 1 })
const results = []
for (var i = 0; i < 20; i++) {

View File

@ -7,13 +7,13 @@ const it = require('mocha').it
const Pool = require('../')
describe('pool', function () {
describe('with callbacks', function () {
it('works totally unconfigured', function (done) {
describe('pool', function() {
describe('with callbacks', function() {
it('works totally unconfigured', function(done) {
const pool = new Pool()
pool.connect(function (err, client, release) {
pool.connect(function(err, client, release) {
if (err) return done(err)
client.query('SELECT NOW()', function (err, res) {
client.query('SELECT NOW()', function(err, res) {
release()
if (err) return done(err)
expect(res.rows).to.have.length(1)
@ -22,9 +22,9 @@ describe('pool', function () {
})
})
it('passes props to clients', function (done) {
it('passes props to clients', function(done) {
const pool = new Pool({ binary: true })
pool.connect(function (err, client, release) {
pool.connect(function(err, client, release) {
release()
if (err) return done(err)
expect(client.binary).to.eql(true)
@ -32,42 +32,42 @@ describe('pool', function () {
})
})
it('can run a query with a callback without parameters', function (done) {
it('can run a query with a callback without parameters', function(done) {
const pool = new Pool()
pool.query('SELECT 1 as num', function (err, res) {
pool.query('SELECT 1 as num', function(err, res) {
expect(res.rows[0]).to.eql({ num: 1 })
pool.end(function () {
pool.end(function() {
done(err)
})
})
})
it('can run a query with a callback', function (done) {
it('can run a query with a callback', function(done) {
const pool = new Pool()
pool.query('SELECT $1::text as name', ['brianc'], function (err, res) {
pool.query('SELECT $1::text as name', ['brianc'], function(err, res) {
expect(res.rows[0]).to.eql({ name: 'brianc' })
pool.end(function () {
pool.end(function() {
done(err)
})
})
})
it('passes connection errors to callback', function (done) {
it('passes connection errors to callback', function(done) {
const pool = new Pool({ port: 53922 })
pool.query('SELECT $1::text as name', ['brianc'], function (err, res) {
pool.query('SELECT $1::text as name', ['brianc'], function(err, res) {
expect(res).to.be(undefined)
expect(err).to.be.an(Error)
// a connection error should not polute the pool with a dead client
expect(pool.totalCount).to.equal(0)
pool.end(function (err) {
pool.end(function(err) {
done(err)
})
})
})
it('does not pass client to error callback', function (done) {
it('does not pass client to error callback', function(done) {
const pool = new Pool({ port: 58242 })
pool.connect(function (err, client, release) {
pool.connect(function(err, client, release) {
expect(err).to.be.an(Error)
expect(client).to.be(undefined)
expect(release).to.be.a(Function)
@ -75,30 +75,30 @@ describe('pool', function () {
})
})
it('removes client if it errors in background', function (done) {
it('removes client if it errors in background', function(done) {
const pool = new Pool()
pool.connect(function (err, client, release) {
pool.connect(function(err, client, release) {
release()
if (err) return done(err)
client.testString = 'foo'
setTimeout(function () {
setTimeout(function() {
client.emit('error', new Error('on purpose'))
}, 10)
})
pool.on('error', function (err) {
pool.on('error', function(err) {
expect(err.message).to.be('on purpose')
expect(err.client).to.not.be(undefined)
expect(err.client.testString).to.be('foo')
err.client.connection.stream.on('end', function () {
err.client.connection.stream.on('end', function() {
pool.end(done)
})
})
})
it('should not change given options', function (done) {
it('should not change given options', function(done) {
const options = { max: 10 }
const pool = new Pool(options)
pool.connect(function (err, client, release) {
pool.connect(function(err, client, release) {
release()
if (err) return done(err)
expect(options).to.eql({ max: 10 })
@ -106,9 +106,9 @@ describe('pool', function () {
})
})
it('does not create promises when connecting', function (done) {
it('does not create promises when connecting', function(done) {
const pool = new Pool()
const returnValue = pool.connect(function (err, client, release) {
const returnValue = pool.connect(function(err, client, release) {
release()
if (err) return done(err)
pool.end(done)
@ -116,23 +116,23 @@ describe('pool', function () {
expect(returnValue).to.be(undefined)
})
it('does not create promises when querying', function (done) {
it('does not create promises when querying', function(done) {
const pool = new Pool()
const returnValue = pool.query('SELECT 1 as num', function (err) {
pool.end(function () {
const returnValue = pool.query('SELECT 1 as num', function(err) {
pool.end(function() {
done(err)
})
})
expect(returnValue).to.be(undefined)
})
it('does not create promises when ending', function (done) {
it('does not create promises when ending', function(done) {
const pool = new Pool()
const returnValue = pool.end(done)
expect(returnValue).to.be(undefined)
})
it('never calls callback syncronously', function (done) {
it('never calls callback syncronously', function(done) {
const pool = new Pool()
pool.connect((err, client) => {
if (err) throw err
@ -153,11 +153,11 @@ describe('pool', function () {
})
})
describe('with promises', function () {
it('connects, queries, and disconnects', function () {
describe('with promises', function() {
it('connects, queries, and disconnects', function() {
const pool = new Pool()
return pool.connect().then(function (client) {
return client.query('select $1::text as name', ['hi']).then(function (res) {
return pool.connect().then(function(client) {
return client.query('select $1::text as name', ['hi']).then(function(res) {
expect(res.rows).to.eql([{ name: 'hi' }])
client.release()
return pool.end()
@ -174,41 +174,41 @@ describe('pool', function () {
})
})
it('properly pools clients', function () {
it('properly pools clients', function() {
const pool = new Pool({ poolSize: 9 })
const promises = _.times(30, function () {
return pool.connect().then(function (client) {
return client.query('select $1::text as name', ['hi']).then(function (res) {
const promises = _.times(30, function() {
return pool.connect().then(function(client) {
return client.query('select $1::text as name', ['hi']).then(function(res) {
client.release()
return res
})
})
})
return Promise.all(promises).then(function (res) {
return Promise.all(promises).then(function(res) {
expect(res).to.have.length(30)
expect(pool.totalCount).to.be(9)
return pool.end()
})
})
it('supports just running queries', function () {
it('supports just running queries', function() {
const pool = new Pool({ poolSize: 9 })
const text = 'select $1::text as name'
const values = ['hi']
const query = { text: text, values: values }
const promises = _.times(30, () => pool.query(query))
return Promise.all(promises).then(function (queries) {
return Promise.all(promises).then(function(queries) {
expect(queries).to.have.length(30)
return pool.end()
})
})
it('recovers from query errors', function () {
it('recovers from query errors', function() {
const pool = new Pool()
const errors = []
const promises = _.times(30, () => {
return pool.query('SELECT asldkfjasldkf').catch(function (e) {
return pool.query('SELECT asldkfjasldkf').catch(function(e) {
errors.push(e)
})
})
@ -216,7 +216,7 @@ describe('pool', function () {
expect(errors).to.have.length(30)
expect(pool.totalCount).to.equal(0)
expect(pool.idleCount).to.equal(0)
return pool.query('SELECT $1::text as name', ['hi']).then(function (res) {
return pool.query('SELECT $1::text as name', ['hi']).then(function(res) {
expect(res.rows).to.eql([{ name: 'hi' }])
return pool.end()
})

View File

@ -5,14 +5,14 @@ const it = require('mocha').it
const Pool = require('../')
describe('logging', function () {
it('logs to supplied log function if given', function () {
describe('logging', function() {
it('logs to supplied log function if given', function() {
const messages = []
const log = function (msg) {
const log = function(msg) {
messages.push(msg)
}
const pool = new Pool({ log: log })
return pool.query('SELECT NOW()').then(function () {
return pool.query('SELECT NOW()').then(function() {
expect(messages.length).to.be.greaterThan(0)
return pool.end()
})

View File

@ -10,7 +10,7 @@ const Pool = require('../')
describe('maxUses', () => {
it(
'can create a single client and use it once',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool({ maxUses: 2 })
expect(pool.waitingCount).to.equal(0)
const client = yield pool.connect()
@ -23,7 +23,7 @@ describe('maxUses', () => {
it(
'getting a connection a second time returns the same connection and releasing it also closes it',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool({ maxUses: 2 })
expect(pool.waitingCount).to.equal(0)
const client = yield pool.connect()
@ -39,7 +39,7 @@ describe('maxUses', () => {
it(
'getting a connection a third time returns a new connection',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool({ maxUses: 2 })
expect(pool.waitingCount).to.equal(0)
const client = yield pool.connect()
@ -56,7 +56,7 @@ describe('maxUses', () => {
it(
'getting a connection from a pending request gets a fresh client when the released candidate is expended',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool({ max: 1, maxUses: 2 })
expect(pool.waitingCount).to.equal(0)
const client1 = yield pool.connect()
@ -83,9 +83,9 @@ describe('maxUses', () => {
it(
'logs when removing an expended client',
co.wrap(function* () {
co.wrap(function*() {
const messages = []
const log = function (msg) {
const log = function(msg) {
messages.push(msg)
}
const pool = new Pool({ maxUses: 1, log })

View File

@ -10,7 +10,7 @@ const Pool = require('../')
describe('pool size of 1', () => {
it(
'can create a single client and use it once',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool({ max: 1 })
expect(pool.waitingCount).to.equal(0)
const client = yield pool.connect()
@ -23,7 +23,7 @@ describe('pool size of 1', () => {
it(
'can create a single client and use it multiple times',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool({ max: 1 })
expect(pool.waitingCount).to.equal(0)
const client = yield pool.connect()
@ -39,7 +39,7 @@ describe('pool size of 1', () => {
it(
'can only send 1 query at a time',
co.wrap(function* () {
co.wrap(function*() {
const pool = new Pool({ max: 1 })
// the query text column name changed in PostgreSQL 9.2

View File

@ -14,7 +14,7 @@ var parseCompleteBuffer = buffers.parseComplete()
var bindCompleteBuffer = buffers.bindComplete()
var portalSuspendedBuffer = buffers.portalSuspended()
var addRow = function (bufferList: BufferList, name: string, offset: number) {
var addRow = function(bufferList: BufferList, name: string, offset: number) {
return bufferList
.addCString(name) // field name
.addInt32(offset++) // table id
@ -144,7 +144,7 @@ var expectedTwoRowMessage = {
],
}
var testForMessage = function (buffer: Buffer, expectedMessage: any) {
var testForMessage = function(buffer: Buffer, expectedMessage: any) {
it('recieves and parses ' + expectedMessage.name, async () => {
const messages = await parseBuffers([buffer])
const [lastMessage] = messages
@ -204,7 +204,7 @@ const parseBuffers = async (buffers: Buffer[]): Promise<BackendMessage[]> => {
return msgs
}
describe('PgPacketStream', function () {
describe('PgPacketStream', function() {
testForMessage(authOkBuffer, expectedAuthenticationOkayMessage)
testForMessage(plainPasswordBuffer, expectedPlainPasswordMessage)
testForMessage(md5PasswordBuffer, expectedMD5PasswordMessage)
@ -226,21 +226,21 @@ describe('PgPacketStream', function () {
name: 'noData',
})
describe('rowDescription messages', function () {
describe('rowDescription messages', function() {
testForMessage(emptyRowDescriptionBuffer, expectedEmptyRowDescriptionMessage)
testForMessage(oneRowDescBuff, expectedOneRowMessage)
testForMessage(twoRowBuf, expectedTwoRowMessage)
})
describe('parsing rows', function () {
describe('parsing empty row', function () {
describe('parsing rows', function() {
describe('parsing empty row', function() {
testForMessage(emptyRowFieldBuf, {
name: 'dataRow',
fieldCount: 0,
})
})
describe('parsing data row with fields', function () {
describe('parsing data row with fields', function() {
testForMessage(oneFieldBuf, {
name: 'dataRow',
fieldCount: 1,
@ -249,7 +249,7 @@ describe('PgPacketStream', function () {
})
})
describe('notice message', function () {
describe('notice message', function() {
// this uses the same logic as error message
var buff = buffers.notice([{ type: 'C', value: 'code' }])
testForMessage(buff, {
@ -262,7 +262,7 @@ describe('PgPacketStream', function () {
name: 'error',
})
describe('with all the fields', function () {
describe('with all the fields', function() {
var buffer = buffers.error([
{
type: 'S',
@ -351,13 +351,13 @@ describe('PgPacketStream', function () {
name: 'closeComplete',
})
describe('parses portal suspended message', function () {
describe('parses portal suspended message', function() {
testForMessage(portalSuspendedBuffer, {
name: 'portalSuspended',
})
})
describe('parses replication start message', function () {
describe('parses replication start message', function() {
testForMessage(Buffer.from([0x57, 0x00, 0x00, 0x00, 0x04]), {
name: 'replicationStart',
length: 4,
@ -408,10 +408,10 @@ describe('PgPacketStream', function () {
// since the data message on a stream can randomly divide the incomming
// tcp packets anywhere, we need to make sure we can parse every single
// split on a tcp message
describe('split buffer, single message parsing', function () {
describe('split buffer, single message parsing', function() {
var fullBuffer = buffers.dataRow([null, 'bang', 'zug zug', null, '!'])
it('parses when full buffer comes in', async function () {
it('parses when full buffer comes in', async function() {
const messages = await parseBuffers([fullBuffer])
const message = messages[0] as any
assert.equal(message.fields.length, 5)
@ -422,7 +422,7 @@ describe('PgPacketStream', function () {
assert.equal(message.fields[4], '!')
})
var testMessageRecievedAfterSpiltAt = async function (split: number) {
var testMessageRecievedAfterSpiltAt = async function(split: number) {
var firstBuffer = Buffer.alloc(fullBuffer.length - split)
var secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length)
fullBuffer.copy(firstBuffer, 0, 0)
@ -437,29 +437,29 @@ describe('PgPacketStream', function () {
assert.equal(message.fields[4], '!')
}
it('parses when split in the middle', function () {
it('parses when split in the middle', function() {
testMessageRecievedAfterSpiltAt(6)
})
it('parses when split at end', function () {
it('parses when split at end', function() {
testMessageRecievedAfterSpiltAt(2)
})
it('parses when split at beginning', function () {
it('parses when split at beginning', function() {
testMessageRecievedAfterSpiltAt(fullBuffer.length - 2)
testMessageRecievedAfterSpiltAt(fullBuffer.length - 1)
testMessageRecievedAfterSpiltAt(fullBuffer.length - 5)
})
})
describe('split buffer, multiple message parsing', function () {
describe('split buffer, multiple message parsing', function() {
var dataRowBuffer = buffers.dataRow(['!'])
var readyForQueryBuffer = buffers.readyForQuery()
var fullBuffer = Buffer.alloc(dataRowBuffer.length + readyForQueryBuffer.length)
dataRowBuffer.copy(fullBuffer, 0, 0)
readyForQueryBuffer.copy(fullBuffer, dataRowBuffer.length, 0)
var verifyMessages = function (messages: any[]) {
var verifyMessages = function(messages: any[]) {
assert.strictEqual(messages.length, 2)
assert.deepEqual(messages[0], {
name: 'dataRow',
@ -475,12 +475,12 @@ describe('PgPacketStream', function () {
})
}
// sanity check
it('recieves both messages when packet is not split', async function () {
it('recieves both messages when packet is not split', async function() {
const messages = await parseBuffers([fullBuffer])
verifyMessages(messages)
})
var splitAndVerifyTwoMessages = async function (split: number) {
var splitAndVerifyTwoMessages = async function(split: number) {
var firstBuffer = Buffer.alloc(fullBuffer.length - split)
var secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length)
fullBuffer.copy(firstBuffer, 0, 0)
@ -489,11 +489,11 @@ describe('PgPacketStream', function () {
verifyMessages(messages)
}
describe('recieves both messages when packet is split', function () {
it('in the middle', function () {
describe('recieves both messages when packet is split', function() {
it('in the middle', function() {
return splitAndVerifyTwoMessages(11)
})
it('at the front', function () {
it('at the front', function() {
return Promise.all([
splitAndVerifyTwoMessages(fullBuffer.length - 1),
splitAndVerifyTwoMessages(fullBuffer.length - 4),
@ -501,7 +501,7 @@ describe('PgPacketStream', function () {
])
})
it('at the end', function () {
it('at the end', function() {
return Promise.all([splitAndVerifyTwoMessages(8), splitAndVerifyTwoMessages(1)])
})
})

View File

@ -3,7 +3,7 @@ import { serialize } from './serializer'
import BufferList from './testing/buffer-list'
describe('serializer', () => {
it('builds startup message', function () {
it('builds startup message', function() {
const actual = serialize.startup({
user: 'brian',
database: 'bang',
@ -24,51 +24,66 @@ describe('serializer', () => {
)
})
it('builds password message', function () {
it('builds password message', function() {
const actual = serialize.password('!')
assert.deepEqual(actual, new BufferList().addCString('!').join(true, 'p'))
})
it('builds request ssl message', function () {
it('builds request ssl message', function() {
const actual = serialize.requestSsl()
const expected = new BufferList().addInt32(80877103).join(true)
assert.deepEqual(actual, expected)
})
it('builds SASLInitialResponseMessage message', function () {
it('builds SASLInitialResponseMessage message', function() {
const actual = serialize.sendSASLInitialResponseMessage('mech', 'data')
assert.deepEqual(actual, new BufferList().addCString('mech').addInt32(4).addString('data').join(true, 'p'))
assert.deepEqual(
actual,
new BufferList()
.addCString('mech')
.addInt32(4)
.addString('data')
.join(true, 'p')
)
})
it('builds SCRAMClientFinalMessage message', function () {
it('builds SCRAMClientFinalMessage message', function() {
const actual = serialize.sendSCRAMClientFinalMessage('data')
assert.deepEqual(actual, new BufferList().addString('data').join(true, 'p'))
})
it('builds query message', function () {
it('builds query message', function() {
var txt = 'select * from boom'
const actual = serialize.query(txt)
assert.deepEqual(actual, new BufferList().addCString(txt).join(true, 'Q'))
})
describe('parse message', () => {
it('builds parse message', function () {
it('builds parse message', function() {
const actual = serialize.parse({ text: '!' })
var expected = new BufferList().addCString('').addCString('!').addInt16(0).join(true, 'P')
var expected = new BufferList()
.addCString('')
.addCString('!')
.addInt16(0)
.join(true, 'P')
assert.deepEqual(actual, expected)
})
it('builds parse message with named query', function () {
it('builds parse message with named query', function() {
const actual = serialize.parse({
name: 'boom',
text: 'select * from boom',
types: [],
})
var expected = new BufferList().addCString('boom').addCString('select * from boom').addInt16(0).join(true, 'P')
var expected = new BufferList()
.addCString('boom')
.addCString('select * from boom')
.addInt16(0)
.join(true, 'P')
assert.deepEqual(actual, expected)
})
it('with multiple parameters', function () {
it('with multiple parameters', function() {
const actual = serialize.parse({
name: 'force',
text: 'select * from bang where name = $1',
@ -87,8 +102,8 @@ describe('serializer', () => {
})
})
describe('bind messages', function () {
it('with no values', function () {
describe('bind messages', function() {
it('with no values', function() {
const actual = serialize.bind()
var expectedBuffer = new BufferList()
@ -101,7 +116,7 @@ describe('serializer', () => {
assert.deepEqual(actual, expectedBuffer)
})
it('with named statement, portal, and values', function () {
it('with named statement, portal, and values', function() {
const actual = serialize.bind({
portal: 'bang',
statement: 'woo',
@ -125,7 +140,7 @@ describe('serializer', () => {
})
})
it('with named statement, portal, and buffer value', function () {
it('with named statement, portal, and buffer value', function() {
const actual = serialize.bind({
portal: 'bang',
statement: 'woo',
@ -152,70 +167,88 @@ describe('serializer', () => {
assert.deepEqual(actual, expectedBuffer)
})
describe('builds execute message', function () {
it('for unamed portal with no row limit', function () {
describe('builds execute message', function() {
it('for unamed portal with no row limit', function() {
const actual = serialize.execute()
var expectedBuffer = new BufferList().addCString('').addInt32(0).join(true, 'E')
var expectedBuffer = new BufferList()
.addCString('')
.addInt32(0)
.join(true, 'E')
assert.deepEqual(actual, expectedBuffer)
})
it('for named portal with row limit', function () {
it('for named portal with row limit', function() {
const actual = serialize.execute({
portal: 'my favorite portal',
rows: 100,
})
var expectedBuffer = new BufferList().addCString('my favorite portal').addInt32(100).join(true, 'E')
var expectedBuffer = new BufferList()
.addCString('my favorite portal')
.addInt32(100)
.join(true, 'E')
assert.deepEqual(actual, expectedBuffer)
})
})
it('builds flush command', function () {
it('builds flush command', function() {
const actual = serialize.flush()
var expected = new BufferList().join(true, 'H')
assert.deepEqual(actual, expected)
})
it('builds sync command', function () {
it('builds sync command', function() {
const actual = serialize.sync()
var expected = new BufferList().join(true, 'S')
assert.deepEqual(actual, expected)
})
it('builds end command', function () {
it('builds end command', function() {
const actual = serialize.end()
var expected = Buffer.from([0x58, 0, 0, 0, 4])
assert.deepEqual(actual, expected)
})
describe('builds describe command', function () {
it('describe statement', function () {
describe('builds describe command', function() {
it('describe statement', function() {
const actual = serialize.describe({ type: 'S', name: 'bang' })
var expected = new BufferList().addChar('S').addCString('bang').join(true, 'D')
var expected = new BufferList()
.addChar('S')
.addCString('bang')
.join(true, 'D')
assert.deepEqual(actual, expected)
})
it('describe unnamed portal', function () {
it('describe unnamed portal', function() {
const actual = serialize.describe({ type: 'P' })
var expected = new BufferList().addChar('P').addCString('').join(true, 'D')
var expected = new BufferList()
.addChar('P')
.addCString('')
.join(true, 'D')
assert.deepEqual(actual, expected)
})
})
describe('builds close command', function () {
it('describe statement', function () {
describe('builds close command', function() {
it('describe statement', function() {
const actual = serialize.close({ type: 'S', name: 'bang' })
var expected = new BufferList().addChar('S').addCString('bang').join(true, 'C')
var expected = new BufferList()
.addChar('S')
.addCString('bang')
.join(true, 'C')
assert.deepEqual(actual, expected)
})
it('describe unnamed portal', function () {
it('describe unnamed portal', function() {
const actual = serialize.close({ type: 'P' })
var expected = new BufferList().addChar('P').addCString('').join(true, 'C')
var expected = new BufferList()
.addChar('P')
.addCString('')
.join(true, 'C')
assert.deepEqual(actual, expected)
})
})
describe('copy messages', function () {
describe('copy messages', function() {
it('builds copyFromChunk', () => {
const actual = serialize.copyData(Buffer.from([1, 2, 3]))
const expected = new BufferList().add(Buffer.from([1, 2, 3])).join(true, 'd')
@ -237,7 +270,12 @@ describe('serializer', () => {
it('builds cancel message', () => {
const actual = serialize.cancel(3, 4)
const expected = new BufferList().addInt16(1234).addInt16(5678).addInt32(3).addInt32(4).join(true)
const expected = new BufferList()
.addInt16(1234)
.addInt16(5678)
.addInt32(3)
.addInt32(4)
.join(true)
assert.deepEqual(actual, expected)
})
})

View File

@ -32,7 +32,10 @@ const startup = (opts: Record<string, string>): Buffer => {
var length = bodyBuffer.length + 4
return new Writer().addInt32(length).add(bodyBuffer).flush()
return new Writer()
.addInt32(length)
.add(bodyBuffer)
.flush()
}
const requestSsl = (): Buffer => {
@ -46,14 +49,17 @@ const password = (password: string): Buffer => {
return writer.addCString(password).flush(code.startup)
}
const sendSASLInitialResponseMessage = function (mechanism: string, initialResponse: string): Buffer {
const sendSASLInitialResponseMessage = function(mechanism: string, initialResponse: string): Buffer {
// 0x70 = 'p'
writer.addCString(mechanism).addInt32(Buffer.byteLength(initialResponse)).addString(initialResponse)
writer
.addCString(mechanism)
.addInt32(Buffer.byteLength(initialResponse))
.addString(initialResponse)
return writer.flush(code.startup)
}
const sendSCRAMClientFinalMessage = function (additionalData: string): Buffer {
const sendSCRAMClientFinalMessage = function(additionalData: string): Buffer {
return writer.addString(additionalData).flush(code.startup)
}

View File

@ -11,7 +11,7 @@ export default class BufferList {
}
public getByteLength(initial?: number) {
return this.buffers.reduce(function (previous, current) {
return this.buffers.reduce(function(previous, current) {
return previous + current.length
}, initial || 0)
}
@ -58,7 +58,7 @@ export default class BufferList {
}
var result = Buffer.alloc(length)
var index = 0
this.buffers.forEach(function (buffer) {
this.buffers.forEach(function(buffer) {
buffer.copy(result, index, 0)
index += buffer.length
})

View File

@ -2,54 +2,70 @@
import BufferList from './buffer-list'
const buffers = {
readyForQuery: function () {
readyForQuery: function() {
return new BufferList().add(Buffer.from('I')).join(true, 'Z')
},
authenticationOk: function () {
authenticationOk: function() {
return new BufferList().addInt32(0).join(true, 'R')
},
authenticationCleartextPassword: function () {
authenticationCleartextPassword: function() {
return new BufferList().addInt32(3).join(true, 'R')
},
authenticationMD5Password: function () {
authenticationMD5Password: function() {
return new BufferList()
.addInt32(5)
.add(Buffer.from([1, 2, 3, 4]))
.join(true, 'R')
},
authenticationSASL: function () {
return new BufferList().addInt32(10).addCString('SCRAM-SHA-256').addCString('').join(true, 'R')
authenticationSASL: function() {
return new BufferList()
.addInt32(10)
.addCString('SCRAM-SHA-256')
.addCString('')
.join(true, 'R')
},
authenticationSASLContinue: function () {
return new BufferList().addInt32(11).addString('data').join(true, 'R')
authenticationSASLContinue: function() {
return new BufferList()
.addInt32(11)
.addString('data')
.join(true, 'R')
},
authenticationSASLFinal: function () {
return new BufferList().addInt32(12).addString('data').join(true, 'R')
authenticationSASLFinal: function() {
return new BufferList()
.addInt32(12)
.addString('data')
.join(true, 'R')
},
parameterStatus: function (name: string, value: string) {
return new BufferList().addCString(name).addCString(value).join(true, 'S')
parameterStatus: function(name: string, value: string) {
return new BufferList()
.addCString(name)
.addCString(value)
.join(true, 'S')
},
backendKeyData: function (processID: number, secretKey: number) {
return new BufferList().addInt32(processID).addInt32(secretKey).join(true, 'K')
backendKeyData: function(processID: number, secretKey: number) {
return new BufferList()
.addInt32(processID)
.addInt32(secretKey)
.join(true, 'K')
},
commandComplete: function (string: string) {
commandComplete: function(string: string) {
return new BufferList().addCString(string).join(true, 'C')
},
rowDescription: function (fields: any[]) {
rowDescription: function(fields: any[]) {
fields = fields || []
var buf = new BufferList()
buf.addInt16(fields.length)
fields.forEach(function (field) {
fields.forEach(function(field) {
buf
.addCString(field.name)
.addInt32(field.tableID || 0)
@ -62,11 +78,11 @@ const buffers = {
return buf.join(true, 'T')
},
dataRow: function (columns: any[]) {
dataRow: function(columns: any[]) {
columns = columns || []
var buf = new BufferList()
buf.addInt16(columns.length)
columns.forEach(function (col) {
columns.forEach(function(col) {
if (col == null) {
buf.addInt32(-1)
} else {
@ -78,49 +94,53 @@ const buffers = {
return buf.join(true, 'D')
},
error: function (fields: any) {
error: function(fields: any) {
return buffers.errorOrNotice(fields).join(true, 'E')
},
notice: function (fields: any) {
notice: function(fields: any) {
return buffers.errorOrNotice(fields).join(true, 'N')
},
errorOrNotice: function (fields: any) {
errorOrNotice: function(fields: any) {
fields = fields || []
var buf = new BufferList()
fields.forEach(function (field: any) {
fields.forEach(function(field: any) {
buf.addChar(field.type)
buf.addCString(field.value)
})
return buf.add(Buffer.from([0])) // terminator
},
parseComplete: function () {
parseComplete: function() {
return new BufferList().join(true, '1')
},
bindComplete: function () {
bindComplete: function() {
return new BufferList().join(true, '2')
},
notification: function (id: number, channel: string, payload: string) {
return new BufferList().addInt32(id).addCString(channel).addCString(payload).join(true, 'A')
notification: function(id: number, channel: string, payload: string) {
return new BufferList()
.addInt32(id)
.addCString(channel)
.addCString(payload)
.join(true, 'A')
},
emptyQuery: function () {
emptyQuery: function() {
return new BufferList().join(true, 'I')
},
portalSuspended: function () {
portalSuspended: function() {
return new BufferList().join(true, 's')
},
closeComplete: function () {
closeComplete: function() {
return new BufferList().join(true, '3')
},
copyIn: function (cols: number) {
copyIn: function(cols: number) {
const list = new BufferList()
// text mode
.addByte(0)
@ -132,7 +152,7 @@ const buffers = {
return list.join(true, 'G')
},
copyOut: function (cols: number) {
copyOut: function(cols: number) {
const list = new BufferList()
// text mode
.addByte(0)
@ -144,11 +164,11 @@ const buffers = {
return list.join(true, 'H')
},
copyData: function (bytes: Buffer) {
copyData: function(bytes: Buffer) {
return new BufferList().add(bytes).join(true, 'd')
},
copyDone: function () {
copyDone: function() {
return new BufferList().join(true, 'c')
},
}

View File

@ -7,37 +7,37 @@ var helper = require('./helper')
if (process.version.startsWith('v8.')) {
console.error('warning! node less than 10lts stream closing semantics may not behave properly')
} else {
helper('close', function (client) {
it('emits close', function (done) {
helper('close', function(client) {
it('emits close', function(done) {
var stream = new QueryStream('SELECT * FROM generate_series(0, $1) num', [3], { batchSize: 2, highWaterMark: 2 })
var query = client.query(stream)
query.pipe(concat(function () {}))
query.pipe(concat(function() {}))
query.on('close', done)
})
})
helper('early close', function (client) {
it('can be closed early', function (done) {
helper('early close', function(client) {
it('can be closed early', function(done) {
var stream = new QueryStream('SELECT * FROM generate_series(0, $1) num', [20000], {
batchSize: 2,
highWaterMark: 2,
})
var query = client.query(stream)
var readCount = 0
query.on('readable', function () {
query.on('readable', function() {
readCount++
query.read()
})
query.once('readable', function () {
query.once('readable', function() {
query.destroy()
})
query.on('close', function () {
query.on('close', function() {
assert(readCount < 10, 'should not have read more than 10 rows')
done()
})
})
it('can destroy stream while reading', function (done) {
it('can destroy stream while reading', function(done) {
var stream = new QueryStream('SELECT * FROM generate_series(0, 100), pg_sleep(1)')
client.query(stream)
stream.on('data', () => done(new Error('stream should not have returned rows')))
@ -47,7 +47,7 @@ if (process.version.startsWith('v8.')) {
}, 100)
})
it('emits an error when calling destroy with an error', function (done) {
it('emits an error when calling destroy with an error', function(done) {
var stream = new QueryStream('SELECT * FROM generate_series(0, 100), pg_sleep(1)')
client.query(stream)
stream.on('data', () => done(new Error('stream should not have returned rows')))
@ -62,7 +62,7 @@ if (process.version.startsWith('v8.')) {
}, 100)
})
it('can destroy stream while reading an error', function (done) {
it('can destroy stream while reading an error', function(done) {
var stream = new QueryStream('SELECT * from pg_sleep(1), basdfasdf;')
client.query(stream)
stream.on('data', () => done(new Error('stream should not have returned rows')))
@ -73,7 +73,7 @@ if (process.version.startsWith('v8.')) {
})
})
it('does not crash when destroying the stream immediately after calling read', function (done) {
it('does not crash when destroying the stream immediately after calling read', function(done) {
var stream = new QueryStream('SELECT * from generate_series(0, 100), pg_sleep(1);')
client.query(stream)
stream.on('data', () => done(new Error('stream should not have returned rows')))
@ -81,7 +81,7 @@ if (process.version.startsWith('v8.')) {
stream.on('close', done)
})
it('does not crash when destroying the stream before its submitted', function (done) {
it('does not crash when destroying the stream before its submitted', function(done) {
var stream = new QueryStream('SELECT * from generate_series(0, 100), pg_sleep(1);')
stream.on('data', () => done(new Error('stream should not have returned rows')))
stream.destroy()

View File

@ -5,19 +5,19 @@ var helper = require('./helper')
var QueryStream = require('../')
helper('concat', function (client) {
it('concats correctly', function (done) {
helper('concat', function(client) {
it('concats correctly', function(done) {
var stream = new QueryStream('SELECT * FROM generate_series(0, 200) num', [])
var query = client.query(stream)
query
.pipe(
through(function (row) {
through(function(row) {
this.push(row.num)
})
)
.pipe(
concat(function (result) {
var total = result.reduce(function (prev, cur) {
concat(function(result) {
var total = result.reduce(function(prev, cur) {
return prev + cur
})
assert.equal(total, 20100)

View File

@ -2,21 +2,21 @@ const assert = require('assert')
const helper = require('./helper')
const QueryStream = require('../')
helper('empty-query', function (client) {
it('handles empty query', function (done) {
helper('empty-query', function(client) {
it('handles empty query', function(done) {
const stream = new QueryStream('-- this is a comment', [])
const query = client.query(stream)
query
.on('end', function () {
.on('end', function() {
// nothing should happen for empty query
done()
})
.on('data', function () {
.on('data', function() {
// noop to kick off reading
})
})
it('continues to function after stream', function (done) {
it('continues to function after stream', function(done) {
client.query('SELECT NOW()', done)
})
})

View File

@ -3,22 +3,22 @@ var helper = require('./helper')
var QueryStream = require('../')
helper('error', function (client) {
it('receives error on stream', function (done) {
helper('error', function(client) {
it('receives error on stream', function(done) {
var stream = new QueryStream('SELECT * FROM asdf num', [])
var query = client.query(stream)
query
.on('error', function (err) {
.on('error', function(err) {
assert(err)
assert.equal(err.code, '42P01')
done()
})
.on('data', function () {
.on('data', function() {
// noop to kick of reading
})
})
it('continues to function after stream', function (done) {
it('continues to function after stream', function(done) {
client.query('SELECT NOW()', done)
})
})

View File

@ -2,12 +2,12 @@ var assert = require('assert')
var helper = require('./helper')
var QueryStream = require('../')
helper('fast reader', function (client) {
it('works', function (done) {
helper('fast reader', function(client) {
it('works', function(done) {
var stream = new QueryStream('SELECT * FROM generate_series(0, 200) num', [])
var query = client.query(stream)
var result = []
stream.on('readable', function () {
stream.on('readable', function() {
var res = stream.read()
while (res) {
if (result.length !== 201) {
@ -23,8 +23,8 @@ helper('fast reader', function (client) {
res = stream.read()
}
})
stream.on('end', function () {
var total = result.reduce(function (prev, cur) {
stream.on('end', function() {
var total = result.reduce(function(prev, cur) {
return prev + cur
})
assert.equal(total, 20100)

View File

@ -1,15 +1,15 @@
var pg = require('pg')
module.exports = function (name, cb) {
describe(name, function () {
module.exports = function(name, cb) {
describe(name, function() {
var client = new pg.Client()
before(function (done) {
before(function(done) {
client.connect(done)
})
cb(client)
after(function (done) {
after(function(done) {
client.end()
client.on('end', done)
})

View File

@ -3,12 +3,12 @@ var concat = require('concat-stream')
var QueryStream = require('../')
require('./helper')('instant', function (client) {
it('instant', function (done) {
require('./helper')('instant', function(client) {
it('instant', function(done) {
var query = new QueryStream('SELECT pg_sleep(1)', [])
var stream = client.query(query)
stream.pipe(
concat(function (res) {
concat(function(res) {
assert.equal(res.length, 1)
done()
})

View File

@ -1,7 +1,7 @@
var pg = require('pg')
var QueryStream = require('../')
describe('end semantics race condition', function () {
before(function (done) {
describe('end semantics race condition', function() {
before(function(done) {
var client = new pg.Client()
client.connect()
client.on('drain', client.end.bind(client))
@ -9,7 +9,7 @@ describe('end semantics race condition', function () {
client.query('create table IF NOT EXISTS p(id serial primary key)')
client.query('create table IF NOT EXISTS c(id int primary key references p)')
})
it('works', function (done) {
it('works', function(done) {
var client1 = new pg.Client()
client1.connect()
var client2 = new pg.Client()
@ -18,11 +18,11 @@ describe('end semantics race condition', function () {
var qr = new QueryStream('INSERT INTO p DEFAULT VALUES RETURNING id')
client1.query(qr)
var id = null
qr.on('data', function (row) {
qr.on('data', function(row) {
id = row.id
})
qr.on('end', function () {
client2.query('INSERT INTO c(id) VALUES ($1)', [id], function (err, rows) {
qr.on('end', function() {
client2.query('INSERT INTO c(id) VALUES ($1)', [id], function(err, rows) {
client1.end()
client2.end()
done(err)

View File

@ -2,8 +2,8 @@ var assert = require('assert')
var helper = require('./helper')
var QueryStream = require('../')
helper('passing options', function (client) {
it('passes row mode array', function (done) {
helper('passing options', function(client) {
it('passes row mode array', function(done) {
var stream = new QueryStream('SELECT * FROM generate_series(0, 10) num', [], { rowMode: 'array' })
var query = client.query(stream)
var result = []
@ -17,7 +17,7 @@ helper('passing options', function (client) {
})
})
it('passes custom types', function (done) {
it('passes custom types', function(done) {
const types = {
getTypeParser: () => (string) => string,
}

View File

@ -4,8 +4,8 @@ var JSONStream = require('JSONStream')
var QueryStream = require('../')
require('./helper')('pauses', function (client) {
it('pauses', function (done) {
require('./helper')('pauses', function(client) {
it('pauses', function(done) {
this.timeout(5000)
var stream = new QueryStream('SELECT * FROM generate_series(0, $1) num', [200], { batchSize: 2, highWaterMark: 2 })
var query = client.query(stream)
@ -14,7 +14,7 @@ require('./helper')('pauses', function (client) {
.pipe(JSONStream.stringify())
.pipe(pauser)
.pipe(
concat(function (json) {
concat(function(json) {
JSON.parse(json)
done()
})

View File

@ -6,24 +6,24 @@ var Transform = require('stream').Transform
var mapper = new Transform({ objectMode: true })
mapper._transform = function (obj, enc, cb) {
mapper._transform = function(obj, enc, cb) {
this.push(obj)
setTimeout(cb, 5)
}
helper('slow reader', function (client) {
it('works', function (done) {
helper('slow reader', function(client) {
it('works', function(done) {
this.timeout(50000)
var stream = new QueryStream('SELECT * FROM generate_series(0, 201) num', [], {
highWaterMark: 100,
batchSize: 50,
})
stream.on('end', function () {
stream.on('end', function() {
// console.log('stream end')
})
client.query(stream)
stream.pipe(mapper).pipe(
concat(function (res) {
concat(function(res) {
done()
})
)

View File

@ -2,17 +2,20 @@ var QueryStream = require('../')
var spec = require('stream-spec')
var assert = require('assert')
require('./helper')('stream tester timestamp', function (client) {
it('should not warn about max listeners', function (done) {
require('./helper')('stream tester timestamp', function(client) {
it('should not warn about max listeners', function(done) {
var sql = "SELECT * FROM generate_series('1983-12-30 00:00'::timestamp, '2013-12-30 00:00', '1 years')"
var stream = new QueryStream(sql, [])
var ended = false
var query = client.query(stream)
query.on('end', function () {
query.on('end', function() {
ended = true
})
spec(query).readable().pausable({ strict: true }).validateOnExit()
var checkListeners = function () {
spec(query)
.readable()
.pausable({ strict: true })
.validateOnExit()
var checkListeners = function() {
assert(stream.listeners('end').length < 10)
if (!ended) {
setImmediate(checkListeners)

View File

@ -2,11 +2,14 @@ var spec = require('stream-spec')
var QueryStream = require('../')
require('./helper')('stream tester', function (client) {
it('passes stream spec', function (done) {
require('./helper')('stream tester', function(client) {
it('passes stream spec', function(done) {
var stream = new QueryStream('SELECT * FROM generate_series(0, 200) num', [])
var query = client.query(stream)
spec(query).readable().pausable({ strict: true }).validateOnExit()
spec(query)
.readable()
.pausable({ strict: true })
.validateOnExit()
stream.on('end', done)
})
})

View File

@ -22,7 +22,7 @@ if (process.env.PG_FAST_CONNECTION) {
Connection = require('./connection-fast')
}
var Client = function (config) {
var Client = function(config) {
EventEmitter.call(this)
this.connectionParameters = new ConnectionParameters(config)
@ -71,7 +71,7 @@ var Client = function (config) {
util.inherits(Client, EventEmitter)
Client.prototype._errorAllQueries = function (err) {
Client.prototype._errorAllQueries = function(err) {
const enqueueError = (query) => {
process.nextTick(() => {
query.handleError(err, this.connection)
@ -87,7 +87,7 @@ Client.prototype._errorAllQueries = function (err) {
this.queryQueue.length = 0
}
Client.prototype._connect = function (callback) {
Client.prototype._connect = function(callback) {
var self = this
var con = this.connection
if (this._connecting || this._connected) {
@ -114,7 +114,7 @@ Client.prototype._connect = function (callback) {
}
// once connection is established send startup message
con.on('connect', function () {
con.on('connect', function() {
if (self.ssl) {
con.requestSsl()
} else {
@ -122,12 +122,12 @@ Client.prototype._connect = function (callback) {
}
})
con.on('sslconnect', function () {
con.on('sslconnect', function() {
con.startup(self.getStartupConf())
})
function checkPgPass(cb) {
return function (msg) {
return function(msg) {
if (typeof self.password === 'function') {
self._Promise
.resolve()
@ -150,7 +150,7 @@ Client.prototype._connect = function (callback) {
} else if (self.password !== null) {
cb(msg)
} else {
pgPass(self.connectionParameters, function (pass) {
pgPass(self.connectionParameters, function(pass) {
if (undefined !== pass) {
self.connectionParameters.password = self.password = pass
}
@ -163,7 +163,7 @@ Client.prototype._connect = function (callback) {
// password request handling
con.on(
'authenticationCleartextPassword',
checkPgPass(function () {
checkPgPass(function() {
con.password(self.password)
})
)
@ -171,7 +171,7 @@ Client.prototype._connect = function (callback) {
// password request handling
con.on(
'authenticationMD5Password',
checkPgPass(function (msg) {
checkPgPass(function(msg) {
con.password(utils.postgresMd5PasswordHash(self.user, self.password, msg.salt))
})
)
@ -180,7 +180,7 @@ Client.prototype._connect = function (callback) {
var saslSession
con.on(
'authenticationSASL',
checkPgPass(function (msg) {
checkPgPass(function(msg) {
saslSession = sasl.startSession(msg.mechanisms)
con.sendSASLInitialResponseMessage(saslSession.mechanism, saslSession.response)
@ -188,20 +188,20 @@ Client.prototype._connect = function (callback) {
)
// password request handling (SASL)
con.on('authenticationSASLContinue', function (msg) {
con.on('authenticationSASLContinue', function(msg) {
sasl.continueSession(saslSession, self.password, msg.data)
con.sendSCRAMClientFinalMessage(saslSession.response)
})
// password request handling (SASL)
con.on('authenticationSASLFinal', function (msg) {
con.on('authenticationSASLFinal', function(msg) {
sasl.finalizeSession(saslSession, msg.data)
saslSession = null
})
con.once('backendKeyData', function (msg) {
con.once('backendKeyData', function(msg) {
self.processID = msg.processID
self.secretKey = msg.secretKey
})
@ -241,7 +241,7 @@ Client.prototype._connect = function (callback) {
// hook up query handling events to connection
// after the connection initially becomes ready for queries
con.once('readyForQuery', function () {
con.once('readyForQuery', function() {
self._connecting = false
self._connected = true
self._attachListeners(con)
@ -261,7 +261,7 @@ Client.prototype._connect = function (callback) {
self.emit('connect')
})
con.on('readyForQuery', function () {
con.on('readyForQuery', function() {
var activeQuery = self.activeQuery
self.activeQuery = null
self.readyForQuery = true
@ -298,12 +298,12 @@ Client.prototype._connect = function (callback) {
})
})
con.on('notice', function (msg) {
con.on('notice', function(msg) {
self.emit('notice', msg)
})
}
Client.prototype.connect = function (callback) {
Client.prototype.connect = function(callback) {
if (callback) {
this._connect(callback)
return
@ -320,32 +320,32 @@ Client.prototype.connect = function (callback) {
})
}
Client.prototype._attachListeners = function (con) {
Client.prototype._attachListeners = function(con) {
const self = this
// delegate rowDescription to active query
con.on('rowDescription', function (msg) {
con.on('rowDescription', function(msg) {
self.activeQuery.handleRowDescription(msg)
})
// delegate dataRow to active query
con.on('dataRow', function (msg) {
con.on('dataRow', function(msg) {
self.activeQuery.handleDataRow(msg)
})
// delegate portalSuspended to active query
// eslint-disable-next-line no-unused-vars
con.on('portalSuspended', function (msg) {
con.on('portalSuspended', function(msg) {
self.activeQuery.handlePortalSuspended(con)
})
// delegate emptyQuery to active query
// eslint-disable-next-line no-unused-vars
con.on('emptyQuery', function (msg) {
con.on('emptyQuery', function(msg) {
self.activeQuery.handleEmptyQuery(con)
})
// delegate commandComplete to active query
con.on('commandComplete', function (msg) {
con.on('commandComplete', function(msg) {
self.activeQuery.handleCommandComplete(msg, con)
})
@ -353,27 +353,27 @@ Client.prototype._attachListeners = function (con) {
// we track that its already been executed so we don't parse
// it again on the same client
// eslint-disable-next-line no-unused-vars
con.on('parseComplete', function (msg) {
con.on('parseComplete', function(msg) {
if (self.activeQuery.name) {
con.parsedStatements[self.activeQuery.name] = self.activeQuery.text
}
})
// eslint-disable-next-line no-unused-vars
con.on('copyInResponse', function (msg) {
con.on('copyInResponse', function(msg) {
self.activeQuery.handleCopyInResponse(self.connection)
})
con.on('copyData', function (msg) {
con.on('copyData', function(msg) {
self.activeQuery.handleCopyData(msg, self.connection)
})
con.on('notification', function (msg) {
con.on('notification', function(msg) {
self.emit('notification', msg)
})
}
Client.prototype.getStartupConf = function () {
Client.prototype.getStartupConf = function() {
var params = this.connectionParameters
var data = {
@ -398,7 +398,7 @@ Client.prototype.getStartupConf = function () {
return data
}
Client.prototype.cancel = function (client, query) {
Client.prototype.cancel = function(client, query) {
if (client.activeQuery === query) {
var con = this.connection
@ -409,7 +409,7 @@ Client.prototype.cancel = function (client, query) {
}
// once connection is established send cancel message
con.on('connect', function () {
con.on('connect', function() {
con.cancel(client.processID, client.secretKey)
})
} else if (client.queryQueue.indexOf(query) !== -1) {
@ -417,21 +417,21 @@ Client.prototype.cancel = function (client, query) {
}
}
Client.prototype.setTypeParser = function (oid, format, parseFn) {
Client.prototype.setTypeParser = function(oid, format, parseFn) {
return this._types.setTypeParser(oid, format, parseFn)
}
Client.prototype.getTypeParser = function (oid, format) {
Client.prototype.getTypeParser = function(oid, format) {
return this._types.getTypeParser(oid, format)
}
// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
Client.prototype.escapeIdentifier = function (str) {
Client.prototype.escapeIdentifier = function(str) {
return '"' + str.replace(/"/g, '""') + '"'
}
// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
Client.prototype.escapeLiteral = function (str) {
Client.prototype.escapeLiteral = function(str) {
var hasBackslash = false
var escaped = "'"
@ -456,7 +456,7 @@ Client.prototype.escapeLiteral = function (str) {
return escaped
}
Client.prototype._pulseQueryQueue = function () {
Client.prototype._pulseQueryQueue = function() {
if (this.readyForQuery === true) {
this.activeQuery = this.queryQueue.shift()
if (this.activeQuery) {
@ -478,7 +478,7 @@ Client.prototype._pulseQueryQueue = function () {
}
}
Client.prototype.query = function (config, values, callback) {
Client.prototype.query = function(config, values, callback) {
// can take in strings, config object or query object
var query
var result
@ -562,7 +562,7 @@ Client.prototype.query = function (config, values, callback) {
return result
}
Client.prototype.end = function (cb) {
Client.prototype.end = function(cb) {
this._ending = true
// if we have never connected, then end is a noop, callback immediately

View File

@ -17,7 +17,7 @@ const { parse, serialize } = require('../../pg-protocol/dist')
// TODO(bmc) support binary mode here
// var BINARY_MODE = 1
console.log('***using faster connection***')
var Connection = function (config) {
var Connection = function(config) {
EventEmitter.call(this)
config = config || {}
this.stream = config.stream || new net.Socket()
@ -30,7 +30,7 @@ var Connection = function (config) {
this._ending = false
this._emitMessage = false
var self = this
this.on('newListener', function (eventName) {
this.on('newListener', function(eventName) {
if (eventName === 'message') {
self._emitMessage = true
}
@ -39,7 +39,7 @@ var Connection = function (config) {
util.inherits(Connection, EventEmitter)
Connection.prototype.connect = function (port, host) {
Connection.prototype.connect = function(port, host) {
var self = this
if (this.stream.readyState === 'closed') {
@ -48,14 +48,14 @@ Connection.prototype.connect = function (port, host) {
this.emit('connect')
}
this.stream.on('connect', function () {
this.stream.on('connect', function() {
if (self._keepAlive) {
self.stream.setKeepAlive(true, self._keepAliveInitialDelayMillis)
}
self.emit('connect')
})
const reportStreamError = function (error) {
const reportStreamError = function(error) {
// errors about disconnections should be ignored during disconnect
if (self._ending && (error.code === 'ECONNRESET' || error.code === 'EPIPE')) {
return
@ -64,7 +64,7 @@ Connection.prototype.connect = function (port, host) {
}
this.stream.on('error', reportStreamError)
this.stream.on('close', function () {
this.stream.on('close', function() {
self.emit('end')
})
@ -72,7 +72,7 @@ Connection.prototype.connect = function (port, host) {
return this.attachListeners(this.stream)
}
this.stream.once('data', function (buffer) {
this.stream.once('data', function(buffer) {
var responseCode = buffer.toString('utf8')
switch (responseCode) {
case 'S': // Server supports SSL connections, continue with a secure connection
@ -103,7 +103,7 @@ Connection.prototype.connect = function (port, host) {
})
}
Connection.prototype.attachListeners = function (stream) {
Connection.prototype.attachListeners = function(stream) {
stream.on('end', () => {
this.emit('end')
})
@ -116,67 +116,67 @@ Connection.prototype.attachListeners = function (stream) {
})
}
Connection.prototype.requestSsl = function () {
Connection.prototype.requestSsl = function() {
this.stream.write(serialize.requestSsl())
}
Connection.prototype.startup = function (config) {
Connection.prototype.startup = function(config) {
this.stream.write(serialize.startup(config))
}
Connection.prototype.cancel = function (processID, secretKey) {
Connection.prototype.cancel = function(processID, secretKey) {
this._send(serialize.cancel(processID, secretKey))
}
Connection.prototype.password = function (password) {
Connection.prototype.password = function(password) {
this._send(serialize.password(password))
}
Connection.prototype.sendSASLInitialResponseMessage = function (mechanism, initialResponse) {
Connection.prototype.sendSASLInitialResponseMessage = function(mechanism, initialResponse) {
this._send(serialize.sendSASLInitialResponseMessage(mechanism, initialResponse))
}
Connection.prototype.sendSCRAMClientFinalMessage = function (additionalData) {
Connection.prototype.sendSCRAMClientFinalMessage = function(additionalData) {
this._send(serialize.sendSCRAMClientFinalMessage(additionalData))
}
Connection.prototype._send = function (buffer) {
Connection.prototype._send = function(buffer) {
if (!this.stream.writable) {
return false
}
return this.stream.write(buffer)
}
Connection.prototype.query = function (text) {
Connection.prototype.query = function(text) {
this._send(serialize.query(text))
}
// send parse message
Connection.prototype.parse = function (query) {
Connection.prototype.parse = function(query) {
this._send(serialize.parse(query))
}
// send bind message
// "more" === true to buffer the message until flush() is called
Connection.prototype.bind = function (config) {
Connection.prototype.bind = function(config) {
this._send(serialize.bind(config))
}
// send execute message
// "more" === true to buffer the message until flush() is called
Connection.prototype.execute = function (config) {
Connection.prototype.execute = function(config) {
this._send(serialize.execute(config))
}
const flushBuffer = serialize.flush()
Connection.prototype.flush = function () {
Connection.prototype.flush = function() {
if (this.stream.writable) {
this.stream.write(flushBuffer)
}
}
const syncBuffer = serialize.sync()
Connection.prototype.sync = function () {
Connection.prototype.sync = function() {
this._ending = true
this._send(syncBuffer)
this._send(flushBuffer)
@ -184,7 +184,7 @@ Connection.prototype.sync = function () {
const endBuffer = serialize.end()
Connection.prototype.end = function () {
Connection.prototype.end = function() {
// 0x58 = 'X'
this._ending = true
if (!this.stream.writable) {
@ -196,23 +196,23 @@ Connection.prototype.end = function () {
})
}
Connection.prototype.close = function (msg) {
Connection.prototype.close = function(msg) {
this._send(serialize.close(msg))
}
Connection.prototype.describe = function (msg) {
Connection.prototype.describe = function(msg) {
this._send(serialize.describe(msg))
}
Connection.prototype.sendCopyFromChunk = function (chunk) {
Connection.prototype.sendCopyFromChunk = function(chunk) {
this._send(serialize.copyData(chunk))
}
Connection.prototype.endCopyFrom = function () {
Connection.prototype.endCopyFrom = function() {
this._send(serialize.copyDone())
}
Connection.prototype.sendCopyFail = function (msg) {
Connection.prototype.sendCopyFail = function(msg) {
this._send(serialize.copyFail(msg))
}

View File

@ -13,7 +13,7 @@ var defaults = require('./defaults')
var parse = require('pg-connection-string').parse // parses a connection string
var val = function (key, config, envVar) {
var val = function(key, config, envVar) {
if (envVar === undefined) {
envVar = process.env['PG' + key.toUpperCase()]
} else if (envVar === false) {
@ -25,7 +25,7 @@ var val = function (key, config, envVar) {
return config[key] || envVar || defaults[key]
}
var useSsl = function () {
var useSsl = function() {
switch (process.env.PGSSLMODE) {
case 'disable':
return false
@ -38,7 +38,7 @@ var useSsl = function () {
return defaults.ssl
}
var ConnectionParameters = function (config) {
var ConnectionParameters = function(config) {
// if a string is passed, it is a raw connection string so we parse it into a config
config = typeof config === 'string' ? parse(config) : config || {}
@ -98,18 +98,18 @@ var ConnectionParameters = function (config) {
}
// Convert arg to a string, surround in single quotes, and escape single quotes and backslashes
var quoteParamValue = function (value) {
var quoteParamValue = function(value) {
return "'" + ('' + value).replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'"
}
var add = function (params, config, paramName) {
var add = function(params, config, paramName) {
var value = config[paramName]
if (value !== undefined && value !== null) {
params.push(paramName + '=' + quoteParamValue(value))
}
}
ConnectionParameters.prototype.getLibpqConnectionString = function (cb) {
ConnectionParameters.prototype.getLibpqConnectionString = function(cb) {
var params = []
add(params, this, 'user')
add(params, this, 'password')
@ -140,7 +140,7 @@ ConnectionParameters.prototype.getLibpqConnectionString = function (cb) {
if (this.client_encoding) {
params.push('client_encoding=' + quoteParamValue(this.client_encoding))
}
dns.lookup(this.host, function (err, address) {
dns.lookup(this.host, function(err, address) {
if (err) return cb(err, null)
params.push('hostaddr=' + quoteParamValue(address))
return cb(null, params.join(' '))

View File

@ -16,7 +16,7 @@ var Reader = require('packet-reader')
var TEXT_MODE = 0
var BINARY_MODE = 1
var Connection = function (config) {
var Connection = function(config) {
EventEmitter.call(this)
config = config || {}
this.stream = config.stream || new net.Socket()
@ -38,7 +38,7 @@ var Connection = function (config) {
lengthPadding: -4,
})
var self = this
this.on('newListener', function (eventName) {
this.on('newListener', function(eventName) {
if (eventName === 'message') {
self._emitMessage = true
}
@ -47,7 +47,7 @@ var Connection = function (config) {
util.inherits(Connection, EventEmitter)
Connection.prototype.connect = function (port, host) {
Connection.prototype.connect = function(port, host) {
var self = this
if (this.stream.readyState === 'closed') {
@ -56,14 +56,14 @@ Connection.prototype.connect = function (port, host) {
this.emit('connect')
}
this.stream.on('connect', function () {
this.stream.on('connect', function() {
if (self._keepAlive) {
self.stream.setKeepAlive(true, self._keepAliveInitialDelayMillis)
}
self.emit('connect')
})
const reportStreamError = function (error) {
const reportStreamError = function(error) {
// errors about disconnections should be ignored during disconnect
if (self._ending && (error.code === 'ECONNRESET' || error.code === 'EPIPE')) {
return
@ -72,7 +72,7 @@ Connection.prototype.connect = function (port, host) {
}
this.stream.on('error', reportStreamError)
this.stream.on('close', function () {
this.stream.on('close', function() {
self.emit('end')
})
@ -80,7 +80,7 @@ Connection.prototype.connect = function (port, host) {
return this.attachListeners(this.stream)
}
this.stream.once('data', function (buffer) {
this.stream.once('data', function(buffer) {
var responseCode = buffer.toString('utf8')
switch (responseCode) {
case 'S': // Server supports SSL connections, continue with a secure connection
@ -110,9 +110,9 @@ Connection.prototype.connect = function (port, host) {
})
}
Connection.prototype.attachListeners = function (stream) {
Connection.prototype.attachListeners = function(stream) {
var self = this
stream.on('data', function (buff) {
stream.on('data', function(buff) {
self._reader.addChunk(buff)
var packet = self._reader.read()
while (packet) {
@ -125,24 +125,30 @@ Connection.prototype.attachListeners = function (stream) {
packet = self._reader.read()
}
})
stream.on('end', function () {
stream.on('end', function() {
self.emit('end')
})
}
Connection.prototype.requestSsl = function () {
var bodyBuffer = this.writer.addInt16(0x04d2).addInt16(0x162f).flush()
Connection.prototype.requestSsl = function() {
var bodyBuffer = this.writer
.addInt16(0x04d2)
.addInt16(0x162f)
.flush()
var length = bodyBuffer.length + 4
var buffer = new Writer().addInt32(length).add(bodyBuffer).join()
var buffer = new Writer()
.addInt32(length)
.add(bodyBuffer)
.join()
this.stream.write(buffer)
}
Connection.prototype.startup = function (config) {
Connection.prototype.startup = function(config) {
var writer = this.writer.addInt16(3).addInt16(0)
Object.keys(config).forEach(function (key) {
Object.keys(config).forEach(function(key) {
var val = config[key]
writer.addCString(key).addCString(val)
})
@ -154,39 +160,53 @@ Connection.prototype.startup = function (config) {
var length = bodyBuffer.length + 4
var buffer = new Writer().addInt32(length).add(bodyBuffer).join()
var buffer = new Writer()
.addInt32(length)
.add(bodyBuffer)
.join()
this.stream.write(buffer)
}
Connection.prototype.cancel = function (processID, secretKey) {
var bodyBuffer = this.writer.addInt16(1234).addInt16(5678).addInt32(processID).addInt32(secretKey).flush()
Connection.prototype.cancel = function(processID, secretKey) {
var bodyBuffer = this.writer
.addInt16(1234)
.addInt16(5678)
.addInt32(processID)
.addInt32(secretKey)
.flush()
var length = bodyBuffer.length + 4
var buffer = new Writer().addInt32(length).add(bodyBuffer).join()
var buffer = new Writer()
.addInt32(length)
.add(bodyBuffer)
.join()
this.stream.write(buffer)
}
Connection.prototype.password = function (password) {
Connection.prototype.password = function(password) {
// 0x70 = 'p'
this._send(0x70, this.writer.addCString(password))
}
Connection.prototype.sendSASLInitialResponseMessage = function (mechanism, initialResponse) {
Connection.prototype.sendSASLInitialResponseMessage = function(mechanism, initialResponse) {
// 0x70 = 'p'
this.writer.addCString(mechanism).addInt32(Buffer.byteLength(initialResponse)).addString(initialResponse)
this.writer
.addCString(mechanism)
.addInt32(Buffer.byteLength(initialResponse))
.addString(initialResponse)
this._send(0x70)
}
Connection.prototype.sendSCRAMClientFinalMessage = function (additionalData) {
Connection.prototype.sendSCRAMClientFinalMessage = function(additionalData) {
// 0x70 = 'p'
this.writer.addString(additionalData)
this._send(0x70)
}
Connection.prototype._send = function (code, more) {
Connection.prototype._send = function(code, more) {
if (!this.stream.writable) {
return false
}
@ -197,14 +217,14 @@ Connection.prototype._send = function (code, more) {
}
}
Connection.prototype.query = function (text) {
Connection.prototype.query = function(text) {
// 0x51 = Q
this.stream.write(this.writer.addCString(text).flush(0x51))
}
// send parse message
// "more" === true to buffer the message until flush() is called
Connection.prototype.parse = function (query, more) {
Connection.prototype.parse = function(query, more) {
// expect something like this:
// { name: 'queryName',
// text: 'select * from blah',
@ -236,7 +256,7 @@ Connection.prototype.parse = function (query, more) {
// send bind message
// "more" === true to buffer the message until flush() is called
Connection.prototype.bind = function (config, more) {
Connection.prototype.bind = function(config, more) {
// normalize config
config = config || {}
config.portal = config.portal || ''
@ -283,7 +303,7 @@ Connection.prototype.bind = function (config, more) {
// send execute message
// "more" === true to buffer the message until flush() is called
Connection.prototype.execute = function (config, more) {
Connection.prototype.execute = function(config, more) {
config = config || {}
config.portal = config.portal || ''
config.rows = config.rows || ''
@ -295,13 +315,13 @@ Connection.prototype.execute = function (config, more) {
var emptyBuffer = Buffer.alloc(0)
Connection.prototype.flush = function () {
Connection.prototype.flush = function() {
// 0x48 = 'H'
this.writer.add(emptyBuffer)
this._send(0x48)
}
Connection.prototype.sync = function () {
Connection.prototype.sync = function() {
// clear out any pending data in the writer
this.writer.flush(0)
@ -312,7 +332,7 @@ Connection.prototype.sync = function () {
const END_BUFFER = Buffer.from([0x58, 0x00, 0x00, 0x00, 0x04])
Connection.prototype.end = function () {
Connection.prototype.end = function() {
// 0x58 = 'X'
this.writer.add(emptyBuffer)
this._ending = true
@ -325,36 +345,36 @@ Connection.prototype.end = function () {
})
}
Connection.prototype.close = function (msg, more) {
Connection.prototype.close = function(msg, more) {
this.writer.addCString(msg.type + (msg.name || ''))
this._send(0x43, more)
}
Connection.prototype.describe = function (msg, more) {
Connection.prototype.describe = function(msg, more) {
this.writer.addCString(msg.type + (msg.name || ''))
this._send(0x44, more)
}
Connection.prototype.sendCopyFromChunk = function (chunk) {
Connection.prototype.sendCopyFromChunk = function(chunk) {
this.stream.write(this.writer.add(chunk).flush(0x64))
}
Connection.prototype.endCopyFrom = function () {
Connection.prototype.endCopyFrom = function() {
this.stream.write(this.writer.add(emptyBuffer).flush(0x63))
}
Connection.prototype.sendCopyFail = function (msg) {
Connection.prototype.sendCopyFail = function(msg) {
// this.stream.write(this.writer.add(emptyBuffer).flush(0x66));
this.writer.addCString(msg)
this._send(0x66)
}
var Message = function (name, length) {
var Message = function(name, length) {
this.name = name
this.length = length
}
Connection.prototype.parseMessage = function (buffer) {
Connection.prototype.parseMessage = function(buffer) {
this.offset = 0
var length = buffer.length + 4
switch (this._reader.header) {
@ -423,7 +443,7 @@ Connection.prototype.parseMessage = function (buffer) {
}
}
Connection.prototype.parseR = function (buffer, length) {
Connection.prototype.parseR = function(buffer, length) {
var code = this.parseInt32(buffer)
var msg = new Message('authenticationOk', length)
@ -474,27 +494,27 @@ Connection.prototype.parseR = function (buffer, length) {
throw new Error('Unknown authenticationOk message type' + util.inspect(msg))
}
Connection.prototype.parseS = function (buffer, length) {
Connection.prototype.parseS = function(buffer, length) {
var msg = new Message('parameterStatus', length)
msg.parameterName = this.parseCString(buffer)
msg.parameterValue = this.parseCString(buffer)
return msg
}
Connection.prototype.parseK = function (buffer, length) {
Connection.prototype.parseK = function(buffer, length) {
var msg = new Message('backendKeyData', length)
msg.processID = this.parseInt32(buffer)
msg.secretKey = this.parseInt32(buffer)
return msg
}
Connection.prototype.parseC = function (buffer, length) {
Connection.prototype.parseC = function(buffer, length) {
var msg = new Message('commandComplete', length)
msg.text = this.parseCString(buffer)
return msg
}
Connection.prototype.parseZ = function (buffer, length) {
Connection.prototype.parseZ = function(buffer, length) {
var msg = new Message('readyForQuery', length)
msg.name = 'readyForQuery'
msg.status = this.readString(buffer, 1)
@ -502,7 +522,7 @@ Connection.prototype.parseZ = function (buffer, length) {
}
var ROW_DESCRIPTION = 'rowDescription'
Connection.prototype.parseT = function (buffer, length) {
Connection.prototype.parseT = function(buffer, length) {
var msg = new Message(ROW_DESCRIPTION, length)
msg.fieldCount = this.parseInt16(buffer)
var fields = []
@ -513,7 +533,7 @@ Connection.prototype.parseT = function (buffer, length) {
return msg
}
var Field = function () {
var Field = function() {
this.name = null
this.tableID = null
this.columnID = null
@ -525,7 +545,7 @@ var Field = function () {
var FORMAT_TEXT = 'text'
var FORMAT_BINARY = 'binary'
Connection.prototype.parseField = function (buffer) {
Connection.prototype.parseField = function(buffer) {
var field = new Field()
field.name = this.parseCString(buffer)
field.tableID = this.parseInt32(buffer)
@ -544,7 +564,7 @@ Connection.prototype.parseField = function (buffer) {
}
var DATA_ROW = 'dataRow'
var DataRowMessage = function (length, fieldCount) {
var DataRowMessage = function(length, fieldCount) {
this.name = DATA_ROW
this.length = length
this.fieldCount = fieldCount
@ -552,7 +572,7 @@ var DataRowMessage = function (length, fieldCount) {
}
// extremely hot-path code
Connection.prototype.parseD = function (buffer, length) {
Connection.prototype.parseD = function(buffer, length) {
var fieldCount = this.parseInt16(buffer)
var msg = new DataRowMessage(length, fieldCount)
for (var i = 0; i < fieldCount; i++) {
@ -562,7 +582,7 @@ Connection.prototype.parseD = function (buffer, length) {
}
// extremely hot-path code
Connection.prototype._readValue = function (buffer) {
Connection.prototype._readValue = function(buffer) {
var length = this.parseInt32(buffer)
if (length === -1) return null
if (this._mode === TEXT_MODE) {
@ -572,7 +592,7 @@ Connection.prototype._readValue = function (buffer) {
}
// parses error
Connection.prototype.parseE = function (buffer, length, isNotice) {
Connection.prototype.parseE = function(buffer, length, isNotice) {
var fields = {}
var fieldType = this.readString(buffer, 1)
while (fieldType !== '\0') {
@ -607,13 +627,13 @@ Connection.prototype.parseE = function (buffer, length, isNotice) {
}
// same thing, different name
Connection.prototype.parseN = function (buffer, length) {
Connection.prototype.parseN = function(buffer, length) {
var msg = this.parseE(buffer, length, true)
msg.name = 'notice'
return msg
}
Connection.prototype.parseA = function (buffer, length) {
Connection.prototype.parseA = function(buffer, length) {
var msg = new Message('notification', length)
msg.processId = this.parseInt32(buffer)
msg.channel = this.parseCString(buffer)
@ -621,17 +641,17 @@ Connection.prototype.parseA = function (buffer, length) {
return msg
}
Connection.prototype.parseG = function (buffer, length) {
Connection.prototype.parseG = function(buffer, length) {
var msg = new Message('copyInResponse', length)
return this.parseGH(buffer, msg)
}
Connection.prototype.parseH = function (buffer, length) {
Connection.prototype.parseH = function(buffer, length) {
var msg = new Message('copyOutResponse', length)
return this.parseGH(buffer, msg)
}
Connection.prototype.parseGH = function (buffer, msg) {
Connection.prototype.parseGH = function(buffer, msg) {
var isBinary = buffer[this.offset] !== 0
this.offset++
msg.binary = isBinary
@ -643,33 +663,33 @@ Connection.prototype.parseGH = function (buffer, msg) {
return msg
}
Connection.prototype.parsed = function (buffer, length) {
Connection.prototype.parsed = function(buffer, length) {
var msg = new Message('copyData', length)
msg.chunk = this.readBytes(buffer, msg.length - 4)
return msg
}
Connection.prototype.parseInt32 = function (buffer) {
Connection.prototype.parseInt32 = function(buffer) {
var value = buffer.readInt32BE(this.offset)
this.offset += 4
return value
}
Connection.prototype.parseInt16 = function (buffer) {
Connection.prototype.parseInt16 = function(buffer) {
var value = buffer.readInt16BE(this.offset)
this.offset += 2
return value
}
Connection.prototype.readString = function (buffer, length) {
Connection.prototype.readString = function(buffer, length) {
return buffer.toString(this.encoding, this.offset, (this.offset += length))
}
Connection.prototype.readBytes = function (buffer, length) {
Connection.prototype.readBytes = function(buffer, length) {
return buffer.slice(this.offset, (this.offset += length))
}
Connection.prototype.parseCString = function (buffer) {
Connection.prototype.parseCString = function(buffer) {
var start = this.offset
var end = buffer.indexOf(0, start)
this.offset = end + 1

View File

@ -79,7 +79,7 @@ var parseBigInteger = pgTypes.getTypeParser(20, 'text')
var parseBigIntegerArray = pgTypes.getTypeParser(1016, 'text')
// parse int8 so you can get your count values as actual numbers
module.exports.__defineSetter__('parseInt8', function (val) {
module.exports.__defineSetter__('parseInt8', function(val) {
pgTypes.setTypeParser(20, 'text', val ? pgTypes.getTypeParser(23, 'text') : parseBigInteger)
pgTypes.setTypeParser(1016, 'text', val ? pgTypes.getTypeParser(1007, 'text') : parseBigIntegerArray)
})

View File

@ -20,7 +20,7 @@ const poolFactory = (Client) => {
}
}
var PG = function (clientConstructor) {
var PG = function(clientConstructor) {
this.defaults = defaults
this.Client = clientConstructor
this.Query = this.Client.Query

View File

@ -22,7 +22,7 @@ assert(semver.gte(Native.version, pkg.minNativeVersion), msg)
var NativeQuery = require('./query')
var Client = (module.exports = function (config) {
var Client = (module.exports = function(config) {
EventEmitter.call(this)
config = config || {}
@ -64,7 +64,7 @@ Client.Query = NativeQuery
util.inherits(Client, EventEmitter)
Client.prototype._errorAllQueries = function (err) {
Client.prototype._errorAllQueries = function(err) {
const enqueueError = (query) => {
process.nextTick(() => {
query.native = this.native
@ -84,7 +84,7 @@ Client.prototype._errorAllQueries = function (err) {
// connect to the backend
// pass an optional callback to be called once connected
// or with an error if there was a connection error
Client.prototype._connect = function (cb) {
Client.prototype._connect = function(cb) {
var self = this
if (this._connecting) {
@ -94,9 +94,9 @@ Client.prototype._connect = function (cb) {
this._connecting = true
this.connectionParameters.getLibpqConnectionString(function (err, conString) {
this.connectionParameters.getLibpqConnectionString(function(err, conString) {
if (err) return cb(err)
self.native.connect(conString, function (err) {
self.native.connect(conString, function(err) {
if (err) {
self.native.end()
return cb(err)
@ -106,13 +106,13 @@ Client.prototype._connect = function (cb) {
self._connected = true
// handle connection errors from the native layer
self.native.on('error', function (err) {
self.native.on('error', function(err) {
self._queryable = false
self._errorAllQueries(err)
self.emit('error', err)
})
self.native.on('notification', function (msg) {
self.native.on('notification', function(msg) {
self.emit('notification', {
channel: msg.relname,
payload: msg.extra,
@ -128,7 +128,7 @@ Client.prototype._connect = function (cb) {
})
}
Client.prototype.connect = function (callback) {
Client.prototype.connect = function(callback) {
if (callback) {
this._connect(callback)
return
@ -155,7 +155,7 @@ Client.prototype.connect = function (callback) {
// optional string name to name & cache the query plan
// optional string rowMode = 'array' for an array of results
// }
Client.prototype.query = function (config, values, callback) {
Client.prototype.query = function(config, values, callback) {
var query
var result
var readTimeout
@ -237,7 +237,7 @@ Client.prototype.query = function (config, values, callback) {
}
// disconnect from the backend server
Client.prototype.end = function (cb) {
Client.prototype.end = function(cb) {
var self = this
this._ending = true
@ -247,11 +247,11 @@ Client.prototype.end = function (cb) {
}
var result
if (!cb) {
result = new this._Promise(function (resolve, reject) {
result = new this._Promise(function(resolve, reject) {
cb = (err) => (err ? reject(err) : resolve())
})
}
this.native.end(function () {
this.native.end(function() {
self._errorAllQueries(new Error('Connection terminated'))
process.nextTick(() => {
@ -262,11 +262,11 @@ Client.prototype.end = function (cb) {
return result
}
Client.prototype._hasActiveQuery = function () {
Client.prototype._hasActiveQuery = function() {
return this._activeQuery && this._activeQuery.state !== 'error' && this._activeQuery.state !== 'end'
}
Client.prototype._pulseQueryQueue = function (initialConnection) {
Client.prototype._pulseQueryQueue = function(initialConnection) {
if (!this._connected) {
return
}
@ -283,24 +283,24 @@ Client.prototype._pulseQueryQueue = function (initialConnection) {
this._activeQuery = query
query.submit(this)
var self = this
query.once('_done', function () {
query.once('_done', function() {
self._pulseQueryQueue()
})
}
// attempt to cancel an in-progress query
Client.prototype.cancel = function (query) {
Client.prototype.cancel = function(query) {
if (this._activeQuery === query) {
this.native.cancel(function () {})
this.native.cancel(function() {})
} else if (this._queryQueue.indexOf(query) !== -1) {
this._queryQueue.splice(this._queryQueue.indexOf(query), 1)
}
}
Client.prototype.setTypeParser = function (oid, format, parseFn) {
Client.prototype.setTypeParser = function(oid, format, parseFn) {
return this._types.setTypeParser(oid, format, parseFn)
}
Client.prototype.getTypeParser = function (oid, format) {
Client.prototype.getTypeParser = function(oid, format) {
return this._types.getTypeParser(oid, format)
}

View File

@ -11,7 +11,7 @@ var EventEmitter = require('events').EventEmitter
var util = require('util')
var utils = require('../utils')
var NativeQuery = (module.exports = function (config, values, callback) {
var NativeQuery = (module.exports = function(config, values, callback) {
EventEmitter.call(this)
config = utils.normalizeQueryConfig(config, values, callback)
this.text = config.text
@ -29,7 +29,7 @@ var NativeQuery = (module.exports = function (config, values, callback) {
this._emitRowEvents = false
this.on(
'newListener',
function (event) {
function(event) {
if (event === 'row') this._emitRowEvents = true
}.bind(this)
)
@ -53,7 +53,7 @@ var errorFieldMap = {
sourceFunction: 'routine',
}
NativeQuery.prototype.handleError = function (err) {
NativeQuery.prototype.handleError = function(err) {
// copy pq error fields into the error object
var fields = this.native.pq.resultErrorFields()
if (fields) {
@ -70,18 +70,18 @@ NativeQuery.prototype.handleError = function (err) {
this.state = 'error'
}
NativeQuery.prototype.then = function (onSuccess, onFailure) {
NativeQuery.prototype.then = function(onSuccess, onFailure) {
return this._getPromise().then(onSuccess, onFailure)
}
NativeQuery.prototype.catch = function (callback) {
NativeQuery.prototype.catch = function(callback) {
return this._getPromise().catch(callback)
}
NativeQuery.prototype._getPromise = function () {
NativeQuery.prototype._getPromise = function() {
if (this._promise) return this._promise
this._promise = new Promise(
function (resolve, reject) {
function(resolve, reject) {
this._once('end', resolve)
this._once('error', reject)
}.bind(this)
@ -89,15 +89,15 @@ NativeQuery.prototype._getPromise = function () {
return this._promise
}
NativeQuery.prototype.submit = function (client) {
NativeQuery.prototype.submit = function(client) {
this.state = 'running'
var self = this
this.native = client.native
client.native.arrayMode = this._arrayMode
var after = function (err, rows, results) {
var after = function(err, rows, results) {
client.native.arrayMode = false
setImmediate(function () {
setImmediate(function() {
self.emit('_done')
})
@ -115,7 +115,7 @@ NativeQuery.prototype.submit = function (client) {
})
})
} else {
rows.forEach(function (row) {
rows.forEach(function(row) {
self.emit('row', row, results)
})
}
@ -154,7 +154,7 @@ NativeQuery.prototype.submit = function (client) {
return client.native.execute(this.name, values, after)
}
// plan the named query the first time, then execute it
return client.native.prepare(this.name, this.text, values.length, function (err) {
return client.native.prepare(this.name, this.text, values.length, function(err) {
if (err) return after(err)
client.namedQueries[self.name] = self.text
return self.native.execute(self.name, values, after)

View File

@ -12,7 +12,7 @@ var types = require('pg-types')
// result object returned from query
// in the 'end' event and also
// passed as second argument to provided callback
var Result = function (rowMode, types) {
var Result = function(rowMode, types) {
this.command = null
this.rowCount = null
this.oid = null
@ -30,7 +30,7 @@ var Result = function (rowMode, types) {
var matchRegexp = /^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/
// adds a command complete message
Result.prototype.addCommandComplete = function (msg) {
Result.prototype.addCommandComplete = function(msg) {
var match
if (msg.text) {
// pure javascript
@ -52,7 +52,7 @@ Result.prototype.addCommandComplete = function (msg) {
}
}
Result.prototype._parseRowAsArray = function (rowData) {
Result.prototype._parseRowAsArray = function(rowData) {
var row = new Array(rowData.length)
for (var i = 0, len = rowData.length; i < len; i++) {
var rawValue = rowData[i]
@ -65,7 +65,7 @@ Result.prototype._parseRowAsArray = function (rowData) {
return row
}
Result.prototype.parseRow = function (rowData) {
Result.prototype.parseRow = function(rowData) {
var row = {}
for (var i = 0, len = rowData.length; i < len; i++) {
var rawValue = rowData[i]
@ -79,11 +79,11 @@ Result.prototype.parseRow = function (rowData) {
return row
}
Result.prototype.addRow = function (row) {
Result.prototype.addRow = function(row) {
this.rows.push(row)
}
Result.prototype.addFields = function (fieldDescriptions) {
Result.prototype.addFields = function(fieldDescriptions) {
// clears field definitions
// multiple query statements in 1 action can result in multiple sets
// of rowDescriptions...eg: 'select NOW(); select 1::int;'

View File

@ -32,7 +32,10 @@ function continueSession(session, password, serverData) {
var saltedPassword = Hi(password, saltBytes, sv.iteration)
var clientKey = createHMAC(saltedPassword, 'Client Key')
var storedKey = crypto.createHash('sha256').update(clientKey).digest()
var storedKey = crypto
.createHash('sha256')
.update(clientKey)
.digest()
var clientFirstMessageBare = 'n=*,r=' + session.clientNonce
var serverFirstMessage = 'r=' + sv.nonce + ',s=' + sv.salt + ',i=' + sv.iteration
@ -62,7 +65,7 @@ function finalizeSession(session, serverData) {
String(serverData)
.split(',')
.forEach(function (part) {
.forEach(function(part) {
switch (part[0]) {
case 'v':
serverSignature = part.substr(2)
@ -80,7 +83,7 @@ function extractVariablesFromFirstServerMessage(data) {
String(data)
.split(',')
.forEach(function (part) {
.forEach(function(part) {
switch (part[0]) {
case 'r':
nonce = part.substr(2)
@ -130,7 +133,10 @@ function xorBuffers(a, b) {
}
function createHMAC(key, msg) {
return crypto.createHmac('sha256', key).update(msg).digest()
return crypto
.createHmac('sha256', key)
.update(msg)
.digest()
}
function Hi(password, saltBytes, iterations) {

View File

@ -15,7 +15,7 @@ function TypeOverrides(userTypes) {
this.binary = {}
}
TypeOverrides.prototype.getOverrides = function (format) {
TypeOverrides.prototype.getOverrides = function(format) {
switch (format) {
case 'text':
return this.text
@ -26,7 +26,7 @@ TypeOverrides.prototype.getOverrides = function (format) {
}
}
TypeOverrides.prototype.setTypeParser = function (oid, format, parseFn) {
TypeOverrides.prototype.setTypeParser = function(oid, format, parseFn) {
if (typeof format === 'function') {
parseFn = format
format = 'text'
@ -34,7 +34,7 @@ TypeOverrides.prototype.setTypeParser = function (oid, format, parseFn) {
this.getOverrides(format)[oid] = parseFn
}
TypeOverrides.prototype.getTypeParser = function (oid, format) {
TypeOverrides.prototype.getTypeParser = function(oid, format) {
format = format || 'text'
return this.getOverrides(format)[oid] || this._types.getTypeParser(oid, format)
}

View File

@ -44,7 +44,7 @@ function arrayString(val) {
// to their 'raw' counterparts for use as a postgres parameter
// note: you can override this function to provide your own conversion mechanism
// for complex types, etc...
var prepareValue = function (val, seen) {
var prepareValue = function(val, seen) {
if (val instanceof Buffer) {
return val
}
@ -170,12 +170,15 @@ function normalizeQueryConfig(config, values, callback) {
return config
}
const md5 = function (string) {
return crypto.createHash('md5').update(string, 'utf-8').digest('hex')
const md5 = function(string) {
return crypto
.createHash('md5')
.update(string, 'utf-8')
.digest('hex')
}
// See AuthenticationMD5Password at https://www.postgresql.org/docs/current/static/protocol-flow.html
const postgresMd5PasswordHash = function (user, password, salt) {
const postgresMd5PasswordHash = function(user, password, salt) {
var inner = md5(password + user)
var outer = md5(Buffer.concat([Buffer.from(inner), salt]))
return 'md5' + outer

View File

@ -4,14 +4,14 @@ var args = require(__dirname + '/../test/cli')
var queries = ['select CURRENT_TIMESTAMP', "select interval '1 day' + interval '1 hour'", "select TIMESTAMP 'today'"]
queries.forEach(function (query) {
queries.forEach(function(query) {
var client = new pg.Client({
user: args.user,
database: args.database,
password: args.password,
})
client.connect()
client.query(query).on('row', function (row) {
client.query(query).on('row', function(row) {
console.log(row)
client.end()
})

View File

@ -3,7 +3,7 @@ var helper = require(__dirname + '/../test/integration/test-helper')
var pg = helper.pg
pg.connect(
helper.config,
assert.success(function (client) {
assert.success(function(client) {
var query = client.query("select oid, typname from pg_type where typtype = 'b' order by oid")
query.on('row', console.log)
})

View File

@ -1,32 +1,32 @@
'use strict'
global.BufferList = function () {
global.BufferList = function() {
this.buffers = []
}
var p = BufferList.prototype
p.add = function (buffer, front) {
p.add = function(buffer, front) {
this.buffers[front ? 'unshift' : 'push'](buffer)
return this
}
p.addInt16 = function (val, front) {
p.addInt16 = function(val, front) {
return this.add(Buffer.from([val >>> 8, val >>> 0]), front)
}
p.getByteLength = function (initial) {
return this.buffers.reduce(function (previous, current) {
p.getByteLength = function(initial) {
return this.buffers.reduce(function(previous, current) {
return previous + current.length
}, initial || 0)
}
p.addInt32 = function (val, first) {
p.addInt32 = function(val, first) {
return this.add(
Buffer.from([(val >>> 24) & 0xff, (val >>> 16) & 0xff, (val >>> 8) & 0xff, (val >>> 0) & 0xff]),
first
)
}
p.addCString = function (val, front) {
p.addCString = function(val, front) {
var len = Buffer.byteLength(val)
var buffer = Buffer.alloc(len + 1)
buffer.write(val)
@ -34,18 +34,18 @@ p.addCString = function (val, front) {
return this.add(buffer, front)
}
p.addString = function (val, front) {
p.addString = function(val, front) {
var len = Buffer.byteLength(val)
var buffer = Buffer.alloc(len)
buffer.write(val)
return this.add(buffer, front)
}
p.addChar = function (char, first) {
p.addChar = function(char, first) {
return this.add(Buffer.from(char, 'utf8'), first)
}
p.join = function (appendLength, char) {
p.join = function(appendLength, char) {
var length = this.getByteLength()
if (appendLength) {
this.addInt32(length + 4, true)
@ -57,14 +57,14 @@ p.join = function (appendLength, char) {
}
var result = Buffer.alloc(length)
var index = 0
this.buffers.forEach(function (buffer) {
this.buffers.forEach(function(buffer) {
buffer.copy(result, index, 0)
index += buffer.length
})
return result
}
BufferList.concat = function () {
BufferList.concat = function() {
var total = new BufferList()
for (var i = 0; i < arguments.length; i++) {
total.add(arguments[i])

View File

@ -4,10 +4,10 @@ var pg = helper.pg
var suite = new helper.Suite()
suite.test('null and undefined are both inserted as NULL', function (done) {
suite.test('null and undefined are both inserted as NULL', function(done) {
const pool = new pg.Pool()
pool.connect(
assert.calls(function (err, client, release) {
assert.calls(function(err, client, release) {
assert(!err)
client.query('CREATE TEMP TABLE my_nulls(a varchar(1), b varchar(1), c integer, d integer, e date, f date)')
client.query('INSERT INTO my_nulls(a,b,c,d,e,f) VALUES ($1,$2,$3,$4,$5,$6)', [
@ -20,7 +20,7 @@ suite.test('null and undefined are both inserted as NULL', function (done) {
])
client.query(
'SELECT * FROM my_nulls',
assert.calls(function (err, result) {
assert.calls(function(err, result) {
console.log(err)
assert.ifError(err)
assert.equal(result.rows.length, 1)
@ -41,7 +41,7 @@ suite.test('null and undefined are both inserted as NULL', function (done) {
suite.test('pool callback behavior', (done) => {
// test weird callback behavior with node-pool
const pool = new pg.Pool()
pool.connect(function (err) {
pool.connect(function(err) {
assert(!err)
arguments[1].emit('drain')
arguments[2]()
@ -54,7 +54,7 @@ suite.test('query timeout', (cb) => {
pool.connect().then((client) => {
client.query(
'SELECT pg_sleep(2)',
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(err)
assert(err.message === 'Query read timeout')
client.release()
@ -69,14 +69,14 @@ suite.test('query recover from timeout', (cb) => {
pool.connect().then((client) => {
client.query(
'SELECT pg_sleep(20)',
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(err)
assert(err.message === 'Query read timeout')
client.release(err)
pool.connect().then((client) => {
client.query(
'SELECT 1',
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(!err)
client.release(err)
pool.end(cb)
@ -93,7 +93,7 @@ suite.test('query no timeout', (cb) => {
pool.connect().then((client) => {
client.query(
'SELECT pg_sleep(1)',
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(!err)
client.release()
pool.end(cb)
@ -135,21 +135,21 @@ suite.test('callback API', (done) => {
})
})
suite.test('executing nested queries', function (done) {
suite.test('executing nested queries', function(done) {
const pool = new pg.Pool()
pool.connect(
assert.calls(function (err, client, release) {
assert.calls(function(err, client, release) {
assert(!err)
client.query(
'select now as now from NOW()',
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert.equal(new Date().getYear(), result.rows[0].now.getYear())
client.query(
'select now as now_again FROM NOW()',
assert.calls(function () {
assert.calls(function() {
client.query(
'select * FROM NOW()',
assert.calls(function () {
assert.calls(function() {
assert.ok('all queries hit')
release()
pool.end(done)
@ -163,25 +163,25 @@ suite.test('executing nested queries', function (done) {
)
})
suite.test('raises error if cannot connect', function () {
suite.test('raises error if cannot connect', function() {
var connectionString = 'pg://sfalsdkf:asdf@localhost/ieieie'
const pool = new pg.Pool({ connectionString: connectionString })
pool.connect(
assert.calls(function (err, client, done) {
assert.calls(function(err, client, done) {
assert.ok(err, 'should have raised an error')
done()
})
)
})
suite.test('query errors are handled and do not bubble if callback is provided', function (done) {
suite.test('query errors are handled and do not bubble if callback is provided', function(done) {
const pool = new pg.Pool()
pool.connect(
assert.calls(function (err, client, release) {
assert.calls(function(err, client, release) {
assert(!err)
client.query(
'SELECT OISDJF FROM LEIWLISEJLSE',
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert.ok(err)
release()
pool.end(done)
@ -191,10 +191,10 @@ suite.test('query errors are handled and do not bubble if callback is provided',
)
})
suite.test('callback is fired once and only once', function (done) {
suite.test('callback is fired once and only once', function(done) {
const pool = new pg.Pool()
pool.connect(
assert.calls(function (err, client, release) {
assert.calls(function(err, client, release) {
assert(!err)
client.query('CREATE TEMP TABLE boom(name varchar(10))')
var callCount = 0
@ -204,7 +204,7 @@ suite.test('callback is fired once and only once', function (done) {
"INSERT INTO boom(name) VALUES('boom')",
"INSERT INTO boom(name) VALUES('zoom')",
].join(';'),
function (err, callback) {
function(err, callback) {
assert.equal(callCount++, 0, 'Call count should be 0. More means this callback fired more than once.')
release()
pool.end(done)
@ -214,17 +214,17 @@ suite.test('callback is fired once and only once', function (done) {
)
})
suite.test('can provide callback and config object', function (done) {
suite.test('can provide callback and config object', function(done) {
const pool = new pg.Pool()
pool.connect(
assert.calls(function (err, client, release) {
assert.calls(function(err, client, release) {
assert(!err)
client.query(
{
name: 'boom',
text: 'select NOW()',
},
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(!err)
assert.equal(result.rows[0].now.getYear(), new Date().getYear())
release()
@ -235,10 +235,10 @@ suite.test('can provide callback and config object', function (done) {
)
})
suite.test('can provide callback and config and parameters', function (done) {
suite.test('can provide callback and config and parameters', function(done) {
const pool = new pg.Pool()
pool.connect(
assert.calls(function (err, client, release) {
assert.calls(function(err, client, release) {
assert(!err)
var config = {
text: 'select $1::text as val',
@ -246,7 +246,7 @@ suite.test('can provide callback and config and parameters', function (done) {
client.query(
config,
['hi'],
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(!err)
assert.equal(result.rows.length, 1)
assert.equal(result.rows[0].val, 'hi')

View File

@ -13,10 +13,10 @@ function getConInfo(override) {
function getAppName(conf, cb) {
var client = new Client(conf)
client.connect(
assert.success(function () {
assert.success(function() {
client.query(
'SHOW application_name',
assert.success(function (res) {
assert.success(function(res) {
var appName = res.rows[0].application_name
cb(appName)
client.end()
@ -26,50 +26,50 @@ function getAppName(conf, cb) {
)
}
suite.test('No default appliation_name ', function (done) {
suite.test('No default appliation_name ', function(done) {
var conf = getConInfo()
getAppName({}, function (res) {
getAppName({}, function(res) {
assert.strictEqual(res, '')
done()
})
})
suite.test('fallback_application_name is used', function (done) {
suite.test('fallback_application_name is used', function(done) {
var fbAppName = 'this is my app'
var conf = getConInfo({
fallback_application_name: fbAppName,
})
getAppName(conf, function (res) {
getAppName(conf, function(res) {
assert.strictEqual(res, fbAppName)
done()
})
})
suite.test('application_name is used', function (done) {
suite.test('application_name is used', function(done) {
var appName = 'some wired !@#$% application_name'
var conf = getConInfo({
application_name: appName,
})
getAppName(conf, function (res) {
getAppName(conf, function(res) {
assert.strictEqual(res, appName)
done()
})
})
suite.test('application_name has precedence over fallback_application_name', function (done) {
suite.test('application_name has precedence over fallback_application_name', function(done) {
var appName = 'some wired !@#$% application_name'
var fbAppName = 'some other strange $$test$$ appname'
var conf = getConInfo({
application_name: appName,
fallback_application_name: fbAppName,
})
getAppName(conf, function (res) {
getAppName(conf, function(res) {
assert.strictEqual(res, appName)
done()
})
})
suite.test('application_name from connection string', function (done) {
suite.test('application_name from connection string', function(done) {
var appName = 'my app'
var conParams = require(__dirname + '/../../../lib/connection-parameters')
var conf
@ -78,7 +78,7 @@ suite.test('application_name from connection string', function (done) {
} else {
conf = 'postgres://?application_name=' + appName
}
getAppName(conf, function (res) {
getAppName(conf, function(res) {
assert.strictEqual(res, appName)
done()
})
@ -86,9 +86,9 @@ suite.test('application_name from connection string', function (done) {
// TODO: make the test work for native client too
if (!helper.args.native) {
suite.test('application_name is read from the env', function (done) {
suite.test('application_name is read from the env', function(done) {
var appName = (process.env.PGAPPNAME = 'testest')
getAppName({}, function (res) {
getAppName({}, function(res) {
delete process.env.PGAPPNAME
assert.strictEqual(res, appName)
done()

View File

@ -7,14 +7,14 @@ var suite = new helper.Suite()
const pool = new pg.Pool()
pool.connect(
assert.calls(function (err, client, release) {
assert.calls(function(err, client, release) {
assert(!err)
suite.test('nulls', function (done) {
suite.test('nulls', function(done) {
client.query(
'SELECT $1::text[] as array',
[[null]],
assert.success(function (result) {
assert.success(function(result) {
var array = result.rows[0].array
assert.lengthIs(array, 1)
assert.isNull(array[0])
@ -23,7 +23,7 @@ pool.connect(
)
})
suite.test('elements containing JSON-escaped characters', function (done) {
suite.test('elements containing JSON-escaped characters', function(done) {
var param = '\\"\\"'
for (var i = 1; i <= 0x1f; i++) {
@ -33,7 +33,7 @@ pool.connect(
client.query(
'SELECT $1::text[] as array',
[[param]],
assert.success(function (result) {
assert.success(function(result) {
var array = result.rows[0].array
assert.lengthIs(array, 1)
assert.equal(array[0], param)
@ -45,17 +45,17 @@ pool.connect(
suite.test('cleanup', () => release())
pool.connect(
assert.calls(function (err, client, release) {
assert.calls(function(err, client, release) {
assert(!err)
client.query('CREATE TEMP TABLE why(names text[], numbors integer[])')
client
.query(new pg.Query('INSERT INTO why(names, numbors) VALUES(\'{"aaron", "brian","a b c" }\', \'{1, 2, 3}\')'))
.on('error', console.log)
suite.test('numbers', function (done) {
suite.test('numbers', function(done) {
// client.connection.on('message', console.log)
client.query(
'SELECT numbors FROM why',
assert.success(function (result) {
assert.success(function(result) {
assert.lengthIs(result.rows[0].numbors, 3)
assert.equal(result.rows[0].numbors[0], 1)
assert.equal(result.rows[0].numbors[1], 2)
@ -65,10 +65,10 @@ pool.connect(
)
})
suite.test('parses string arrays', function (done) {
suite.test('parses string arrays', function(done) {
client.query(
'SELECT names FROM why',
assert.success(function (result) {
assert.success(function(result) {
var names = result.rows[0].names
assert.lengthIs(names, 3)
assert.equal(names[0], 'aaron')
@ -79,10 +79,10 @@ pool.connect(
)
})
suite.test('empty array', function (done) {
suite.test('empty array', function(done) {
client.query(
"SELECT '{}'::text[] as names",
assert.success(function (result) {
assert.success(function(result) {
var names = result.rows[0].names
assert.lengthIs(names, 0)
done()
@ -90,10 +90,10 @@ pool.connect(
)
})
suite.test('element containing comma', function (done) {
suite.test('element containing comma', function(done) {
client.query(
'SELECT \'{"joe,bob",jim}\'::text[] as names',
assert.success(function (result) {
assert.success(function(result) {
var names = result.rows[0].names
assert.lengthIs(names, 2)
assert.equal(names[0], 'joe,bob')
@ -103,10 +103,10 @@ pool.connect(
)
})
suite.test('bracket in quotes', function (done) {
suite.test('bracket in quotes', function(done) {
client.query(
'SELECT \'{"{","}"}\'::text[] as names',
assert.success(function (result) {
assert.success(function(result) {
var names = result.rows[0].names
assert.lengthIs(names, 2)
assert.equal(names[0], '{')
@ -116,10 +116,10 @@ pool.connect(
)
})
suite.test('null value', function (done) {
suite.test('null value', function(done) {
client.query(
'SELECT \'{joe,null,bob,"NULL"}\'::text[] as names',
assert.success(function (result) {
assert.success(function(result) {
var names = result.rows[0].names
assert.lengthIs(names, 4)
assert.equal(names[0], 'joe')
@ -131,10 +131,10 @@ pool.connect(
)
})
suite.test('element containing quote char', function (done) {
suite.test('element containing quote char', function(done) {
client.query(
"SELECT ARRAY['joe''', 'jim', 'bob\"'] AS names",
assert.success(function (result) {
assert.success(function(result) {
var names = result.rows[0].names
assert.lengthIs(names, 3)
assert.equal(names[0], "joe'")
@ -145,10 +145,10 @@ pool.connect(
)
})
suite.test('nested array', function (done) {
suite.test('nested array', function(done) {
client.query(
"SELECT '{{1,joe},{2,bob}}'::text[] as names",
assert.success(function (result) {
assert.success(function(result) {
var names = result.rows[0].names
assert.lengthIs(names, 2)
@ -164,10 +164,10 @@ pool.connect(
)
})
suite.test('integer array', function (done) {
suite.test('integer array', function(done) {
client.query(
"SELECT '{1,2,3}'::integer[] as names",
assert.success(function (result) {
assert.success(function(result) {
var names = result.rows[0].names
assert.lengthIs(names, 3)
assert.equal(names[0], 1)
@ -178,10 +178,10 @@ pool.connect(
)
})
suite.test('integer nested array', function (done) {
suite.test('integer nested array', function(done) {
client.query(
"SELECT '{{1,100},{2,100},{3,100}}'::integer[] as names",
assert.success(function (result) {
assert.success(function(result) {
var names = result.rows[0].names
assert.lengthIs(names, 3)
assert.equal(names[0][0], 1)
@ -197,7 +197,7 @@ pool.connect(
)
})
suite.test('JS array parameter', function (done) {
suite.test('JS array parameter', function(done) {
client.query(
'SELECT $1::integer[] as names',
[
@ -207,7 +207,7 @@ pool.connect(
[3, 100],
],
],
assert.success(function (result) {
assert.success(function(result) {
var names = result.rows[0].names
assert.lengthIs(names, 3)
assert.equal(names[0][0], 1)

File diff suppressed because one or more lines are too long

View File

@ -11,7 +11,7 @@ for (var key in process.env) {
if (!key.indexOf('PG')) delete process.env[key]
}
suite.test('default values are used in new clients', function () {
suite.test('default values are used in new clients', function() {
assert.same(pg.defaults, {
user: process.env.USER,
database: undefined,
@ -37,7 +37,7 @@ suite.test('default values are used in new clients', function () {
})
})
suite.test('modified values are passed to created clients', function () {
suite.test('modified values are passed to created clients', function() {
pg.defaults.user = 'boom'
pg.defaults.password = 'zap'
pg.defaults.database = 'pow'

View File

@ -13,7 +13,7 @@ suite.test('custom type parser in client config', (done) => {
client.connect().then(() => {
client.query(
'SELECT NOW() as val',
assert.success(function (res) {
assert.success(function(res) {
assert.equal(res.rows[0].val, 'okay!')
client.end().then(done)
})
@ -32,7 +32,7 @@ if (!helper.args.native) {
text: 'SELECT NOW() as val',
types: customTypes,
},
assert.success(function (res) {
assert.success(function(res) {
assert.equal(res.rows[0].val, 'okay!')
client.end().then(done)
})

View File

@ -2,17 +2,17 @@
var helper = require('./test-helper')
const suite = new helper.Suite()
suite.test('empty query message handling', function (done) {
suite.test('empty query message handling', function(done) {
const client = helper.client()
assert.emits(client, 'drain', function () {
assert.emits(client, 'drain', function() {
client.end(done)
})
client.query({ text: '' })
})
suite.test('callback supported', function (done) {
suite.test('callback supported', function(done) {
const client = helper.client()
client.query('', function (err, result) {
client.query('', function(err, result) {
assert(!err)
assert.empty(result.rows)
client.end(done)

View File

@ -6,9 +6,9 @@ var util = require('util')
var pg = helper.pg
const Client = pg.Client
var createErorrClient = function () {
var createErorrClient = function() {
var client = helper.client()
client.once('error', function (err) {
client.once('error', function(err) {
assert.fail('Client shoud not throw error during query execution')
})
client.on('drain', client.end.bind(client))
@ -67,10 +67,10 @@ suite.test('using a client after closing it results in error', (done) => {
})
})
suite.test('query receives error on client shutdown', function (done) {
suite.test('query receives error on client shutdown', function(done) {
var client = new Client()
client.connect(
assert.success(function () {
assert.success(function() {
const config = {
text: 'select pg_sleep(5)',
name: 'foobar',
@ -78,7 +78,7 @@ suite.test('query receives error on client shutdown', function (done) {
let queryError
client.query(
new pg.Query(config),
assert.calls(function (err, res) {
assert.calls(function(err, res) {
assert(err instanceof Error)
queryError = err
})
@ -92,9 +92,9 @@ suite.test('query receives error on client shutdown', function (done) {
)
})
var ensureFuture = function (testClient, done) {
var ensureFuture = function(testClient, done) {
var goodQuery = testClient.query(new pg.Query('select age from boom'))
assert.emits(goodQuery, 'row', function (row) {
assert.emits(goodQuery, 'row', function(row) {
assert.equal(row.age, 28)
done()
})
@ -113,12 +113,12 @@ suite.test('when query is parsing', (done) => {
})
)
assert.emits(query, 'error', function (err) {
assert.emits(query, 'error', function(err) {
ensureFuture(client, done)
})
})
suite.test('when a query is binding', function (done) {
suite.test('when a query is binding', function(done) {
var client = createErorrClient()
var q = client.query({ text: 'CREATE TEMP TABLE boom(age integer); INSERT INTO boom (age) VALUES (28);' })
@ -130,25 +130,25 @@ suite.test('when a query is binding', function (done) {
})
)
assert.emits(query, 'error', function (err) {
assert.emits(query, 'error', function(err) {
assert.equal(err.severity, 'ERROR')
ensureFuture(client, done)
})
})
suite.test('non-query error with callback', function (done) {
suite.test('non-query error with callback', function(done) {
var client = new Client({
user: 'asldkfjsadlfkj',
})
client.connect(
assert.calls(function (error, client) {
assert.calls(function(error, client) {
assert(error instanceof Error)
done()
})
)
})
suite.test('non-error calls supplied callback', function (done) {
suite.test('non-error calls supplied callback', function(done) {
var client = new Client({
user: helper.args.user,
password: helper.args.password,
@ -158,27 +158,27 @@ suite.test('non-error calls supplied callback', function (done) {
})
client.connect(
assert.calls(function (err) {
assert.calls(function(err) {
assert.ifError(err)
client.end(done)
})
)
})
suite.test('when connecting to an invalid host with callback', function (done) {
suite.test('when connecting to an invalid host with callback', function(done) {
var client = new Client({
user: 'very invalid username',
})
client.on('error', () => {
assert.fail('unexpected error event when connecting')
})
client.connect(function (error, client) {
client.connect(function(error, client) {
assert(error instanceof Error)
done()
})
})
suite.test('when connecting to invalid host with promise', function (done) {
suite.test('when connecting to invalid host with promise', function(done) {
var client = new Client({
user: 'very invalid username',
})
@ -188,7 +188,7 @@ suite.test('when connecting to invalid host with promise', function (done) {
client.connect().catch((e) => done())
})
suite.test('non-query error', function (done) {
suite.test('non-query error', function(done) {
var client = new Client({
user: 'asldkfjsadlfkj',
})
@ -203,7 +203,7 @@ suite.test('within a simple query', (done) => {
var query = client.query(new pg.Query("select eeeee from yodas_dsflsd where pixistix = 'zoiks!!!'"))
assert.emits(query, 'error', function (error) {
assert.emits(query, 'error', function(error) {
assert.equal(error.severity, 'ERROR')
done()
})

View File

@ -4,7 +4,7 @@ var sql = 'SELECT 1 AS "\\\'/*", 2 AS "\\\'*/\n + process.exit(-1)] = null;\n//"
var client = new pg.Client()
client.connect()
client.query(sql, function (err, res) {
client.query(sql, function(err, res) {
if (err) throw err
client.end()
})

View File

@ -3,13 +3,13 @@ var helper = require('./test-helper')
const pool = new helper.pg.Pool()
pool.connect(
assert.success(function (client, done) {
assert.success(function(client, done) {
var types = require('pg-types')
// 1231 = numericOID
types.setTypeParser(1700, function () {
types.setTypeParser(1700, function() {
return 'yes'
})
types.setTypeParser(1700, 'binary', function () {
types.setTypeParser(1700, 'binary', function() {
return 'yes'
})
var bignum = '294733346389144765940638005275322203805'
@ -17,7 +17,7 @@ pool.connect(
client.query('INSERT INTO bignumz(id) VALUES ($1)', [bignum])
client.query(
'SELECT * FROM bignumz',
assert.success(function (result) {
assert.success(function(result) {
assert.equal(result.rows[0].id, 'yes')
done()
pool.end()

View File

@ -13,13 +13,13 @@ function getConInfo(override) {
function testClientVersion(cb) {
var client = new Client({})
client.connect(
assert.success(function () {
assert.success(function() {
helper.versionGTE(
client,
100000,
assert.success(function (isGreater) {
assert.success(function(isGreater) {
return client.end(
assert.success(function () {
assert.success(function() {
if (!isGreater) {
console.log(
'skip idle_in_transaction_session_timeout at client-level is only available in v10 and above'
@ -38,10 +38,10 @@ function testClientVersion(cb) {
function getIdleTransactionSessionTimeout(conf, cb) {
var client = new Client(conf)
client.connect(
assert.success(function () {
assert.success(function() {
client.query(
'SHOW idle_in_transaction_session_timeout',
assert.success(function (res) {
assert.success(function(res) {
var timeout = res.rows[0].idle_in_transaction_session_timeout
cb(timeout)
client.end()
@ -53,40 +53,40 @@ function getIdleTransactionSessionTimeout(conf, cb) {
if (!helper.args.native) {
// idle_in_transaction_session_timeout is not supported with the native client
testClientVersion(function () {
suite.test('No default idle_in_transaction_session_timeout ', function (done) {
testClientVersion(function() {
suite.test('No default idle_in_transaction_session_timeout ', function(done) {
getConInfo()
getIdleTransactionSessionTimeout({}, function (res) {
getIdleTransactionSessionTimeout({}, function(res) {
assert.strictEqual(res, '0') // 0 = no timeout
done()
})
})
suite.test('idle_in_transaction_session_timeout integer is used', function (done) {
suite.test('idle_in_transaction_session_timeout integer is used', function(done) {
var conf = getConInfo({
idle_in_transaction_session_timeout: 3000,
})
getIdleTransactionSessionTimeout(conf, function (res) {
getIdleTransactionSessionTimeout(conf, function(res) {
assert.strictEqual(res, '3s')
done()
})
})
suite.test('idle_in_transaction_session_timeout float is used', function (done) {
suite.test('idle_in_transaction_session_timeout float is used', function(done) {
var conf = getConInfo({
idle_in_transaction_session_timeout: 3000.7,
})
getIdleTransactionSessionTimeout(conf, function (res) {
getIdleTransactionSessionTimeout(conf, function(res) {
assert.strictEqual(res, '3s')
done()
})
})
suite.test('idle_in_transaction_session_timeout string is used', function (done) {
suite.test('idle_in_transaction_session_timeout string is used', function(done) {
var conf = getConInfo({
idle_in_transaction_session_timeout: '3000',
})
getIdleTransactionSessionTimeout(conf, function (res) {
getIdleTransactionSessionTimeout(conf, function(res) {
assert.strictEqual(res, '3s')
done()
})

View File

@ -4,11 +4,11 @@ var assert = require('assert')
const pool = new helper.pg.Pool()
pool.connect(
assert.success(function (client, done) {
assert.success(function(client, done) {
helper.versionGTE(
client,
90200,
assert.success(function (jsonSupported) {
assert.success(function(jsonSupported) {
if (!jsonSupported) {
console.log('skip json test on older versions of postgres')
done()
@ -19,7 +19,7 @@ pool.connect(
client.query('INSERT INTO stuff (data) VALUES ($1)', [value])
client.query(
'SELECT * FROM stuff',
assert.success(function (result) {
assert.success(function(result) {
assert.equal(result.rows.length, 1)
assert.equal(typeof result.rows[0].data, 'object')
var row = result.rows[0].data

View File

@ -8,7 +8,7 @@ const suite = new helper.Suite('multiple result sets')
suite.test(
'two select results work',
co.wrap(function* () {
co.wrap(function*() {
const client = new helper.Client()
yield client.connect()
@ -27,7 +27,7 @@ suite.test(
suite.test(
'multiple selects work',
co.wrap(function* () {
co.wrap(function*() {
const client = new helper.Client()
yield client.connect()
@ -57,7 +57,7 @@ suite.test(
suite.test(
'mixed queries and statements',
co.wrap(function* () {
co.wrap(function*() {
const client = new helper.Client()
yield client.connect()

View File

@ -5,24 +5,24 @@ var suite = new helper.Suite()
var net = require('net')
var Server = function (response) {
var Server = function(response) {
this.server = undefined
this.socket = undefined
this.response = response
}
Server.prototype.start = function (cb) {
Server.prototype.start = function(cb) {
// this is our fake postgres server
// it responds with our specified response immediatley after receiving every buffer
// this is sufficient into convincing the client its connectet to a valid backend
// if we respond with a readyForQuery message
this.server = net.createServer(
function (socket) {
function(socket) {
this.socket = socket
if (this.response) {
this.socket.on(
'data',
function (data) {
function(data) {
// deny request for SSL
if (data.length == 8) {
this.socket.write(Buffer.from('N', 'utf8'))
@ -45,22 +45,22 @@ Server.prototype.start = function (cb) {
host: 'localhost',
port: port,
}
this.server.listen(options.port, options.host, function () {
this.server.listen(options.port, options.host, function() {
cb(options)
})
}
Server.prototype.drop = function () {
Server.prototype.drop = function() {
this.socket.destroy()
}
Server.prototype.close = function (cb) {
Server.prototype.close = function(cb) {
this.server.close(cb)
}
var testServer = function (server, cb) {
var testServer = function(server, cb) {
// wait for our server to start
server.start(function (options) {
server.start(function(options) {
// connect a client to it
var client = new helper.Client(options)
client.connect().catch((err) => {
@ -71,13 +71,13 @@ var testServer = function (server, cb) {
server.server.on('connection', () => {
// after 50 milliseconds, drop the client
setTimeout(function () {
setTimeout(function() {
server.drop()
}, 50)
})
// blow up if we don't receive an error
var timeoutId = setTimeout(function () {
var timeoutId = setTimeout(function() {
throw new Error('Client should have emitted an error but it did not.')
}, 5000)
})

View File

@ -2,7 +2,7 @@
var helper = require('./test-helper')
const suite = new helper.Suite()
suite.test('noData message handling', function () {
suite.test('noData message handling', function() {
var client = helper.client()
var q = client.query({
@ -16,7 +16,7 @@ suite.test('noData message handling', function () {
text: 'insert into boom(size) values($1)',
values: [100],
},
function (err, result) {
function(err, result) {
if (err) {
console.log(err)
throw err

View File

@ -4,8 +4,8 @@ var pg = helper.pg
const suite = new helper.Suite()
const pool = new pg.Pool()
suite.test('can access results when no rows are returned', function (done) {
var checkResult = function (result) {
suite.test('can access results when no rows are returned', function(done) {
var checkResult = function(result) {
assert(result.fields, 'should have fields definition')
assert.equal(result.fields.length, 1)
assert.equal(result.fields[0].name, 'val')
@ -13,11 +13,11 @@ suite.test('can access results when no rows are returned', function (done) {
}
pool.connect(
assert.success(function (client, release) {
assert.success(function(client, release) {
const q = new pg.Query('select $1::text as val limit 0', ['hi'])
var query = client.query(
q,
assert.success(function (result) {
assert.success(function(result) {
checkResult(result)
release()
pool.end(done)

View File

@ -3,19 +3,19 @@ const helper = require('./test-helper')
const assert = require('assert')
const suite = new helper.Suite()
suite.test('emits notify message', function (done) {
suite.test('emits notify message', function(done) {
const client = helper.client()
client.query(
'LISTEN boom',
assert.calls(function () {
assert.calls(function() {
const otherClient = helper.client()
let bothEmitted = -1
otherClient.query(
'LISTEN boom',
assert.calls(function () {
assert.emits(client, 'notification', function (msg) {
assert.calls(function() {
assert.emits(client, 'notification', function(msg) {
// make sure PQfreemem doesn't invalidate string pointers
setTimeout(function () {
setTimeout(function() {
assert.equal(msg.channel, 'boom')
assert.ok(
msg.payload == 'omg!' /* 9.x */ || msg.payload == '' /* 8.x */,
@ -24,12 +24,12 @@ suite.test('emits notify message', function (done) {
client.end(++bothEmitted ? done : undefined)
}, 100)
})
assert.emits(otherClient, 'notification', function (msg) {
assert.emits(otherClient, 'notification', function(msg) {
assert.equal(msg.channel, 'boom')
otherClient.end(++bothEmitted ? done : undefined)
})
client.query("NOTIFY boom, 'omg!'", function (err, q) {
client.query("NOTIFY boom, 'omg!'", function(err, q) {
if (err) {
// notify not supported with payload on 8.x
client.query('NOTIFY boom')
@ -42,7 +42,7 @@ suite.test('emits notify message', function (done) {
})
// this test fails on travis due to their config
suite.test('emits notice message', function (done) {
suite.test('emits notice message', function(done) {
if (helper.args.native) {
console.error('notice messages do not work curreintly with node-libpq')
return done()
@ -62,7 +62,7 @@ $$;
client.end()
})
})
assert.emits(client, 'notice', function (notice) {
assert.emits(client, 'notice', function(notice) {
assert.ok(notice != null)
// notice messages should not be error instances
assert(notice instanceof Error === false)

View File

@ -5,15 +5,15 @@ var pg = helper.pg
const suite = new helper.Suite()
const pool = new pg.Pool(helper.config)
suite.test('ability to turn on and off parser', function () {
suite.test('ability to turn on and off parser', function() {
if (helper.args.binary) return false
pool.connect(
assert.success(function (client, done) {
assert.success(function(client, done) {
pg.defaults.parseInt8 = true
client.query('CREATE TEMP TABLE asdf(id SERIAL PRIMARY KEY)')
client.query(
'SELECT COUNT(*) as "count", \'{1,2,3}\'::bigint[] as array FROM asdf',
assert.success(function (res) {
assert.success(function(res) {
assert.strictEqual(0, res.rows[0].count)
assert.strictEqual(1, res.rows[0].array[0])
assert.strictEqual(2, res.rows[0].array[1])
@ -21,7 +21,7 @@ suite.test('ability to turn on and off parser', function () {
pg.defaults.parseInt8 = false
client.query(
'SELECT COUNT(*) as "count", \'{1,2,3}\'::bigint[] as array FROM asdf',
assert.success(function (res) {
assert.success(function(res) {
done()
assert.strictEqual('0', res.rows[0].count)
assert.strictEqual('1', res.rows[0].array[0])

View File

@ -4,14 +4,14 @@ var Query = helper.pg.Query
var suite = new helper.Suite()
;(function () {
;(function() {
var client = helper.client()
client.on('drain', client.end.bind(client))
var queryName = 'user by age and like name'
var parseCount = 0
suite.test('first named prepared statement', function (done) {
suite.test('first named prepared statement', function(done) {
var query = client.query(
new Query({
text: 'select name from person where age <= $1 and name LIKE $2',
@ -20,14 +20,14 @@ var suite = new helper.Suite()
})
)
assert.emits(query, 'row', function (row) {
assert.emits(query, 'row', function(row) {
assert.equal(row.name, 'Brian')
})
query.on('end', () => done())
})
suite.test('second named prepared statement with same name & text', function (done) {
suite.test('second named prepared statement with same name & text', function(done) {
var cachedQuery = client.query(
new Query({
text: 'select name from person where age <= $1 and name LIKE $2',
@ -36,14 +36,14 @@ var suite = new helper.Suite()
})
)
assert.emits(cachedQuery, 'row', function (row) {
assert.emits(cachedQuery, 'row', function(row) {
assert.equal(row.name, 'Aaron')
})
cachedQuery.on('end', () => done())
})
suite.test('with same name, but without query text', function (done) {
suite.test('with same name, but without query text', function(done) {
var q = client.query(
new Query({
name: queryName,
@ -51,11 +51,11 @@ var suite = new helper.Suite()
})
)
assert.emits(q, 'row', function (row) {
assert.emits(q, 'row', function(row) {
assert.equal(row.name, 'Aaron')
// test second row is emitted as well
assert.emits(q, 'row', function (row) {
assert.emits(q, 'row', function(row) {
assert.equal(row.name, 'Brian')
})
})
@ -63,7 +63,7 @@ var suite = new helper.Suite()
q.on('end', () => done())
})
suite.test('with same name, but with different text', function (done) {
suite.test('with same name, but with different text', function(done) {
client.query(
new Query({
text: 'select name from person where age >= $1 and name LIKE $2',
@ -80,7 +80,7 @@ var suite = new helper.Suite()
)
})
})()
;(function () {
;(function() {
var statementName = 'differ'
var statement1 = 'select count(*)::int4 as count from person'
var statement2 = 'select count(*)::int4 as count from person where age < $1'
@ -88,7 +88,7 @@ var suite = new helper.Suite()
var client1 = helper.client()
var client2 = helper.client()
suite.test('client 1 execution', function (done) {
suite.test('client 1 execution', function(done) {
var query = client1.query(
{
name: statementName,
@ -102,7 +102,7 @@ var suite = new helper.Suite()
)
})
suite.test('client 2 execution', function (done) {
suite.test('client 2 execution', function(done) {
var query = client2.query(
new Query({
name: statementName,
@ -111,11 +111,11 @@ var suite = new helper.Suite()
})
)
assert.emits(query, 'row', function (row) {
assert.emits(query, 'row', function(row) {
assert.equal(row.count, 1)
})
assert.emits(query, 'end', function () {
assert.emits(query, 'end', function() {
done()
})
})
@ -124,28 +124,28 @@ var suite = new helper.Suite()
return client1.end().then(() => client2.end())
})
})()
;(function () {
;(function() {
var client = helper.client()
client.query('CREATE TEMP TABLE zoom(name varchar(100));')
client.query("INSERT INTO zoom (name) VALUES ('zed')")
client.query("INSERT INTO zoom (name) VALUES ('postgres')")
client.query("INSERT INTO zoom (name) VALUES ('node postgres')")
var checkForResults = function (q) {
assert.emits(q, 'row', function (row) {
var checkForResults = function(q) {
assert.emits(q, 'row', function(row) {
assert.equal(row.name, 'node postgres')
assert.emits(q, 'row', function (row) {
assert.emits(q, 'row', function(row) {
assert.equal(row.name, 'postgres')
assert.emits(q, 'row', function (row) {
assert.emits(q, 'row', function(row) {
assert.equal(row.name, 'zed')
})
})
})
}
suite.test('with small row count', function (done) {
suite.test('with small row count', function(done) {
var query = client.query(
new Query(
{
@ -160,7 +160,7 @@ var suite = new helper.Suite()
checkForResults(query)
})
suite.test('with large row count', function (done) {
suite.test('with large row count', function(done) {
var query = client.query(
new Query(
{

View File

@ -3,7 +3,7 @@ var bluebird = require('bluebird')
var helper = require(__dirname + '/../test-helper')
var pg = helper.pg
process.on('unhandledRejection', function (e) {
process.on('unhandledRejection', function(e) {
console.error(e, e.stack)
process.exit(1)
})
@ -15,14 +15,14 @@ suite.test('promise API', (cb) => {
pool.connect().then((client) => {
client
.query('SELECT $1::text as name', ['foo'])
.then(function (result) {
.then(function(result) {
assert.equal(result.rows[0].name, 'foo')
return client
})
.then(function (client) {
client.query('ALKJSDF').catch(function (e) {
.then(function(client) {
client.query('ALKJSDF').catch(function(e) {
assert(e instanceof Error)
client.query('SELECT 1 as num').then(function (result) {
client.query('SELECT 1 as num').then(function(result) {
assert.equal(result.rows[0].num, 1)
client.release()
pool.end(cb)

View File

@ -2,14 +2,14 @@
var helper = require(__dirname + '/../test-helper')
var pg = helper.pg
new helper.Suite().test('support for complex column names', function () {
new helper.Suite().test('support for complex column names', function() {
const pool = new pg.Pool()
pool.connect(
assert.success(function (client, done) {
assert.success(function(client, done) {
client.query('CREATE TEMP TABLE t ( "complex\'\'column" TEXT )')
client.query(
'SELECT * FROM t',
assert.success(function (res) {
assert.success(function(res) {
done()
assert.strictEqual(res.fields[0].name, "complex''column")
pool.end()

View File

@ -5,10 +5,10 @@ var util = require('util')
var suite = new helper.Suite()
suite.test('client end during query execution of prepared statement', function (done) {
suite.test('client end during query execution of prepared statement', function(done) {
var client = new Client()
client.connect(
assert.success(function () {
assert.success(function() {
var sleepQuery = 'select pg_sleep($1)'
var queryConfig = {
@ -19,7 +19,7 @@ suite.test('client end during query execution of prepared statement', function (
var queryInstance = new Query(
queryConfig,
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert.equal(err.message, 'Connection terminated')
done()
})
@ -27,15 +27,15 @@ suite.test('client end during query execution of prepared statement', function (
var query1 = client.query(queryInstance)
query1.on('error', function (err) {
query1.on('error', function(err) {
assert.fail('Prepared statement should not emit error')
})
query1.on('row', function (row) {
query1.on('row', function(row) {
assert.fail('Prepared statement should not emit row')
})
query1.on('end', function (err) {
query1.on('end', function(err) {
assert.fail('Prepared statement when executed should not return before being killed')
})
@ -49,11 +49,11 @@ function killIdleQuery(targetQuery, cb) {
var pidColName = 'procpid'
var queryColName = 'current_query'
client2.connect(
assert.success(function () {
assert.success(function() {
helper.versionGTE(
client2,
90200,
assert.success(function (isGreater) {
assert.success(function(isGreater) {
if (isGreater) {
pidColName = 'pid'
queryColName = 'query'
@ -69,7 +69,7 @@ function killIdleQuery(targetQuery, cb) {
client2.query(
killIdleQuery,
[targetQuery],
assert.calls(function (err, res) {
assert.calls(function(err, res) {
assert.ifError(err)
assert.equal(res.rows.length, 1)
client2.end(cb)
@ -82,13 +82,13 @@ function killIdleQuery(targetQuery, cb) {
)
}
suite.test('query killed during query execution of prepared statement', function (done) {
suite.test('query killed during query execution of prepared statement', function(done) {
if (helper.args.native) {
return done()
}
var client = new Client(helper.args)
client.connect(
assert.success(function () {
assert.success(function() {
var sleepQuery = 'select pg_sleep($1)'
const queryConfig = {
@ -102,20 +102,20 @@ suite.test('query killed during query execution of prepared statement', function
var query1 = client.query(
new Query(queryConfig),
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert.equal(err.message, 'terminating connection due to administrator command')
})
)
query1.on('error', function (err) {
query1.on('error', function(err) {
assert.fail('Prepared statement should not emit error')
})
query1.on('row', function (row) {
query1.on('row', function(row) {
assert.fail('Prepared statement should not emit row')
})
query1.on('end', function (err) {
query1.on('end', function(err) {
assert.fail('Prepared statement when executed should not return before being killed')
})

View File

@ -3,10 +3,10 @@ var helper = require('./test-helper')
var util = require('util')
var Query = helper.pg.Query
test('error during query execution', function () {
test('error during query execution', function() {
var client = new Client(helper.args)
client.connect(
assert.success(function () {
assert.success(function() {
var queryText = 'select pg_sleep(10)'
var sleepQuery = new Query(queryText)
var pidColName = 'procpid'
@ -14,14 +14,14 @@ test('error during query execution', function () {
helper.versionGTE(
client,
90200,
assert.success(function (isGreater) {
assert.success(function(isGreater) {
if (isGreater) {
pidColName = 'pid'
queryColName = 'query'
}
var query1 = client.query(
sleepQuery,
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(err)
client.end()
})
@ -29,18 +29,18 @@ test('error during query execution', function () {
//ensure query1 does not emit an 'end' event
//because it was killed and received an error
//https://github.com/brianc/node-postgres/issues/547
query1.on('end', function () {
query1.on('end', function() {
assert.fail('Query with an error should not emit "end" event')
})
setTimeout(function () {
setTimeout(function() {
var client2 = new Client(helper.args)
client2.connect(
assert.success(function () {
assert.success(function() {
var killIdleQuery = `SELECT ${pidColName}, (SELECT pg_cancel_backend(${pidColName})) AS killed FROM pg_stat_activity WHERE ${queryColName} LIKE $1`
client2.query(
killIdleQuery,
[queryText],
assert.calls(function (err, res) {
assert.calls(function(err, res) {
assert.ifError(err)
assert(res.rows.length > 0)
client2.end()
@ -60,20 +60,20 @@ if (helper.config.native) {
return
}
test('9.3 column error fields', function () {
test('9.3 column error fields', function() {
var client = new Client(helper.args)
client.connect(
assert.success(function () {
assert.success(function() {
helper.versionGTE(
client,
90300,
assert.success(function (isGreater) {
assert.success(function(isGreater) {
if (!isGreater) {
return client.end()
}
client.query('CREATE TEMP TABLE column_err_test(a int NOT NULL)')
client.query('INSERT INTO column_err_test(a) VALUES (NULL)', function (err) {
client.query('INSERT INTO column_err_test(a) VALUES (NULL)', function(err) {
assert.equal(err.severity, 'ERROR')
assert.equal(err.code, '23502')
assert.equal(err.table, 'column_err_test')
@ -86,14 +86,14 @@ test('9.3 column error fields', function () {
)
})
test('9.3 constraint error fields', function () {
test('9.3 constraint error fields', function() {
var client = new Client(helper.args)
client.connect(
assert.success(function () {
assert.success(function() {
helper.versionGTE(
client,
90300,
assert.success(function (isGreater) {
assert.success(function(isGreater) {
if (!isGreater) {
console.log('skip 9.3 error field on older versions of postgres')
return client.end()
@ -101,7 +101,7 @@ test('9.3 constraint error fields', function () {
client.query('CREATE TEMP TABLE constraint_err_test(a int PRIMARY KEY)')
client.query('INSERT INTO constraint_err_test(a) VALUES (1)')
client.query('INSERT INTO constraint_err_test(a) VALUES (1)', function (err) {
client.query('INSERT INTO constraint_err_test(a) VALUES (1)', function(err) {
assert.equal(err.severity, 'ERROR')
assert.equal(err.code, '23505')
assert.equal(err.table, 'constraint_err_test')

View File

@ -3,32 +3,32 @@ var helper = require('./test-helper')
var pg = helper.pg
const pool = new pg.Pool()
new helper.Suite().test('should return insert metadata', function () {
new helper.Suite().test('should return insert metadata', function() {
pool.connect(
assert.calls(function (err, client, done) {
assert.calls(function(err, client, done) {
assert(!err)
helper.versionGTE(
client,
90000,
assert.success(function (hasRowCount) {
assert.success(function(hasRowCount) {
client.query(
'CREATE TEMP TABLE zugzug(name varchar(10))',
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(!err)
assert.equal(result.oid, null)
assert.equal(result.command, 'CREATE')
var q = client.query(
"INSERT INTO zugzug(name) VALUES('more work?')",
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(!err)
assert.equal(result.command, 'INSERT')
assert.equal(result.rowCount, 1)
client.query(
'SELECT * FROM zugzug',
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(!err)
if (hasRowCount) assert.equal(result.rowCount, 1)
assert.equal(result.command, 'SELECT')

View File

@ -6,9 +6,9 @@ var Client = helper.Client
var conInfo = helper.config
test('returns results as array', function () {
test('returns results as array', function() {
var client = new Client(conInfo)
var checkRow = function (row) {
var checkRow = function(row) {
assert(util.isArray(row), 'row should be an array')
assert.equal(row.length, 4)
assert.equal(row[0].getFullYear(), new Date().getFullYear())
@ -17,7 +17,7 @@ test('returns results as array', function () {
assert.strictEqual(row[3], null)
}
client.connect(
assert.success(function () {
assert.success(function() {
var config = {
text: 'SELECT NOW(), 1::int, $1::text, null',
values: ['hai'],
@ -25,7 +25,7 @@ test('returns results as array', function () {
}
var query = client.query(
config,
assert.success(function (result) {
assert.success(function(result) {
assert.equal(result.rows.length, 1)
checkRow(result.rows[0])
client.end()

View File

@ -5,7 +5,7 @@ var Client = helper.Client
var conInfo = helper.config
var checkResult = function (result) {
var checkResult = function(result) {
assert(result.fields)
assert.equal(result.fields.length, 3)
var fields = result.fields
@ -17,14 +17,14 @@ var checkResult = function (result) {
assert.equal(fields[2].dataTypeID, 25)
}
test('row descriptions on result object', function () {
test('row descriptions on result object', function() {
var client = new Client(conInfo)
client.connect(
assert.success(function () {
assert.success(function() {
client.query(
'SELECT NOW() as now, 1::int as num, $1::text as texty',
['hello'],
assert.success(function (result) {
assert.success(function(result) {
checkResult(result)
client.end()
})
@ -33,14 +33,14 @@ test('row descriptions on result object', function () {
)
})
test('row description on no rows', function () {
test('row description on no rows', function() {
var client = new Client(conInfo)
client.connect(
assert.success(function () {
assert.success(function() {
client.query(
'SELECT NOW() as now, 1::int as num, $1::text as texty LIMIT 0',
['hello'],
assert.success(function (result) {
assert.success(function(result) {
checkResult(result)
client.end()
})

View File

@ -3,7 +3,7 @@ var helper = require('./test-helper')
var Query = helper.pg.Query
// before running this test make sure you run the script create-test-tables
test('simple query interface', function () {
test('simple query interface', function() {
var client = helper.client()
var query = client.query(new Query('select name from person order by name collate "C"'))
@ -11,12 +11,12 @@ test('simple query interface', function () {
client.on('drain', client.end.bind(client))
var rows = []
query.on('row', function (row, result) {
query.on('row', function(row, result) {
assert.ok(result)
rows.push(row['name'])
})
query.once('row', function (row) {
test('Can iterate through columns', function () {
query.once('row', function(row) {
test('Can iterate through columns', function() {
var columnCount = 0
for (var column in row) {
columnCount++
@ -31,18 +31,18 @@ test('simple query interface', function () {
})
})
assert.emits(query, 'end', function () {
test('returned right number of rows', function () {
assert.emits(query, 'end', function() {
test('returned right number of rows', function() {
assert.lengthIs(rows, 26)
})
test('row ordering', function () {
test('row ordering', function() {
assert.equal(rows[0], 'Aaron')
assert.equal(rows[25], 'Zanzabar')
})
})
})
test('prepared statements do not mutate params', function () {
test('prepared statements do not mutate params', function() {
var client = helper.client()
var params = [1]
@ -54,12 +54,12 @@ test('prepared statements do not mutate params', function () {
client.on('drain', client.end.bind(client))
const rows = []
query.on('row', function (row, result) {
query.on('row', function(row, result) {
assert.ok(result)
rows.push(row)
})
query.on('end', function (result) {
query.on('end', function(result) {
assert.lengthIs(rows, 26, 'result returned wrong number of rows')
assert.lengthIs(rows, result.rowCount)
assert.equal(rows[0].name, 'Aaron')
@ -67,30 +67,30 @@ test('prepared statements do not mutate params', function () {
})
})
test('multiple simple queries', function () {
test('multiple simple queries', function() {
var client = helper.client()
client.query({ text: "create temp table bang(id serial, name varchar(5));insert into bang(name) VALUES('boom');" })
client.query("insert into bang(name) VALUES ('yes');")
var query = client.query(new Query('select name from bang'))
assert.emits(query, 'row', function (row) {
assert.emits(query, 'row', function(row) {
assert.equal(row['name'], 'boom')
assert.emits(query, 'row', function (row) {
assert.emits(query, 'row', function(row) {
assert.equal(row['name'], 'yes')
})
})
client.on('drain', client.end.bind(client))
})
test('multiple select statements', function () {
test('multiple select statements', function() {
var client = helper.client()
client.query(
'create temp table boom(age integer); insert into boom(age) values(1); insert into boom(age) values(2); insert into boom(age) values(3)'
)
client.query({ text: "create temp table bang(name varchar(5)); insert into bang(name) values('zoom');" })
var result = client.query(new Query({ text: 'select age from boom where age < 2; select name from bang' }))
assert.emits(result, 'row', function (row) {
assert.emits(result, 'row', function(row) {
assert.strictEqual(row['age'], 1)
assert.emits(result, 'row', function (row) {
assert.emits(result, 'row', function(row) {
assert.strictEqual(row['name'], 'zoom')
})
})

View File

@ -1,18 +1,18 @@
'use strict'
var pg = require(__dirname + '/../../../lib')
var config = require(__dirname + '/test-helper').config
test('can connect with ssl', function () {
test('can connect with ssl', function() {
return false
config.ssl = {
rejectUnauthorized: false,
}
pg.connect(
config,
assert.success(function (client) {
assert.success(function(client) {
return false
client.query(
'SELECT NOW()',
assert.success(function () {
assert.success(function() {
pg.end()
})
)

View File

@ -13,10 +13,10 @@ function getConInfo(override) {
function getStatementTimeout(conf, cb) {
var client = new Client(conf)
client.connect(
assert.success(function () {
assert.success(function() {
client.query(
'SHOW statement_timeout',
assert.success(function (res) {
assert.success(function(res) {
var statementTimeout = res.rows[0].statement_timeout
cb(statementTimeout)
client.end()
@ -28,52 +28,52 @@ function getStatementTimeout(conf, cb) {
if (!helper.args.native) {
// statement_timeout is not supported with the native client
suite.test('No default statement_timeout ', function (done) {
suite.test('No default statement_timeout ', function(done) {
getConInfo()
getStatementTimeout({}, function (res) {
getStatementTimeout({}, function(res) {
assert.strictEqual(res, '0') // 0 = no timeout
done()
})
})
suite.test('statement_timeout integer is used', function (done) {
suite.test('statement_timeout integer is used', function(done) {
var conf = getConInfo({
statement_timeout: 3000,
})
getStatementTimeout(conf, function (res) {
getStatementTimeout(conf, function(res) {
assert.strictEqual(res, '3s')
done()
})
})
suite.test('statement_timeout float is used', function (done) {
suite.test('statement_timeout float is used', function(done) {
var conf = getConInfo({
statement_timeout: 3000.7,
})
getStatementTimeout(conf, function (res) {
getStatementTimeout(conf, function(res) {
assert.strictEqual(res, '3s')
done()
})
})
suite.test('statement_timeout string is used', function (done) {
suite.test('statement_timeout string is used', function(done) {
var conf = getConInfo({
statement_timeout: '3000',
})
getStatementTimeout(conf, function (res) {
getStatementTimeout(conf, function(res) {
assert.strictEqual(res, '3s')
done()
})
})
suite.test('statement_timeout actually cancels long running queries', function (done) {
suite.test('statement_timeout actually cancels long running queries', function(done) {
var conf = getConInfo({
statement_timeout: '10', // 10ms to keep tests running fast
})
var client = new Client(conf)
client.connect(
assert.success(function () {
client.query('SELECT pg_sleep( 1 )', function (error) {
assert.success(function() {
client.query('SELECT pg_sleep( 1 )', function(error) {
client.end()
assert.strictEqual(error.code, '57014') // query_cancelled
done()

View File

@ -10,19 +10,19 @@ var date = new Date()
const pool = new helper.pg.Pool()
const suite = new helper.Suite()
pool.connect(function (err, client, done) {
pool.connect(function(err, client, done) {
assert(!err)
suite.test('timestamp without time zone', function (cb) {
client.query('SELECT CAST($1 AS TIMESTAMP WITHOUT TIME ZONE) AS "val"', [date], function (err, result) {
suite.test('timestamp without time zone', function(cb) {
client.query('SELECT CAST($1 AS TIMESTAMP WITHOUT TIME ZONE) AS "val"', [date], function(err, result) {
assert(!err)
assert.equal(result.rows[0].val.getTime(), date.getTime())
cb()
})
})
suite.test('timestamp with time zone', function (cb) {
client.query('SELECT CAST($1 AS TIMESTAMP WITH TIME ZONE) AS "val"', [date], function (err, result) {
suite.test('timestamp with time zone', function(cb) {
client.query('SELECT CAST($1 AS TIMESTAMP WITH TIME ZONE) AS "val"', [date], function(err, result) {
assert(!err)
assert.equal(result.rows[0].val.getTime(), date.getTime())

View File

@ -5,7 +5,7 @@ const pg = helper.pg
const client = new pg.Client()
client.connect(
assert.success(function () {
assert.success(function() {
client.query('begin')
var getZed = {
@ -13,10 +13,10 @@ client.connect(
values: ['Zed'],
}
suite.test('name should not exist in the database', function (done) {
suite.test('name should not exist in the database', function(done) {
client.query(
getZed,
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(!err)
assert.empty(result.rows)
done()
@ -28,17 +28,17 @@ client.connect(
client.query(
'INSERT INTO person(name, age) VALUES($1, $2)',
['Zed', 270],
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(!err)
done()
})
)
})
suite.test('name should exist in the database', function (done) {
suite.test('name should exist in the database', function(done) {
client.query(
getZed,
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(!err)
assert.equal(result.rows[0].name, 'Zed')
done()
@ -50,10 +50,10 @@ client.connect(
client.query('rollback', done)
})
suite.test('name should not exist in the database', function (done) {
suite.test('name should not exist in the database', function(done) {
client.query(
getZed,
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(!err)
assert.empty(result.rows)
client.end(done)
@ -63,10 +63,10 @@ client.connect(
})
)
suite.test('gh#36', function (cb) {
suite.test('gh#36', function(cb) {
const pool = new pg.Pool()
pool.connect(
assert.success(function (client, done) {
assert.success(function(client, done) {
client.query('BEGIN')
client.query(
{
@ -74,7 +74,7 @@ suite.test('gh#36', function (cb) {
text: 'SELECT $1::INTEGER',
values: [0],
},
assert.calls(function (err, result) {
assert.calls(function(err, result) {
if (err) throw err
assert.equal(result.rows.length, 1)
})
@ -85,12 +85,12 @@ suite.test('gh#36', function (cb) {
text: 'SELECT $1::INTEGER',
values: [0],
},
assert.calls(function (err, result) {
assert.calls(function(err, result) {
if (err) throw err
assert.equal(result.rows.length, 1)
})
)
client.query('COMMIT', function () {
client.query('COMMIT', function() {
done()
pool.end(cb)
})

View File

@ -4,21 +4,21 @@ var pg = helper.pg
var sink
const suite = new helper.Suite()
var testForTypeCoercion = function (type) {
var testForTypeCoercion = function(type) {
const pool = new pg.Pool()
suite.test(`test type coercion ${type.name}`, (cb) => {
pool.connect(function (err, client, done) {
pool.connect(function(err, client, done) {
assert(!err)
client.query(
'create temp table test_type(col ' + type.name + ')',
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(!err)
type.values.forEach(function (val) {
type.values.forEach(function(val) {
var insertQuery = client.query(
'insert into test_type(col) VALUES($1)',
[val],
assert.calls(function (err, result) {
assert.calls(function(err, result) {
assert(!err)
})
)
@ -30,7 +30,7 @@ var testForTypeCoercion = function (type) {
})
)
query.on('error', function (err) {
query.on('error', function(err) {
console.log(err)
throw err
})
@ -38,7 +38,7 @@ var testForTypeCoercion = function (type) {
assert.emits(
query,
'row',
function (row) {
function(row) {
var expected = val + ' (' + typeof val + ')'
var returned = row.col + ' (' + typeof row.col + ')'
assert.strictEqual(row.col, val, 'expected ' + type.name + ' of ' + expected + ' but got ' + returned)
@ -49,7 +49,7 @@ var testForTypeCoercion = function (type) {
client.query('delete from test_type')
})
client.query('drop table test_type', function () {
client.query('drop table test_type', function() {
done()
pool.end(cb)
})
@ -131,18 +131,18 @@ var types = [
// ignore some tests in binary mode
if (helper.config.binary) {
types = types.filter(function (type) {
types = types.filter(function(type) {
return !(type.name in { real: 1, timetz: 1, time: 1, numeric: 1, bigint: 1 })
})
}
var valueCount = 0
types.forEach(function (type) {
types.forEach(function(type) {
testForTypeCoercion(type)
})
suite.test('timestampz round trip', function (cb) {
suite.test('timestampz round trip', function(cb) {
var now = new Date()
var client = helper.client()
client.query('create temp table date_tests(name varchar(10), tstz timestamptz(3))')
@ -159,7 +159,7 @@ suite.test('timestampz round trip', function (cb) {
})
)
assert.emits(result, 'row', function (row) {
assert.emits(result, 'row', function(row) {
var date = row.tstz
assert.equal(date.getYear(), now.getYear())
assert.equal(date.getMonth(), now.getMonth())
@ -178,16 +178,16 @@ suite.test('timestampz round trip', function (cb) {
suite.test('selecting nulls', (cb) => {
const pool = new pg.Pool()
pool.connect(
assert.calls(function (err, client, done) {
assert.calls(function(err, client, done) {
assert.ifError(err)
client.query(
'select null as res;',
assert.calls(function (err, res) {
assert.calls(function(err, res) {
assert(!err)
assert.strictEqual(res.rows[0].res, null)
})
)
client.query('select 7 <> $1 as res;', [null], function (err, res) {
client.query('select 7 <> $1 as res;', [null], function(err, res) {
assert(!err)
assert.strictEqual(res.rows[0].res, null)
done()
@ -197,7 +197,7 @@ suite.test('selecting nulls', (cb) => {
)
})
suite.test('date range extremes', function (done) {
suite.test('date range extremes', function(done) {
var client = helper.client()
// Set the server timeszone to the same as used for the test,
@ -206,7 +206,7 @@ suite.test('date range extremes', function (done) {
// in the case of "275760-09-13 00:00:00 GMT" the timevalue overflows.
client.query(
'SET TIMEZONE TO GMT',
assert.success(function (res) {
assert.success(function(res) {
// PostgreSQL supports date range of 4713 BCE to 294276 CE
// http://www.postgresql.org/docs/9.2/static/datatype-datetime.html
// ECMAScript supports date range of Apr 20 271821 BCE to Sep 13 275760 CE
@ -214,7 +214,7 @@ suite.test('date range extremes', function (done) {
client.query(
'SELECT $1::TIMESTAMPTZ as when',
['275760-09-13 00:00:00 GMT'],
assert.success(function (res) {
assert.success(function(res) {
assert.equal(res.rows[0].when.getFullYear(), 275760)
})
)
@ -222,7 +222,7 @@ suite.test('date range extremes', function (done) {
client.query(
'SELECT $1::TIMESTAMPTZ as when',
['4713-12-31 12:31:59 BC GMT'],
assert.success(function (res) {
assert.success(function(res) {
assert.equal(res.rows[0].when.getFullYear(), -4712)
})
)
@ -230,7 +230,7 @@ suite.test('date range extremes', function (done) {
client.query(
'SELECT $1::TIMESTAMPTZ as when',
['275760-09-13 00:00:00 -15:00'],
assert.success(function (res) {
assert.success(function(res) {
assert(isNaN(res.rows[0].when.getTime()))
})
)

View File

@ -7,7 +7,7 @@ function testTypeParser(client, expectedResult, done) {
client.query('INSERT INTO parserOverrideTest(id) VALUES ($1)', [boolValue])
client.query(
'SELECT * FROM parserOverrideTest',
assert.success(function (result) {
assert.success(function(result) {
assert.equal(result.rows[0].id, expectedResult)
done()
})
@ -16,21 +16,21 @@ function testTypeParser(client, expectedResult, done) {
const pool = new helper.pg.Pool(helper.config)
pool.connect(
assert.success(function (client1, done1) {
assert.success(function(client1, done1) {
pool.connect(
assert.success(function (client2, done2) {
assert.success(function(client2, done2) {
var boolTypeOID = 16
client1.setTypeParser(boolTypeOID, function () {
client1.setTypeParser(boolTypeOID, function() {
return 'first client'
})
client2.setTypeParser(boolTypeOID, function () {
client2.setTypeParser(boolTypeOID, function() {
return 'second client'
})
client1.setTypeParser(boolTypeOID, 'binary', function () {
client1.setTypeParser(boolTypeOID, 'binary', function() {
return 'first client binary'
})
client2.setTypeParser(boolTypeOID, 'binary', function () {
client2.setTypeParser(boolTypeOID, 'binary', function() {
return 'second client binary'
})

View File

@ -14,15 +14,15 @@ suite.test('errors emitted on checked-out clients', (cb) => {
const pool = new pg.Pool({ max: 2 })
// get first client
pool.connect(
assert.success(function (client, done) {
client.query('SELECT NOW()', function () {
assert.success(function(client, done) {
client.query('SELECT NOW()', function() {
pool.connect(
assert.success(function (client2, done2) {
assert.success(function(client2, done2) {
var pidColName = 'procpid'
helper.versionGTE(
client2,
90200,
assert.success(function (isGreater) {
assert.success(function(isGreater) {
var killIdleQuery =
'SELECT pid, (SELECT pg_terminate_backend(pid)) AS killed FROM pg_stat_activity WHERE state = $1'
var params = ['idle']
@ -42,7 +42,7 @@ suite.test('errors emitted on checked-out clients', (cb) => {
client2.query(
killIdleQuery,
params,
assert.success(function (res) {
assert.success(function(res) {
// check to make sure client connection actually was killed
// return client2 to the pool
done2()

View File

@ -1,11 +1,11 @@
'use strict'
var helper = require('./test-helper')
new helper.Suite().test('idle timeout', function () {
new helper.Suite().test('idle timeout', function() {
const config = Object.assign({}, helper.config, { idleTimeoutMillis: 50 })
const pool = new helper.pg.Pool(config)
pool.connect(
assert.calls(function (err, client, done) {
assert.calls(function(err, client, done) {
assert(!err)
client.query('SELECT NOW()')
done()

View File

@ -6,7 +6,7 @@ var native = helper.args.native
var pool = new pg.Pool()
pool.connect(
assert.calls(function (err, client, done) {
assert.calls(function(err, client, done) {
if (native) {
assert(client.native)
} else {

View File

@ -3,19 +3,19 @@ var helper = require('./../test-helper')
const suite = new helper.Suite()
helper.testPoolSize = function (max) {
helper.testPoolSize = function(max) {
suite.test(`test ${max} queries executed on a pool rapidly`, (cb) => {
const pool = new helper.pg.Pool({ max: 10 })
var sink = new helper.Sink(max, function () {
var sink = new helper.Sink(max, function() {
pool.end(cb)
})
for (var i = 0; i < max; i++) {
pool.connect(function (err, client, done) {
pool.connect(function(err, client, done) {
assert(!err)
client.query('SELECT * FROM NOW()')
client.query('select generate_series(0, 25)', function (err, result) {
client.query('select generate_series(0, 25)', function(err, result) {
assert.equal(result.rows.length, 26)
})
var query = client.query('SELECT * FROM NOW()', (err) => {

View File

@ -5,7 +5,7 @@ var co = require('co')
const pool = new helper.pg.Pool()
new helper.Suite().test(
'using coroutines works with promises',
co.wrap(function* () {
co.wrap(function*() {
var client = yield pool.connect()
var res = yield client.query('SELECT $1::text as name', ['foo'])
assert.equal(res.rows[0].name, 'foo')

View File

@ -2,8 +2,8 @@
var helper = require(__dirname + '/test-helper')
// http://developer.postgresql.org/pgdocs/postgres/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY
test('flushing once', function () {
helper.connect(function (con) {
test('flushing once', function() {
helper.connect(function(con) {
con.parse({
text: 'select * from ids',
})
@ -15,35 +15,35 @@ test('flushing once', function () {
assert.emits(con, 'parseComplete')
assert.emits(con, 'bindComplete')
assert.emits(con, 'dataRow')
assert.emits(con, 'commandComplete', function () {
assert.emits(con, 'commandComplete', function() {
con.sync()
})
assert.emits(con, 'readyForQuery', function () {
assert.emits(con, 'readyForQuery', function() {
con.end()
})
})
})
test('sending many flushes', function () {
helper.connect(function (con) {
assert.emits(con, 'parseComplete', function () {
test('sending many flushes', function() {
helper.connect(function(con) {
assert.emits(con, 'parseComplete', function() {
con.bind()
con.flush()
})
assert.emits(con, 'bindComplete', function () {
assert.emits(con, 'bindComplete', function() {
con.execute()
con.flush()
})
assert.emits(con, 'dataRow', function (msg) {
assert.emits(con, 'dataRow', function(msg) {
assert.equal(msg.fields[0], 1)
assert.emits(con, 'dataRow', function (msg) {
assert.emits(con, 'dataRow', function(msg) {
assert.equal(msg.fields[0], 2)
assert.emits(con, 'commandComplete', function () {
assert.emits(con, 'commandComplete', function() {
con.sync()
})
assert.emits(con, 'readyForQuery', function () {
assert.emits(con, 'readyForQuery', function() {
con.end()
})
})

View File

@ -2,16 +2,16 @@
var helper = require(__dirname + '/test-helper')
var assert = require('assert')
test('COPY FROM events check', function () {
helper.connect(function (con) {
test('COPY FROM events check', function() {
helper.connect(function(con) {
var stdinStream = con.query('COPY person FROM STDIN')
con.on('copyInResponse', function () {
con.on('copyInResponse', function() {
con.endCopyFrom()
})
assert.emits(
con,
'copyInResponse',
function () {
function() {
con.endCopyFrom()
},
'backend should emit copyInResponse after COPY FROM query'
@ -19,22 +19,22 @@ test('COPY FROM events check', function () {
assert.emits(
con,
'commandComplete',
function () {
function() {
con.end()
},
'backend should emit commandComplete after COPY FROM stream ends'
)
})
})
test('COPY TO events check', function () {
helper.connect(function (con) {
test('COPY TO events check', function() {
helper.connect(function(con) {
var stdoutStream = con.query('COPY person TO STDOUT')
assert.emits(con, 'copyOutResponse', function () {}, 'backend should emit copyOutResponse after COPY TO query')
assert.emits(con, 'copyData', function () {}, 'backend should emit copyData on every data row')
assert.emits(con, 'copyOutResponse', function() {}, 'backend should emit copyOutResponse after COPY TO query')
assert.emits(con, 'copyData', function() {}, 'backend should emit copyData on every data row')
assert.emits(
con,
'copyDone',
function () {
function() {
con.end()
},
'backend should emit copyDone after all data rows'

View File

@ -1,12 +1,12 @@
'use strict'
var helper = require(__dirname + '/test-helper')
// http://www.postgresql.org/docs/8.3/static/libpq-notify.html
test('recieves notification from same connection with no payload', function () {
helper.connect(function (con) {
test('recieves notification from same connection with no payload', function() {
helper.connect(function(con) {
con.query('LISTEN boom')
assert.emits(con, 'readyForQuery', function () {
assert.emits(con, 'readyForQuery', function() {
con.query('NOTIFY boom')
assert.emits(con, 'notification', function (msg) {
assert.emits(con, 'notification', function(msg) {
assert.equal(msg.payload, '')
assert.equal(msg.channel, 'boom')
con.end()

View File

@ -5,20 +5,20 @@ var assert = require('assert')
var rows = []
// testing the low level 1-1 mapping api of client to postgres messages
// it's cumbersome to use the api this way
test('simple query', function () {
helper.connect(function (con) {
test('simple query', function() {
helper.connect(function(con) {
con.query('select * from ids')
assert.emits(con, 'dataRow')
con.on('dataRow', function (msg) {
con.on('dataRow', function(msg) {
rows.push(msg.fields)
})
assert.emits(con, 'readyForQuery', function () {
assert.emits(con, 'readyForQuery', function() {
con.end()
})
})
})
process.on('exit', function () {
process.on('exit', function() {
assert.equal(rows.length, 2)
assert.equal(rows[0].length, 1)
assert.strictEqual(String(rows[0][0]), '1')

View File

@ -3,31 +3,31 @@ var net = require('net')
var helper = require(__dirname + '/../test-helper')
var Connection = require(__dirname + '/../../../lib/connection')
var utils = require(__dirname + '/../../../lib/utils')
var connect = function (callback) {
var connect = function(callback) {
var username = helper.args.user
var database = helper.args.database
var con = new Connection({ stream: new net.Stream() })
con.on('error', function (error) {
con.on('error', function(error) {
console.log(error)
throw new Error('Connection error')
})
con.connect(helper.args.port || '5432', helper.args.host || 'localhost')
con.once('connect', function () {
con.once('connect', function() {
con.startup({
user: username,
database: database,
})
con.once('authenticationCleartextPassword', function () {
con.once('authenticationCleartextPassword', function() {
con.password(helper.args.password)
})
con.once('authenticationMD5Password', function (msg) {
con.once('authenticationMD5Password', function(msg) {
con.password(utils.postgresMd5PasswordHash(helper.args.user, helper.args.password, msg.salt))
})
con.once('readyForQuery', function () {
con.once('readyForQuery', function() {
con.query('create temp table ids(id integer)')
con.once('readyForQuery', function () {
con.once('readyForQuery', function() {
con.query('insert into ids(id) values(1); insert into ids(id) values(2);')
con.once('readyForQuery', function () {
con.once('readyForQuery', function() {
callback(con)
})
})

View File

@ -7,11 +7,11 @@ var suite = new helper.Suite()
const Pool = helper.pg.Pool
suite.test('no domain', function (cb) {
suite.test('no domain', function(cb) {
assert(!process.domain)
const pool = new Pool()
pool.connect(
assert.success(function (client, done) {
assert.success(function(client, done) {
assert(!process.domain)
done()
pool.end(cb)
@ -19,20 +19,20 @@ suite.test('no domain', function (cb) {
)
})
suite.test('with domain', function (cb) {
suite.test('with domain', function(cb) {
assert(!process.domain)
const pool = new Pool()
var domain = require('domain').create()
domain.run(function () {
domain.run(function() {
var startingDomain = process.domain
assert(startingDomain)
pool.connect(
assert.success(function (client, done) {
assert.success(function(client, done) {
assert(process.domain, 'no domain exists in connect callback')
assert.equal(startingDomain, process.domain, 'domain was lost when checking out a client')
var query = client.query(
'SELECT NOW()',
assert.success(function () {
assert.success(function() {
assert(process.domain, 'no domain exists in query callback')
assert.equal(startingDomain, process.domain, 'domain was lost when checking out a client')
done(true)
@ -45,15 +45,15 @@ suite.test('with domain', function (cb) {
})
})
suite.test('error on domain', function (cb) {
suite.test('error on domain', function(cb) {
var domain = require('domain').create()
const pool = new Pool()
domain.on('error', function () {
domain.on('error', function() {
pool.end(cb)
})
domain.run(function () {
domain.run(function() {
pool.connect(
assert.success(function (client, done) {
assert.success(function(client, done) {
client.query(new Query('SELECT SLDKJFLSKDJF'))
client.on('drain', done)
})

View File

@ -5,13 +5,13 @@ var exec = require('child_process').exec
helper.pg.defaults.poolIdleTimeout = 1000
const pool = new helper.pg.Pool()
pool.connect(function (err, client, done) {
pool.connect(function(err, client, done) {
assert.ifError(err)
client.once('error', function (err) {
client.once('error', function(err) {
client.on('error', (err) => {})
done(err)
})
client.query('SELECT pg_backend_pid()', function (err, result) {
client.query('SELECT pg_backend_pid()', function(err, result) {
assert.ifError(err)
var pid = result.rows[0].pg_backend_pid
var psql = 'psql'
@ -20,7 +20,7 @@ pool.connect(function (err, client, done) {
if (helper.args.user) psql = psql + ' -U ' + helper.args.user
exec(
psql + ' -c "select pg_terminate_backend(' + pid + ')" template1',
assert.calls(function (error, stdout, stderr) {
assert.calls(function(error, stdout, stderr) {
assert.ifError(error)
})
)

View File

@ -4,10 +4,10 @@ var pg = helper.pg
var suite = new helper.Suite()
suite.test('parsing array decimal results', function (done) {
suite.test('parsing array decimal results', function(done) {
const pool = new pg.Pool()
pool.connect(
assert.calls(function (err, client, release) {
assert.calls(function(err, client, release) {
assert(!err)
client.query('CREATE TEMP TABLE why(names text[], numbors integer[], decimals double precision[])')
client
@ -19,7 +19,7 @@ suite.test('parsing array decimal results', function (done) {
.on('error', console.log)
client.query(
'SELECT decimals FROM why',
assert.success(function (result) {
assert.success(function(result) {
assert.lengthIs(result.rows[0].decimals, 3)
assert.equal(result.rows[0].decimals[0], 0.1)
assert.equal(result.rows[0].decimals[1], 0.05)

View File

@ -14,7 +14,7 @@ suite.test('Parameter serialization errors should not cause query to hang', (don
.connect()
.then(() => {
const obj = {
toPostgres: function () {
toPostgres: function() {
throw expectedErr
},
}

Some files were not shown because too many files have changed in this diff Show More