Remove deprecated methods

This commit is contained in:
Brian M. Carlson 2017-06-18 14:20:55 -05:00 committed by Brian C
parent 313c41a39f
commit 1bc1758579
40 changed files with 374 additions and 561 deletions

View File

@ -17,7 +17,7 @@ help:
test: test-unit
test-all: jshint test-missing-native test-unit test-integration test-native test-binary
test-all: jshint test-missing-native test-unit test-integration test-native
update-npm:

View File

@ -15,7 +15,6 @@ var ConnectionParameters = require('./connection-parameters');
var poolFactory = require('./pool-factory');
var PG = function(clientConstructor) {
EventEmitter.call(this);
this.defaults = defaults;
this.Client = clientConstructor;
this.Query = this.Client.Query;
@ -25,74 +24,6 @@ var PG = function(clientConstructor) {
this.types = require('pg-types');
};
util.inherits(PG, EventEmitter);
PG.prototype.end = util.deprecate(function() {
var self = this;
var keys = Object.keys(this._pools);
var count = keys.length;
if(count === 0) {
self.emit('end');
} else {
keys.forEach(function(key) {
var pool = self._pools[key];
delete self._pools[key];
pool.pool.drain(function() {
pool.pool.destroyAllNow(function() {
count--;
if(count === 0) {
self.emit('end');
}
});
});
});
}
},
'pg.end() is deprecated - please construct pools directly via new pg.Pool()');
PG.prototype.connect = util.deprecate(function(config, callback) {
if(typeof config == "function") {
callback = config;
config = null;
}
if (typeof config == 'string') {
config = new ConnectionParameters(config);
}
config = config || {};
//for backwards compatibility
config.max = config.max || config.poolSize || defaults.poolSize;
config.idleTimeoutMillis = config.idleTimeoutMillis || config.poolIdleTimeout || defaults.poolIdleTimeout;
config.log = config.log || config.poolLog || defaults.poolLog;
var poolName = JSON.stringify(config);
this._pools[poolName] = this._pools[poolName] || new this.Pool(config);
var pool = this._pools[poolName];
if(!pool.listeners('error').length) {
//propagate errors up to pg object
pool.on('error', function(e) {
this.emit('error', e, e.client);
}.bind(this));
}
return pool.connect(callback);
},
'pg.connect() is deprecated - please construct pools directly via new pg.Pool()');
// cancel the query running on the given client
PG.prototype.cancel = util.deprecate(function(config, client, query) {
if(client.native) {
return client.cancel(query);
}
var c = config;
//allow for no config to be passed
if(typeof c === 'function') {
c = defaults;
}
var cancellingClient = new this.Client(c);
cancellingClient.cancel(client, query);
}, 'pg.cancel() is deprecated - please create your own client instances to cancel queries');
if(typeof process.env.NODE_PG_FORCE_NATIVE != 'undefined') {
module.exports = new PG(require('./native'));
} else {

View File

@ -109,8 +109,6 @@ Client.prototype.connect = function(cb) {
return result
};
const DeprecatedQuery = require('../utils').deprecateEventEmitter(NativeQuery)
//send a query to the server
//this method is highly overloaded to take
//1) string query, optional array of parameters, optional function callback
@ -132,10 +130,19 @@ Client.prototype.query = function(config, values, callback) {
return config;
}
var query = new DeprecatedQuery(config, values, callback);
var query = new NativeQuery(config, values, callback);
var result
if (!query.callback) {
let resolve, reject;
result = new Promise((res, rej) => {
resolve = res
reject = rej
})
query.callback = (err, res) => err ? reject(err) : resolve(res)
}
this._queryQueue.push(query);
this._pulseQueryQueue();
return query;
return result;
};
//disconnect from the backend server

View File

@ -53,23 +53,6 @@ Query.prototype.requiresPreparation = function() {
return this.values.length > 0;
};
Query.prototype.then = function(onSuccess, onFailure) {
return this._getPromise().then(onSuccess, onFailure);
};
Query.prototype.catch = function(callback) {
return this._getPromise().catch(callback);
};
Query.prototype._getPromise = function() {
if (this._promise) return this._promise;
this._promise = new Promise(function(resolve, reject) {
this._once('end', resolve);
this._once('error', reject);
}.bind(this));
return this._promise;
};
//associates row metadata from the supplied
//message with this query object
//metadata used when parsing row results

View File

@ -138,23 +138,6 @@ function normalizeQueryConfig (config, values, callback) {
return config;
}
const queryEventEmitterOverloadDeprecationMessage = `
Using the automatically created return value from client.query as an event emitter is deprecated.
Use either the callback or promise interface.
`
const deprecateEventEmitter = function(Emitter) {
const Result = function () {
Emitter.apply(this, arguments)
}
util.inherits(Result, Emitter)
Result.prototype._on = Result.prototype.on
Result.prototype._once = Result.prototype.once
Result.prototype.on = util.deprecate(Result.prototype.on, queryEventEmitterOverloadDeprecationMessage)
Result.prototype.once = util.deprecate(Result.prototype.once, queryEventEmitterOverloadDeprecationMessage)
return Result
}
module.exports = {
prepareValue: function prepareValueWrapper (value) {
//this ensures that extra arguments do not get passed into prepareValue
@ -162,5 +145,4 @@ module.exports = {
return prepareValue(value);
},
normalizeQueryConfig: normalizeQueryConfig,
deprecateEventEmitter: deprecateEventEmitter,
};

View File

@ -3,7 +3,8 @@ var pg = helper.pg;
var suite = new helper.Suite()
pg.connect(assert.calls(function(err, client, release) {
const pool = new pg.Pool()
pool.connect(assert.calls(function(err, client, release) {
assert.isNull(err);
suite.test('nulls', function(done) {
@ -33,7 +34,7 @@ pg.connect(assert.calls(function(err, client, release) {
suite.test('cleanup', () => release())
}));
pg.connect(assert.calls(function (err, client, release) {
pool.connect(assert.calls(function (err, client, release) {
assert.isNull(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);
@ -166,8 +167,7 @@ pg.connect(assert.calls(function (err, client, release) {
assert.equal(names[2][0], 3);
assert.equal(names[2][1], 100);
release();
pg.end();
done();
pool.end(done)
}))
})

View File

@ -1,41 +0,0 @@
var helper = require("./test-helper");
var Query = helper.pg.Query;
//before running this test make sure you run the script create-test-tables
new helper.Suite().test("cancellation of a query", function() {
var client = helper.client();
var qry = "select name from person order by name";
client.on('drain', client.end.bind(client));
var rows3 = 0;
var query1 = client.query(new Query(qry));
query1.on('row', function(row) {
throw new Error('Should not emit a row')
});
var query2 = client.query(new Query(qry));
query2.on('row', function(row) {
throw new Error('Should not emit a row')
});
var query3 = client.query(new Query(qry));
query3.on('row', function(row) {
rows3++;
});
var query4 = client.query(new Query(qry));
query4.on('row', function(row) {
throw new Error('Should not emit a row')
});
helper.pg.cancel(helper.config, client, query1);
helper.pg.cancel(helper.config, client, query2);
helper.pg.cancel(helper.config, client, query4);
assert.emits(query3, 'end', function() {
test("returned right number of rows", function() {
assert.equal(rows3, 26);
});
});
});

View File

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

View File

@ -1,7 +1,8 @@
var helper = require('./test-helper');
var assert = require('assert');
helper.pg.connect(assert.success(function (client, done) {
const pool = new helper.pg.Pool()
pool.connect(assert.success(function (client, done) {
helper.versionGTE(client, '9.2.0', assert.success(function (jsonSupported) {
if (!jsonSupported) {
console.log('skip json test on older versions of postgres');
@ -20,7 +21,7 @@ helper.pg.connect(assert.success(function (client, done) {
assert.strictEqual(row.alive, value.alive);
assert.equal(JSON.stringify(row.now), JSON.stringify(value.now));
done();
helper.pg.end();
pool.end()
}));
}));
}));

View File

@ -1,23 +1,27 @@
var helper = require(__dirname + '/test-helper');
var helper = require("./test-helper");
var pg = helper.pg;
const suite = new helper.Suite()
const suite = new helper.Suite();
const pool = new pg.Pool();
suite.test('can access results when no rows are returned', function() {
var checkResult = function(result) {
assert(result.fields, 'should have fields definition');
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');
assert.equal(result.fields[0].name, "val");
assert.equal(result.fields[0].dataTypeID, 25);
pg.end();
};
pg.connect(assert.success(function(client, done) {
const q = new pg.Query('select $1::text as val limit 0', ['hi'])
var query = client.query(q, assert.success(function(result) {
checkResult(result);
done();
}));
pool.connect(
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) {
checkResult(result);
release();
pool.end(done);
})
);
assert.emits(query, 'end', checkResult);
}));
assert.emits(query, "end", checkResult);
})
);
});

View File

@ -3,9 +3,10 @@ var helper = require('../test-helper');
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() {
if(helper.args.binary) return false;
pg.connect(helper.config, assert.success(function(client, done) {
pool.connect(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) {
@ -20,7 +21,7 @@ suite.test('ability to turn on and off parser', function() {
assert.strictEqual('1', res.rows[0].array[0]);
assert.strictEqual('2', res.rows[0].array[1]);
assert.strictEqual('3', res.rows[0].array[2]);
pg.end();
pool.end();
}));
}));
}));

View File

@ -6,22 +6,27 @@ process.on('unhandledRejection', function(e) {
process.exit(1)
})
pg.connect(helper.config, assert.success(function(client, done) {
client.query('SELECT $1::text as name', ['foo'])
.then(function(result) {
assert.equal(result.rows[0].name, 'foo')
return client
})
.then(function(client) {
client.query('ALKJSDF')
.catch(function(e) {
assert(e instanceof Error)
client.query('SELECT 1 as num')
.then(function (result) {
assert.equal(result.rows[0].num, 1)
done()
pg.end()
})
})
})
}))
const pool = new pg.Pool()
const suite = new helper.Suite()
suite.test('promise API', (cb) => {
pool.connect().then((client) => {
client.query('SELECT $1::text as name', ['foo'])
.then(function (result) {
assert.equal(result.rows[0].name, 'foo')
return client
})
.then(function (client) {
client.query('ALKJSDF')
.catch(function (e) {
assert(e instanceof Error)
client.query('SELECT 1 as num')
.then(function (result) {
assert.equal(result.rows[0].num, 1)
client.release()
pool.end(cb)
})
})
})
})
})

View File

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

View File

@ -1,8 +1,9 @@
var helper = require(__dirname + "/test-helper");
var helper = require("./test-helper");
var pg = helper.pg;
test('should return insert metadata', function() {
pg.connect(helper.config, assert.calls(function(err, client, done) {
const pool = new pg.Pool()
new helper.Suite().test('should return insert metadata', function() {
pool.connect(assert.calls(function(err, client, done) {
assert.isNull(err);
helper.versionGTE(client, '9.0.0', assert.success(function(hasRowCount) {
@ -21,7 +22,7 @@ test('should return insert metadata', function() {
if(hasRowCount) assert.equal(result.rowCount, 1);
assert.equal(result.command, 'SELECT');
done();
process.nextTick(pg.end.bind(pg));
process.nextTick(pool.end.bind(pool));
}));
}));
}));

View File

@ -1,4 +1,4 @@
var helper = require(__dirname + '/../test-helper');
var helper = require('./../test-helper');
var exec = require('child_process').exec;
var oldTz = process.env.TZ;
@ -6,24 +6,28 @@ process.env.TZ = 'Europe/Berlin';
var date = new Date();
helper.pg.connect(helper.config, function(err, client, done) {
const pool = new helper.pg.Pool()
const suite = new helper.Suite()
pool.connect(function (err, client, done) {
assert.isNull(err);
test('timestamp without time zone', function() {
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.isNull(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) {
assert.isNull(err);
assert.equal(result.rows[0].val.getTime(), date.getTime());
test('timestamp with time zone', function() {
client.query("SELECT CAST($1 AS TIMESTAMP WITH TIME ZONE) AS \"val\"", [ date ], function(err, result) {
assert.isNull(err);
assert.equal(result.rows[0].val.getTime(), date.getTime());
done();
helper.pg.end();
process.env.TZ = oldTz;
});
});
done();
pool.end(cb)
process.env.TZ = oldTz;
});
});
});
});

View File

@ -1,72 +1,76 @@
var helper = require(__dirname + '/test-helper');
var helper = require('./test-helper');
const suite = new helper.Suite()
const pg = helper.pg
var sink = new helper.Sink(2, function() {
helper.pg.end();
});
const client = new pg.Client()
client.connect(assert.success(function () {
test('a single connection transaction', function() {
helper.pg.connect(helper.config, assert.success(function(client, done) {
client.query('begin');
client.query('begin');
var getZed = {
text: 'SELECT * FROM person WHERE name = $1',
values: ['Zed']
};
var getZed = {
text: 'SELECT * FROM person WHERE name = $1',
values: ['Zed']
};
suite.test('name should not exist in the database', function (done) {
client.query(getZed, assert.calls(function (err, result) {
assert.isNull(err);
assert.empty(result.rows);
done()
}))
})
test('Zed should not exist in the database', function() {
client.query(getZed, assert.calls(function(err, result) {
assert.isNull(err);
assert.empty(result.rows);
}))
})
client.query("INSERT INTO person(name, age) VALUES($1, $2)", ['Zed', 270], assert.calls(function(err, result) {
suite.test('can insert name', (done) => {
client.query("INSERT INTO person(name, age) VALUES($1, $2)", ['Zed', 270], assert.calls(function (err, result) {
assert.isNull(err)
done()
}));
})
test('Zed should exist in the database', function() {
client.query(getZed, assert.calls(function(err, result) {
assert.isNull(err);
assert.equal(result.rows[0].name, 'Zed');
}))
})
suite.test('name should exist in the database', function (done) {
client.query(getZed, assert.calls(function (err, result) {
assert.isNull(err);
assert.equal(result.rows[0].name, 'Zed');
done()
}))
})
client.query('rollback');
suite.test('rollback', (done) => {
client.query('rollback', done);
})
test('Zed should not exist in the database', function() {
client.query(getZed, assert.calls(function(err, result) {
assert.isNull(err);
assert.empty(result.rows);
done();
sink.add();
}))
})
}))
})
suite.test('name should not exist in the database', function (done) {
client.query(getZed, assert.calls(function (err, result) {
assert.isNull(err);
assert.empty(result.rows);
client.end(done)
}))
})
}))
test('gh#36', function() {
helper.pg.connect(helper.config, assert.success(function(client, done) {
suite.test('gh#36', function (cb) {
const pool = new pg.Pool()
pool.connect(assert.success(function (client, done) {
client.query("BEGIN");
client.query({
name: 'X',
text: "SELECT $1::INTEGER",
values: [0]
}, assert.calls(function(err, result) {
if(err) throw err;
}, assert.calls(function (err, result) {
if (err) throw err;
assert.equal(result.rows.length, 1);
}))
client.query({
name: 'X',
text: "SELECT $1::INTEGER",
values: [0]
}, assert.calls(function(err, result) {
if(err) throw err;
}, assert.calls(function (err, result) {
if (err) throw err;
assert.equal(result.rows.length, 1);
}))
client.query("COMMIT", function() {
sink.add();
client.query("COMMIT", function () {
done();
pool.end(cb)
})
}));
})

View File

@ -1,29 +1,33 @@
var helper = require(__dirname + '/test-helper');
var pg = helper.pg;
var sink;
const suite = new helper.Suite()
var testForTypeCoercion = function(type){
helper.pg.connect(helper.config, function(err, client, done) {
assert.isNull(err);
client.query("create temp table test_type(col " + type.name + ")", assert.calls(function(err, result) {
var testForTypeCoercion = function (type) {
const pool = new pg.Pool()
suite.test(`test type coercion ${type.name}`, (cb) => {
pool.connect(function (err, client, done) {
assert.isNull(err);
test("Coerces " + type.name, function() {
type.values.forEach(function(val) {
client.query("create temp table test_type(col " + type.name + ")", assert.calls(function (err, result) {
assert.isNull(err);
var insertQuery = client.query('insert into test_type(col) VALUES($1)',[val],assert.calls(function(err, result) {
type.values.forEach(function (val) {
var insertQuery = client.query('insert into test_type(col) VALUES($1)', [val], assert.calls(function (err, result) {
assert.isNull(err);
}));
var query = client.query(new pg.Query({
name: 'get type ' + type.name ,
name: 'get type ' + type.name,
text: 'select col from test_type'
}));
query.on('error', function(err) {
query.on('error', function (err) {
console.log(err);
throw err;
});
assert.emits(query, 'row', function(row) {
assert.emits(query, '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);
@ -32,22 +36,23 @@ var testForTypeCoercion = function(type){
client.query('delete from test_type');
});
client.query('drop table test_type', function() {
sink.add();
client.query('drop table test_type', function () {
done();
pool.end(cb)
});
})
}));
}));
})
})
};
var types = [{
name: 'integer',
values: [-2147483648, -1, 0, 1, 2147483647, null]
},{
}, {
name: 'smallint',
values: [-32768, -1, 0, 1, 32767, null]
},{
}, {
name: 'bigint',
values: [
'-9223372036854775808',
@ -58,16 +63,16 @@ var types = [{
'9223372036854775807',
null
]
},{
}, {
name: 'varchar(5)',
values: ['yo', '', 'zomg!', null]
},{
}, {
name: 'oid',
values: [0, 204410, null]
},{
}, {
name: 'bool',
values: [true, false, null]
},{
}, {
name: 'numeric',
values: [
'-12.34',
@ -77,52 +82,42 @@ var types = [{
'3141592653589793238462643383279502.1618033988749894848204586834365638',
null
]
},{
}, {
name: 'real',
values: [-101.3, -1.2, 0, 1.2, 101.1, null]
},{
}, {
name: 'double precision',
values: [-101.3, -1.2, 0, 1.2, 101.1, null]
},{
}, {
name: 'timestamptz',
values: [null]
},{
}, {
name: 'timestamp',
values: [null]
},{
}, {
name: 'timetz',
values: ['13:11:12.1234-05:30',null]
},{
values: ['13:11:12.1234-05:30', null]
}, {
name: 'time',
values: ['13:12:12.321', null]
}];
// ignore some tests in binary mode
if (helper.config.binary) {
types = types.filter(function(type) {
return !(type.name in {'real': 1, 'timetz':1, 'time':1, 'numeric': 1, 'bigint': 1});
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) {
valueCount += type.values.length;
})
sink = new helper.Sink(types.length + 1, function() {
helper.pg.end();
})
types.forEach(function(type) {
types.forEach(function (type) {
testForTypeCoercion(type)
});
test("timestampz round trip", function() {
suite.test("timestampz round trip", function (cb) {
var now = new Date();
var client = helper.client();
client.on('error', function(err) {
console.log(err);
client.end();
});
client.query("create temp table date_tests(name varchar(10), tstz timestamptz(3))");
client.query({
text: "insert into date_tests(name, tstz)VALUES($1, $2)",
@ -135,67 +130,66 @@ test("timestampz round trip", function() {
values: ['now']
}));
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.getYear(), now.getYear());
assert.equal(date.getMonth(), now.getMonth());
assert.equal(date.getDate(), now.getDate());
assert.equal(date.getHours(), now.getHours());
assert.equal(date.getMinutes(), now.getMinutes());
assert.equal(date.getSeconds(), now.getSeconds());
test("milliseconds are equal", function() {
assert.equal(date.getMilliseconds(), now.getMilliseconds());
});
assert.equal(date.getMilliseconds(), now.getMilliseconds());
});
client.on('drain', client.end.bind(client));
client.on('drain', () => {
client.end(cb)
});
});
if(!helper.config.binary) {
test('date range extremes', function() {
var client = helper.client();
client.on('error', function(err) {
console.log(err);
client.end();
});
// Set the server timeszone to the same as used for the test,
// otherwise (if server's timezone is ahead of GMT) in
// textParsers.js::parseDate() the timezone offest is added to the date;
// in the case of "275760-09-13 00:00:00 GMT" the timevalue overflows.
client.query('SET TIMEZONE TO GMT', 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
// http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.1
client.query('SELECT $1::TIMESTAMPTZ as when', ["275760-09-13 00:00:00 GMT"], assert.success(function(res) {
assert.equal(res.rows[0].when.getFullYear(), 275760);
}));
client.query('SELECT $1::TIMESTAMPTZ as when', ["4713-12-31 12:31:59 BC GMT"], assert.success(function(res) {
assert.equal(res.rows[0].when.getFullYear(), -4713);
}));
client.query('SELECT $1::TIMESTAMPTZ as when', ["275760-09-13 00:00:00 -15:00"], assert.success(function(res) {
assert( isNaN(res.rows[0].when.getTime()) );
}));
client.on('drain', client.end.bind(client));
}));
});
}
helper.pg.connect(helper.config, assert.calls(function(err, client, done) {
assert.ifError(err);
client.query('select null as res;', assert.calls(function(err, res) {
assert.isNull(err);
assert.strictEqual(res.rows[0].res, null)
suite.test('selecting nulls', cb => {
const pool = new pg.Pool()
pool.connect(assert.calls(function (err, client, done) {
assert.ifError(err);
client.query('select null as res;', assert.calls(function (err, res) {
assert.isNull(err);
assert.strictEqual(res.rows[0].res, null)
}))
client.query('select 7 <> $1 as res;', [null], function (err, res) {
assert.isNull(err);
assert.strictEqual(res.rows[0].res, null);
done();
pool.end(cb)
})
}))
client.query('select 7 <> $1 as res;',[null], function(err, res) {
assert.isNull(err);
assert.strictEqual(res.rows[0].res, null);
sink.add();
done();
})
}))
})
suite.test('date range extremes', function (done) {
var client = helper.client();
// Set the server timeszone to the same as used for the test,
// otherwise (if server's timezone is ahead of GMT) in
// textParsers.js::parseDate() the timezone offest is added to the date;
// in the case of "275760-09-13 00:00:00 GMT" the timevalue overflows.
client.query('SET TIMEZONE TO GMT', 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
// http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.1
client.query('SELECT $1::TIMESTAMPTZ as when', ["275760-09-13 00:00:00 GMT"], assert.success(function (res) {
assert.equal(res.rows[0].when.getFullYear(), 275760);
}));
client.query('SELECT $1::TIMESTAMPTZ as when', ["4713-12-31 12:31:59 BC GMT"], assert.success(function (res) {
assert.equal(res.rows[0].when.getFullYear(), -4713);
}));
client.query('SELECT $1::TIMESTAMPTZ as when', ["275760-09-13 00:00:00 -15:00"], assert.success(function (res) {
assert(isNaN(res.rows[0].when.getTime()));
}));
client.on('drain', () => {
client.end(done)
});
}));
});

View File

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

View File

@ -0,0 +1,9 @@
var helper = require("./test-helper")
helper.testPoolSize(1);
helper.testPoolSize(2);
helper.testPoolSize(40);
helper.testPoolSize(200);

View File

@ -1,2 +0,0 @@
var helper = require("./test-helper")
helper.testPoolSize(2);

View File

@ -1,15 +0,0 @@
var helper = require('./test-helper')
var called = false;
test('disconnects', function() {
called = true;
var eventSink = new helper.Sink(1, function() {});
helper.pg.on('end', function() {
eventSink.add();
});
//this should exit the process
helper.pg.end();
})

View File

@ -1,30 +0,0 @@
var helper = require('./test-helper')
var called = false;
test('disconnects', function() {
var sink = new helper.Sink(4, function() {
called = true;
var eventSink = new helper.Sink(1, function() {});
helper.pg.on('end', function() {
eventSink.add();
});
//this should exit the process, killing each connection pool
helper.pg.end();
});
[helper.config, helper.config, helper.config, helper.config].forEach(function(config) {
helper.pg.connect(config, function(err, client, done) {
assert.isNull(err);
client.query("SELECT * FROM NOW()", function(err, result) {
setTimeout(function() {
assert.equal(called, false, "Should not have disconnected yet")
sink.add();
done();
}, 0)
})
})
})
})

View File

@ -1,40 +1,46 @@
var helper = require("../test-helper");
var pg = require("../../../lib");
var helper = require("./test-helper");
const pg = helper.pg
//first make pool hold 2 clients
pg.defaults.poolSize = 2;
//get first client
pg.connect(helper.config, assert.success(function(client, done) {
client.id = 1;
client.query('SELECT NOW()', function() {
pg.connect(helper.config, assert.success(function(client2, done2) {
client2.id = 2;
var pidColName = 'procpid';
helper.versionGTE(client2, '9.2.0', 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'];
if(!isGreater) {
killIdleQuery = 'SELECT procpid, (SELECT pg_terminate_backend(procpid)) AS killed FROM pg_stat_activity WHERE current_query LIKE $1';
params = ['%IDLE%']
}
const pool = new pg.Pool()
//subscribe to the pg error event
assert.emits(pg, 'error', function(error, brokenClient) {
assert.ok(error);
assert.ok(brokenClient);
assert.equal(client.id, brokenClient.id);
});
const suite = new helper.Suite()
suite.test('errors emitted on pool', (cb) => {
//get first client
pool.connect(assert.success(function (client, done) {
client.id = 1;
client.query('SELECT NOW()', function () {
pool.connect(assert.success(function (client2, done2) {
client2.id = 2;
var pidColName = 'procpid';
helper.versionGTE(client2, '9.2.0', 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'];
if (!isGreater) {
killIdleQuery = 'SELECT procpid, (SELECT pg_terminate_backend(procpid)) AS killed FROM pg_stat_activity WHERE current_query LIKE $1';
params = ['%IDLE%']
}
//kill the connection from client
client2.query(killIdleQuery, params, assert.success(function(res) {
//check to make sure client connection actually was killed
//return client2 to the pool
done2();
pg.end();
pool.once('error', (err, brokenClient) => {
assert.ok(err);
assert.ok(brokenClient);
assert.equal(client.id, brokenClient.id);
cb()
})
//kill the connection from client
client2.query(killIdleQuery, params, assert.success(function (res) {
//check to make sure client connection actually was killed
//return client2 to the pool
done2();
pool.end();
}));
}));
}));
}));
})
}));
})
}));
})

View File

@ -1,13 +1,12 @@
var helper = require(__dirname + '/test-helper');
var helper = require('./test-helper');
const config = Object.assign({ }, helper.config, { idleTimeoutMillis: 50 })
test('idle timeout', function() {
helper.pg.connect(config, assert.calls(function(err, client, done) {
assert.isNull(err);
client.query('SELECT NOW()');
//just let this one time out
//test will hang if pool doesn't timeout
done();
}));
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.isNull(err);
client.query('SELECT NOW()');
done();
}));
});

View File

@ -1,2 +0,0 @@
var helper = require("./test-helper")
helper.testPoolSize(40);

View File

@ -1,20 +0,0 @@
var helper = require('./test-helper');
//setup defaults
helper.pg.defaults.user = helper.args.user;
helper.pg.defaults.password = helper.args.password;
helper.pg.defaults.host = helper.args.host;
helper.pg.defaults.port = helper.args.port;
helper.pg.defaults.database = helper.args.database;
helper.pg.defaults.poolSize = 1;
helper.pg.connect(assert.calls(function(err, client, done) {
assert.isNull(err);
client.query('SELECT NOW()');
client.once('drain', function() {
setTimeout(function() {
helper.pg.end();
done();
}, 10);
});
}));

View File

@ -1,2 +0,0 @@
var helper = require("./test-helper")
helper.testPoolSize(1);

View File

@ -1,13 +0,0 @@
var helper = require("../test-helper");
var pg = require("../../../lib");
pg.connect(helper.config, assert.success(function(client, done) {
assert.equal(Object.keys(pg._pools).length, 1);
pg.connect(helper.config, assert.success(function(client2, done2) {
assert.equal(Object.keys(pg._pools).length, 1);
done();
done2();
pg.end();
}));
}));

View File

@ -1,32 +1,31 @@
var helper = require(__dirname + "/../test-helper");
var helper = require("./../test-helper");
helper.testPoolSize = function(max) {
var sink = new helper.Sink(max, function() {
helper.pg.end();
});
const suite = new helper.Suite()
test("can pool " + max + " times", function() {
for(var i = 0; i < max; i++) {
helper.pg.poolSize = 10;
test("connection #" + i + " executes", function() {
helper.pg.connect(helper.config, function(err, client, done) {
assert.isNull(err);
client.query("select * from person", function(err, result) {
assert.lengthIs(result.rows, 26)
})
client.query("select count(*) as c from person", function(err, result) {
assert.equal(result.rows[0].c, 26)
})
var query = client.query("SELECT * FROM NOW()", (err) => {
assert(!err)
sink.add();
done();
})
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 () {
pool.end(cb)
});
for (var i = 0; i < max; i++) {
pool.connect(function (err, client, done) {
assert.isNull(err);
client.query("SELECT * FROM NOW()")
client.query("select generate_series(0, 25)", function (err, result) {
assert.equal(result.rows.length, 26)
})
var query = client.query("SELECT * FROM NOW()", (err) => {
assert(!err)
sink.add();
done();
})
})
}
})
}
module.exports = helper;
module.exports = Object.assign({}, helper, { suite: suite })

View File

@ -1,2 +0,0 @@
var helper = require("./test-helper")
helper.testPoolSize(200);

View File

@ -1,28 +1,19 @@
var helper = require('./test-helper')
var co = require('co')
var tid = setTimeout(function() {
throw new Error('Tests did not complete in time')
}, 1000)
co(function * () {
var client = yield helper.pg.connect()
const pool = new helper.pg.Pool()
new helper.Suite().test('using coroutines works with promises', 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')
var threw = false
try {
yield client.query('SELECT LKDSJDSLKFJ')
} catch(e) {
} catch (e) {
threw = true
}
assert(threw)
client.release()
helper.pg.end()
clearTimeout(tid)
})
.catch(function(e) {
setImmediate(function() {
throw e
})
})
yield pool.end()
}))

View File

@ -4,22 +4,26 @@ var helper = require('./test-helper')
var Query = helper.pg.Query
var suite = new helper.Suite()
const Pool = helper.pg.Pool
suite.test('no domain', function (cb) {
assert(!process.domain)
helper.pg.connect(assert.success(function (client, done) {
const pool = new Pool()
pool.connect(assert.success(function (client, done) {
assert(!process.domain)
done()
cb()
pool.end(cb)
}))
})
suite.test('with domain', function (cb) {
assert(!process.domain)
const pool = new Pool()
var domain = require('domain').create()
domain.run(function () {
var startingDomain = process.domain
assert(startingDomain)
helper.pg.connect(helper.config, assert.success(function (client, done) {
pool.connect(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 () {
@ -27,7 +31,7 @@ suite.test('with domain', function (cb) {
assert.equal(startingDomain, process.domain, 'domain was lost when checking out a client')
done(true)
process.domain.exit()
cb()
pool.end(cb)
}))
}))
})
@ -35,15 +39,14 @@ suite.test('with domain', function (cb) {
suite.test('error on domain', function (cb) {
var domain = require('domain').create()
const pool = new Pool()
domain.on('error', function () {
cb()
pool.end(cb)
})
domain.run(function () {
helper.pg.connect(helper.config, assert.success(function (client, done) {
pool.connect(assert.success(function (client, done) {
client.query(new Query('SELECT SLDKJFLSKDJF'))
client.on('drain', done)
}))
})
})
suite.test('cleanup', () => helper.pg.end())

View File

@ -3,7 +3,8 @@ var exec = require('child_process').exec;
helper.pg.defaults.poolIdleTimeout = 1000;
helper.pg.connect(helper.config, function(err,client) {
const pool = new helper.pg.Pool()
pool.connect(function(err,client) {
client.query("SELECT pg_backend_pid()", function(err, result) {
var pid = result.rows[0].pg_backend_pid;
var psql = 'psql';
@ -16,6 +17,6 @@ helper.pg.connect(helper.config, function(err,client) {
});
});
helper.pg.on('error', function(err, client) {
pool.on('error', function(err, client) {
//swallow errors
});

View File

@ -4,7 +4,8 @@ var pg = helper.pg;
var suite = new helper.Suite()
suite.test('parsing array decimal results', function (done) {
pg.connect(helper.config, assert.calls(function (err, client, release) {
const pool = new pg.Pool()
pool.connect(assert.calls(function (err, client, release) {
assert.isNull(err);
client.query("CREATE TEMP TABLE why(names text[], numbors integer[], decimals double precision[])");
client.query(new pg.Query('INSERT INTO why(names, numbors, decimals) VALUES(\'{"aaron", "brian","a b c" }\', \'{1, 2, 3}\', \'{.1, 0.05, 3.654}\')')).on('error', console.log);
@ -14,8 +15,7 @@ suite.test('parsing array decimal results', function (done) {
assert.equal(result.rows[0].decimals[1], 0.05);
assert.equal(result.rows[0].decimals[2], 3.654);
release()
pg.end();
done()
pool.end(done)
}))
}))
})

View File

@ -2,15 +2,15 @@ var helper = require(__dirname + "/../test-helper");
var pg = helper.pg;
new helper.Suite().test('parsing array results', function(cb) {
pg.connect(helper.config, assert.success(function(client, done) {
const pool = new pg.Pool()
pool.connect(assert.success(function(client, done) {
client.query('CREATE TEMP TABLE test_table(bar integer, "baz\'s" integer)')
client.query('INSERT INTO test_table(bar, "baz\'s") VALUES(1, 1), (2, 2)')
client.query('SELECT * FROM test_table', function(err, res) {
assert.equal(res.rows[0]["baz's"], 1)
assert.equal(res.rows[1]["baz's"], 2)
done()
pg.end()
cb()
pool.end(cb)
})
}))
})

View File

@ -1,7 +1,8 @@
var helper = require('../test-helper');
var assert = require('assert');
helper.pg.connect(function(err, client, done) {
const pool = new helper.pg.Pool()
pool.connect(function(err, client, done) {
if (err) throw err;
var c = 'CREATE TEMP TABLE posts (body TEXT)';
@ -21,7 +22,7 @@ helper.pg.connect(function(err, client, done) {
if (err) throw err;
assert.equal(res.rows[0].body, '')
helper.pg.end();
pool.end();
});
});
});

View File

@ -4,7 +4,8 @@ var copyFrom = require('pg-copy-streams').from;
if(helper.args.native) return;
helper.pg.connect(function (err, client, done) {
const pool = new helper.pg.Pool()
pool.connect(function (err, client, done) {
if (err) throw err;
var c = 'CREATE TEMP TABLE employee (id integer, fname varchar(400), lname varchar(400))';
@ -16,7 +17,7 @@ helper.pg.connect(function (err, client, done) {
stream.on('end', function () {
done();
setTimeout(() => {
helper.pg.end();
pool.end()
}, 50)
});

View File

@ -1,6 +1,7 @@
var helper = require('../test-helper');
const pool = new helper.pg.Pool()
helper.pg.connect(function(err,client) {
pool.connect(function(err,client) {
var q = {
name: 'This is a super long query name just so I can test that an error message is properly spit out to console.error without throwing an exception or anything',
text: 'SELECT NOW()'

View File

@ -1,7 +1,7 @@
var helper = require(__dirname + '/../test-helper');
var helper = require('./../test-helper');
//native bindings are only installed for native tests
if(!helper.args.native) {
if (!helper.args.native) {
return;
}
@ -15,13 +15,23 @@ var NativeClient = require('../../../lib/native')
assert(pg.Client === JsClient);
assert(native.Client === NativeClient);
pg.connect(function(err, client, done) {
assert(client instanceof JsClient);
client.end();
const jsPool = new pg.Pool()
const nativePool = new native.Pool()
native.connect(function(err, client, done) {
const suite = new helper.Suite()
suite.test('js pool returns js client', cb => {
jsPool.connect(function (err, client, done) {
assert(client instanceof JsClient);
done()
jsPool.end(cb)
})
})
suite.test('native pool returns native client', cb => {
nativePool.connect(function (err, client, done) {
assert(client instanceof NativeClient);
client.end();
done()
nativePool.end(cb)
});
});
})

View File

@ -3,8 +3,6 @@ assert = require('assert');
var EventEmitter = require('events').EventEmitter;
var sys = require('util');
process.noDeprecation = true;
var BufferList = require('./buffer-list')
const Suite = require('./suite')
const args = require('./cli');