diff --git a/.eslintrc b/.eslintrc index fd9bb8ddc..d6b20038b 100644 --- a/.eslintrc +++ b/.eslintrc @@ -16,6 +16,8 @@ "@typescript-eslint/no-unused-vars": ["error", { "args": "none" }], - "no-unused-vars": "off" + "no-unused-vars": "off", + "no-var": "error", + "prefer-const": "error" } } diff --git a/package.json b/package.json index ce4ede68c..33af3bd31 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,8 @@ "docs:start": "cd docs && yarn start", "pretest": "yarn build", "prepublish": "yarn build", - "lint": "eslint --cache 'packages/**/*.{js,ts,tsx}'" + "lint": "eslint --cache 'packages/**/*.{js,ts,tsx}'", + "lint:fix": "eslint --cache 'packages/**/*.{js,ts,tsx}' --fix" }, "devDependencies": { "@typescript-eslint/eslint-plugin": "^7.0.0", diff --git a/packages/pg-connection-string/test/parse.js b/packages/pg-connection-string/test/parse.js index 59f16a62e..9b37eebf9 100644 --- a/packages/pg-connection-string/test/parse.js +++ b/packages/pg-connection-string/test/parse.js @@ -1,13 +1,13 @@ 'use strict' -var chai = require('chai') +const chai = require('chai') chai.should() -var parse = require('../').parse +const parse = require('../').parse describe('parse', function () { it('using connection string in client constructor', function () { - var subject = parse('postgres://brian:pw@boom:381/lala') + const subject = parse('postgres://brian:pw@boom:381/lala') subject.user.should.equal('brian') subject.password.should.equal('pw') subject.host.should.equal('boom') @@ -16,42 +16,42 @@ describe('parse', function () { }) it('escape spaces if present', function () { - var subject = parse('postgres://localhost/post gres') + const subject = parse('postgres://localhost/post gres') subject.database.should.equal('post gres') }) it('do not double escape spaces', function () { - var subject = parse('postgres://localhost/post%20gres') + const subject = parse('postgres://localhost/post%20gres') subject.database.should.equal('post gres') }) it('initializing with unix domain socket', function () { - var subject = parse('/var/run/') + const subject = parse('/var/run/') subject.host.should.equal('/var/run/') }) it('initializing with unix domain socket and a specific database, the simple way', function () { - var subject = parse('/var/run/ mydb') + const subject = parse('/var/run/ mydb') subject.host.should.equal('/var/run/') subject.database.should.equal('mydb') }) it('initializing with unix domain socket, the health way', function () { - var subject = parse('socket:/some path/?db=my[db]&encoding=utf8') + const subject = parse('socket:/some path/?db=my[db]&encoding=utf8') subject.host.should.equal('/some path/') subject.database.should.equal('my[db]', 'must to be escaped and unescaped trough "my%5Bdb%5D"') subject.client_encoding.should.equal('utf8') }) it('initializing with unix domain socket, the escaped health way', function () { - var subject = parse('socket:/some%20path/?db=my%2Bdb&encoding=utf8') + const subject = parse('socket:/some%20path/?db=my%2Bdb&encoding=utf8') subject.host.should.equal('/some path/') subject.database.should.equal('my+db') subject.client_encoding.should.equal('utf8') }) it('initializing with unix domain socket, username and password', function () { - var subject = parse('socket://brian:pw@/var/run/?db=mydb') + const subject = parse('socket://brian:pw@/var/run/?db=mydb') subject.user.should.equal('brian') subject.password.should.equal('pw') subject.host.should.equal('/var/run/') @@ -59,14 +59,14 @@ describe('parse', function () { }) it('password contains < and/or > characters', function () { - var sourceConfig = { + const sourceConfig = { user: 'brian', password: 'helloe', host: 'localhost', port: 5432, database: 'postgres', } - var connectionString = + const connectionString = 'postgres://' + sourceConfig.user + ':' + @@ -77,19 +77,19 @@ describe('parse', function () { sourceConfig.port + '/' + sourceConfig.database - var subject = parse(connectionString) + const subject = parse(connectionString) subject.password.should.equal(sourceConfig.password) }) it('password contains colons', function () { - var sourceConfig = { + const sourceConfig = { user: 'brian', password: 'hello:pass:world', host: 'localhost', port: 5432, database: 'postgres', } - var connectionString = + const connectionString = 'postgres://' + sourceConfig.user + ':' + @@ -100,21 +100,21 @@ describe('parse', function () { sourceConfig.port + '/' + sourceConfig.database - var subject = parse(connectionString) + const subject = parse(connectionString) subject.password.should.equal(sourceConfig.password) }) it('username or password contains weird characters', function () { - var strang = 'pg://my f%irst name:is&%awesome!@localhost:9000' - var subject = parse(strang) + const strang = 'pg://my f%irst name:is&%awesome!@localhost:9000' + const subject = parse(strang) subject.user.should.equal('my f%irst name') subject.password.should.equal('is&%awesome!') subject.host.should.equal('localhost') }) it('url is properly encoded', function () { - var encoded = 'pg://bi%25na%25%25ry%20:s%40f%23@localhost/%20u%2520rl' - var subject = parse(encoded) + const encoded = 'pg://bi%25na%25%25ry%20:s%40f%23@localhost/%20u%2520rl' + const subject = parse(encoded) subject.user.should.equal('bi%na%%ry ') subject.password.should.equal('s@f#') subject.host.should.equal('localhost') @@ -122,24 +122,24 @@ describe('parse', function () { }) it('relative url sets database', function () { - var relative = 'different_db_on_default_host' - var subject = parse(relative) + const relative = 'different_db_on_default_host' + const subject = parse(relative) subject.database.should.equal('different_db_on_default_host') }) it('no pathname returns null database', function () { - var subject = parse('pg://myhost') + const subject = parse('pg://myhost') ;(subject.database === null).should.equal(true) }) it('pathname of "/" returns null database', function () { - var subject = parse('pg://myhost/') + const subject = parse('pg://myhost/') subject.host.should.equal('myhost') ;(subject.database === null).should.equal(true) }) it('configuration parameter host', function () { - var subject = parse('pg://user:pass@/dbname?host=/unix/socket') + const subject = parse('pg://user:pass@/dbname?host=/unix/socket') subject.user.should.equal('user') subject.password.should.equal('pass') subject.host.should.equal('/unix/socket') @@ -147,13 +147,13 @@ describe('parse', function () { }) it('configuration parameter host overrides url host', function () { - var subject = parse('pg://user:pass@localhost/dbname?host=/unix/socket') + const subject = parse('pg://user:pass@localhost/dbname?host=/unix/socket') subject.database.should.equal('dbname') subject.host.should.equal('/unix/socket') }) it('url with encoded socket', function () { - var subject = parse('pg://user:pass@%2Funix%2Fsocket/dbname') + const subject = parse('pg://user:pass@%2Funix%2Fsocket/dbname') subject.user.should.equal('user') subject.password.should.equal('pass') subject.host.should.equal('/unix/socket') @@ -161,7 +161,7 @@ describe('parse', function () { }) it('url with real host and an encoded db name', function () { - var subject = parse('pg://user:pass@localhost/%2Fdbname') + const subject = parse('pg://user:pass@localhost/%2Fdbname') subject.user.should.equal('user') subject.password.should.equal('pass') subject.host.should.equal('localhost') @@ -169,7 +169,7 @@ describe('parse', function () { }) it('configuration parameter host treats encoded host as part of the db name', function () { - var subject = parse('pg://user:pass@%2Funix%2Fsocket/dbname?host=localhost') + const subject = parse('pg://user:pass@%2Funix%2Fsocket/dbname?host=localhost') subject.user.should.equal('user') subject.password.should.equal('pass') subject.host.should.equal('localhost') @@ -177,150 +177,150 @@ describe('parse', function () { }) it('configuration parameter application_name', function () { - var connectionString = 'pg:///?application_name=TheApp' - var subject = parse(connectionString) + const connectionString = 'pg:///?application_name=TheApp' + const subject = parse(connectionString) subject.application_name.should.equal('TheApp') }) it('configuration parameter fallback_application_name', function () { - var connectionString = 'pg:///?fallback_application_name=TheAppFallback' - var subject = parse(connectionString) + const connectionString = 'pg:///?fallback_application_name=TheAppFallback' + const subject = parse(connectionString) subject.fallback_application_name.should.equal('TheAppFallback') }) it('configuration parameter options', function () { - var connectionString = 'pg:///?options=-c geqo=off' - var subject = parse(connectionString) + const connectionString = 'pg:///?options=-c geqo=off' + const subject = parse(connectionString) subject.options.should.equal('-c geqo=off') }) it('configuration parameter ssl=true', function () { - var connectionString = 'pg:///?ssl=true' - var subject = parse(connectionString) + const connectionString = 'pg:///?ssl=true' + const subject = parse(connectionString) subject.ssl.should.equal(true) }) it('configuration parameter ssl=1', function () { - var connectionString = 'pg:///?ssl=1' - var subject = parse(connectionString) + const connectionString = 'pg:///?ssl=1' + const subject = parse(connectionString) subject.ssl.should.equal(true) }) it('configuration parameter ssl=0', function () { - var connectionString = 'pg:///?ssl=0' - var subject = parse(connectionString) + const connectionString = 'pg:///?ssl=0' + const subject = parse(connectionString) subject.ssl.should.equal(false) }) it('set ssl', function () { - var subject = parse('pg://myhost/db?ssl=1') + const subject = parse('pg://myhost/db?ssl=1') subject.ssl.should.equal(true) }) it('configuration parameter sslcert=/path/to/cert', function () { - var connectionString = 'pg:///?sslcert=' + __dirname + '/example.cert' - var subject = parse(connectionString) + const connectionString = 'pg:///?sslcert=' + __dirname + '/example.cert' + const subject = parse(connectionString) subject.ssl.should.eql({ cert: 'example cert\n', }) }) it('configuration parameter sslkey=/path/to/key', function () { - var connectionString = 'pg:///?sslkey=' + __dirname + '/example.key' - var subject = parse(connectionString) + const connectionString = 'pg:///?sslkey=' + __dirname + '/example.key' + const subject = parse(connectionString) subject.ssl.should.eql({ key: 'example key\n', }) }) it('configuration parameter sslrootcert=/path/to/ca', function () { - var connectionString = 'pg:///?sslrootcert=' + __dirname + '/example.ca' - var subject = parse(connectionString) + const connectionString = 'pg:///?sslrootcert=' + __dirname + '/example.ca' + const subject = parse(connectionString) subject.ssl.should.eql({ ca: 'example ca\n', }) }) it('configuration parameter sslmode=no-verify', function () { - var connectionString = 'pg:///?sslmode=no-verify' - var subject = parse(connectionString) + const connectionString = 'pg:///?sslmode=no-verify' + const subject = parse(connectionString) subject.ssl.should.eql({ rejectUnauthorized: false, }) }) it('configuration parameter sslmode=disable', function () { - var connectionString = 'pg:///?sslmode=disable' - var subject = parse(connectionString) + const connectionString = 'pg:///?sslmode=disable' + const subject = parse(connectionString) subject.ssl.should.eql(false) }) it('configuration parameter sslmode=prefer', function () { - var connectionString = 'pg:///?sslmode=prefer' - var subject = parse(connectionString) + const connectionString = 'pg:///?sslmode=prefer' + const subject = parse(connectionString) subject.ssl.should.eql({}) }) it('configuration parameter sslmode=require', function () { - var connectionString = 'pg:///?sslmode=require' - var subject = parse(connectionString) + const connectionString = 'pg:///?sslmode=require' + const subject = parse(connectionString) subject.ssl.should.eql({}) }) it('configuration parameter sslmode=verify-ca', function () { - var connectionString = 'pg:///?sslmode=verify-ca' - var subject = parse(connectionString) + const connectionString = 'pg:///?sslmode=verify-ca' + const subject = parse(connectionString) subject.ssl.should.eql({}) }) it('configuration parameter sslmode=verify-full', function () { - var connectionString = 'pg:///?sslmode=verify-full' - var subject = parse(connectionString) + const connectionString = 'pg:///?sslmode=verify-full' + const subject = parse(connectionString) subject.ssl.should.eql({}) }) it('configuration parameter ssl=true and sslmode=require still work with sslrootcert=/path/to/ca', function () { - var connectionString = 'pg:///?ssl=true&sslrootcert=' + __dirname + '/example.ca&sslmode=require' - var subject = parse(connectionString) + const connectionString = 'pg:///?ssl=true&sslrootcert=' + __dirname + '/example.ca&sslmode=require' + const subject = parse(connectionString) subject.ssl.should.eql({ ca: 'example ca\n', }) }) it('allow other params like max, ...', function () { - var subject = parse('pg://myhost/db?max=18&min=4') + const subject = parse('pg://myhost/db?max=18&min=4') subject.max.should.equal('18') subject.min.should.equal('4') }) it('configuration parameter keepalives', function () { - var connectionString = 'pg:///?keepalives=1' - var subject = parse(connectionString) + const connectionString = 'pg:///?keepalives=1' + const subject = parse(connectionString) subject.keepalives.should.equal('1') }) it('unknown configuration parameter is passed into client', function () { - var connectionString = 'pg:///?ThereIsNoSuchPostgresParameter=1234' - var subject = parse(connectionString) + const connectionString = 'pg:///?ThereIsNoSuchPostgresParameter=1234' + const subject = parse(connectionString) subject.ThereIsNoSuchPostgresParameter.should.equal('1234') }) it('do not override a config field with value from query string', function () { - var subject = parse('socket:/some path/?db=my[db]&encoding=utf8&client_encoding=bogus') + const subject = parse('socket:/some path/?db=my[db]&encoding=utf8&client_encoding=bogus') subject.host.should.equal('/some path/') subject.database.should.equal('my[db]', 'must to be escaped and unescaped through "my%5Bdb%5D"') subject.client_encoding.should.equal('utf8') }) it('return last value of repeated parameter', function () { - var connectionString = 'pg:///?keepalives=1&keepalives=0' - var subject = parse(connectionString) + const connectionString = 'pg:///?keepalives=1&keepalives=0' + const subject = parse(connectionString) subject.keepalives.should.equal('0') }) it('use the port specified in the query parameters', function () { - var connectionString = 'postgres:///?host=localhost&port=1234' - var subject = parse(connectionString) + const connectionString = 'postgres:///?host=localhost&port=1234' + const subject = parse(connectionString) subject.port.should.equal('1234') }) }) diff --git a/packages/pg-native/bench/index.js b/packages/pg-native/bench/index.js index 05dbc949b..06d5fb59b 100644 --- a/packages/pg-native/bench/index.js +++ b/packages/pg-native/bench/index.js @@ -1,10 +1,10 @@ -var pg = require('pg').native -var Native = require('../') +const pg = require('pg').native +const Native = require('../') -var warmup = function (fn, cb) { - var count = 0 - var max = 10 - var run = function (err) { +const warmup = function (fn, cb) { + let count = 0 + const max = 10 + const run = function (err) { if (err) return cb(err) if (max >= count++) { @@ -16,27 +16,27 @@ var warmup = function (fn, cb) { run() } -var native = Native() +const native = Native() native.connectSync() -var queryText = 'SELECT generate_series(0, 1000)' -var client = new pg.Client() +const queryText = 'SELECT generate_series(0, 1000)' +const client = new pg.Client() client.connect(function () { - var pure = function (cb) { + const pure = function (cb) { client.query(queryText, function (err) { if (err) throw err cb(err) }) } - var nativeQuery = function (cb) { + const nativeQuery = function (cb) { native.query(queryText, function (err) { if (err) throw err cb(err) }) } - var run = function () { - var start = Date.now() + const run = function () { + let start = Date.now() warmup(pure, function () { console.log('pure done', Date.now() - start) start = Date.now() diff --git a/packages/pg-native/bench/leaks.js b/packages/pg-native/bench/leaks.js index 57fe36da2..72fb8bcef 100644 --- a/packages/pg-native/bench/leaks.js +++ b/packages/pg-native/bench/leaks.js @@ -1,29 +1,29 @@ -var Client = require('../') -var async = require('async') +const Client = require('../') +const async = require('async') -var loop = function () { - var client = new Client() +const loop = function () { + const client = new Client() - var connect = function (cb) { + const connect = function (cb) { client.connect(cb) } - var simpleQuery = function (cb) { + const simpleQuery = function (cb) { client.query('SELECT NOW()', cb) } - var paramsQuery = function (cb) { + const paramsQuery = function (cb) { client.query('SELECT $1::text as name', ['Brian'], cb) } - var prepared = function (cb) { + const prepared = function (cb) { client.prepare('test', 'SELECT $1::text as name', 1, function (err) { if (err) return cb(err) client.execute('test', ['Brian'], cb) }) } - var sync = function (cb) { + const sync = function (cb) { client.querySync('SELECT NOW()') client.querySync('SELECT $1::text as name', ['Brian']) client.prepareSync('boom', 'SELECT $1::text as name', 1) @@ -31,13 +31,13 @@ var loop = function () { setImmediate(cb) } - var end = function (cb) { + const end = function (cb) { client.end(cb) } - var ops = [connect, simpleQuery, paramsQuery, prepared, sync, end] + const ops = [connect, simpleQuery, paramsQuery, prepared, sync, end] - var start = Date.now() + const start = Date.now() async.series(ops, function (err) { if (err) throw err console.log(Date.now() - start) diff --git a/packages/pg-native/index.js b/packages/pg-native/index.js index a3c3f070b..0cc2f646d 100644 --- a/packages/pg-native/index.js +++ b/packages/pg-native/index.js @@ -1,12 +1,12 @@ -var Libpq = require('libpq') -var EventEmitter = require('events').EventEmitter -var util = require('util') -var assert = require('assert') -var types = require('pg-types') -var buildResult = require('./lib/build-result') -var CopyStream = require('./lib/copy-stream') - -var Client = (module.exports = function (config) { +const Libpq = require('libpq') +const EventEmitter = require('events').EventEmitter +const util = require('util') +const assert = require('assert') +const types = require('pg-types') +const buildResult = require('./lib/build-result') +const CopyStream = require('./lib/copy-stream') + +const Client = (module.exports = function (config) { if (!(this instanceof Client)) { return new Client(config) } @@ -51,7 +51,7 @@ Client.prototype.connectSync = function (params) { } Client.prototype.query = function (text, values, cb) { - var queryFn + let queryFn if (typeof values === 'function') { cb = values @@ -67,7 +67,7 @@ Client.prototype.query = function (text, values, cb) { } } - var self = this + const self = this self._dispatchQuery(self.pq, queryFn, function (err) { if (err) return cb(err) @@ -77,8 +77,8 @@ Client.prototype.query = function (text, values, cb) { } Client.prototype.prepare = function (statementName, text, nParams, cb) { - var self = this - var fn = function () { + const self = this + const fn = function () { return self.pq.sendPrepare(statementName, text, nParams) } @@ -89,9 +89,9 @@ Client.prototype.prepare = function (statementName, text, nParams, cb) { } Client.prototype.execute = function (statementName, parameters, cb) { - var self = this + const self = this - var fn = function () { + const fn = function () { return self.pq.sendQueryPrepared(statementName, parameters) } @@ -111,7 +111,7 @@ Client.prototype.getCopyStream = function () { Client.prototype.cancel = function (cb) { assert(cb, 'Callback is required') // result is either true or a string containing an error - var result = this.pq.cancel() + const result = this.pq.cancel() return setImmediate(function () { cb(result === true ? undefined : new Error(result)) }) @@ -158,7 +158,7 @@ Client.prototype.end = function (cb) { } Client.prototype._readError = function (message) { - var err = new Error(message || this.pq.errorMessage()) + const err = new Error(message || this.pq.errorMessage()) this.emit('error', err) } @@ -174,7 +174,7 @@ Client.prototype._consumeQueryResults = function (pq) { } Client.prototype._emitResult = function (pq) { - var status = pq.resultStatus() + const status = pq.resultStatus() switch (status) { case 'PGRES_FATAL_ERROR': this._queryError = new Error(this.pq.resultErrorMessage()) @@ -201,7 +201,7 @@ Client.prototype._emitResult = function (pq) { // called when libpq is readable Client.prototype._read = function () { - var pq = this.pq + const pq = this.pq // read waiting data from the socket // e.g. clear the pending 'select' if (!pq.consumeInput()) { @@ -236,7 +236,7 @@ Client.prototype._read = function () { this.emit('readyForQuery') - var notice = this.pq.notifies() + let notice = this.pq.notifies() while (notice) { this.emit('notification', notice) notice = this.pq.notifies() @@ -252,8 +252,8 @@ Client.prototype._startReading = function () { this.pq.startReader() } -var throwIfError = function (pq) { - var err = pq.resultErrorMessage() || pq.errorMessage() +const throwIfError = function (pq) { + const err = pq.resultErrorMessage() || pq.errorMessage() if (err) { throw new Error(err) } @@ -266,7 +266,7 @@ Client.prototype._awaitResult = function (cb) { // wait for the writable socket to drain Client.prototype._waitForDrain = function (pq, cb) { - var res = pq.flush() + const res = pq.flush() // res of 0 is success if (res === 0) return cb() @@ -275,7 +275,7 @@ Client.prototype._waitForDrain = function (pq, cb) { // otherwise outgoing message didn't flush to socket // wait for it to flush and try again - var self = this + const self = this // you cannot read & write on a socket at the same time return pq.writable(function () { self._waitForDrain(pq, cb) @@ -286,9 +286,9 @@ Client.prototype._waitForDrain = function (pq, cb) { // finish writing query text to the socket Client.prototype._dispatchQuery = function (pq, fn, cb) { this._stopReading() - var success = pq.setNonBlocking(true) + const success = pq.setNonBlocking(true) if (!success) return cb(new Error('Unable to set non-blocking to true')) - var sent = fn() + const sent = fn() if (!sent) return cb(new Error(pq.errorMessage() || 'Something went wrong dispatching the query')) this._waitForDrain(pq, cb) } diff --git a/packages/pg-native/lib/build-result.js b/packages/pg-native/lib/build-result.js index 38408a608..7d313372b 100644 --- a/packages/pg-native/lib/build-result.js +++ b/packages/pg-native/lib/build-result.js @@ -18,7 +18,7 @@ class Result { consumeFields(pq) { const nfields = pq.nfields() - for (var x = 0; x < nfields; x++) { + for (let x = 0; x < nfields; x++) { this.fields.push({ name: pq.fname(x), dataTypeID: pq.ftype(x), @@ -28,7 +28,7 @@ class Result { consumeRows(pq) { const tupleCount = pq.ntuples() - for (var i = 0; i < tupleCount; i++) { + for (let i = 0; i < tupleCount; i++) { const row = this._arrayMode ? this.consumeRowAsArray(pq, i) : this.consumeRowAsObject(pq, i) this.rows.push(row) } @@ -36,7 +36,7 @@ class Result { consumeRowAsObject(pq, rowIndex) { const row = {} - for (var j = 0; j < this.fields.length; j++) { + for (let j = 0; j < this.fields.length; j++) { const value = this.readValue(pq, rowIndex, j) row[this.fields[j].name] = value } @@ -45,7 +45,7 @@ class Result { consumeRowAsArray(pq, rowIndex) { const row = [] - for (var j = 0; j < this.fields.length; j++) { + for (let j = 0; j < this.fields.length; j++) { const value = this.readValue(pq, rowIndex, j) row.push(value) } @@ -53,7 +53,7 @@ class Result { } readValue(pq, rowIndex, colIndex) { - var rawValue = pq.getvalue(rowIndex, colIndex) + const rawValue = pq.getvalue(rowIndex, colIndex) if (rawValue === '') { if (pq.getisnull(rowIndex, colIndex)) { return null diff --git a/packages/pg-native/lib/copy-stream.js b/packages/pg-native/lib/copy-stream.js index 13b455383..94ae4f7e5 100644 --- a/packages/pg-native/lib/copy-stream.js +++ b/packages/pg-native/lib/copy-stream.js @@ -1,8 +1,8 @@ -var Duplex = require('stream').Duplex -var Writable = require('stream').Writable -var util = require('util') +const Duplex = require('stream').Duplex +const Writable = require('stream').Writable +const util = require('util') -var CopyStream = (module.exports = function (pq, options) { +const CopyStream = (module.exports = function (pq, options) { Duplex.call(this, options) this.pq = pq this._reading = false @@ -12,7 +12,7 @@ util.inherits(CopyStream, Duplex) // writer methods CopyStream.prototype._write = function (chunk, encoding, cb) { - var result = this.pq.putCopyData(chunk) + const result = this.pq.putCopyData(chunk) // sent successfully if (result === 1) return cb() @@ -21,22 +21,22 @@ CopyStream.prototype._write = function (chunk, encoding, cb) { if (result === -1) return cb(new Error(this.pq.errorMessage())) // command would block. wait for writable and call again. - var self = this + const self = this this.pq.writable(function () { self._write(chunk, encoding, cb) }) } CopyStream.prototype.end = function () { - var args = Array.prototype.slice.call(arguments, 0) - var self = this + const args = Array.prototype.slice.call(arguments, 0) + const self = this - var callback = args.pop() + const callback = args.pop() if (args.length) { this.write(args[0]) } - var result = this.pq.putCopyEnd() + const result = this.pq.putCopyEnd() // sent successfully if (result === 1) { @@ -55,7 +55,7 @@ CopyStream.prototype.end = function () { // error if (result === -1) { - var err = new Error(this.pq.errorMessage()) + const err = new Error(this.pq.errorMessage()) return this.emit('error', err) } @@ -70,7 +70,7 @@ CopyStream.prototype.end = function () { // reader methods CopyStream.prototype._consumeBuffer = function (cb) { - var result = this.pq.getCopyData(true) + const result = this.pq.getCopyData(true) if (result instanceof Buffer) { return setImmediate(function () { cb(null, result) @@ -81,7 +81,7 @@ CopyStream.prototype._consumeBuffer = function (cb) { return cb(null, null) } if (result === 0) { - var self = this + const self = this this.pq.once('readable', function () { self.pq.stopReader() self.pq.consumeInput() @@ -96,7 +96,7 @@ CopyStream.prototype._read = function (size) { if (this._reading) return this._reading = true // console.log('read begin'); - var self = this + const self = this this._consumeBuffer(function (err, buffer) { self._reading = false if (err) { @@ -110,18 +110,18 @@ CopyStream.prototype._read = function (size) { }) } -var consumeResults = function (pq, cb) { - var cleanup = function () { +const consumeResults = function (pq, cb) { + const cleanup = function () { pq.removeListener('readable', onReadable) pq.stopReader() } - var readError = function (message) { + const readError = function (message) { cleanup() return cb(new Error(message || pq.errorMessage())) } - var onReadable = function () { + const onReadable = function () { // read waiting data from the socket // e.g. clear the pending 'select' if (!pq.consumeInput()) { diff --git a/packages/pg-native/test/array-mode.js b/packages/pg-native/test/array-mode.js index c79d471d2..0e6978a0a 100644 --- a/packages/pg-native/test/array-mode.js +++ b/packages/pg-native/test/array-mode.js @@ -1,16 +1,16 @@ -var Client = require('../') -var assert = require('assert') +const Client = require('../') +const assert = require('assert') describe('client with arrayMode', function () { it('returns result as array', function (done) { - var client = new Client({ arrayMode: true }) + const client = new Client({ arrayMode: true }) client.connectSync() client.querySync('CREATE TEMP TABLE blah(name TEXT)') client.querySync('INSERT INTO blah (name) VALUES ($1)', ['brian']) client.querySync('INSERT INTO blah (name) VALUES ($1)', ['aaron']) - var rows = client.querySync('SELECT * FROM blah') + const rows = client.querySync('SELECT * FROM blah') assert.equal(rows.length, 2) - var row = rows[0] + const row = rows[0] assert.equal(row.length, 1) assert.equal(row[0], 'brian') assert.equal(rows[1][0], 'aaron') diff --git a/packages/pg-native/test/async-workflow.js b/packages/pg-native/test/async-workflow.js index 975c5a97f..e86774b87 100644 --- a/packages/pg-native/test/async-workflow.js +++ b/packages/pg-native/test/async-workflow.js @@ -1,7 +1,7 @@ -var Client = require('../') -var ok = require('okay') -var assert = require('assert') -var concat = require('concat-stream') +const Client = require('../') +const ok = require('okay') +const assert = require('assert') +const concat = require('concat-stream') describe('async workflow', function () { before(function (done) { @@ -9,7 +9,7 @@ describe('async workflow', function () { this.client.connect(done) }) - var echoParams = function (params, cb) { + const echoParams = function (params, cb) { this.client.query( 'SELECT $1::text as first, $2::text as second', params, @@ -20,20 +20,20 @@ describe('async workflow', function () { ) } - var checkParams = function (params, rows) { + const checkParams = function (params, rows) { assert.equal(rows.length, 1) assert.equal(rows[0].first, params[0]) assert.equal(rows[0].second, params[1]) } it('sends async query', function (done) { - var params = ['one', 'two'] + const params = ['one', 'two'] echoParams.call(this, params, done) }) it('sends multiple async queries', function (done) { - var self = this - var params = ['bang', 'boom'] + const self = this + const params = ['bang', 'boom'] echoParams.call( this, params, @@ -44,13 +44,13 @@ describe('async workflow', function () { }) it('sends an async query, copies in, copies out, and sends another query', function (done) { - var self = this + const self = this this.client.querySync('CREATE TEMP TABLE test(name text, age int)') this.client.query( "INSERT INTO test(name, age) VALUES('brian', 32)", ok(done, function () { self.client.querySync('COPY test FROM stdin') - var input = self.client.getCopyStream() + const input = self.client.getCopyStream() input.write(Buffer.from('Aaron\t30\n', 'utf8')) input.end(function () { self.client.query( @@ -60,7 +60,7 @@ describe('async workflow', function () { self.client.query( 'COPY test TO stdout', ok(done, function () { - var output = self.client.getCopyStream() + const output = self.client.getCopyStream() // pump the stream output.read() diff --git a/packages/pg-native/test/cancel.js b/packages/pg-native/test/cancel.js index 80b1494df..8360c37f3 100644 --- a/packages/pg-native/test/cancel.js +++ b/packages/pg-native/test/cancel.js @@ -1,9 +1,9 @@ -var Client = require('../') -var assert = require('assert') +const Client = require('../') +const assert = require('assert') describe('cancel query', function () { it('works', function (done) { - var client = new Client() + const client = new Client() client.connectSync() client.query('SELECT pg_sleep(1000);', function (err) { assert(err instanceof Error) @@ -17,7 +17,7 @@ describe('cancel query', function () { }) it('does not raise error if no active query', function (done) { - var client = new Client() + const client = new Client() client.connectSync() client.cancel(function (err) { assert.ifError(err) diff --git a/packages/pg-native/test/connection-errors.js b/packages/pg-native/test/connection-errors.js index e02f2025b..ed836da2d 100644 --- a/packages/pg-native/test/connection-errors.js +++ b/packages/pg-native/test/connection-errors.js @@ -1,11 +1,11 @@ 'use strict' -var Client = require('../') -var assert = require('assert') +const Client = require('../') +const assert = require('assert') describe('connection errors', function () { it('raise error events', function (done) { - var client = new Client() + const client = new Client() client.connectSync() client.query('SELECT pg_terminate_backend(pg_backend_pid())', assert.fail) client.on('error', function (err) { diff --git a/packages/pg-native/test/connection.js b/packages/pg-native/test/connection.js index af81ffda9..0c7059ea4 100644 --- a/packages/pg-native/test/connection.js +++ b/packages/pg-native/test/connection.js @@ -1,9 +1,9 @@ -var Client = require('../') -var assert = require('assert') +const Client = require('../') +const assert = require('assert') describe('connection error', function () { it('doesnt segfault', function (done) { - var client = new Client() + const client = new Client() client.connect('asldgsdgasgdasdg', function (err) { assert(err) // calling error on a closed client was segfaulting @@ -15,7 +15,7 @@ describe('connection error', function () { describe('reading while not connected', function () { it('does not seg fault but does throw execption', function () { - var client = new Client() + const client = new Client() assert.throws(function () { client.on('notification', function (msg) {}) }) diff --git a/packages/pg-native/test/copy-from.js b/packages/pg-native/test/copy-from.js index 87501a957..37c64b7cd 100644 --- a/packages/pg-native/test/copy-from.js +++ b/packages/pg-native/test/copy-from.js @@ -1,5 +1,5 @@ -var assert = require('assert') -var Client = require('../') +const assert = require('assert') +const Client = require('../') describe('COPY FROM', function () { before(function (done) { @@ -12,17 +12,17 @@ describe('COPY FROM', function () { }) it('works', function (done) { - var client = this.client + const client = this.client this.client.querySync('CREATE TEMP TABLE blah(name text, age int)') this.client.querySync('COPY blah FROM stdin') - var stream = this.client.getCopyStream() + const stream = this.client.getCopyStream() stream.write(Buffer.from('Brian\t32\n', 'utf8')) stream.write(Buffer.from('Aaron\t30\n', 'utf8')) stream.write(Buffer.from('Shelley\t28\n', 'utf8')) stream.end() stream.once('finish', function () { - var rows = client.querySync('SELECT COUNT(*) FROM blah') + const rows = client.querySync('SELECT COUNT(*) FROM blah') assert.equal(rows.length, 1) assert.equal(rows[0].count, 3) done() @@ -30,14 +30,14 @@ describe('COPY FROM', function () { }) it('works with a callback passed to end', function (done) { - var client = this.client + const client = this.client this.client.querySync('CREATE TEMP TABLE boom(name text, age int)') this.client.querySync('COPY boom FROM stdin') - var stream = this.client.getCopyStream() + const stream = this.client.getCopyStream() stream.write(Buffer.from('Brian\t32\n', 'utf8')) stream.write(Buffer.from('Aaron\t30\n', 'utf8'), function () { stream.end(Buffer.from('Shelley\t28\n', 'utf8'), function () { - var rows = client.querySync('SELECT COUNT(*) FROM boom') + const rows = client.querySync('SELECT COUNT(*) FROM boom') assert.equal(rows.length, 1) assert.equal(rows[0].count, 3) done() diff --git a/packages/pg-native/test/copy-to.js b/packages/pg-native/test/copy-to.js index 28e062556..7322735db 100644 --- a/packages/pg-native/test/copy-to.js +++ b/packages/pg-native/test/copy-to.js @@ -1,7 +1,7 @@ -var assert = require('assert') -var Client = require('../') -var concat = require('concat-stream') -var _ = require('lodash') +const assert = require('assert') +const Client = require('../') +const concat = require('concat-stream') +const _ = require('lodash') describe('COPY TO', function () { before(function (done) { @@ -14,18 +14,18 @@ describe('COPY TO', function () { }) it('works - basic check', function (done) { - var limit = 1000 - var qText = 'COPY (SELECT * FROM generate_series(0, ' + (limit - 1) + ')) TO stdout' - var self = this + const limit = 1000 + const qText = 'COPY (SELECT * FROM generate_series(0, ' + (limit - 1) + ')) TO stdout' + const self = this this.client.query(qText, function (err) { if (err) return done(err) - var stream = self.client.getCopyStream() + const stream = self.client.getCopyStream() // pump the stream for node v0.11.x stream.read() stream.pipe( concat(function (buff) { - var res = buff.toString('utf8') - var expected = _.range(0, limit).join('\n') + '\n' + const res = buff.toString('utf8') + const expected = _.range(0, limit).join('\n') + '\n' assert.equal(res, expected) done() }) diff --git a/packages/pg-native/test/custom-types.js b/packages/pg-native/test/custom-types.js index 4930c85ae..329ff63af 100644 --- a/packages/pg-native/test/custom-types.js +++ b/packages/pg-native/test/custom-types.js @@ -1,10 +1,10 @@ -var Client = require('../') -var ok = require('okay') -var assert = require('assert') +const Client = require('../') +const ok = require('okay') +const assert = require('assert') describe('Custom type parser', function () { it('is used by client', function (done) { - var client = new Client({ + const client = new Client({ types: { getTypeParser: function () { return function () { @@ -14,7 +14,7 @@ describe('Custom type parser', function () { }, }) client.connectSync() - var rows = client.querySync('SELECT NOW() AS when') + const rows = client.querySync('SELECT NOW() AS when') assert.equal(rows[0].when, 'blah') client.query( 'SELECT NOW() as when', diff --git a/packages/pg-native/test/domains.js b/packages/pg-native/test/domains.js index 90ae4d58e..2deadab1f 100644 --- a/packages/pg-native/test/domains.js +++ b/packages/pg-native/test/domains.js @@ -1,7 +1,7 @@ -var Client = require('../') -var assert = require('assert') +const Client = require('../') +const assert = require('assert') -var checkDomain = function (domain, when) { +const checkDomain = function (domain, when) { assert(process.domain, 'Domain was lost after ' + when) assert.strictEqual(process.domain, domain, 'Domain switched after ' + when) } @@ -10,7 +10,7 @@ describe('domains', function () { it('remains bound after a query', function (done) { var domain = require('domain').create() // eslint-disable-line domain.run(function () { - var client = new Client() + const client = new Client() client.connect(function () { checkDomain(domain, 'connection') client.query('SELECT NOW()', function () { diff --git a/packages/pg-native/test/empty-query.js b/packages/pg-native/test/empty-query.js index d8ec5611f..aa3f05a0d 100644 --- a/packages/pg-native/test/empty-query.js +++ b/packages/pg-native/test/empty-query.js @@ -1,5 +1,5 @@ -var Client = require('../') -var assert = require('assert') +const Client = require('../') +const assert = require('assert') describe('empty query', () => { it('has field metadata in result', (done) => { diff --git a/packages/pg-native/test/huge-query.js b/packages/pg-native/test/huge-query.js index d3bf5cda2..838a23823 100644 --- a/packages/pg-native/test/huge-query.js +++ b/packages/pg-native/test/huge-query.js @@ -1,5 +1,5 @@ -var Client = require('../') -var assert = require('assert') +const Client = require('../') +const assert = require('assert') describe('huge async query', function () { before(function (done) { @@ -12,12 +12,12 @@ describe('huge async query', function () { }) it('works', function (done) { - var params = [''] - var len = 100000 - for (var i = 0; i < len; i++) { + const params = [''] + const len = 100000 + for (let i = 0; i < len; i++) { params[0] += 'A' } - var qText = "SELECT '" + params[0] + "'::text as my_text" + const qText = "SELECT '" + params[0] + "'::text as my_text" this.client.query(qText, function (err, rows) { if (err) return done(err) assert.equal(rows[0].my_text.length, len) diff --git a/packages/pg-native/test/index.js b/packages/pg-native/test/index.js index 1ef15b09f..6770fe143 100644 --- a/packages/pg-native/test/index.js +++ b/packages/pg-native/test/index.js @@ -1,5 +1,5 @@ -var Client = require('../') -var assert = require('assert') +const Client = require('../') +const assert = require('assert') describe('connection', function () { it('works', function (done) { @@ -24,7 +24,7 @@ describe('connectSync', function () { }) it('works with args', function () { - var args = 'host=' + (process.env.PGHOST || 'localhost') + const args = 'host=' + (process.env.PGHOST || 'localhost') Client().connectSync(args) }) diff --git a/packages/pg-native/test/load.js b/packages/pg-native/test/load.js index 039ea7d06..886be5d24 100644 --- a/packages/pg-native/test/load.js +++ b/packages/pg-native/test/load.js @@ -1,11 +1,11 @@ -var Client = require('../') -var async = require('async') -var ok = require('okay') +const Client = require('../') +const async = require('async') +const ok = require('okay') -var execute = function (x, done) { - var client = new Client() +const execute = function (x, done) { + const client = new Client() client.connectSync() - var query = function (n, cb) { + const query = function (n, cb) { client.query('SELECT $1::int as num', [n], function (err) { cb(err) }) diff --git a/packages/pg-native/test/many-connections.js b/packages/pg-native/test/many-connections.js index fe32ede16..b1ed9fd47 100644 --- a/packages/pg-native/test/many-connections.js +++ b/packages/pg-native/test/many-connections.js @@ -1,16 +1,16 @@ -var Client = require('../') -var async = require('async') -var ok = require('okay') -var bytes = require('crypto').pseudoRandomBytes +const Client = require('../') +const async = require('async') +const ok = require('okay') +const bytes = require('crypto').pseudoRandomBytes describe('many connections', function () { describe('async', function () { - var test = function (count, times) { + const test = function (count, times) { it(`connecting ${count} clients ${times} times`, function (done) { this.timeout(200000) - var connectClient = function (n, cb) { - var client = new Client() + const connectClient = function (n, cb) { + const client = new Client() client.connect( ok(cb, function () { bytes( @@ -29,7 +29,7 @@ describe('many connections', function () { ) } - var run = function (n, cb) { + const run = function (n, cb) { async.times(count, connectClient, cb) } diff --git a/packages/pg-native/test/many-errors.js b/packages/pg-native/test/many-errors.js index f8958f54b..243e6d491 100644 --- a/packages/pg-native/test/many-errors.js +++ b/packages/pg-native/test/many-errors.js @@ -1,14 +1,14 @@ -var Client = require('../') -var async = require('async') -var assert = require('assert') +const Client = require('../') +const async = require('async') +const assert = require('assert') describe('many errors', function () { it('functions properly without segfault', function (done) { - var throwError = function (n, cb) { - var client = new Client() + const throwError = function (n, cb) { + const client = new Client() client.connectSync() - var doIt = function (n, cb) { + const doIt = function (n, cb) { client.query('select asdfiasdf', function (err) { assert(err, 'bad query should emit an error') cb(null) diff --git a/packages/pg-native/test/multiple-queries.js b/packages/pg-native/test/multiple-queries.js index ea67defed..438215ff3 100644 --- a/packages/pg-native/test/multiple-queries.js +++ b/packages/pg-native/test/multiple-queries.js @@ -1,5 +1,5 @@ -var Client = require('../') -var assert = require('assert') +const Client = require('../') +const assert = require('assert') describe('multiple commands in a single query', function () { before(function (done) { @@ -22,7 +22,7 @@ describe('multiple commands in a single query', function () { }) it('inserts and reads at once', function (done) { - var txt = 'CREATE TEMP TABLE boom(age int);' + let txt = 'CREATE TEMP TABLE boom(age int);' txt += 'INSERT INTO boom(age) VALUES(10);' txt += 'SELECT * FROM boom;' this.client.query(txt, function (err, rows, results) { diff --git a/packages/pg-native/test/multiple-statement-results.js b/packages/pg-native/test/multiple-statement-results.js index ae0f9bafb..8c0a8574e 100644 --- a/packages/pg-native/test/multiple-statement-results.js +++ b/packages/pg-native/test/multiple-statement-results.js @@ -1,5 +1,5 @@ -var Client = require('../') -var assert = require('assert') +const Client = require('../') +const assert = require('assert') describe('multiple statements', () => { before(() => { diff --git a/packages/pg-native/test/notify.js b/packages/pg-native/test/notify.js index 769faf39a..6fe7a7072 100644 --- a/packages/pg-native/test/notify.js +++ b/packages/pg-native/test/notify.js @@ -1,8 +1,8 @@ -var Client = require('../') -var ok = require('okay') +const Client = require('../') +const ok = require('okay') -var notify = function (channel, payload) { - var client = new Client() +const notify = function (channel, payload) { + const client = new Client() client.connectSync() client.querySync('NOTIFY ' + channel + ", '" + payload + "'") client.end() @@ -10,12 +10,12 @@ var notify = function (channel, payload) { describe('simple LISTEN/NOTIFY', function () { before(function (done) { - var client = (this.client = new Client()) + const client = (this.client = new Client()) client.connect(done) }) it('works', function (done) { - var client = this.client + const client = this.client client.querySync('LISTEN boom') client.on('notification', function (msg) { done() @@ -31,14 +31,14 @@ describe('simple LISTEN/NOTIFY', function () { if (!process.env.TRAVIS_CI) { describe('async LISTEN/NOTIFY', function () { before(function (done) { - var client = (this.client = new Client()) + const client = (this.client = new Client()) client.connect(done) }) it('works', function (done) { - var client = this.client - var count = 0 - var check = function () { + const client = this.client + let count = 0 + const check = function () { count++ if (count >= 2) return done() } diff --git a/packages/pg-native/test/prepare.js b/packages/pg-native/test/prepare.js index bae3fb34c..60ec32045 100644 --- a/packages/pg-native/test/prepare.js +++ b/packages/pg-native/test/prepare.js @@ -1,13 +1,13 @@ -var Client = require('../') -var ok = require('okay') -var async = require('async') +const Client = require('../') +const ok = require('okay') +const async = require('async') describe('async prepare', function () { - var run = function (n, cb) { - var client = new Client() + const run = function (n, cb) { + const client = new Client() client.connectSync() - var exec = function (x, done) { + const exec = function (x, done) { client.prepare('get_now' + x, 'SELECT NOW()', 0, done) } @@ -20,7 +20,7 @@ describe('async prepare', function () { ) } - var t = function (n) { + const t = function (n) { it('works for ' + n + ' clients', function (done) { async.times(n, run, function (err) { done(err) @@ -28,17 +28,17 @@ describe('async prepare', function () { }) } - for (var i = 0; i < 10; i++) { + for (let i = 0; i < 10; i++) { t(i) } }) describe('async execute', function () { - var run = function (n, cb) { - var client = new Client() + const run = function (n, cb) { + const client = new Client() client.connectSync() client.prepareSync('get_now', 'SELECT NOW()', 0) - var exec = function (x, cb) { + const exec = function (x, cb) { client.execute('get_now', [], cb) } async.timesSeries( @@ -50,7 +50,7 @@ describe('async execute', function () { ) } - var t = function (n) { + const t = function (n) { it('works for ' + n + ' clients', function (done) { async.times(n, run, function (err) { done(err) @@ -58,7 +58,7 @@ describe('async execute', function () { }) } - for (var i = 0; i < 10; i++) { + for (let i = 0; i < 10; i++) { t(i) } }) diff --git a/packages/pg-native/test/query-async.js b/packages/pg-native/test/query-async.js index 9e2d05258..5e6cd17b2 100644 --- a/packages/pg-native/test/query-async.js +++ b/packages/pg-native/test/query-async.js @@ -1,7 +1,7 @@ -var Client = require('../') -var assert = require('assert') -var async = require('async') -var ok = require('okay') +const Client = require('../') +const assert = require('assert') +const async = require('async') +const ok = require('okay') describe('async query', function () { before(function (done) { @@ -24,7 +24,7 @@ describe('async query', function () { }) it('simple query works', function (done) { - var runQuery = function (n, done) { + const runQuery = function (n, done) { this.client.query('SELECT NOW() AS the_time', function (err, rows) { if (err) return done(err) assert.equal(rows[0].the_time.getFullYear(), new Date().getFullYear()) @@ -35,14 +35,14 @@ describe('async query', function () { }) it('parameters work', function (done) { - var runQuery = function (n, done) { + const runQuery = function (n, done) { this.client.query('SELECT $1::text AS name', ['Brian'], done) }.bind(this) async.timesSeries(3, runQuery, done) }) it('prepared, named statements work', function (done) { - var client = this.client + const client = this.client client.prepare('test', 'SELECT $1::text as name', 1, function (err) { if (err) return done(err) client.execute( @@ -80,7 +80,7 @@ describe('async query', function () { }) it('returns an error if there was a query error', function (done) { - var runErrorQuery = function (n, done) { + const runErrorQuery = function (n, done) { this.client.query('SELECT ALKJSFDSLFKJ', function (err) { assert(err instanceof Error, 'Should return an error instance') done() diff --git a/packages/pg-native/test/query-sync.js b/packages/pg-native/test/query-sync.js index 7bd86d8c6..baf4e15ec 100644 --- a/packages/pg-native/test/query-sync.js +++ b/packages/pg-native/test/query-sync.js @@ -1,5 +1,5 @@ -var Client = require('../') -var assert = require('assert') +const Client = require('../') +const assert = require('assert') describe('query sync', function () { before(function () { @@ -12,13 +12,13 @@ describe('query sync', function () { }) it('simple query works', function () { - var rows = this.client.querySync('SELECT NOW() AS the_time') + const rows = this.client.querySync('SELECT NOW() AS the_time') assert.equal(rows.length, 1) assert.equal(rows[0].the_time.getFullYear(), new Date().getFullYear()) }) it('parameterized query works', function () { - var rows = this.client.querySync('SELECT $1::text AS name', ['Brian']) + const rows = this.client.querySync('SELECT $1::text AS name', ['Brian']) assert.equal(rows.length, 1) assert.equal(rows[0].name, 'Brian') }) @@ -37,11 +37,11 @@ describe('query sync', function () { it('prepared statement works', function () { this.client.prepareSync('test', 'SELECT $1::text as name', 1) - var rows = this.client.executeSync('test', ['Brian']) + const rows = this.client.executeSync('test', ['Brian']) assert.equal(rows.length, 1) assert.equal(rows[0].name, 'Brian') - var rows2 = this.client.executeSync('test', ['Aaron']) + const rows2 = this.client.executeSync('test', ['Aaron']) assert.equal(rows2.length, 1) assert.equal(rows2[0].name, 'Aaron') }) @@ -70,13 +70,13 @@ describe('query sync', function () { }) it('is still usable after an error', function () { - var rows = this.client.querySync('SELECT NOW()') + const rows = this.client.querySync('SELECT NOW()') assert(rows, 'should have returned rows') assert.equal(rows.length, 1) }) it('supports empty query', function () { - var rows = this.client.querySync('') + const rows = this.client.querySync('') assert(rows, 'should return rows') assert.equal(rows.length, 0, 'should return no rows') }) diff --git a/packages/pg-native/test/version.js b/packages/pg-native/test/version.js index 204d83682..f8e4d2b29 100644 --- a/packages/pg-native/test/version.js +++ b/packages/pg-native/test/version.js @@ -1,6 +1,6 @@ -var Client = require('../') -var assert = require('assert') -var semver = require('semver') +const Client = require('../') +const assert = require('assert') +const semver = require('semver') describe('version', function () { it('is exported', function () { diff --git a/packages/pg-pool/test/connection-timeout.js b/packages/pg-pool/test/connection-timeout.js index 05e8931df..cb83f7006 100644 --- a/packages/pg-pool/test/connection-timeout.js +++ b/packages/pg-pool/test/connection-timeout.js @@ -57,7 +57,7 @@ describe('connection timeout', () => { function* () { const errors = [] const pool = new Pool({ connectionTimeoutMillis: 1, port: this.port, host: 'localhost' }) - for (var i = 0; i < 15; i++) { + for (let i = 0; i < 15; i++) { try { yield pool.connect() } catch (e) { diff --git a/packages/pg-pool/test/error-handling.js b/packages/pg-pool/test/error-handling.js index 7b1570859..60354325c 100644 --- a/packages/pg-pool/test/error-handling.js +++ b/packages/pg-pool/test/error-handling.js @@ -198,7 +198,7 @@ describe('pool error handling', function () { co.wrap(function* () { const pool = new Pool({ max: 1 }) const errors = [] - for (var i = 0; i < 20; i++) { + for (let i = 0; i < 20; i++) { try { yield pool.query('invalid sql') } catch (err) { diff --git a/packages/pg-pool/test/idle-timeout.js b/packages/pg-pool/test/idle-timeout.js index 0bb097565..c1dee48f6 100644 --- a/packages/pg-pool/test/idle-timeout.js +++ b/packages/pg-pool/test/idle-timeout.js @@ -54,8 +54,8 @@ describe('idle timeout', () => { co.wrap(function* () { const pool = new Pool({ idleTimeoutMillis: 1 }) const results = [] - for (var i = 0; i < 20; i++) { - let query = pool.query('SELECT NOW()') + for (let i = 0; i < 20; i++) { + const query = pool.query('SELECT NOW()') expect(pool.idleCount).to.equal(0) expect(pool.totalCount).to.equal(1) results.push(yield query) @@ -72,8 +72,8 @@ describe('idle timeout', () => { co.wrap(function* () { const pool = new Pool({ idleTimeoutMillis: 1 }) const results = [] - for (var i = 0; i < 20; i++) { - let client = yield pool.connect() + for (let i = 0; i < 20; i++) { + const client = yield pool.connect() expect(pool.totalCount).to.equal(1) expect(pool.idleCount).to.equal(0) yield wait(10) diff --git a/packages/pg-pool/test/lifetime-timeout.js b/packages/pg-pool/test/lifetime-timeout.js index 4eac10778..0cdd8c886 100644 --- a/packages/pg-pool/test/lifetime-timeout.js +++ b/packages/pg-pool/test/lifetime-timeout.js @@ -32,7 +32,7 @@ describe('lifetime timeout', () => { 'can remove expired clients and recreate them', co.wrap(function* () { const pool = new Pool({ maxLifetimeSeconds: 1 }) - let query = pool.query('SELECT pg_sleep(1.4)') + const query = pool.query('SELECT pg_sleep(1.4)') expect(pool.expiredCount).to.equal(0) expect(pool.totalCount).to.equal(1) yield query diff --git a/packages/pg-protocol/src/b.ts b/packages/pg-protocol/src/b.ts index 088ca1857..8357623a5 100644 --- a/packages/pg-protocol/src/b.ts +++ b/packages/pg-protocol/src/b.ts @@ -4,7 +4,7 @@ import { BufferReader } from './buffer-reader' const LOOPS = 1000 let count = 0 -let start = Date.now() +const start = Date.now() const reader = new BufferReader() const buffer = Buffer.from([33, 33, 33, 33, 33, 33, 33, 0]) diff --git a/packages/pg-protocol/src/buffer-writer.ts b/packages/pg-protocol/src/buffer-writer.ts index 756cdc9f3..cebb0d9ed 100644 --- a/packages/pg-protocol/src/buffer-writer.ts +++ b/packages/pg-protocol/src/buffer-writer.ts @@ -9,12 +9,12 @@ export class Writer { } private ensure(size: number): void { - var remaining = this.buffer.length - this.offset + const remaining = this.buffer.length - this.offset if (remaining < size) { - var oldBuffer = this.buffer + const oldBuffer = this.buffer // exponential growth factor of around ~ 1.5 // https://stackoverflow.com/questions/2269063/buffer-growth-strategy - var newSize = oldBuffer.length + (oldBuffer.length >> 1) + size + const newSize = oldBuffer.length + (oldBuffer.length >> 1) + size this.buffer = Buffer.allocUnsafe(newSize) oldBuffer.copy(this.buffer) } @@ -40,7 +40,7 @@ export class Writer { if (!string) { this.ensure(1) } else { - var len = Buffer.byteLength(string) + const len = Buffer.byteLength(string) this.ensure(len + 1) // +1 for null terminator this.buffer.write(string, this.offset, 'utf-8') this.offset += len @@ -51,7 +51,7 @@ export class Writer { } public addString(string: string = ''): Writer { - var len = Buffer.byteLength(string) + const len = Buffer.byteLength(string) this.ensure(len) this.buffer.write(string, this.offset) this.offset += len @@ -76,7 +76,7 @@ export class Writer { } public flush(code?: number): Buffer { - var result = this.join(code) + const result = this.join(code) this.offset = 5 this.headerPosition = 0 this.buffer = Buffer.allocUnsafe(this.size) diff --git a/packages/pg-protocol/src/inbound-parser.test.ts b/packages/pg-protocol/src/inbound-parser.test.ts index adf5aac66..6f576cbfb 100644 --- a/packages/pg-protocol/src/inbound-parser.test.ts +++ b/packages/pg-protocol/src/inbound-parser.test.ts @@ -5,16 +5,16 @@ import assert from 'assert' import { PassThrough } from 'stream' import { BackendMessage } from './messages' -var authOkBuffer = buffers.authenticationOk() -var paramStatusBuffer = buffers.parameterStatus('client_encoding', 'UTF8') -var readyForQueryBuffer = buffers.readyForQuery() -var backendKeyDataBuffer = buffers.backendKeyData(1, 2) -var commandCompleteBuffer = buffers.commandComplete('SELECT 3') -var parseCompleteBuffer = buffers.parseComplete() -var bindCompleteBuffer = buffers.bindComplete() -var portalSuspendedBuffer = buffers.portalSuspended() - -var row1 = { +const authOkBuffer = buffers.authenticationOk() +const paramStatusBuffer = buffers.parameterStatus('client_encoding', 'UTF8') +const readyForQueryBuffer = buffers.readyForQuery() +const backendKeyDataBuffer = buffers.backendKeyData(1, 2) +const commandCompleteBuffer = buffers.commandComplete('SELECT 3') +const parseCompleteBuffer = buffers.parseComplete() +const bindCompleteBuffer = buffers.bindComplete() +const portalSuspendedBuffer = buffers.portalSuspended() + +const row1 = { name: 'id', tableID: 1, attributeNumber: 2, @@ -23,10 +23,10 @@ var row1 = { typeModifier: 5, formatCode: 0, } -var oneRowDescBuff = buffers.rowDescription([row1]) +const oneRowDescBuff = buffers.rowDescription([row1]) row1.name = 'bang' -var twoRowBuf = buffers.rowDescription([ +const twoRowBuf = buffers.rowDescription([ row1, { name: 'whoah', @@ -39,7 +39,7 @@ var twoRowBuf = buffers.rowDescription([ }, ]) -var rowWithBigOids = { +const rowWithBigOids = { name: 'bigoid', tableID: 3000000001, attributeNumber: 2, @@ -48,60 +48,60 @@ var rowWithBigOids = { typeModifier: 5, formatCode: 0, } -var bigOidDescBuff = buffers.rowDescription([rowWithBigOids]) +const bigOidDescBuff = buffers.rowDescription([rowWithBigOids]) -var emptyRowFieldBuf = new BufferList().addInt16(0).join(true, 'D') +let emptyRowFieldBuf = new BufferList().addInt16(0).join(true, 'D') -var emptyRowFieldBuf = buffers.dataRow([]) +emptyRowFieldBuf = buffers.dataRow([]) -var oneFieldBuf = new BufferList() +let oneFieldBuf = new BufferList() .addInt16(1) // number of fields .addInt32(5) // length of bytes of fields .addCString('test') .join(true, 'D') -var oneFieldBuf = buffers.dataRow(['test']) +oneFieldBuf = buffers.dataRow(['test']) -var expectedAuthenticationOkayMessage = { +const expectedAuthenticationOkayMessage = { name: 'authenticationOk', length: 8, } -var expectedParameterStatusMessage = { +const expectedParameterStatusMessage = { name: 'parameterStatus', parameterName: 'client_encoding', parameterValue: 'UTF8', length: 25, } -var expectedBackendKeyDataMessage = { +const expectedBackendKeyDataMessage = { name: 'backendKeyData', processID: 1, secretKey: 2, } -var expectedReadyForQueryMessage = { +const expectedReadyForQueryMessage = { name: 'readyForQuery', length: 5, status: 'I', } -var expectedCommandCompleteMessage = { +const expectedCommandCompleteMessage = { name: 'commandComplete', length: 13, text: 'SELECT 3', } -var emptyRowDescriptionBuffer = new BufferList() +const emptyRowDescriptionBuffer = new BufferList() .addInt16(0) // number of fields .join(true, 'T') -var expectedEmptyRowDescriptionMessage = { +const expectedEmptyRowDescriptionMessage = { name: 'rowDescription', length: 6, fieldCount: 0, fields: [], } -var expectedOneRowMessage = { +const expectedOneRowMessage = { name: 'rowDescription', length: 27, fieldCount: 1, @@ -118,7 +118,7 @@ var expectedOneRowMessage = { ], } -var expectedTwoRowMessage = { +const expectedTwoRowMessage = { name: 'rowDescription', length: 53, fieldCount: 2, @@ -143,7 +143,7 @@ var expectedTwoRowMessage = { }, ], } -var expectedBigOidMessage = { +const expectedBigOidMessage = { name: 'rowDescription', length: 31, fieldCount: 1, @@ -160,36 +160,36 @@ var expectedBigOidMessage = { ], } -var emptyParameterDescriptionBuffer = new BufferList() +const emptyParameterDescriptionBuffer = new BufferList() .addInt16(0) // number of parameters .join(true, 't') -var oneParameterDescBuf = buffers.parameterDescription([1111]) +const oneParameterDescBuf = buffers.parameterDescription([1111]) -var twoParameterDescBuf = buffers.parameterDescription([2222, 3333]) +const twoParameterDescBuf = buffers.parameterDescription([2222, 3333]) -var expectedEmptyParameterDescriptionMessage = { +const expectedEmptyParameterDescriptionMessage = { name: 'parameterDescription', length: 6, parameterCount: 0, dataTypeIDs: [], } -var expectedOneParameterMessage = { +const expectedOneParameterMessage = { name: 'parameterDescription', length: 10, parameterCount: 1, dataTypeIDs: [1111], } -var expectedTwoParameterMessage = { +const expectedTwoParameterMessage = { name: 'parameterDescription', length: 14, parameterCount: 2, dataTypeIDs: [2222, 3333], } -var testForMessage = function (buffer: Buffer, expectedMessage: any) { +const testForMessage = function (buffer: Buffer, expectedMessage: any) { it('recieves and parses ' + expectedMessage.name, async () => { const messages = await parseBuffers([buffer]) const [lastMessage] = messages @@ -200,38 +200,38 @@ var testForMessage = function (buffer: Buffer, expectedMessage: any) { }) } -var plainPasswordBuffer = buffers.authenticationCleartextPassword() -var md5PasswordBuffer = buffers.authenticationMD5Password() -var SASLBuffer = buffers.authenticationSASL() -var SASLContinueBuffer = buffers.authenticationSASLContinue() -var SASLFinalBuffer = buffers.authenticationSASLFinal() +const plainPasswordBuffer = buffers.authenticationCleartextPassword() +const md5PasswordBuffer = buffers.authenticationMD5Password() +const SASLBuffer = buffers.authenticationSASL() +const SASLContinueBuffer = buffers.authenticationSASLContinue() +const SASLFinalBuffer = buffers.authenticationSASLFinal() -var expectedPlainPasswordMessage = { +const expectedPlainPasswordMessage = { name: 'authenticationCleartextPassword', } -var expectedMD5PasswordMessage = { +const expectedMD5PasswordMessage = { name: 'authenticationMD5Password', salt: Buffer.from([1, 2, 3, 4]), } -var expectedSASLMessage = { +const expectedSASLMessage = { name: 'authenticationSASL', mechanisms: ['SCRAM-SHA-256'], } -var expectedSASLContinueMessage = { +const expectedSASLContinueMessage = { name: 'authenticationSASLContinue', data: 'data', } -var expectedSASLFinalMessage = { +const expectedSASLFinalMessage = { name: 'authenticationSASLFinal', data: 'data', } -var notificationResponseBuffer = buffers.notification(4, 'hi', 'boom') -var expectedNotificationResponseMessage = { +const notificationResponseBuffer = buffers.notification(4, 'hi', 'boom') +const expectedNotificationResponseMessage = { name: 'notification', processId: 4, channel: 'hi', @@ -316,7 +316,7 @@ describe('PgPacketStream', function () { describe('notice message', function () { // this uses the same logic as error message - var buff = buffers.notice([{ type: 'C', value: 'code' }]) + const buff = buffers.notice([{ type: 'C', value: 'code' }]) testForMessage(buff, { name: 'notice', code: 'code', @@ -328,7 +328,7 @@ describe('PgPacketStream', function () { }) describe('with all the fields', function () { - var buffer = buffers.error([ + const buffer = buffers.error([ { type: 'S', value: 'ERROR', @@ -474,7 +474,7 @@ describe('PgPacketStream', function () { // 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 () { - var fullBuffer = buffers.dataRow([null, 'bang', 'zug zug', null, '!']) + const fullBuffer = buffers.dataRow([null, 'bang', 'zug zug', null, '!']) it('parses when full buffer comes in', async function () { const messages = await parseBuffers([fullBuffer]) @@ -487,9 +487,9 @@ describe('PgPacketStream', function () { assert.equal(message.fields[4], '!') }) - var testMessageRecievedAfterSpiltAt = async function (split: number) { - var firstBuffer = Buffer.alloc(fullBuffer.length - split) - var secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length) + const testMessageRecievedAfterSpiltAt = async function (split: number) { + const firstBuffer = Buffer.alloc(fullBuffer.length - split) + const secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length) fullBuffer.copy(firstBuffer, 0, 0) fullBuffer.copy(secondBuffer, 0, firstBuffer.length) const messages = await parseBuffers([fullBuffer]) @@ -518,13 +518,13 @@ describe('PgPacketStream', function () { }) describe('split buffer, multiple message parsing', function () { - var dataRowBuffer = buffers.dataRow(['!']) - var readyForQueryBuffer = buffers.readyForQuery() - var fullBuffer = Buffer.alloc(dataRowBuffer.length + readyForQueryBuffer.length) + const dataRowBuffer = buffers.dataRow(['!']) + const readyForQueryBuffer = buffers.readyForQuery() + const fullBuffer = Buffer.alloc(dataRowBuffer.length + readyForQueryBuffer.length) dataRowBuffer.copy(fullBuffer, 0, 0) readyForQueryBuffer.copy(fullBuffer, dataRowBuffer.length, 0) - var verifyMessages = function (messages: any[]) { + const verifyMessages = function (messages: any[]) { assert.strictEqual(messages.length, 2) assert.deepEqual(messages[0], { name: 'dataRow', @@ -545,9 +545,9 @@ describe('PgPacketStream', function () { verifyMessages(messages) }) - var splitAndVerifyTwoMessages = async function (split: number) { - var firstBuffer = Buffer.alloc(fullBuffer.length - split) - var secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length) + const splitAndVerifyTwoMessages = async function (split: number) { + const firstBuffer = Buffer.alloc(fullBuffer.length - split) + const secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length) fullBuffer.copy(firstBuffer, 0, 0) fullBuffer.copy(secondBuffer, 0, firstBuffer.length) const messages = await parseBuffers([firstBuffer, secondBuffer]) diff --git a/packages/pg-protocol/src/outbound-serializer.test.ts b/packages/pg-protocol/src/outbound-serializer.test.ts index f6669becd..48dc25b20 100644 --- a/packages/pg-protocol/src/outbound-serializer.test.ts +++ b/packages/pg-protocol/src/outbound-serializer.test.ts @@ -46,7 +46,7 @@ describe('serializer', () => { }) it('builds query message', function () { - var txt = 'select * from boom' + const txt = 'select * from boom' const actual = serialize.query(txt) assert.deepEqual(actual, new BufferList().addCString(txt).join(true, 'Q')) }) @@ -54,7 +54,7 @@ describe('serializer', () => { describe('parse message', () => { it('builds parse message', function () { const actual = serialize.parse({ text: '!' }) - var expected = new BufferList().addCString('').addCString('!').addInt16(0).join(true, 'P') + const expected = new BufferList().addCString('').addCString('!').addInt16(0).join(true, 'P') assert.deepEqual(actual, expected) }) @@ -64,7 +64,7 @@ describe('serializer', () => { text: 'select * from boom', types: [], }) - var expected = new BufferList().addCString('boom').addCString('select * from boom').addInt16(0).join(true, 'P') + const expected = new BufferList().addCString('boom').addCString('select * from boom').addInt16(0).join(true, 'P') assert.deepEqual(actual, expected) }) @@ -74,7 +74,7 @@ describe('serializer', () => { text: 'select * from bang where name = $1', types: [1, 2, 3, 4], }) - var expected = new BufferList() + const expected = new BufferList() .addCString('force') .addCString('select * from bang where name = $1') .addInt16(4) @@ -91,7 +91,7 @@ describe('serializer', () => { it('with no values', function () { const actual = serialize.bind() - var expectedBuffer = new BufferList() + const expectedBuffer = new BufferList() .addCString('') .addCString('') .addInt16(0) @@ -107,7 +107,7 @@ describe('serializer', () => { statement: 'woo', values: ['1', 'hi', null, 'zing'], }) - var expectedBuffer = new BufferList() + const expectedBuffer = new BufferList() .addCString('bang') // portal name .addCString('woo') // statement name .addInt16(4) @@ -136,7 +136,7 @@ describe('serializer', () => { values: ['1', 'hi', null, 'zing'], valueMapper: () => null, }) - var expectedBuffer = new BufferList() + const expectedBuffer = new BufferList() .addCString('bang') // portal name .addCString('woo') // statement name .addInt16(4) @@ -160,7 +160,7 @@ describe('serializer', () => { statement: 'woo', values: ['1', 'hi', null, Buffer.from('zing', 'utf8')], }) - var expectedBuffer = new BufferList() + const expectedBuffer = new BufferList() .addCString('bang') // portal name .addCString('woo') // statement name .addInt16(4) // value count @@ -184,7 +184,7 @@ describe('serializer', () => { 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') + const expectedBuffer = new BufferList().addCString('').addInt32(0).join(true, 'E') assert.deepEqual(actual, expectedBuffer) }) @@ -193,39 +193,39 @@ describe('serializer', () => { portal: 'my favorite portal', rows: 100, }) - var expectedBuffer = new BufferList().addCString('my favorite portal').addInt32(100).join(true, 'E') + const expectedBuffer = new BufferList().addCString('my favorite portal').addInt32(100).join(true, 'E') assert.deepEqual(actual, expectedBuffer) }) }) it('builds flush command', function () { const actual = serialize.flush() - var expected = new BufferList().join(true, 'H') + const expected = new BufferList().join(true, 'H') assert.deepEqual(actual, expected) }) it('builds sync command', function () { const actual = serialize.sync() - var expected = new BufferList().join(true, 'S') + const expected = new BufferList().join(true, 'S') assert.deepEqual(actual, expected) }) it('builds end command', function () { const actual = serialize.end() - var expected = Buffer.from([0x58, 0, 0, 0, 4]) + const expected = Buffer.from([0x58, 0, 0, 0, 4]) assert.deepEqual(actual, expected) }) 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') + const expected = new BufferList().addChar('S').addCString('bang').join(true, 'D') assert.deepEqual(actual, expected) }) it('describe unnamed portal', function () { const actual = serialize.describe({ type: 'P' }) - var expected = new BufferList().addChar('P').addCString('').join(true, 'D') + const expected = new BufferList().addChar('P').addCString('').join(true, 'D') assert.deepEqual(actual, expected) }) }) @@ -233,13 +233,13 @@ describe('serializer', () => { 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') + const expected = new BufferList().addChar('S').addCString('bang').join(true, 'C') assert.deepEqual(actual, expected) }) it('describe unnamed portal', function () { const actual = serialize.close({ type: 'P' }) - var expected = new BufferList().addChar('P').addCString('').join(true, 'C') + const expected = new BufferList().addChar('P').addCString('').join(true, 'C') assert.deepEqual(actual, expected) }) }) diff --git a/packages/pg-protocol/src/serializer.ts b/packages/pg-protocol/src/serializer.ts index 07e2fe498..fb1dd89db 100644 --- a/packages/pg-protocol/src/serializer.ts +++ b/packages/pg-protocol/src/serializer.ts @@ -27,10 +27,10 @@ const startup = (opts: Record): Buffer => { writer.addCString('client_encoding').addCString('UTF8') - var bodyBuffer = writer.addCString('').flush() + const bodyBuffer = writer.addCString('').flush() // this message is sent without a code - var length = bodyBuffer.length + 4 + const length = bodyBuffer.length + 4 return new Writer().addInt32(length).add(bodyBuffer).flush() } @@ -87,14 +87,14 @@ const parse = (query: ParseOpts): Buffer => { const types = query.types || emptyArray - var len = types.length + const len = types.length - var buffer = writer + const buffer = writer .addCString(name) // name of query .addCString(query.text) // actual query text .addInt16(len) - for (var i = 0; i < len; i++) { + for (let i = 0; i < len; i++) { buffer.addInt32(types[i]) } diff --git a/packages/pg-protocol/src/testing/buffer-list.ts b/packages/pg-protocol/src/testing/buffer-list.ts index 15ac785cc..4888b8577 100644 --- a/packages/pg-protocol/src/testing/buffer-list.ts +++ b/packages/pg-protocol/src/testing/buffer-list.ts @@ -24,16 +24,16 @@ export default class BufferList { } public addCString(val: string, front?: boolean) { - var len = Buffer.byteLength(val) - var buffer = Buffer.alloc(len + 1) + const len = Buffer.byteLength(val) + const buffer = Buffer.alloc(len + 1) buffer.write(val) buffer[len] = 0 return this.add(buffer, front) } public addString(val: string, front?: boolean) { - var len = Buffer.byteLength(val) - var buffer = Buffer.alloc(len) + const len = Buffer.byteLength(val) + const buffer = Buffer.alloc(len) buffer.write(val) return this.add(buffer, front) } @@ -47,7 +47,7 @@ export default class BufferList { } public join(appendLength?: boolean, char?: string): Buffer { - var length = this.getByteLength() + let length = this.getByteLength() if (appendLength) { this.addInt32(length + 4, true) return this.join(false, char) @@ -56,8 +56,8 @@ export default class BufferList { this.addChar(char, true) length++ } - var result = Buffer.alloc(length) - var index = 0 + const result = Buffer.alloc(length) + let index = 0 this.buffers.forEach(function (buffer) { buffer.copy(result, index, 0) index += buffer.length @@ -66,8 +66,8 @@ export default class BufferList { } public static concat(): Buffer { - var total = new BufferList() - for (var i = 0; i < arguments.length; i++) { + const total = new BufferList() + for (let i = 0; i < arguments.length; i++) { total.add(arguments[i]) } return total.join() diff --git a/packages/pg-protocol/src/testing/test-buffers.ts b/packages/pg-protocol/src/testing/test-buffers.ts index a4d49f322..1f0d71f2d 100644 --- a/packages/pg-protocol/src/testing/test-buffers.ts +++ b/packages/pg-protocol/src/testing/test-buffers.ts @@ -47,7 +47,7 @@ const buffers = { rowDescription: function (fields: any[]) { fields = fields || [] - var buf = new BufferList() + const buf = new BufferList() buf.addInt16(fields.length) fields.forEach(function (field) { buf @@ -64,7 +64,7 @@ const buffers = { parameterDescription: function (dataTypeIDs: number[]) { dataTypeIDs = dataTypeIDs || [] - var buf = new BufferList() + const buf = new BufferList() buf.addInt16(dataTypeIDs.length) dataTypeIDs.forEach(function (dataTypeID) { buf.addInt32(dataTypeID) @@ -74,13 +74,13 @@ const buffers = { dataRow: function (columns: any[]) { columns = columns || [] - var buf = new BufferList() + const buf = new BufferList() buf.addInt16(columns.length) columns.forEach(function (col) { if (col == null) { buf.addInt32(-1) } else { - var strBuf = Buffer.from(col, 'utf8') + const strBuf = Buffer.from(col, 'utf8') buf.addInt32(strBuf.length) buf.add(strBuf) } @@ -98,7 +98,7 @@ const buffers = { errorOrNotice: function (fields: any) { fields = fields || [] - var buf = new BufferList() + const buf = new BufferList() fields.forEach(function (field: any) { buf.addChar(field.type) buf.addCString(field.value) diff --git a/packages/pg/bench.js b/packages/pg/bench.js index 223b10278..32b370a4c 100644 --- a/packages/pg/bench.js +++ b/packages/pg/bench.js @@ -23,7 +23,7 @@ const exec = async (client, q) => { } const bench = async (client, q, time) => { - let start = Date.now() + const start = Date.now() let count = 0 while (true) { await exec(client, q) diff --git a/packages/pg/lib/client.js b/packages/pg/lib/client.js index 527f62e4f..c26137841 100644 --- a/packages/pg/lib/client.js +++ b/packages/pg/lib/client.js @@ -1,14 +1,14 @@ 'use strict' -var EventEmitter = require('events').EventEmitter -var utils = require('./utils') -var sasl = require('./crypto/sasl') -var TypeOverrides = require('./type-overrides') - -var ConnectionParameters = require('./connection-parameters') -var Query = require('./query') -var defaults = require('./defaults') -var Connection = require('./connection') +const EventEmitter = require('events').EventEmitter +const utils = require('./utils') +const sasl = require('./crypto/sasl') +const TypeOverrides = require('./type-overrides') + +const ConnectionParameters = require('./connection-parameters') +const Query = require('./query') +const defaults = require('./defaults') +const Connection = require('./connection') const crypto = require('./crypto/utils') class Client extends EventEmitter { @@ -32,7 +32,7 @@ class Client extends EventEmitter { this.replication = this.connectionParameters.replication - var c = config || {} + const c = config || {} this._Promise = c.Promise || global.Promise this._types = new TypeOverrides(c.types) @@ -86,8 +86,8 @@ class Client extends EventEmitter { } _connect(callback) { - var self = this - var con = this.connection + const self = this + const con = this.connection this._connectionCallback = callback if (this._connecting || this._connected) { @@ -417,14 +417,14 @@ class Client extends EventEmitter { } getStartupConf() { - var params = this.connectionParameters + const params = this.connectionParameters - var data = { + const data = { user: params.user, database: params.database, } - var appName = params.application_name || params.fallback_application_name + const appName = params.application_name || params.fallback_application_name if (appName) { data.application_name = appName } @@ -449,7 +449,7 @@ class Client extends EventEmitter { cancel(client, query) { if (client.activeQuery === query) { - var con = this.connection + const con = this.connection if (this.host && this.host.indexOf('/') === 0) { con.connect(this.host + '/.s.PGSQL.' + this.port) @@ -509,11 +509,11 @@ class Client extends EventEmitter { query(config, values, callback) { // can take in strings, config object or query object - var query - var result - var readTimeout - var readTimeoutTimer - var queryCallback + let query + let result + let readTimeout + let readTimeoutTimer + let queryCallback if (config === null || config === undefined) { throw new TypeError('Client was passed a null or undefined query') @@ -542,7 +542,7 @@ class Client extends EventEmitter { queryCallback = query.callback readTimeoutTimer = setTimeout(() => { - var error = new Error('Query read timeout') + const error = new Error('Query read timeout') process.nextTick(() => { query.handleError(error, this.connection) @@ -555,7 +555,7 @@ class Client extends EventEmitter { query.callback = () => {} // Remove from queue - var index = this.queryQueue.indexOf(query) + const index = this.queryQueue.indexOf(query) if (index > -1) { this.queryQueue.splice(index, 1) } diff --git a/packages/pg/lib/connection-parameters.js b/packages/pg/lib/connection-parameters.js index 6a535a820..a7b941c10 100644 --- a/packages/pg/lib/connection-parameters.js +++ b/packages/pg/lib/connection-parameters.js @@ -1,12 +1,12 @@ 'use strict' -var dns = require('dns') +const dns = require('dns') -var defaults = require('./defaults') +const defaults = require('./defaults') -var parse = require('pg-connection-string').parse // parses a connection string +const parse = require('pg-connection-string').parse // parses a connection string -var val = function (key, config, envVar) { +const val = function (key, config, envVar) { if (envVar === undefined) { envVar = process.env['PG' + key.toUpperCase()] } else if (envVar === false) { @@ -18,7 +18,7 @@ var val = function (key, config, envVar) { return config[key] || envVar || defaults[key] } -var readSSLConfigFromEnvironment = function () { +const readSSLConfigFromEnvironment = function () { switch (process.env.PGSSLMODE) { case 'disable': return false @@ -34,12 +34,12 @@ var readSSLConfigFromEnvironment = function () { } // Convert arg to a string, surround in single quotes, and escape single quotes and backslashes -var quoteParamValue = function (value) { +const quoteParamValue = function (value) { return "'" + ('' + value).replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'" } -var add = function (params, config, paramName) { - var value = config[paramName] +const add = function (params, config, paramName) { + const value = config[paramName] if (value !== undefined && value !== null) { params.push(paramName + '=' + quoteParamValue(value)) } @@ -125,7 +125,7 @@ class ConnectionParameters { } getLibpqConnectionString(cb) { - var params = [] + const params = [] add(params, this, 'user') add(params, this, 'password') add(params, this, 'port') @@ -134,7 +134,7 @@ class ConnectionParameters { add(params, this, 'connect_timeout') add(params, this, 'options') - var ssl = typeof this.ssl === 'object' ? this.ssl : this.ssl ? { sslmode: this.ssl } : {} + const ssl = typeof this.ssl === 'object' ? this.ssl : this.ssl ? { sslmode: this.ssl } : {} add(params, ssl, 'sslmode') add(params, ssl, 'sslca') add(params, ssl, 'sslkey') diff --git a/packages/pg/lib/connection.js b/packages/pg/lib/connection.js index c426b152c..8045af858 100644 --- a/packages/pg/lib/connection.js +++ b/packages/pg/lib/connection.js @@ -1,6 +1,6 @@ 'use strict' -var EventEmitter = require('events').EventEmitter +const EventEmitter = require('events').EventEmitter const { parse, serialize } = require('pg-protocol') const { getStream, getSecureStream } = require('./stream') @@ -27,7 +27,7 @@ class Connection extends EventEmitter { this.ssl = config.ssl || false this._ending = false this._emitMessage = false - var self = this + const self = this this.on('newListener', function (eventName) { if (eventName === 'message') { self._emitMessage = true @@ -36,7 +36,7 @@ class Connection extends EventEmitter { } connect(port, host) { - var self = this + const self = this this._connecting = true this.stream.setNoDelay(true) @@ -67,7 +67,7 @@ class Connection extends EventEmitter { } this.stream.once('data', function (buffer) { - var responseCode = buffer.toString('utf8') + const responseCode = buffer.toString('utf8') switch (responseCode) { case 'S': // Server supports SSL connections, continue with a secure connection break @@ -91,7 +91,7 @@ class Connection extends EventEmitter { } } - var net = require('net') + const net = require('net') if (net.isIP && net.isIP(host) === 0) { options.servername = host } @@ -109,7 +109,7 @@ class Connection extends EventEmitter { attachListeners(stream) { parse(stream, (msg) => { - var eventName = msg.name === 'error' ? 'errorMessage' : msg.name + const eventName = msg.name === 'error' ? 'errorMessage' : msg.name if (this._emitMessage) { this.emit('message', msg) } diff --git a/packages/pg/lib/crypto/sasl.js b/packages/pg/lib/crypto/sasl.js index 04ae19724..b7304265e 100644 --- a/packages/pg/lib/crypto/sasl.js +++ b/packages/pg/lib/crypto/sasl.js @@ -38,19 +38,19 @@ async function continueSession(session, password, serverData) { throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short') } - var clientFirstMessageBare = 'n=*,r=' + session.clientNonce - var serverFirstMessage = 'r=' + sv.nonce + ',s=' + sv.salt + ',i=' + sv.iteration - var clientFinalMessageWithoutProof = 'c=biws,r=' + sv.nonce - var authMessage = clientFirstMessageBare + ',' + serverFirstMessage + ',' + clientFinalMessageWithoutProof - - var saltBytes = Buffer.from(sv.salt, 'base64') - var saltedPassword = await crypto.deriveKey(password, saltBytes, sv.iteration) - var clientKey = await crypto.hmacSha256(saltedPassword, 'Client Key') - var storedKey = await crypto.sha256(clientKey) - var clientSignature = await crypto.hmacSha256(storedKey, authMessage) - var clientProof = xorBuffers(Buffer.from(clientKey), Buffer.from(clientSignature)).toString('base64') - var serverKey = await crypto.hmacSha256(saltedPassword, 'Server Key') - var serverSignatureBytes = await crypto.hmacSha256(serverKey, authMessage) + const clientFirstMessageBare = 'n=*,r=' + session.clientNonce + const serverFirstMessage = 'r=' + sv.nonce + ',s=' + sv.salt + ',i=' + sv.iteration + const clientFinalMessageWithoutProof = 'c=biws,r=' + sv.nonce + const authMessage = clientFirstMessageBare + ',' + serverFirstMessage + ',' + clientFinalMessageWithoutProof + + const saltBytes = Buffer.from(sv.salt, 'base64') + const saltedPassword = await crypto.deriveKey(password, saltBytes, sv.iteration) + const clientKey = await crypto.hmacSha256(saltedPassword, 'Client Key') + const storedKey = await crypto.sha256(clientKey) + const clientSignature = await crypto.hmacSha256(storedKey, authMessage) + const clientProof = xorBuffers(Buffer.from(clientKey), Buffer.from(clientSignature)).toString('base64') + const serverKey = await crypto.hmacSha256(saltedPassword, 'Server Key') + const serverSignatureBytes = await crypto.hmacSha256(serverKey, authMessage) session.message = 'SASLResponse' session.serverSignature = Buffer.from(serverSignatureBytes).toString('base64') diff --git a/packages/pg/lib/crypto/utils-legacy.js b/packages/pg/lib/crypto/utils-legacy.js index 86544ad00..ac9654319 100644 --- a/packages/pg/lib/crypto/utils-legacy.js +++ b/packages/pg/lib/crypto/utils-legacy.js @@ -10,8 +10,8 @@ function md5(string) { // See AuthenticationMD5Password at https://www.postgresql.org/docs/current/static/protocol-flow.html function postgresMd5PasswordHash(user, password, salt) { - var inner = md5(password + user) - var outer = md5(Buffer.concat([Buffer.from(inner), salt])) + const inner = md5(password + user) + const outer = md5(Buffer.concat([Buffer.from(inner), salt])) return 'md5' + outer } diff --git a/packages/pg/lib/crypto/utils-webcrypto.js b/packages/pg/lib/crypto/utils-webcrypto.js index 0433f010c..fbfe3b35d 100644 --- a/packages/pg/lib/crypto/utils-webcrypto.js +++ b/packages/pg/lib/crypto/utils-webcrypto.js @@ -47,8 +47,8 @@ async function md5(string) { // See AuthenticationMD5Password at https://www.postgresql.org/docs/current/static/protocol-flow.html async function postgresMd5PasswordHash(user, password, salt) { - var inner = await md5(password + user) - var outer = await md5(Buffer.concat([Buffer.from(inner), salt])) + const inner = await md5(password + user) + const outer = await md5(Buffer.concat([Buffer.from(inner), salt])) return 'md5' + outer } diff --git a/packages/pg/lib/defaults.js b/packages/pg/lib/defaults.js index 5c5d997d2..015909dcd 100644 --- a/packages/pg/lib/defaults.js +++ b/packages/pg/lib/defaults.js @@ -72,10 +72,10 @@ module.exports = { keepalives_idle: 0, } -var pgTypes = require('pg-types') +const pgTypes = require('pg-types') // save default parsers -var parseBigInteger = pgTypes.getTypeParser(20, 'text') -var parseBigIntegerArray = pgTypes.getTypeParser(1016, 'text') +const parseBigInteger = pgTypes.getTypeParser(20, 'text') +const parseBigIntegerArray = pgTypes.getTypeParser(1016, 'text') // parse int8 so you can get your count values as actual numbers module.exports.__defineSetter__('parseInt8', function (val) { diff --git a/packages/pg/lib/index.js b/packages/pg/lib/index.js index 1742d168a..d7b694c2a 100644 --- a/packages/pg/lib/index.js +++ b/packages/pg/lib/index.js @@ -1,9 +1,9 @@ 'use strict' -var Client = require('./client') -var defaults = require('./defaults') -var Connection = require('./connection') -var Pool = require('pg-pool') +const Client = require('./client') +const defaults = require('./defaults') +const Connection = require('./connection') +const Pool = require('pg-pool') const { DatabaseError } = require('pg-protocol') const { escapeIdentifier, escapeLiteral } = require('./utils') @@ -15,7 +15,7 @@ const poolFactory = (Client) => { } } -var PG = function (clientConstructor) { +const PG = function (clientConstructor) { this.defaults = defaults this.Client = clientConstructor this.Query = this.Client.Query @@ -38,7 +38,7 @@ if (typeof process.env.NODE_PG_FORCE_NATIVE !== 'undefined') { configurable: true, enumerable: false, get() { - var native = null + let native = null try { native = new PG(require('./native')) } catch (err) { diff --git a/packages/pg/lib/native/client.js b/packages/pg/lib/native/client.js index 6494375f1..677011d44 100644 --- a/packages/pg/lib/native/client.js +++ b/packages/pg/lib/native/client.js @@ -8,14 +8,14 @@ try { } catch (e) { throw e } -var TypeOverrides = require('../type-overrides') -var EventEmitter = require('events').EventEmitter -var util = require('util') -var ConnectionParameters = require('../connection-parameters') +const TypeOverrides = require('../type-overrides') +const EventEmitter = require('events').EventEmitter +const util = require('util') +const ConnectionParameters = require('../connection-parameters') -var NativeQuery = require('./query') +const NativeQuery = require('./query') -var Client = (module.exports = function (config) { +const Client = (module.exports = function (config) { EventEmitter.call(this) config = config || {} @@ -34,7 +34,7 @@ var Client = (module.exports = function (config) { // keep these on the object for legacy reasons // for the time being. TODO: deprecate all this jazz - var cp = (this.connectionParameters = new ConnectionParameters(config)) + const cp = (this.connectionParameters = new ConnectionParameters(config)) if (config.nativeConnectionString) cp.nativeConnectionString = config.nativeConnectionString this.user = cp.user @@ -79,7 +79,7 @@ Client.prototype._errorAllQueries = function (err) { // pass an optional callback to be called once connected // or with an error if there was a connection error Client.prototype._connect = function (cb) { - var self = this + const self = this if (this._connecting) { process.nextTick(() => cb(new Error('Client has already been connected. You cannot reuse a client.'))) @@ -151,11 +151,11 @@ Client.prototype.connect = function (callback) { // optional string rowMode = 'array' for an array of results // } Client.prototype.query = function (config, values, callback) { - var query - var result - var readTimeout - var readTimeoutTimer - var queryCallback + let query + let result + let readTimeout + let readTimeoutTimer + let queryCallback if (config === null || config === undefined) { throw new TypeError('Client was passed a null or undefined query') @@ -186,7 +186,7 @@ Client.prototype.query = function (config, values, callback) { queryCallback = query.callback readTimeoutTimer = setTimeout(() => { - var error = new Error('Query read timeout') + const error = new Error('Query read timeout') process.nextTick(() => { query.handleError(error, this.connection) @@ -199,7 +199,7 @@ Client.prototype.query = function (config, values, callback) { query.callback = () => {} // Remove from queue - var index = this._queryQueue.indexOf(query) + const index = this._queryQueue.indexOf(query) if (index > -1) { this._queryQueue.splice(index, 1) } @@ -236,14 +236,14 @@ Client.prototype.query = function (config, values, callback) { // disconnect from the backend server Client.prototype.end = function (cb) { - var self = this + const self = this this._ending = true if (!this._connected) { this.once('connect', this.end.bind(this, cb)) } - var result + let result if (!cb) { result = new this._Promise(function (resolve, reject) { cb = (err) => (err ? reject(err) : resolve()) @@ -271,7 +271,7 @@ Client.prototype._pulseQueryQueue = function (initialConnection) { if (this._hasActiveQuery()) { return } - var query = this._queryQueue.shift() + const query = this._queryQueue.shift() if (!query) { if (!initialConnection) { this.emit('drain') @@ -280,7 +280,7 @@ Client.prototype._pulseQueryQueue = function (initialConnection) { } this._activeQuery = query query.submit(this) - var self = this + const self = this query.once('_done', function () { self._pulseQueryQueue() }) diff --git a/packages/pg/lib/native/query.js b/packages/pg/lib/native/query.js index 0cfed1fda..e6d9296d1 100644 --- a/packages/pg/lib/native/query.js +++ b/packages/pg/lib/native/query.js @@ -1,10 +1,10 @@ 'use strict' -var EventEmitter = require('events').EventEmitter -var util = require('util') -var utils = require('../utils') +const EventEmitter = require('events').EventEmitter +const util = require('util') +const utils = require('../utils') -var NativeQuery = (module.exports = function (config, values, callback) { +const NativeQuery = (module.exports = function (config, values, callback) { EventEmitter.call(this) config = utils.normalizeQueryConfig(config, values, callback) this.text = config.text @@ -31,7 +31,7 @@ var NativeQuery = (module.exports = function (config, values, callback) { util.inherits(NativeQuery, EventEmitter) -var errorFieldMap = { +const errorFieldMap = { /* eslint-disable quote-props */ sqlState: 'code', statementPosition: 'position', @@ -49,10 +49,10 @@ var errorFieldMap = { NativeQuery.prototype.handleError = function (err) { // copy pq error fields into the error object - var fields = this.native.pq.resultErrorFields() + const fields = this.native.pq.resultErrorFields() if (fields) { - for (var key in fields) { - var normalizedFieldName = errorFieldMap[key] || key + for (const key in fields) { + const normalizedFieldName = errorFieldMap[key] || key err[normalizedFieldName] = fields[key] } } @@ -85,11 +85,11 @@ NativeQuery.prototype._getPromise = function () { NativeQuery.prototype.submit = function (client) { this.state = 'running' - var self = this + const self = this this.native = client.native client.native.arrayMode = this._arrayMode - var after = function (err, rows, results) { + let after = function (err, rows, results) { client.native.arrayMode = false setImmediate(function () { self.emit('_done') @@ -136,7 +136,7 @@ NativeQuery.prototype.submit = function (client) { console.error('This can cause conflicts and silent errors executing queries') /* eslint-enable no-console */ } - var values = (this.values || []).map(utils.prepareValue) + const values = (this.values || []).map(utils.prepareValue) // check if the client has already executed this named query // if so...just execute it again - skip the planning phase @@ -158,7 +158,7 @@ NativeQuery.prototype.submit = function (client) { const err = new Error('Query values must be an array') return after(err) } - var vals = this.values.map(utils.prepareValue) + const vals = this.values.map(utils.prepareValue) client.native.query(this.text, vals, after) } else if (this.queryMode === 'extended') { client.native.query(this.text, [], after) diff --git a/packages/pg/lib/result.js b/packages/pg/lib/result.js index 98018a7d8..044ae7d36 100644 --- a/packages/pg/lib/result.js +++ b/packages/pg/lib/result.js @@ -1,8 +1,8 @@ 'use strict' -var types = require('pg-types') +const types = require('pg-types') -var matchRegexp = /^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/ +const matchRegexp = /^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/ // result object returned from query // in the 'end' event and also @@ -26,7 +26,7 @@ class Result { // adds a command complete message addCommandComplete(msg) { - var match + let match if (msg.text) { // pure javascript match = matchRegexp.exec(msg.text) @@ -48,9 +48,9 @@ class Result { } _parseRowAsArray(rowData) { - var row = new Array(rowData.length) - for (var i = 0, len = rowData.length; i < len; i++) { - var rawValue = rowData[i] + const row = new Array(rowData.length) + for (let i = 0, len = rowData.length; i < len; i++) { + const rawValue = rowData[i] if (rawValue !== null) { row[i] = this._parsers[i](rawValue) } else { @@ -61,10 +61,10 @@ class Result { } parseRow(rowData) { - var row = { ...this._prebuiltEmptyResultObject } - for (var i = 0, len = rowData.length; i < len; i++) { - var rawValue = rowData[i] - var field = this.fields[i].name + const row = { ...this._prebuiltEmptyResultObject } + for (let i = 0, len = rowData.length; i < len; i++) { + const rawValue = rowData[i] + const field = this.fields[i].name if (rawValue !== null) { row[field] = this._parsers[i](rawValue) } else { @@ -88,10 +88,10 @@ class Result { this._parsers = new Array(fieldDescriptions.length) } - var row = {} + const row = {} - for (var i = 0; i < fieldDescriptions.length; i++) { - var desc = fieldDescriptions[i] + for (let i = 0; i < fieldDescriptions.length; i++) { + const desc = fieldDescriptions[i] row[desc.name] = null if (this._types) { diff --git a/packages/pg/lib/stream.js b/packages/pg/lib/stream.js index cb0839878..2b09d71ee 100644 --- a/packages/pg/lib/stream.js +++ b/packages/pg/lib/stream.js @@ -24,7 +24,7 @@ function getNodejsStreamFuncs() { } function getSecureStream(options) { - var tls = require('tls') + const tls = require('tls') return tls.connect(options) } return { diff --git a/packages/pg/lib/type-overrides.js b/packages/pg/lib/type-overrides.js index 66693482b..9d219e525 100644 --- a/packages/pg/lib/type-overrides.js +++ b/packages/pg/lib/type-overrides.js @@ -1,6 +1,6 @@ 'use strict' -var types = require('pg-types') +const types = require('pg-types') function TypeOverrides(userTypes) { this._types = userTypes || types diff --git a/packages/pg/lib/utils.js b/packages/pg/lib/utils.js index 09b8d3dd8..35489b519 100644 --- a/packages/pg/lib/utils.js +++ b/packages/pg/lib/utils.js @@ -3,7 +3,7 @@ const defaults = require('./defaults') function escapeElement(elementRepresentation) { - var escaped = elementRepresentation.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + const escaped = elementRepresentation.replace(/\\/g, '\\\\').replace(/"/g, '\\"') return '"' + escaped + '"' } @@ -12,8 +12,8 @@ function escapeElement(elementRepresentation) { // uses comma separator so won't work for types like box that use // a different array separator. function arrayString(val) { - var result = '{' - for (var i = 0; i < val.length; i++) { + let result = '{' + for (let i = 0; i < val.length; i++) { if (i > 0) { result = result + ',' } @@ -22,9 +22,9 @@ function arrayString(val) { } else if (Array.isArray(val[i])) { result = result + arrayString(val[i]) } else if (ArrayBuffer.isView(val[i])) { - var item = val[i] + let item = val[i] if (!(item instanceof Buffer)) { - var buf = Buffer.from(item.buffer, item.byteOffset, item.byteLength) + const buf = Buffer.from(item.buffer, item.byteOffset, item.byteLength) if (buf.length === item.byteLength) { item = buf } else { @@ -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) { +const prepareValue = function (val, seen) { // null and undefined are both null for postgres if (val == null) { return null @@ -53,7 +53,7 @@ var prepareValue = function (val, seen) { return val } if (ArrayBuffer.isView(val)) { - var buf = Buffer.from(val.buffer, val.byteOffset, val.byteLength) + const buf = Buffer.from(val.buffer, val.byteOffset, val.byteLength) if (buf.length === val.byteLength) { return buf } @@ -97,13 +97,13 @@ function pad(number, digits) { } function dateToString(date) { - var offset = -date.getTimezoneOffset() + let offset = -date.getTimezoneOffset() - var year = date.getFullYear() - var isBCYear = year < 1 + let year = date.getFullYear() + const isBCYear = year < 1 if (isBCYear) year = Math.abs(year) + 1 // negative years are 1 off their BC representation - var ret = + let ret = pad(year, 4) + '-' + pad(date.getMonth() + 1, 2) + @@ -131,11 +131,11 @@ function dateToString(date) { } function dateToStringUTC(date) { - var year = date.getUTCFullYear() - var isBCYear = year < 1 + let year = date.getUTCFullYear() + const isBCYear = year < 1 if (isBCYear) year = Math.abs(year) + 1 // negative years are 1 off their BC representation - var ret = + let ret = pad(year, 4) + '-' + pad(date.getUTCMonth() + 1, 2) + @@ -177,11 +177,11 @@ const escapeIdentifier = function (str) { } const escapeLiteral = function (str) { - var hasBackslash = false - var escaped = "'" + let hasBackslash = false + let escaped = "'" - for (var i = 0; i < str.length; i++) { - var c = str[i] + for (let i = 0; i < str.length; i++) { + const c = str[i] if (c === "'") { escaped += c + c } else if (c === '\\') { diff --git a/packages/pg/script/create-test-tables.js b/packages/pg/script/create-test-tables.js index 622b0cd20..76ba2dbe4 100644 --- a/packages/pg/script/create-test-tables.js +++ b/packages/pg/script/create-test-tables.js @@ -1,8 +1,8 @@ 'use strict' -var args = require('../test/cli') -var pg = require('../lib') +const args = require('../test/cli') +const pg = require('../lib') -var people = [ +const people = [ { name: 'Aaron', age: 10 }, { name: 'Brian', age: 20 }, { name: 'Chris', age: 30 }, @@ -32,7 +32,7 @@ var people = [ ] async function run() { - var con = new pg.Client({ + const con = new pg.Client({ user: args.user, password: args.password, host: args.host, diff --git a/packages/pg/script/dump-db-types.js b/packages/pg/script/dump-db-types.js index f76249483..46d1d1867 100644 --- a/packages/pg/script/dump-db-types.js +++ b/packages/pg/script/dump-db-types.js @@ -1,11 +1,11 @@ 'use strict' -var pg = require('../lib') -var args = require('../test/cli') +const pg = require('../lib') +const args = require('../test/cli') -var queries = ['select CURRENT_TIMESTAMP', "select interval '1 day' + interval '1 hour'", "select TIMESTAMP 'today'"] +const queries = ['select CURRENT_TIMESTAMP', "select interval '1 day' + interval '1 hour'", "select TIMESTAMP 'today'"] queries.forEach(function (query) { - var client = new pg.Client({ + const client = new pg.Client({ user: args.user, database: args.database, password: args.password, diff --git a/packages/pg/test/buffer-list.js b/packages/pg/test/buffer-list.js index ec48b6ad6..81985bace 100644 --- a/packages/pg/test/buffer-list.js +++ b/packages/pg/test/buffer-list.js @@ -3,7 +3,7 @@ const BufferList = function () { this.buffers = [] } -var p = BufferList.prototype +const p = BufferList.prototype p.add = function (buffer, front) { this.buffers[front ? 'unshift' : 'push'](buffer) @@ -28,16 +28,16 @@ p.addInt32 = function (val, first) { } p.addCString = function (val, front) { - var len = Buffer.byteLength(val) - var buffer = Buffer.alloc(len + 1) + const len = Buffer.byteLength(val) + const buffer = Buffer.alloc(len + 1) buffer.write(val) buffer[len] = 0 return this.add(buffer, front) } p.addString = function (val, front) { - var len = Buffer.byteLength(val) - var buffer = Buffer.alloc(len) + const len = Buffer.byteLength(val) + const buffer = Buffer.alloc(len) buffer.write(val) return this.add(buffer, front) } @@ -47,7 +47,7 @@ p.addChar = function (char, first) { } p.join = function (appendLength, char) { - var length = this.getByteLength() + let length = this.getByteLength() if (appendLength) { this.addInt32(length + 4, true) return this.join(false, char) @@ -56,8 +56,8 @@ p.join = function (appendLength, char) { this.addChar(char, true) length++ } - var result = Buffer.alloc(length) - var index = 0 + const result = Buffer.alloc(length) + let index = 0 this.buffers.forEach(function (buffer) { buffer.copy(result, index, 0) index += buffer.length @@ -66,8 +66,8 @@ p.join = function (appendLength, char) { } BufferList.concat = function () { - var total = new BufferList() - for (var i = 0; i < arguments.length; i++) { + const total = new BufferList() + for (let i = 0; i < arguments.length; i++) { total.add(arguments[i]) } return total.join() diff --git a/packages/pg/test/cli.js b/packages/pg/test/cli.js index 03699b9ba..5bea4912c 100644 --- a/packages/pg/test/cli.js +++ b/packages/pg/test/cli.js @@ -1,8 +1,8 @@ 'use strict' -var ConnectionParameters = require('../lib/connection-parameters') -var config = new ConnectionParameters(process.argv[2]) +const ConnectionParameters = require('../lib/connection-parameters') +const config = new ConnectionParameters(process.argv[2]) -for (var i = 0; i < process.argv.length; i++) { +for (let i = 0; i < process.argv.length; i++) { switch (process.argv[i].toLowerCase()) { case 'native': config.native = true diff --git a/packages/pg/test/integration/client/api-tests.js b/packages/pg/test/integration/client/api-tests.js index 686eabb28..ab7ad6db8 100644 --- a/packages/pg/test/integration/client/api-tests.js +++ b/packages/pg/test/integration/client/api-tests.js @@ -1,9 +1,9 @@ 'use strict' -var helper = require('../test-helper') -var pg = helper.pg +const helper = require('../test-helper') +const pg = helper.pg const assert = require('assert') -var suite = new helper.Suite() +const suite = new helper.Suite() suite.test('null and undefined are both inserted as NULL', function (done) { const pool = new pg.Pool() @@ -180,7 +180,7 @@ suite.test('executing nested queries', function (done) { }) suite.test('raises error if cannot connect', function () { - var connectionString = 'pg://sfalsdkf:asdf@localhost/ieieie' + const connectionString = 'pg://sfalsdkf:asdf@localhost/ieieie' const pool = new pg.Pool({ connectionString: connectionString }) pool.connect( assert.calls(function (err, client, done) { @@ -213,7 +213,7 @@ suite.test('callback is fired once and only once', function (done) { assert.calls(function (err, client, release) { assert(!err) client.query('CREATE TEMP TABLE boom(name varchar(10))') - var callCount = 0 + let callCount = 0 client.query( [ "INSERT INTO boom(name) VALUES('hai')", @@ -256,7 +256,7 @@ suite.test('can provide callback and config and parameters', function (done) { pool.connect( assert.calls(function (err, client, release) { assert(!err) - var config = { + const config = { text: 'select $1::text as val', } client.query( diff --git a/packages/pg/test/integration/client/appname-tests.js b/packages/pg/test/integration/client/appname-tests.js index e69f805bf..b091a7835 100644 --- a/packages/pg/test/integration/client/appname-tests.js +++ b/packages/pg/test/integration/client/appname-tests.js @@ -1,24 +1,24 @@ 'use strict' -var helper = require('./test-helper') -var Client = helper.Client +const helper = require('./test-helper') +const Client = helper.Client const assert = require('assert') -var suite = new helper.Suite() +const suite = new helper.Suite() -var conInfo = helper.config +const conInfo = helper.config function getConInfo(override) { return Object.assign({}, conInfo, override) } function getAppName(conf, cb) { - var client = new Client(conf) + const client = new Client(conf) client.connect( assert.success(function () { client.query( 'SHOW application_name', assert.success(function (res) { - var appName = res.rows[0].application_name + const appName = res.rows[0].application_name cb(appName) client.end() }) @@ -35,8 +35,8 @@ suite.test('No default appliation_name ', function (done) { }) suite.test('fallback_application_name is used', function (done) { - var fbAppName = 'this is my app' - var conf = getConInfo({ + const fbAppName = 'this is my app' + const conf = getConInfo({ fallback_application_name: fbAppName, }) getAppName(conf, function (res) { @@ -46,8 +46,8 @@ suite.test('fallback_application_name is used', function (done) { }) suite.test('application_name is used', function (done) { - var appName = 'some wired !@#$% application_name' - var conf = getConInfo({ + const appName = 'some wired !@#$% application_name' + const conf = getConInfo({ application_name: appName, }) getAppName(conf, function (res) { @@ -57,9 +57,9 @@ suite.test('application_name is used', 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({ + const appName = 'some wired !@#$% application_name' + const fbAppName = 'some other strange $$test$$ appname' + const conf = getConInfo({ application_name: appName, fallback_application_name: fbAppName, }) @@ -70,9 +70,9 @@ suite.test('application_name has precedence over fallback_application_name', fun }) suite.test('application_name from connection string', function (done) { - var appName = 'my app' - var conParams = require('../../../lib/connection-parameters') - var conf + const appName = 'my app' + const conParams = require('../../../lib/connection-parameters') + let conf if (process.argv[2]) { conf = new conParams(process.argv[2] + '?application_name=' + appName) } else { @@ -87,7 +87,7 @@ 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) { - var appName = (process.env.PGAPPNAME = 'testest') + const appName = (process.env.PGAPPNAME = 'testest') getAppName({}, function (res) { delete process.env.PGAPPNAME assert.strictEqual(res, appName) diff --git a/packages/pg/test/integration/client/array-tests.js b/packages/pg/test/integration/client/array-tests.js index ce25bb778..24814be91 100644 --- a/packages/pg/test/integration/client/array-tests.js +++ b/packages/pg/test/integration/client/array-tests.js @@ -1,9 +1,9 @@ 'use strict' -var helper = require('./test-helper') -var pg = helper.pg +const helper = require('./test-helper') +const pg = helper.pg const assert = require('assert') -var suite = new helper.Suite() +const suite = new helper.Suite() const pool = new pg.Pool() @@ -16,7 +16,7 @@ pool.connect( 'SELECT $1::text[] as array', [[null]], assert.success(function (result) { - var array = result.rows[0].array + const array = result.rows[0].array assert.lengthIs(array, 1) assert.isNull(array[0]) done() @@ -25,9 +25,9 @@ pool.connect( }) suite.test('elements containing JSON-escaped characters', function (done) { - var param = '\\"\\"' + let param = '\\"\\"' - for (var i = 1; i <= 0x1f; i++) { + for (let i = 1; i <= 0x1f; i++) { param += String.fromCharCode(i) } @@ -35,7 +35,7 @@ pool.connect( 'SELECT $1::text[] as array', [[param]], assert.success(function (result) { - var array = result.rows[0].array + const array = result.rows[0].array assert.lengthIs(array, 1) assert.equal(array[0], param) done() @@ -70,7 +70,7 @@ pool.connect( client.query( 'SELECT names FROM why', assert.success(function (result) { - var names = result.rows[0].names + const names = result.rows[0].names assert.lengthIs(names, 3) assert.equal(names[0], 'aaron') assert.equal(names[1], 'brian') @@ -84,7 +84,7 @@ pool.connect( client.query( "SELECT '{}'::text[] as names", assert.success(function (result) { - var names = result.rows[0].names + const names = result.rows[0].names assert.lengthIs(names, 0) done() }) @@ -95,7 +95,7 @@ pool.connect( client.query( 'SELECT \'{"joe,bob",jim}\'::text[] as names', assert.success(function (result) { - var names = result.rows[0].names + const names = result.rows[0].names assert.lengthIs(names, 2) assert.equal(names[0], 'joe,bob') assert.equal(names[1], 'jim') @@ -108,7 +108,7 @@ pool.connect( client.query( 'SELECT \'{"{","}"}\'::text[] as names', assert.success(function (result) { - var names = result.rows[0].names + const names = result.rows[0].names assert.lengthIs(names, 2) assert.equal(names[0], '{') assert.equal(names[1], '}') @@ -121,7 +121,7 @@ pool.connect( client.query( 'SELECT \'{joe,null,bob,"NULL"}\'::text[] as names', assert.success(function (result) { - var names = result.rows[0].names + const names = result.rows[0].names assert.lengthIs(names, 4) assert.equal(names[0], 'joe') assert.equal(names[1], null) @@ -136,7 +136,7 @@ pool.connect( client.query( "SELECT ARRAY['joe''', 'jim', 'bob\"'] AS names", assert.success(function (result) { - var names = result.rows[0].names + const names = result.rows[0].names assert.lengthIs(names, 3) assert.equal(names[0], "joe'") assert.equal(names[1], 'jim') @@ -150,7 +150,7 @@ pool.connect( client.query( "SELECT '{{1,joe},{2,bob}}'::text[] as names", assert.success(function (result) { - var names = result.rows[0].names + const names = result.rows[0].names assert.lengthIs(names, 2) assert.lengthIs(names[0], 2) @@ -169,7 +169,7 @@ pool.connect( client.query( "SELECT '{1,2,3}'::integer[] as names", assert.success(function (result) { - var names = result.rows[0].names + const names = result.rows[0].names assert.lengthIs(names, 3) assert.equal(names[0], 1) assert.equal(names[1], 2) @@ -183,7 +183,7 @@ pool.connect( client.query( "SELECT '{{1,100},{2,100},{3,100}}'::integer[] as names", assert.success(function (result) { - var names = result.rows[0].names + const names = result.rows[0].names assert.lengthIs(names, 3) assert.equal(names[0][0], 1) assert.equal(names[0][1], 100) @@ -209,7 +209,7 @@ pool.connect( ], ], assert.success(function (result) { - var names = result.rows[0].names + const names = result.rows[0].names assert.lengthIs(names, 3) assert.equal(names[0][0], 1) assert.equal(names[0][1], 100) diff --git a/packages/pg/test/integration/client/async-stack-trace-tests.js b/packages/pg/test/integration/client/async-stack-trace-tests.js index 0baa03ea8..fd5b15da4 100644 --- a/packages/pg/test/integration/client/async-stack-trace-tests.js +++ b/packages/pg/test/integration/client/async-stack-trace-tests.js @@ -1,6 +1,6 @@ 'use strict' -var helper = require('../test-helper') -var pg = helper.pg +const helper = require('../test-helper') +const pg = helper.pg process.on('unhandledRejection', function (e) { console.error(e, e.stack) diff --git a/packages/pg/test/integration/client/big-simple-query-tests.js b/packages/pg/test/integration/client/big-simple-query-tests.js index a7e6770e8..3c50c1da1 100644 --- a/packages/pg/test/integration/client/big-simple-query-tests.js +++ b/packages/pg/test/integration/client/big-simple-query-tests.js @@ -1,6 +1,6 @@ 'use strict' -var helper = require('./test-helper') -var Query = helper.pg.Query +const helper = require('./test-helper') +const Query = helper.pg.Query const assert = require('assert') const suite = new helper.Suite() @@ -13,13 +13,13 @@ const suite = new helper.Suite() */ // Big query with a where clouse from supplied value -var big_query_rows_1 = [] -var big_query_rows_2 = [] -var big_query_rows_3 = [] +const big_query_rows_1 = [] +const big_query_rows_2 = [] +const big_query_rows_3 = [] // Works suite.test('big simple query 1', function (done) { - var client = helper.client() + const client = helper.client() client .query( new Query( @@ -41,7 +41,7 @@ suite.test('big simple query 1', function (done) { // Works suite.test('big simple query 2', function (done) { - var client = helper.client() + const client = helper.client() client .query( new Query( @@ -65,7 +65,7 @@ suite.test('big simple query 2', function (done) { // Fails most of the time with 'invalid byte sequence for encoding "UTF8": 0xb9' or 'insufficient data left in message' // If test 1 and 2 are commented out it works suite.test('big simple query 3', function (done) { - var client = helper.client() + const client = helper.client() client .query( new Query( @@ -92,7 +92,7 @@ process.on('exit', function () { assert.equal(big_query_rows_3.length, 26, 'big simple query 3 should return 26 rows') }) -var runBigQuery = function (client) { +const runBigQuery = function (client) { client.query( "select 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' as bla from person where name = $1 or 1 = 1", [''], @@ -107,8 +107,8 @@ var runBigQuery = function (client) { } suite.test('many times', function (done) { - var client = helper.client() - for (var i = 0; i < 20; i++) { + const client = helper.client() + for (let i = 0; i < 20; i++) { runBigQuery(client) } client.on('drain', function () { diff --git a/packages/pg/test/integration/client/configuration-tests.js b/packages/pg/test/integration/client/configuration-tests.js index a4b0790a6..a5a11560d 100644 --- a/packages/pg/test/integration/client/configuration-tests.js +++ b/packages/pg/test/integration/client/configuration-tests.js @@ -1,14 +1,14 @@ 'use strict' -var helper = require('./test-helper') -var pg = helper.pg +const helper = require('./test-helper') +const pg = helper.pg const assert = require('assert') const { Client } = helper -var suite = new helper.Suite() +const suite = new helper.Suite() // clear process.env -var realEnv = {} -for (var key in process.env) { +const realEnv = {} +for (const key in process.env) { realEnv[key] = process.env[key] if (!key.indexOf('PG')) delete process.env[key] } @@ -30,7 +30,7 @@ suite.test('default values are used in new clients', function () { parseInputDatesAsUTC: false, }) - var client = new pg.Client() + const client = new pg.Client() assert.same(client, { user: process.env.USER, password: null, @@ -46,7 +46,7 @@ suite.test('modified values are passed to created clients', function () { pg.defaults.port = 1234 pg.defaults.database = 'pow' - var client = new Client() + const client = new Client() assert.same(client, { user: 'boom', password: 'zap', @@ -80,7 +80,7 @@ suite.test('database defaults to user when user is non-default', () => { suite.test('cleanup', () => { // restore process.env - for (var key in realEnv) { + for (const key in realEnv) { process.env[key] = realEnv[key] } }) diff --git a/packages/pg/test/integration/client/empty-query-tests.js b/packages/pg/test/integration/client/empty-query-tests.js index 458a6f3a4..61d46512e 100644 --- a/packages/pg/test/integration/client/empty-query-tests.js +++ b/packages/pg/test/integration/client/empty-query-tests.js @@ -1,5 +1,5 @@ 'use strict' -var helper = require('./test-helper') +const helper = require('./test-helper') const suite = new helper.Suite() const assert = require('assert') diff --git a/packages/pg/test/integration/client/error-handling-tests.js b/packages/pg/test/integration/client/error-handling-tests.js index 0cf7dfabb..8a6fc667f 100644 --- a/packages/pg/test/integration/client/error-handling-tests.js +++ b/packages/pg/test/integration/client/error-handling-tests.js @@ -1,14 +1,14 @@ 'use strict' -var helper = require('./test-helper') +const helper = require('./test-helper') -var pg = helper.pg +const pg = helper.pg const assert = require('assert') const Client = pg.Client const DatabaseError = pg.DatabaseError -var createErorrClient = function () { - var client = helper.client() +const createErorrClient = function () { + const client = helper.client() client.once('error', function (err) { assert.fail('Client shoud not throw error during query execution') }) @@ -78,7 +78,7 @@ suite.test('using a client after closing it results in error', (done) => { }) suite.test('query receives error on client shutdown', function (done) { - var client = new Client() + const client = new Client() client.connect( assert.success(function () { const config = { @@ -102,8 +102,8 @@ suite.test('query receives error on client shutdown', function (done) { ) }) -var ensureFuture = function (testClient, done) { - var goodQuery = testClient.query(new pg.Query('select age from boom')) +const ensureFuture = function (testClient, done) { + const goodQuery = testClient.query(new pg.Query('select age from boom')) assert.emits(goodQuery, 'row', function (row) { assert.equal(row.age, 28) done() @@ -111,12 +111,12 @@ var ensureFuture = function (testClient, done) { } suite.test('when query is parsing', (done) => { - var client = createErorrClient() + const client = createErorrClient() client.query({ text: 'CREATE TEMP TABLE boom(age integer); INSERT INTO boom (age) VALUES (28);' }) // this query wont parse since there isn't a table named bang - var query = client.query( + const query = client.query( new pg.Query({ text: 'select * from bang where name = $1', values: ['0'], @@ -129,11 +129,11 @@ suite.test('when query is parsing', (done) => { }) suite.test('when a query is binding', function (done) { - var client = createErorrClient() + const client = createErorrClient() client.query({ text: 'CREATE TEMP TABLE boom(age integer); INSERT INTO boom (age) VALUES (28);' }) - var query = client.query( + const query = client.query( new pg.Query({ text: 'select * from boom where age = $1', values: ['asldkfjasdf'], @@ -150,7 +150,7 @@ suite.test('when a query is binding', function (done) { }) suite.test('non-query error with callback', function (done) { - var client = new Client({ + const client = new Client({ user: 'asldkfjsadlfkj', }) client.connect( @@ -162,7 +162,7 @@ suite.test('non-query error with callback', function (done) { }) suite.test('non-error calls supplied callback', function (done) { - var client = new Client({ + const client = new Client({ user: helper.args.user, password: helper.args.password, host: helper.args.host, @@ -179,7 +179,7 @@ suite.test('non-error calls supplied callback', function (done) { }) suite.test('when connecting to an invalid host with callback', function (done) { - var client = new Client({ + const client = new Client({ user: 'very invalid username', }) client.on('error', () => { @@ -192,7 +192,7 @@ suite.test('when connecting to an invalid host with callback', function (done) { }) suite.test('when connecting to invalid host with promise', function (done) { - var client = new Client({ + const client = new Client({ user: 'very invalid username', }) client.on('error', () => { @@ -202,7 +202,7 @@ suite.test('when connecting to invalid host with promise', function (done) { }) suite.test('non-query error', function (done) { - var client = new Client({ + const client = new Client({ user: 'asldkfjsadlfkj', }) client.connect().catch((e) => { @@ -212,9 +212,9 @@ suite.test('non-query error', function (done) { }) suite.test('within a simple query', (done) => { - var client = createErorrClient() + const client = createErorrClient() - var query = client.query(new pg.Query("select eeeee from yodas_dsflsd where pixistix = 'zoiks!!!'")) + const query = client.query(new pg.Query("select eeeee from yodas_dsflsd where pixistix = 'zoiks!!!'")) assert.emits(query, 'error', function (error) { if (!helper.config.native) { diff --git a/packages/pg/test/integration/client/field-name-escape-tests.js b/packages/pg/test/integration/client/field-name-escape-tests.js index 146ad1b68..4261c198e 100644 --- a/packages/pg/test/integration/client/field-name-escape-tests.js +++ b/packages/pg/test/integration/client/field-name-escape-tests.js @@ -1,8 +1,8 @@ -var pg = require('./test-helper').pg +const pg = require('./test-helper').pg -var sql = 'SELECT 1 AS "\\\'/*", 2 AS "\\\'*/\n + process.exit(-1)] = null;\n//"' +const sql = 'SELECT 1 AS "\\\'/*", 2 AS "\\\'*/\n + process.exit(-1)] = null;\n//"' -var client = new pg.Client() +const client = new pg.Client() client.connect() client.query(sql, function (err, res) { if (err) throw err diff --git a/packages/pg/test/integration/client/huge-numeric-tests.js b/packages/pg/test/integration/client/huge-numeric-tests.js index 719e9b428..fd4c28295 100644 --- a/packages/pg/test/integration/client/huge-numeric-tests.js +++ b/packages/pg/test/integration/client/huge-numeric-tests.js @@ -1,11 +1,11 @@ 'use strict' -var helper = require('./test-helper') +const helper = require('./test-helper') const pool = new helper.pg.Pool() const assert = require('assert') pool.connect( assert.success(function (client, done) { - var types = require('pg-types') + const types = require('pg-types') // 1231 = numericOID types.setTypeParser(1700, function () { return 'yes' @@ -13,7 +13,7 @@ pool.connect( types.setTypeParser(1700, 'binary', function () { return 'yes' }) - var bignum = '294733346389144765940638005275322203805' + const bignum = '294733346389144765940638005275322203805' client.query('CREATE TEMP TABLE bignumz(id numeric)') client.query('INSERT INTO bignumz(id) VALUES ($1)', [bignum]) client.query( diff --git a/packages/pg/test/integration/client/idle_in_transaction_session_timeout-tests.js b/packages/pg/test/integration/client/idle_in_transaction_session_timeout-tests.js index 1e327492f..933542600 100644 --- a/packages/pg/test/integration/client/idle_in_transaction_session_timeout-tests.js +++ b/packages/pg/test/integration/client/idle_in_transaction_session_timeout-tests.js @@ -1,18 +1,18 @@ 'use strict' -var helper = require('./test-helper') -var Client = helper.Client +const helper = require('./test-helper') +const Client = helper.Client const assert = require('assert') -var suite = new helper.Suite() +const suite = new helper.Suite() -var conInfo = helper.config +const conInfo = helper.config function getConInfo(override) { return Object.assign({}, conInfo, override) } function testClientVersion(cb) { - var client = new Client({}) + const client = new Client({}) client.connect( assert.success(function () { helper.versionGTE( @@ -37,13 +37,13 @@ function testClientVersion(cb) { } function getIdleTransactionSessionTimeout(conf, cb) { - var client = new Client(conf) + const client = new Client(conf) client.connect( assert.success(function () { client.query( 'SHOW idle_in_transaction_session_timeout', assert.success(function (res) { - var timeout = res.rows[0].idle_in_transaction_session_timeout + const timeout = res.rows[0].idle_in_transaction_session_timeout cb(timeout) client.end() }) @@ -64,7 +64,7 @@ if (!helper.args.native) { }) suite.test('idle_in_transaction_session_timeout integer is used', function (done) { - var conf = getConInfo({ + const conf = getConInfo({ idle_in_transaction_session_timeout: 3000, }) getIdleTransactionSessionTimeout(conf, function (res) { @@ -74,7 +74,7 @@ if (!helper.args.native) { }) suite.test('idle_in_transaction_session_timeout float is used', function (done) { - var conf = getConInfo({ + const conf = getConInfo({ idle_in_transaction_session_timeout: 3000.7, }) getIdleTransactionSessionTimeout(conf, function (res) { @@ -84,7 +84,7 @@ if (!helper.args.native) { }) suite.test('idle_in_transaction_session_timeout string is used', function (done) { - var conf = getConInfo({ + const conf = getConInfo({ idle_in_transaction_session_timeout: '3000', }) getIdleTransactionSessionTimeout(conf, function (res) { diff --git a/packages/pg/test/integration/client/json-type-parsing-tests.js b/packages/pg/test/integration/client/json-type-parsing-tests.js index ba7696020..c5882e9d8 100644 --- a/packages/pg/test/integration/client/json-type-parsing-tests.js +++ b/packages/pg/test/integration/client/json-type-parsing-tests.js @@ -1,6 +1,6 @@ 'use strict' -var helper = require('./test-helper') -var assert = require('assert') +const helper = require('./test-helper') +const assert = require('assert') const pool = new helper.pg.Pool() pool.connect( @@ -15,14 +15,14 @@ pool.connect( return pool.end() } client.query('CREATE TEMP TABLE stuff(id SERIAL PRIMARY KEY, data JSON)') - var value = { name: 'Brian', age: 250, alive: true, now: new Date() } + const value = { name: 'Brian', age: 250, alive: true, now: new Date() } client.query('INSERT INTO stuff (data) VALUES ($1)', [value]) client.query( 'SELECT * FROM stuff', assert.success(function (result) { assert.equal(result.rows.length, 1) assert.equal(typeof result.rows[0].data, 'object') - var row = result.rows[0].data + const row = result.rows[0].data assert.strictEqual(row.name, value.name) assert.strictEqual(row.age, value.age) assert.strictEqual(row.alive, value.alive) diff --git a/packages/pg/test/integration/client/network-partition-tests.js b/packages/pg/test/integration/client/network-partition-tests.js index 589ae123b..6ebdb8b45 100644 --- a/packages/pg/test/integration/client/network-partition-tests.js +++ b/packages/pg/test/integration/client/network-partition-tests.js @@ -1,12 +1,12 @@ 'use strict' -var buffers = require('../../test-buffers') -var helper = require('./test-helper') -var suite = new helper.Suite() +const buffers = require('../../test-buffers') +const helper = require('./test-helper') +const suite = new helper.Suite() const assert = require('assert') -var net = require('net') +const net = require('net') -var Server = function (response) { +const Server = function (response) { this.server = undefined this.socket = undefined this.response = response @@ -58,11 +58,11 @@ Server.prototype.close = function (cb) { this.server.close(cb) } -var testServer = function (server, cb) { +const testServer = function (server, cb) { // wait for our server to start server.start(function (options) { // connect a client to it - var client = new helper.Client(options) + const client = new helper.Client(options) client.connect().catch((err) => { assert(err instanceof Error) clearTimeout(timeoutId) @@ -77,7 +77,7 @@ var testServer = function (server, cb) { }) // blow up if we don't receive an error - var timeoutId = setTimeout(function () { + const timeoutId = setTimeout(function () { throw new Error('Client should have emitted an error but it did not.') }, 5000) }) diff --git a/packages/pg/test/integration/client/no-data-tests.js b/packages/pg/test/integration/client/no-data-tests.js index 382b6ffd0..bf61d6d13 100644 --- a/packages/pg/test/integration/client/no-data-tests.js +++ b/packages/pg/test/integration/client/no-data-tests.js @@ -1,10 +1,10 @@ 'use strict' -var helper = require('./test-helper') +const helper = require('./test-helper') const suite = new helper.Suite() const assert = require('assert') suite.test('noData message handling', function () { - var client = helper.client() + const client = helper.client() client.query({ name: 'boom', @@ -37,7 +37,7 @@ suite.test('noData message handling', function () { values: [101], }, (err, res) => { - var row = res.rows[0] + const row = res.rows[0] assert.strictEqual(row.size, 100) } ) diff --git a/packages/pg/test/integration/client/no-row-result-tests.js b/packages/pg/test/integration/client/no-row-result-tests.js index fa84f1d0a..d53470040 100644 --- a/packages/pg/test/integration/client/no-row-result-tests.js +++ b/packages/pg/test/integration/client/no-row-result-tests.js @@ -1,12 +1,12 @@ 'use strict' -var helper = require('./test-helper') -var pg = helper.pg +const helper = require('./test-helper') +const pg = helper.pg const suite = new helper.Suite() const pool = new pg.Pool() const assert = require('assert') suite.test('can access results when no rows are returned', function (done) { - var checkResult = function (result) { + const checkResult = function (result) { assert(result.fields, 'should have fields definition') assert.equal(result.fields.length, 1) assert.equal(result.fields[0].name, 'val') @@ -16,7 +16,7 @@ suite.test('can access results when no rows are returned', function (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( + const query = client.query( q, assert.success(function (result) { checkResult(result) diff --git a/packages/pg/test/integration/client/parse-int-8-tests.js b/packages/pg/test/integration/client/parse-int-8-tests.js index 150ee7bbd..114fd8227 100644 --- a/packages/pg/test/integration/client/parse-int-8-tests.js +++ b/packages/pg/test/integration/client/parse-int-8-tests.js @@ -1,7 +1,7 @@ 'use strict' -var helper = require('../test-helper') -var pg = helper.pg +const helper = require('../test-helper') +const pg = helper.pg const suite = new helper.Suite() const assert = require('assert') diff --git a/packages/pg/test/integration/client/prepared-statement-tests.js b/packages/pg/test/integration/client/prepared-statement-tests.js index 0d01007af..9047eae6c 100644 --- a/packages/pg/test/integration/client/prepared-statement-tests.js +++ b/packages/pg/test/integration/client/prepared-statement-tests.js @@ -1,18 +1,18 @@ 'use strict' -var helper = require('./test-helper') -var Query = helper.pg.Query +const helper = require('./test-helper') +const Query = helper.pg.Query const assert = require('assert') -var suite = new helper.Suite() +const suite = new helper.Suite() ;(function () { - var client = helper.client() + const client = helper.client() client.on('drain', client.end.bind(client)) - var queryName = 'user by age and like name' + const queryName = 'user by age and like name' suite.test('first named prepared statement', function (done) { - var query = client.query( + const query = client.query( new Query({ text: 'select name from person where age <= $1 and name LIKE $2', values: [20, 'Bri%'], @@ -28,7 +28,7 @@ var suite = new helper.Suite() }) suite.test('second named prepared statement with same name & text', function (done) { - var cachedQuery = client.query( + const cachedQuery = client.query( new Query({ text: 'select name from person where age <= $1 and name LIKE $2', name: queryName, @@ -44,7 +44,7 @@ var suite = new helper.Suite() }) suite.test('with same name, but without query text', function (done) { - var q = client.query( + const q = client.query( new Query({ name: queryName, values: [30, '%n%'], @@ -81,12 +81,12 @@ var suite = new helper.Suite() }) })() ;(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' + const statementName = 'differ' + const statement1 = 'select count(*)::int4 as count from person' + const statement2 = 'select count(*)::int4 as count from person where age < $1' - var client1 = helper.client() - var client2 = helper.client() + const client1 = helper.client() + const client2 = helper.client() suite.test('client 1 execution', function (done) { client1.query( @@ -103,7 +103,7 @@ var suite = new helper.Suite() }) suite.test('client 2 execution', function (done) { - var query = client2.query( + const query = client2.query( new Query({ name: statementName, text: statement2, @@ -125,13 +125,13 @@ var suite = new helper.Suite() }) })() ;(function () { - var client = helper.client() + const 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) { + const checkForResults = function (q) { assert.emits(q, 'row', function (row) { assert.equal(row.name, 'node postgres') @@ -146,7 +146,7 @@ var suite = new helper.Suite() } suite.test('with small row count', function (done) { - var query = client.query( + const query = client.query( new Query( { name: 'get names', @@ -161,7 +161,7 @@ var suite = new helper.Suite() }) suite.test('with large row count', function (done) { - var query = client.query( + const query = client.query( new Query( { name: 'get names', diff --git a/packages/pg/test/integration/client/query-as-promise-tests.js b/packages/pg/test/integration/client/query-as-promise-tests.js index beb17b12e..8e1ba5c71 100644 --- a/packages/pg/test/integration/client/query-as-promise-tests.js +++ b/packages/pg/test/integration/client/query-as-promise-tests.js @@ -1,7 +1,7 @@ 'use strict' -var bluebird = require('bluebird') -var helper = require('../test-helper') -var pg = helper.pg +const bluebird = require('bluebird') +const helper = require('../test-helper') +const pg = helper.pg const assert = require('assert') process.on('unhandledRejection', function (e) { diff --git a/packages/pg/test/integration/client/query-column-names-tests.js b/packages/pg/test/integration/client/query-column-names-tests.js index fe537a928..d64e876b8 100644 --- a/packages/pg/test/integration/client/query-column-names-tests.js +++ b/packages/pg/test/integration/client/query-column-names-tests.js @@ -1,6 +1,6 @@ 'use strict' -var helper = require('../test-helper') -var pg = helper.pg +const helper = require('../test-helper') +const pg = helper.pg const assert = require('assert') new helper.Suite().test('support for complex column names', function () { diff --git a/packages/pg/test/integration/client/query-error-handling-prepared-statement-tests.js b/packages/pg/test/integration/client/query-error-handling-prepared-statement-tests.js index 6b8af7008..13ecf4b53 100644 --- a/packages/pg/test/integration/client/query-error-handling-prepared-statement-tests.js +++ b/packages/pg/test/integration/client/query-error-handling-prepared-statement-tests.js @@ -1,24 +1,24 @@ 'use strict' -var helper = require('./test-helper') -var Query = helper.pg.Query +const helper = require('./test-helper') +const Query = helper.pg.Query const { Client } = helper const assert = require('assert') -var suite = new helper.Suite() +const suite = new helper.Suite() suite.test('client end during query execution of prepared statement', function (done) { - var client = new Client() + const client = new Client() client.connect( assert.success(function () { - var sleepQuery = 'select pg_sleep($1)' + const sleepQuery = 'select pg_sleep($1)' - var queryConfig = { + const queryConfig = { name: 'sleep query', text: sleepQuery, values: [5], } - var queryInstance = new Query( + const queryInstance = new Query( queryConfig, assert.calls(function (err, result) { assert.equal(err.message, 'Connection terminated') @@ -26,7 +26,7 @@ suite.test('client end during query execution of prepared statement', function ( }) ) - var query1 = client.query(queryInstance) + const query1 = client.query(queryInstance) query1.on('error', function (err) { assert.fail('Prepared statement should not emit error') @@ -46,9 +46,9 @@ suite.test('client end during query execution of prepared statement', function ( }) function killIdleQuery(targetQuery, cb) { - var client2 = new Client(helper.args) - var pidColName = 'procpid' - var queryColName = 'current_query' + const client2 = new Client(helper.args) + let pidColName = 'procpid' + let queryColName = 'current_query' client2.connect( assert.success(function () { helper.versionGTE( @@ -59,7 +59,7 @@ function killIdleQuery(targetQuery, cb) { pidColName = 'pid' queryColName = 'query' } - var killIdleQuery = + const killIdleQuery = 'SELECT ' + pidColName + ', (SELECT pg_terminate_backend(' + @@ -87,10 +87,10 @@ suite.test('query killed during query execution of prepared statement', function if (helper.args.native) { return done() } - var client = new Client(helper.args) + const client = new Client(helper.args) client.connect( assert.success(function () { - var sleepQuery = 'select pg_sleep($1)' + const sleepQuery = 'select pg_sleep($1)' const queryConfig = { name: 'sleep query', @@ -101,7 +101,7 @@ suite.test('query killed during query execution of prepared statement', function // client should emit an error because it is unexpectedly disconnected assert.emits(client, 'error') - var query1 = client.query( + const query1 = client.query( new Query(queryConfig), assert.calls(function (err, result) { assert.equal(err.message, 'terminating connection due to administrator command') diff --git a/packages/pg/test/integration/client/query-error-handling-tests.js b/packages/pg/test/integration/client/query-error-handling-tests.js index c7af6bda9..eaceec03e 100644 --- a/packages/pg/test/integration/client/query-error-handling-tests.js +++ b/packages/pg/test/integration/client/query-error-handling-tests.js @@ -1,19 +1,19 @@ 'use strict' -var helper = require('./test-helper') -var Query = helper.pg.Query -var DatabaseError = helper.pg.DatabaseError +const helper = require('./test-helper') +const Query = helper.pg.Query +const DatabaseError = helper.pg.DatabaseError const assert = require('assert') const { Client } = helper const suite = new helper.Suite() suite.test('error during query execution', function () { - var client = new Client(helper.args) + const client = new Client(helper.args) client.connect( assert.success(function () { - var queryText = 'select pg_sleep(10)' - var sleepQuery = new Query(queryText) - var pidColName = 'procpid' - var queryColName = 'current_query' + const queryText = 'select pg_sleep(10)' + const sleepQuery = new Query(queryText) + let pidColName = 'procpid' + let queryColName = 'current_query' helper.versionGTE( client, 90200, @@ -22,7 +22,7 @@ suite.test('error during query execution', function () { pidColName = 'pid' queryColName = 'query' } - var query1 = client.query( + const query1 = client.query( sleepQuery, assert.calls(function (err, result) { assert(err) @@ -36,10 +36,10 @@ suite.test('error during query execution', function () { assert.fail('Query with an error should not emit "end" event') }) setTimeout(function () { - var client2 = new Client(helper.args) + const client2 = new Client(helper.args) client2.connect( assert.success(function () { - var killIdleQuery = `SELECT ${pidColName}, (SELECT pg_cancel_backend(${pidColName})) AS killed FROM pg_stat_activity WHERE ${queryColName} LIKE $1` + const killIdleQuery = `SELECT ${pidColName}, (SELECT pg_cancel_backend(${pidColName})) AS killed FROM pg_stat_activity WHERE ${queryColName} LIKE $1` client2.query( killIdleQuery, [queryText], @@ -64,7 +64,7 @@ if (helper.config.native) { } suite.test('9.3 column error fields', function () { - var client = new Client(helper.args) + const client = new Client(helper.args) client.connect( assert.success(function () { helper.versionGTE( @@ -93,7 +93,7 @@ suite.test('9.3 column error fields', function () { }) suite.test('9.3 constraint error fields', function () { - var client = new Client(helper.args) + const client = new Client(helper.args) client.connect( assert.success(function () { helper.versionGTE( diff --git a/packages/pg/test/integration/client/quick-disconnect-tests.js b/packages/pg/test/integration/client/quick-disconnect-tests.js index 066411fc8..8c14214da 100644 --- a/packages/pg/test/integration/client/quick-disconnect-tests.js +++ b/packages/pg/test/integration/client/quick-disconnect-tests.js @@ -1,8 +1,8 @@ 'use strict' // test for issue #320 // -var helper = require('./test-helper') +const helper = require('./test-helper') -var client = new helper.pg.Client(helper.config) +const client = new helper.pg.Client(helper.config) client.connect() client.end() diff --git a/packages/pg/test/integration/client/result-metadata-tests.js b/packages/pg/test/integration/client/result-metadata-tests.js index fbd375ece..fe6eaf919 100644 --- a/packages/pg/test/integration/client/result-metadata-tests.js +++ b/packages/pg/test/integration/client/result-metadata-tests.js @@ -1,6 +1,6 @@ 'use strict' -var helper = require('./test-helper') -var pg = helper.pg +const helper = require('./test-helper') +const pg = helper.pg const assert = require('assert') const pool = new pg.Pool() diff --git a/packages/pg/test/integration/client/results-as-array-tests.js b/packages/pg/test/integration/client/results-as-array-tests.js index 3e30e9796..3e2a36ad9 100644 --- a/packages/pg/test/integration/client/results-as-array-tests.js +++ b/packages/pg/test/integration/client/results-as-array-tests.js @@ -1,16 +1,16 @@ 'use strict' -var util = require('util') -var helper = require('./test-helper') +const util = require('util') +const helper = require('./test-helper') const assert = require('assert') const suite = new helper.Suite() -var Client = helper.Client +const Client = helper.Client -var conInfo = helper.config +const conInfo = helper.config suite.test('returns results as array', function () { - var client = new Client(conInfo) - var checkRow = function (row) { + const client = new Client(conInfo) + const 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()) @@ -20,7 +20,7 @@ suite.test('returns results as array', function () { } client.connect( assert.success(function () { - var config = { + const config = { text: 'SELECT NOW(), 1::int, $1::text, null', values: ['hai'], rowMode: 'array', diff --git a/packages/pg/test/integration/client/row-description-on-results-tests.js b/packages/pg/test/integration/client/row-description-on-results-tests.js index deb9a212d..728e0b96f 100644 --- a/packages/pg/test/integration/client/row-description-on-results-tests.js +++ b/packages/pg/test/integration/client/row-description-on-results-tests.js @@ -1,16 +1,16 @@ 'use strict' -var helper = require('./test-helper') +const helper = require('./test-helper') const assert = require('assert') const suite = new helper.Suite() -var Client = helper.Client +const Client = helper.Client -var conInfo = helper.config +const conInfo = helper.config -var checkResult = function (result) { +const checkResult = function (result) { assert(result.fields) assert.equal(result.fields.length, 3) - var fields = result.fields + const fields = result.fields assert.equal(fields[0].name, 'now') assert.equal(fields[1].name, 'num') assert.equal(fields[2].name, 'texty') @@ -20,7 +20,7 @@ var checkResult = function (result) { } suite.test('row descriptions on result object', function () { - var client = new Client(conInfo) + const client = new Client(conInfo) client.connect( assert.success(function () { client.query( @@ -36,7 +36,7 @@ suite.test('row descriptions on result object', function () { }) suite.test('row description on no rows', function () { - var client = new Client(conInfo) + const client = new Client(conInfo) client.connect( assert.success(function () { client.query( diff --git a/packages/pg/test/integration/client/simple-query-tests.js b/packages/pg/test/integration/client/simple-query-tests.js index 93d859bd3..f5f834432 100644 --- a/packages/pg/test/integration/client/simple-query-tests.js +++ b/packages/pg/test/integration/client/simple-query-tests.js @@ -1,28 +1,28 @@ 'use strict' -var helper = require('./test-helper') -var Query = helper.pg.Query +const helper = require('./test-helper') +const Query = helper.pg.Query const assert = require('assert') const suite = new helper.Suite() const test = suite.test.bind(suite) // before running this test make sure you run the script create-test-tables test('simple query interface', function () { - var client = helper.client() + const client = helper.client() - var query = client.query(new Query('select name from person order by name collate "C"')) + const query = client.query(new Query('select name from person order by name collate "C"')) client.on('drain', client.end.bind(client)) - var rows = [] + const rows = [] query.on('row', function (row, result) { assert.ok(result) rows.push(row['name']) }) query.once('row', function (row) { test('Can iterate through columns', function () { - var columnCount = 0 + let columnCount = 0 // eslint-disable-next-line @typescript-eslint/no-unused-vars - for (var column in row) { + for (const column in row) { columnCount++ } if ('length' in row) { @@ -47,11 +47,11 @@ test('simple query interface', function () { }) test('prepared statements do not mutate params', function () { - var client = helper.client() + const client = helper.client() - var params = [1] + const params = [1] - var query = client.query(new Query('select name from person where $1 = 1 order by name collate "C"', params)) + const query = client.query(new Query('select name from person where $1 = 1 order by name collate "C"', params)) assert.deepEqual(params, [1]) @@ -72,10 +72,10 @@ test('prepared statements do not mutate params', function () { }) test('multiple simple queries', function () { - var client = helper.client() + const 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')) + const query = client.query(new Query('select name from bang')) assert.emits(query, 'row', function (row) { assert.equal(row['name'], 'boom') assert.emits(query, 'row', function (row) { @@ -86,12 +86,12 @@ test('multiple simple queries', function () { }) test('multiple select statements', function () { - var client = helper.client() + const 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' })) + const result = client.query(new Query({ text: 'select age from boom where age < 2; select name from bang' })) assert.emits(result, 'row', function (row) { assert.strictEqual(row['age'], 1) assert.emits(result, 'row', function (row) { diff --git a/packages/pg/test/integration/client/statement_timeout-tests.js b/packages/pg/test/integration/client/statement_timeout-tests.js index fc67a7c4a..b45c71fcc 100644 --- a/packages/pg/test/integration/client/statement_timeout-tests.js +++ b/packages/pg/test/integration/client/statement_timeout-tests.js @@ -1,24 +1,24 @@ 'use strict' -var helper = require('./test-helper') -var Client = helper.Client +const helper = require('./test-helper') +const Client = helper.Client const assert = require('assert') -var suite = new helper.Suite() +const suite = new helper.Suite() -var conInfo = helper.config +const conInfo = helper.config function getConInfo(override) { return Object.assign({}, conInfo, override) } function getStatementTimeout(conf, cb) { - var client = new Client(conf) + const client = new Client(conf) client.connect( assert.success(function () { client.query( 'SHOW statement_timeout', assert.success(function (res) { - var statementTimeout = res.rows[0].statement_timeout + const statementTimeout = res.rows[0].statement_timeout cb(statementTimeout) client.end() }) @@ -38,7 +38,7 @@ if (!helper.args.native) { }) suite.test('statement_timeout integer is used', function (done) { - var conf = getConInfo({ + const conf = getConInfo({ statement_timeout: 3000, }) getStatementTimeout(conf, function (res) { @@ -48,7 +48,7 @@ if (!helper.args.native) { }) suite.test('statement_timeout float is used', function (done) { - var conf = getConInfo({ + const conf = getConInfo({ statement_timeout: 3000.7, }) getStatementTimeout(conf, function (res) { @@ -58,7 +58,7 @@ if (!helper.args.native) { }) suite.test('statement_timeout string is used', function (done) { - var conf = getConInfo({ + const conf = getConInfo({ statement_timeout: '3000', }) getStatementTimeout(conf, function (res) { @@ -68,10 +68,10 @@ if (!helper.args.native) { }) suite.test('statement_timeout actually cancels long running queries', function (done) { - var conf = getConInfo({ + const conf = getConInfo({ statement_timeout: '10', // 10ms to keep tests running fast }) - var client = new Client(conf) + const client = new Client(conf) client.connect( assert.success(function () { client.query('SELECT pg_sleep( 1 )', function (error) { diff --git a/packages/pg/test/integration/client/test-helper.js b/packages/pg/test/integration/client/test-helper.js index 14f8134eb..c915ce09b 100644 --- a/packages/pg/test/integration/client/test-helper.js +++ b/packages/pg/test/integration/client/test-helper.js @@ -1,4 +1,4 @@ 'use strict' -var helper = require('./../test-helper') +const helper = require('./../test-helper') module.exports = helper diff --git a/packages/pg/test/integration/client/timezone-tests.js b/packages/pg/test/integration/client/timezone-tests.js index f00599087..df87dcc74 100644 --- a/packages/pg/test/integration/client/timezone-tests.js +++ b/packages/pg/test/integration/client/timezone-tests.js @@ -1,11 +1,11 @@ 'use strict' -var helper = require('./../test-helper') +const helper = require('./../test-helper') const assert = require('assert') -var oldTz = process.env.TZ +const oldTz = process.env.TZ process.env.TZ = 'Europe/Berlin' -var date = new Date() +const date = new Date() const pool = new helper.pg.Pool() const suite = new helper.Suite() diff --git a/packages/pg/test/integration/client/transaction-tests.js b/packages/pg/test/integration/client/transaction-tests.js index 11cffe24c..feb178fef 100644 --- a/packages/pg/test/integration/client/transaction-tests.js +++ b/packages/pg/test/integration/client/transaction-tests.js @@ -1,5 +1,5 @@ 'use strict' -var helper = require('./test-helper') +const helper = require('./test-helper') const suite = new helper.Suite() const pg = helper.pg const assert = require('assert') @@ -9,7 +9,7 @@ client.connect( assert.success(function () { client.query('begin') - var getZed = { + const getZed = { text: 'SELECT * FROM person WHERE name = $1', values: ['Zed'], } diff --git a/packages/pg/test/integration/client/type-coercion-tests.js b/packages/pg/test/integration/client/type-coercion-tests.js index 587a28c61..705ff0946 100644 --- a/packages/pg/test/integration/client/type-coercion-tests.js +++ b/packages/pg/test/integration/client/type-coercion-tests.js @@ -1,10 +1,10 @@ 'use strict' -var helper = require('./test-helper') -var pg = helper.pg +const helper = require('./test-helper') +const pg = helper.pg const suite = new helper.Suite() const assert = require('assert') -var testForTypeCoercion = function (type) { +const testForTypeCoercion = function (type) { const pool = new pg.Pool() suite.test(`test type coercion ${type.name}`, (cb) => { pool.connect(function (err, client, done) { @@ -23,7 +23,7 @@ var testForTypeCoercion = function (type) { }) ) - var query = client.query( + const query = client.query( new pg.Query({ name: 'get type ' + type.name, text: 'select col from test_type', @@ -39,8 +39,8 @@ var testForTypeCoercion = function (type) { query, 'row', function (row) { - var expected = val + ' (' + typeof val + ')' - var returned = row.col + ' (' + typeof row.col + ')' + const expected = val + ' (' + typeof val + ')' + const returned = row.col + ' (' + typeof row.col + ')' assert.strictEqual(row.col, val, 'expected ' + type.name + ' of ' + expected + ' but got ' + returned) }, 'row should have been called for ' + type.name + ' of ' + val @@ -59,7 +59,7 @@ var testForTypeCoercion = function (type) { }) } -var types = [ +let types = [ { name: 'integer', values: [-2147483648, -1, 0, 1, 2147483647, null], @@ -141,15 +141,15 @@ types.forEach(function (type) { }) suite.test('timestamptz round trip', function (cb) { - var now = new Date() - var client = helper.client() + const now = new Date() + const client = helper.client() 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)', name: 'add date', values: ['now', now], }) - var result = client.query( + const result = client.query( new pg.Query({ name: 'get date', text: 'select * from date_tests where name = $1', @@ -158,7 +158,7 @@ suite.test('timestamptz round trip', function (cb) { ) assert.emits(result, 'row', function (row) { - var date = row.tstz + const date = row.tstz assert.equal(date.getYear(), now.getYear()) assert.equal(date.getMonth(), now.getMonth()) assert.equal(date.getDate(), now.getDate()) @@ -196,7 +196,7 @@ suite.test('selecting nulls', (cb) => { }) suite.test('date range extremes', function (done) { - var client = helper.client() + const 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 diff --git a/packages/pg/test/integration/client/type-parser-override-tests.js b/packages/pg/test/integration/client/type-parser-override-tests.js index 5f7216ad6..883e61bad 100644 --- a/packages/pg/test/integration/client/type-parser-override-tests.js +++ b/packages/pg/test/integration/client/type-parser-override-tests.js @@ -1,9 +1,9 @@ 'use strict' -var helper = require('./test-helper') +const helper = require('./test-helper') const assert = require('assert') function testTypeParser(client, expectedResult, done) { - var boolValue = true + const boolValue = true client.query('CREATE TEMP TABLE parserOverrideTest(id bool)') client.query('INSERT INTO parserOverrideTest(id) VALUES ($1)', [boolValue]) client.query( @@ -20,7 +20,7 @@ pool.connect( assert.success(function (client1, done1) { pool.connect( assert.success(function (client2, done2) { - var boolTypeOID = 16 + const boolTypeOID = 16 client1.setTypeParser(boolTypeOID, function () { return 'first client' }) diff --git a/packages/pg/test/integration/connection-pool/connection-pool-size-tests.js b/packages/pg/test/integration/connection-pool/connection-pool-size-tests.js index 2d16fe49f..260e922d3 100644 --- a/packages/pg/test/integration/connection-pool/connection-pool-size-tests.js +++ b/packages/pg/test/integration/connection-pool/connection-pool-size-tests.js @@ -11,7 +11,7 @@ const testPoolSize = function (max) { let count = 0 return new Promise((resolve) => { - for (var i = 0; i < max; i++) { + for (let i = 0; i < max; i++) { pool.connect(function (err, client, release) { assert(!err) client.query('SELECT * FROM NOW()') diff --git a/packages/pg/test/integration/connection-pool/error-tests.js b/packages/pg/test/integration/connection-pool/error-tests.js index 9f20aa4e6..d5857b583 100644 --- a/packages/pg/test/integration/connection-pool/error-tests.js +++ b/packages/pg/test/integration/connection-pool/error-tests.js @@ -1,5 +1,5 @@ 'use strict' -var helper = require('./test-helper') +const helper = require('./test-helper') const pg = helper.pg const native = helper.args.native const assert = require('assert') @@ -23,9 +23,9 @@ suite.test('errors emitted on checked-out clients', (cb) => { client2, 90200, assert.success(function (isGreater) { - var killIdleQuery = + let killIdleQuery = 'SELECT pid, (SELECT pg_terminate_backend(pid)) AS killed FROM pg_stat_activity WHERE state = $1' - var params = ['idle'] + let params = ['idle'] if (!isGreater) { killIdleQuery = 'SELECT procpid, (SELECT pg_terminate_backend(procpid)) AS killed FROM pg_stat_activity WHERE current_query LIKE $1' diff --git a/packages/pg/test/integration/connection-pool/idle-timeout-tests.js b/packages/pg/test/integration/connection-pool/idle-timeout-tests.js index 2bfe8e409..bc67f856f 100644 --- a/packages/pg/test/integration/connection-pool/idle-timeout-tests.js +++ b/packages/pg/test/integration/connection-pool/idle-timeout-tests.js @@ -1,5 +1,5 @@ 'use strict' -var helper = require('./test-helper') +const helper = require('./test-helper') const assert = require('assert') new helper.Suite().test('idle timeout', function () { diff --git a/packages/pg/test/integration/connection-pool/native-instance-tests.js b/packages/pg/test/integration/connection-pool/native-instance-tests.js index 8cd494e72..6f713411d 100644 --- a/packages/pg/test/integration/connection-pool/native-instance-tests.js +++ b/packages/pg/test/integration/connection-pool/native-instance-tests.js @@ -1,10 +1,10 @@ 'use strict' -var helper = require('./../test-helper') -var pg = helper.pg -var native = helper.args.native +const helper = require('./../test-helper') +const pg = helper.pg +const native = helper.args.native const assert = require('assert') -var pool = new pg.Pool() +const pool = new pg.Pool() pool.connect( assert.calls(function (err, client, done) { diff --git a/packages/pg/test/integration/connection-pool/test-helper.js b/packages/pg/test/integration/connection-pool/test-helper.js index 14f8134eb..c915ce09b 100644 --- a/packages/pg/test/integration/connection-pool/test-helper.js +++ b/packages/pg/test/integration/connection-pool/test-helper.js @@ -1,4 +1,4 @@ 'use strict' -var helper = require('./../test-helper') +const helper = require('./../test-helper') module.exports = helper diff --git a/packages/pg/test/integration/connection-pool/yield-support-tests.js b/packages/pg/test/integration/connection-pool/yield-support-tests.js index cc3d270d6..d3b33cc21 100644 --- a/packages/pg/test/integration/connection-pool/yield-support-tests.js +++ b/packages/pg/test/integration/connection-pool/yield-support-tests.js @@ -1,17 +1,17 @@ 'use strict' -var helper = require('./test-helper') -var co = require('co') +const helper = require('./test-helper') +const co = require('co') const assert = require('assert') 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']) + const client = yield pool.connect() + const res = yield client.query('SELECT $1::text as name', ['foo']) assert.equal(res.rows[0].name, 'foo') - var threw = false + let threw = false try { yield client.query('SELECT LKDSJDSLKFJ') } catch (e) { diff --git a/packages/pg/test/integration/domain-tests.js b/packages/pg/test/integration/domain-tests.js index 78c7663e8..ae63a4a8e 100644 --- a/packages/pg/test/integration/domain-tests.js +++ b/packages/pg/test/integration/domain-tests.js @@ -1,8 +1,8 @@ 'use strict' -var helper = require('./test-helper') -var Query = helper.pg.Query -var suite = new helper.Suite() +const helper = require('./test-helper') +const Query = helper.pg.Query +const suite = new helper.Suite() const assert = require('assert') const Pool = helper.pg.Pool @@ -22,9 +22,9 @@ suite.test('no domain', function (cb) { suite.test('with domain', function (cb) { assert(!process.domain) const pool = new Pool() - var domain = require('domain').create() + const domain = require('domain').create() domain.run(function () { - var startingDomain = process.domain + const startingDomain = process.domain assert(startingDomain) pool.connect( assert.success(function (client, done) { @@ -46,7 +46,7 @@ suite.test('with domain', function (cb) { }) suite.test('error on domain', function (cb) { - var domain = require('domain').create() + const domain = require('domain').create() const pool = new Pool() domain.on('error', function () { pool.end(cb) diff --git a/packages/pg/test/integration/gh-issues/130-tests.js b/packages/pg/test/integration/gh-issues/130-tests.js index 00aae4208..88c4dfb79 100644 --- a/packages/pg/test/integration/gh-issues/130-tests.js +++ b/packages/pg/test/integration/gh-issues/130-tests.js @@ -1,6 +1,6 @@ 'use strict' -var helper = require('../test-helper') -var exec = require('child_process').exec +const helper = require('../test-helper') +const exec = require('child_process').exec const assert = require('assert') helper.pg.defaults.poolIdleTimeout = 1000 @@ -14,8 +14,8 @@ pool.connect(function (err, client, done) { }) client.query('SELECT pg_backend_pid()', function (err, result) { assert.ifError(err) - var pid = result.rows[0].pg_backend_pid - var psql = 'psql' + const pid = result.rows[0].pg_backend_pid + let psql = 'psql' if (helper.args.host) psql = psql + ' -h ' + helper.args.host if (helper.args.port) psql = psql + ' -p ' + helper.args.port if (helper.args.user) psql = psql + ' -U ' + helper.args.user diff --git a/packages/pg/test/integration/gh-issues/131-tests.js b/packages/pg/test/integration/gh-issues/131-tests.js index b169849c1..b2144e6f4 100644 --- a/packages/pg/test/integration/gh-issues/131-tests.js +++ b/packages/pg/test/integration/gh-issues/131-tests.js @@ -1,9 +1,9 @@ 'use strict' -var helper = require('../test-helper') -var pg = helper.pg +const helper = require('../test-helper') +const pg = helper.pg const assert = require('assert') -var suite = new helper.Suite() +const suite = new helper.Suite() suite.test('parsing array decimal results', function (done) { const pool = new pg.Pool() diff --git a/packages/pg/test/integration/gh-issues/1382-tests.js b/packages/pg/test/integration/gh-issues/1382-tests.js index e80924c64..ea2a60f77 100644 --- a/packages/pg/test/integration/gh-issues/1382-tests.js +++ b/packages/pg/test/integration/gh-issues/1382-tests.js @@ -1,5 +1,5 @@ 'use strict' -var helper = require('./../test-helper') +const helper = require('./../test-helper') const suite = new helper.Suite() diff --git a/packages/pg/test/integration/gh-issues/1854-tests.js b/packages/pg/test/integration/gh-issues/1854-tests.js index 92ac6ec35..6e345f4cf 100644 --- a/packages/pg/test/integration/gh-issues/1854-tests.js +++ b/packages/pg/test/integration/gh-issues/1854-tests.js @@ -1,5 +1,5 @@ 'use strict' -var helper = require('./../test-helper') +const helper = require('./../test-helper') const suite = new helper.Suite() diff --git a/packages/pg/test/integration/gh-issues/199-tests.js b/packages/pg/test/integration/gh-issues/199-tests.js index 78d4cd32b..10246eb98 100644 --- a/packages/pg/test/integration/gh-issues/199-tests.js +++ b/packages/pg/test/integration/gh-issues/199-tests.js @@ -1,12 +1,12 @@ 'use strict' -var helper = require('../test-helper') -var client = helper.client() +const helper = require('../test-helper') +const client = helper.client() const assert = require('assert') client.query('CREATE TEMP TABLE arrtest (n integer, s varchar)') client.query("INSERT INTO arrtest VALUES (4, 'foo'), (5, 'bar'), (6, 'baz');") -var qText = +const qText = "SELECT \ ARRAY[1, 2, 3] AS b,\ ARRAY['xx', 'yy', 'zz'] AS c,\ @@ -15,8 +15,8 @@ ARRAY(SELECT s FROM arrtest) AS e;" client.query(qText, function (err, result) { if (err) throw err - var row = result.rows[0] - for (var key in row) { + const row = result.rows[0] + for (const key in row) { assert.equal(typeof row[key], 'object') assert.equal(row[key].length, 3) } diff --git a/packages/pg/test/integration/gh-issues/2056-tests.js b/packages/pg/test/integration/gh-issues/2056-tests.js index 2a12678b9..cf1be338f 100644 --- a/packages/pg/test/integration/gh-issues/2056-tests.js +++ b/packages/pg/test/integration/gh-issues/2056-tests.js @@ -1,6 +1,6 @@ 'use strict' -var helper = require('./../test-helper') -var assert = require('assert') +const helper = require('./../test-helper') +const assert = require('assert') const suite = new helper.Suite() diff --git a/packages/pg/test/integration/gh-issues/2079-tests.js b/packages/pg/test/integration/gh-issues/2079-tests.js index ad1c82aac..5c31b83d2 100644 --- a/packages/pg/test/integration/gh-issues/2079-tests.js +++ b/packages/pg/test/integration/gh-issues/2079-tests.js @@ -1,11 +1,11 @@ 'use strict' -var helper = require('./../test-helper') -var assert = require('assert') +const helper = require('./../test-helper') +const assert = require('assert') const suite = new helper.Suite() // makes a backend server that responds with a non 'S' ssl response buffer -let makeTerminatingBackend = (byte) => { +const makeTerminatingBackend = (byte) => { const { createServer } = require('net') const server = createServer((socket) => { diff --git a/packages/pg/test/integration/gh-issues/2085-tests.js b/packages/pg/test/integration/gh-issues/2085-tests.js index 2536bba82..d71c55c0d 100644 --- a/packages/pg/test/integration/gh-issues/2085-tests.js +++ b/packages/pg/test/integration/gh-issues/2085-tests.js @@ -1,6 +1,6 @@ 'use strict' -var helper = require('./../test-helper') -var assert = require('assert') +const helper = require('./../test-helper') +const assert = require('assert') const suite = new helper.Suite() diff --git a/packages/pg/test/integration/gh-issues/2108-tests.js b/packages/pg/test/integration/gh-issues/2108-tests.js index cbf2caabd..648b0df52 100644 --- a/packages/pg/test/integration/gh-issues/2108-tests.js +++ b/packages/pg/test/integration/gh-issues/2108-tests.js @@ -1,5 +1,5 @@ 'use strict' -var helper = require('./../test-helper') +const helper = require('./../test-helper') const suite = new helper.Suite() suite.test('Closing an unconnected client calls callback', (done) => { diff --git a/packages/pg/test/integration/gh-issues/2556-tests.js b/packages/pg/test/integration/gh-issues/2556-tests.js index 13fdf80eb..7ba0a0ade 100644 --- a/packages/pg/test/integration/gh-issues/2556-tests.js +++ b/packages/pg/test/integration/gh-issues/2556-tests.js @@ -1,15 +1,15 @@ 'use strict' -var helper = require('./../test-helper') -var assert = require('assert') +const helper = require('./../test-helper') +const assert = require('assert') -var callbackError = new Error('TEST: Throw in callback') +const callbackError = new Error('TEST: Throw in callback') const suite = new helper.Suite() suite.test('it should cleanup client even if an error is thrown in a callback', (done) => { // temporarily replace the test framework's uncaughtException handlers // with a custom one that ignores the callbackError - let original_handlers = process.listeners('uncaughtException') + const original_handlers = process.listeners('uncaughtException') process.removeAllListeners('uncaughtException') process.on('uncaughtException', (err) => { if (err != callbackError) { @@ -18,7 +18,7 @@ suite.test('it should cleanup client even if an error is thrown in a callback', }) // throw an error in a callback and verify that a subsequent query works without error - var client = helper.client() + const client = helper.client() client.query('SELECT NOW()', (err) => { assert(!err) setTimeout(reuseClient, 50) @@ -30,7 +30,7 @@ suite.test('it should cleanup client even if an error is thrown in a callback', assert(!err) // restore the test framework's uncaughtException handlers - for (let handler of original_handlers) { + for (const handler of original_handlers) { process.on('uncaughtException', handler) } diff --git a/packages/pg/test/integration/gh-issues/3062-tests.js b/packages/pg/test/integration/gh-issues/3062-tests.js index 76cee2952..325bcf9a4 100644 --- a/packages/pg/test/integration/gh-issues/3062-tests.js +++ b/packages/pg/test/integration/gh-issues/3062-tests.js @@ -1,6 +1,6 @@ 'use strict' const helper = require('../test-helper') -var assert = require('assert') +const assert = require('assert') const suite = new helper.Suite() // https://github.com/brianc/node-postgres/issues/3062 diff --git a/packages/pg/test/integration/gh-issues/507-tests.js b/packages/pg/test/integration/gh-issues/507-tests.js index 19fa67f62..1486bcd34 100644 --- a/packages/pg/test/integration/gh-issues/507-tests.js +++ b/packages/pg/test/integration/gh-issues/507-tests.js @@ -1,6 +1,6 @@ 'use strict' -var helper = require('../test-helper') -var pg = helper.pg +const helper = require('../test-helper') +const pg = helper.pg const assert = require('assert') new helper.Suite().test('parsing array results', function (cb) { diff --git a/packages/pg/test/integration/gh-issues/600-tests.js b/packages/pg/test/integration/gh-issues/600-tests.js index 586db151a..f477e8499 100644 --- a/packages/pg/test/integration/gh-issues/600-tests.js +++ b/packages/pg/test/integration/gh-issues/600-tests.js @@ -1,10 +1,10 @@ 'use strict' -var async = require('async') -var helper = require('../test-helper') +const async = require('async') +const helper = require('../test-helper') const suite = new helper.Suite() const assert = require('assert') -var db = helper.client() +const db = helper.client() function createTableFoo(callback) { db.query('create temp table foo(column1 int, column2 int)', callback) @@ -55,7 +55,7 @@ function doTransaction(callback) { }) } -var steps = [createTableFoo, createTableBar, doTransaction, insertDataBar] +const steps = [createTableFoo, createTableBar, doTransaction, insertDataBar] suite.test('test if query fails', function (done) { async.series( @@ -68,8 +68,8 @@ suite.test('test if query fails', function (done) { }) suite.test('test if prepare works but bind fails', function (done) { - var client = helper.client() - var q = { + const client = helper.client() + const q = { text: 'SELECT $1::int as name', values: ['brian'], name: 'test', diff --git a/packages/pg/test/integration/gh-issues/675-tests.js b/packages/pg/test/integration/gh-issues/675-tests.js index 2e281ecc6..8517fdbef 100644 --- a/packages/pg/test/integration/gh-issues/675-tests.js +++ b/packages/pg/test/integration/gh-issues/675-tests.js @@ -1,19 +1,19 @@ 'use strict' -var helper = require('../test-helper') -var assert = require('assert') +const helper = require('../test-helper') +const assert = require('assert') const pool = new helper.pg.Pool() pool.connect(function (err, client, done) { if (err) throw err - var c = 'CREATE TEMP TABLE posts (body TEXT)' + let c = 'CREATE TEMP TABLE posts (body TEXT)' client.query(c, function (err) { if (err) throw err c = 'INSERT INTO posts (body) VALUES ($1) RETURNING *' - var body = Buffer.from('foo') + let body = Buffer.from('foo') client.query(c, [body], function (err) { if (err) throw err diff --git a/packages/pg/test/integration/gh-issues/699-tests.js b/packages/pg/test/integration/gh-issues/699-tests.js index 6ec99a5c9..7af83b8fd 100644 --- a/packages/pg/test/integration/gh-issues/699-tests.js +++ b/packages/pg/test/integration/gh-issues/699-tests.js @@ -1,6 +1,6 @@ 'use strict' -var helper = require('../test-helper') -var copyFrom = require('pg-copy-streams').from +const helper = require('../test-helper') +const copyFrom = require('pg-copy-streams').from if (helper.args.native) return @@ -8,12 +8,12 @@ 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))' + const c = 'CREATE TEMP TABLE employee (id integer, fname varchar(400), lname varchar(400))' client.query(c, function (err) { if (err) throw err - var stream = client.query(copyFrom('COPY employee FROM STDIN')) + const stream = client.query(copyFrom('COPY employee FROM STDIN')) stream.on('end', function () { done() setTimeout(() => { @@ -21,8 +21,8 @@ pool.connect(function (err, client, done) { }, 50) }) - for (var i = 1; i <= 5; i++) { - var line = ['1\ttest', i, '\tuser', i, '\n'] + for (let i = 1; i <= 5; i++) { + const line = ['1\ttest', i, '\tuser', i, '\n'] stream.write(line.join('')) } stream.end() diff --git a/packages/pg/test/integration/gh-issues/787-tests.js b/packages/pg/test/integration/gh-issues/787-tests.js index 510e5a7ae..5d518475b 100644 --- a/packages/pg/test/integration/gh-issues/787-tests.js +++ b/packages/pg/test/integration/gh-issues/787-tests.js @@ -1,9 +1,9 @@ 'use strict' -var helper = require('../test-helper') +const helper = require('../test-helper') const pool = new helper.pg.Pool() pool.connect(function (err, client) { - var q = { + const 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()', } diff --git a/packages/pg/test/integration/gh-issues/882-tests.js b/packages/pg/test/integration/gh-issues/882-tests.js index 4a8ef6474..17d7aafcf 100644 --- a/packages/pg/test/integration/gh-issues/882-tests.js +++ b/packages/pg/test/integration/gh-issues/882-tests.js @@ -1,7 +1,7 @@ 'use strict' // client should not hang on an empty query -var helper = require('../test-helper') -var client = helper.client() +const helper = require('../test-helper') +const client = helper.client() client.query({ name: 'foo1', text: null }) client.query({ name: 'foo2', text: ' ' }) client.query({ name: 'foo3', text: '' }, function (err, res) { diff --git a/packages/pg/test/integration/gh-issues/981-tests.js b/packages/pg/test/integration/gh-issues/981-tests.js index 998adea3a..68cfb0b1f 100644 --- a/packages/pg/test/integration/gh-issues/981-tests.js +++ b/packages/pg/test/integration/gh-issues/981-tests.js @@ -1,17 +1,17 @@ 'use strict' -var helper = require('./../test-helper') +const helper = require('./../test-helper') //native bindings are only installed for native tests if (!helper.args.native) { return } -var assert = require('assert') -var pg = require('../../../lib') -var native = require('../../../lib').native +const assert = require('assert') +const pg = require('../../../lib') +const native = require('../../../lib').native -var JsClient = require('../../../lib/client') -var NativeClient = require('../../../lib/native') +const JsClient = require('../../../lib/client') +const NativeClient = require('../../../lib/native') assert(pg.Client === JsClient) assert(native.Client === NativeClient) diff --git a/packages/pg/test/integration/test-helper.js b/packages/pg/test/integration/test-helper.js index 654b2f745..631acbae3 100644 --- a/packages/pg/test/integration/test-helper.js +++ b/packages/pg/test/integration/test-helper.js @@ -1,5 +1,5 @@ 'use strict' -var helper = require('./../test-helper') +const helper = require('./../test-helper') let { Client } = helper const assert = require('assert') @@ -11,7 +11,7 @@ if (helper.args.native) { // creates a client from cli parameters helper.client = function (cb) { - var client = new Client() + const client = new Client() client.connect(cb) return client } @@ -21,7 +21,7 @@ helper.versionGTE = function (client, testVersion, callback) { 'SHOW server_version_num', assert.calls(function (err, result) { if (err) return callback(err) - var version = parseInt(result.rows[0].server_version_num, 10) + const version = parseInt(result.rows[0].server_version_num, 10) return callback(null, version >= testVersion) }) ) diff --git a/packages/pg/test/native/callback-api-tests.js b/packages/pg/test/native/callback-api-tests.js index 8ee5e69d7..d129e4a24 100644 --- a/packages/pg/test/native/callback-api-tests.js +++ b/packages/pg/test/native/callback-api-tests.js @@ -1,12 +1,12 @@ 'use strict' -var domain = require('domain') -var helper = require('./../test-helper') -var Client = require('./../../lib/native') +const domain = require('domain') +const helper = require('./../test-helper') +const Client = require('./../../lib/native') const suite = new helper.Suite() const assert = require('assert') suite.test('fires callback with results', function (done) { - var client = new Client(helper.config) + const client = new Client(helper.config) client.connect() client.query( 'SELECT 1 as num', @@ -28,10 +28,10 @@ suite.test('fires callback with results', function (done) { }) suite.test('preserves domain', function (done) { - var dom = domain.create() + const dom = domain.create() dom.run(function () { - var client = new Client(helper.config) + const client = new Client(helper.config) assert.ok(dom === require('domain').active, 'domain is active') client.connect() client.query('select 1', function () { diff --git a/packages/pg/test/native/evented-api-tests.js b/packages/pg/test/native/evented-api-tests.js index 5db9e2901..220fcaece 100644 --- a/packages/pg/test/native/evented-api-tests.js +++ b/packages/pg/test/native/evented-api-tests.js @@ -1,13 +1,13 @@ 'use strict' -var helper = require('../test-helper') -var Client = require('../../lib/native') -var Query = Client.Query +const helper = require('../test-helper') +const Client = require('../../lib/native') +const Query = Client.Query const assert = require('assert') const suite = new helper.Suite() const test = suite.test.bind(suite) -var setupClient = function () { - var client = new Client(helper.config) +const setupClient = function () { + const client = new Client(helper.config) client.connect() client.query('CREATE TEMP TABLE boom(name varchar(10), age integer)') client.query("INSERT INTO boom(name, age) VALUES('Aaron', 26)") @@ -17,8 +17,8 @@ var setupClient = function () { test('multiple results', function () { test('queued queries', function () { - var client = setupClient() - var q = client.query(new Query('SELECT name FROM BOOM')) + const client = setupClient() + const q = client.query(new Query('SELECT name FROM BOOM')) assert.emits(q, 'row', function (row) { assert.equal(row.name, 'Aaron') assert.emits(q, 'row', function (row) { @@ -27,7 +27,7 @@ test('multiple results', function () { }) assert.emits(q, 'end', function () { test('query with config', function () { - var q2 = client.query(new Query({ text: 'SELECT 1 as num' })) + const q2 = client.query(new Query({ text: 'SELECT 1 as num' })) assert.emits(q2, 'row', function (row) { assert.strictEqual(row.num, 1) assert.emits(q2, 'end', function () { @@ -41,8 +41,8 @@ test('multiple results', function () { test('parameterized queries', function () { test('with a single string param', function () { - var client = setupClient() - var q = client.query(new Query('SELECT * FROM boom WHERE name = $1', ['Aaron'])) + const client = setupClient() + const q = client.query(new Query('SELECT * FROM boom WHERE name = $1', ['Aaron'])) assert.emits(q, 'row', function (row) { assert.equal(row.name, 'Aaron') }) @@ -52,8 +52,8 @@ test('parameterized queries', function () { }) test('with object config for query', function () { - var client = setupClient() - var q = client.query( + const client = setupClient() + const q = client.query( new Query({ text: 'SELECT name FROM boom WHERE name = $1', values: ['Brian'], @@ -68,8 +68,8 @@ test('parameterized queries', function () { }) test('multiple parameters', function () { - var client = setupClient() - var q = client.query( + const client = setupClient() + const q = client.query( new Query('SELECT name FROM boom WHERE name = $1 or name = $2 ORDER BY name COLLATE "C"', ['Aaron', 'Brian']) ) assert.emits(q, 'row', function (row) { @@ -84,8 +84,8 @@ test('parameterized queries', function () { }) test('integer parameters', function () { - var client = setupClient() - var q = client.query(new Query('SELECT * FROM boom WHERE age > $1', [27])) + const client = setupClient() + const q = client.query(new Query('SELECT * FROM boom WHERE age > $1', [27])) assert.emits(q, 'row', function (row) { assert.equal(row.name, 'Brian') assert.equal(row.age, 28) diff --git a/packages/pg/test/native/native-connection-string-tests.js b/packages/pg/test/native/native-connection-string-tests.js index fe814deea..506a45551 100644 --- a/packages/pg/test/native/native-connection-string-tests.js +++ b/packages/pg/test/native/native-connection-string-tests.js @@ -1,6 +1,6 @@ 'use strict' -var helper = require('../test-helper') -var Client = require('../../lib/native') +const helper = require('../test-helper') +const Client = require('../../lib/native') const suite = new helper.Suite() const assert = require('assert') @@ -11,7 +11,7 @@ suite.test('respects nativeConnectionString in config', function (done) { // setting wrong port to make sure config is take from nativeConnectionString and not env helper.config.port = '90929' - var client = new Client({ + const client = new Client({ ...helper.config, nativeConnectionString, }) @@ -35,7 +35,7 @@ suite.test('respects nativeConnectionString in config', function (done) { suite.test('respects nativeConnectionString in config even when it is corrupted', function (done) { const nativeConnectionString = `foobar` - var client = new Client({ + const client = new Client({ nativeConnectionString, }) diff --git a/packages/pg/test/native/native-vs-js-error-tests.js b/packages/pg/test/native/native-vs-js-error-tests.js index 842e01aae..d61b0c69d 100644 --- a/packages/pg/test/native/native-vs-js-error-tests.js +++ b/packages/pg/test/native/native-vs-js-error-tests.js @@ -1,10 +1,10 @@ 'use strict' -var assert = require('assert') -var Client = require('../../lib/client') -var NativeClient = require('../../lib/native') +const assert = require('assert') +const Client = require('../../lib/client') +const NativeClient = require('../../lib/native') -var client = new Client() -var nativeClient = new NativeClient() +const client = new Client() +const nativeClient = new NativeClient() client.connect() nativeClient.connect((err) => { @@ -12,7 +12,7 @@ nativeClient.connect((err) => { client.end() nativeClient.query('SELECT lkdasjfasd', (nativeErr) => { - for (var key in nativeErr) { + for (const key in nativeErr) { assert.equal(err[key], nativeErr[key], `Expected err.${key} to equal nativeErr.${key}`) } nativeClient.end() diff --git a/packages/pg/test/native/stress-tests.js b/packages/pg/test/native/stress-tests.js index 13f03dcdf..2cccb44bf 100644 --- a/packages/pg/test/native/stress-tests.js +++ b/packages/pg/test/native/stress-tests.js @@ -1,15 +1,15 @@ 'use strict' -var helper = require('../test-helper') -var Client = require('../../lib/native') -var Query = Client.Query +const helper = require('../test-helper') +const Client = require('../../lib/native') +const Query = Client.Query const assert = require('assert') const suite = new helper.Suite() suite.test('many rows', function () { - var client = new Client(helper.config) + const client = new Client(helper.config) client.connect() - var q = client.query(new Query('SELECT * FROM person')) - var rows = [] + const q = client.query(new Query('SELECT * FROM person')) + const rows = [] q.on('row', function (row) { rows.push(row) }) @@ -20,12 +20,12 @@ suite.test('many rows', function () { }) suite.test('many queries', function () { - var client = new Client(helper.config) + const client = new Client(helper.config) client.connect() - var count = 0 - var expected = 100 - for (var i = 0; i < expected; i++) { - var q = client.query(new Query('SELECT * FROM person')) + let count = 0 + const expected = 100 + for (let i = 0; i < expected; i++) { + const q = client.query(new Query('SELECT * FROM person')) assert.emits(q, 'end', function () { count++ }) @@ -37,13 +37,13 @@ suite.test('many queries', function () { }) suite.test('many clients', function () { - var clients = [] - for (var i = 0; i < 10; i++) { + const clients = [] + for (let i = 0; i < 10; i++) { clients.push(new Client(helper.config)) } clients.forEach(function (client) { client.connect() - for (var i = 0; i < 20; i++) { + for (let i = 0; i < 20; i++) { client.query('SELECT * FROM person') } assert.emits(client, 'drain', function () { diff --git a/packages/pg/test/test-buffers.js b/packages/pg/test/test-buffers.js index 2989434d4..576d22f7e 100644 --- a/packages/pg/test/test-buffers.js +++ b/packages/pg/test/test-buffers.js @@ -3,7 +3,7 @@ require('./test-helper') const BufferList = require('./buffer-list') // http://developer.postgresql.org/pgdocs/postgres/protocol-message-formats.html -var buffers = {} +const buffers = {} buffers.readyForQuery = function () { return new BufferList().add(Buffer.from('I')).join(true, 'Z') } @@ -49,7 +49,7 @@ buffers.commandComplete = function (string) { buffers.rowDescription = function (fields) { fields = fields || [] - var buf = new BufferList() + const buf = new BufferList() buf.addInt16(fields.length) fields.forEach(function (field) { buf @@ -66,13 +66,13 @@ buffers.rowDescription = function (fields) { buffers.dataRow = function (columns) { columns = columns || [] - var buf = new BufferList() + const buf = new BufferList() buf.addInt16(columns.length) columns.forEach(function (col) { if (col == null) { buf.addInt32(-1) } else { - var strBuf = Buffer.from(col, 'utf8') + const strBuf = Buffer.from(col, 'utf8') buf.addInt32(strBuf.length) buf.add(strBuf) } @@ -88,9 +88,9 @@ buffers.notice = function (fields) { return errorOrNotice(fields).join(true, 'N') } -var errorOrNotice = function (fields) { +const errorOrNotice = function (fields) { fields = fields || [] - var buf = new BufferList() + const buf = new BufferList() fields.forEach(function (field) { buf.addChar(field.type) buf.addCString(field.value) diff --git a/packages/pg/test/test-helper.js b/packages/pg/test/test-helper.js index 7a50aac65..a025ab24b 100644 --- a/packages/pg/test/test-helper.js +++ b/packages/pg/test/test-helper.js @@ -1,6 +1,6 @@ 'use strict' const assert = require('assert') -var sys = require('util') +const sys = require('util') const Suite = require('./suite') const args = require('./cli') @@ -18,14 +18,14 @@ process.on('uncaughtException', function (d) { }) assert.same = function (actual, expected) { - for (var key in expected) { + for (const key in expected) { assert.equal(actual[key], expected[key]) } } assert.emits = function (item, eventName, callback, message) { - var called = false - var id = setTimeout(function () { + let called = false + const id = setTimeout(function () { test("Should have called '" + eventName + "' event", function () { assert.ok(called, message || "Expected '" + eventName + "' to be called.") }) @@ -49,25 +49,25 @@ assert.emits = function (item, eventName, callback, message) { } assert.UTCDate = function (actual, year, month, day, hours, min, sec, milisecond) { - var actualYear = actual.getUTCFullYear() + const actualYear = actual.getUTCFullYear() assert.equal(actualYear, year, 'expected year ' + year + ' but got ' + actualYear) - var actualMonth = actual.getUTCMonth() + const actualMonth = actual.getUTCMonth() assert.equal(actualMonth, month, 'expected month ' + month + ' but got ' + actualMonth) - var actualDate = actual.getUTCDate() + const actualDate = actual.getUTCDate() assert.equal(actualDate, day, 'expected day ' + day + ' but got ' + actualDate) - var actualHours = actual.getUTCHours() + const actualHours = actual.getUTCHours() assert.equal(actualHours, hours, 'expected hours ' + hours + ' but got ' + actualHours) - var actualMin = actual.getUTCMinutes() + const actualMin = actual.getUTCMinutes() assert.equal(actualMin, min, 'expected min ' + min + ' but got ' + actualMin) - var actualSec = actual.getUTCSeconds() + const actualSec = actual.getUTCSeconds() assert.equal(actualSec, sec, 'expected sec ' + sec + ' but got ' + actualSec) - var actualMili = actual.getUTCMilliseconds() + const actualMili = actual.getUTCMilliseconds() assert.equal(actualMili, milisecond, 'expected milisecond ' + milisecond + ' but got ' + actualMili) } @@ -76,7 +76,7 @@ assert.equalBuffers = function (actual, expected) { spit(actual, expected) assert.equal(actual.length, expected.length) } - for (var i = 0; i < actual.length; i++) { + for (let i = 0; i < actual.length; i++) { if (actual[i] != expected[i]) { spit(actual, expected) } @@ -114,10 +114,10 @@ assert.lengthIs = function (actual, expectedLength) { assert.equal(actual.length, expectedLength) } -var expect = function (callback, timeout) { - var executed = false +const expect = function (callback, timeout) { + const executed = false timeout = timeout || parseInt(process.env.TEST_TIMEOUT) || 5000 - var id = setTimeout(function () { + const id = setTimeout(function () { assert.ok( executed, 'Expected execution of function to be fired within ' + @@ -171,15 +171,15 @@ process.on('uncaughtException', function (err) { process.exit(255) }) -var getTimezoneOffset = Date.prototype.getTimezoneOffset +const getTimezoneOffset = Date.prototype.getTimezoneOffset -var setTimezoneOffset = function (minutesOffset) { +const setTimezoneOffset = function (minutesOffset) { Date.prototype.getTimezoneOffset = function () { return minutesOffset } } -var resetTimezoneOffset = function () { +const resetTimezoneOffset = function () { Date.prototype.getTimezoneOffset = getTimezoneOffset } diff --git a/packages/pg/test/unit/client/cleartext-password-tests.js b/packages/pg/test/unit/client/cleartext-password-tests.js index 0cf0b9fe5..388d94cf9 100644 --- a/packages/pg/test/unit/client/cleartext-password-tests.js +++ b/packages/pg/test/unit/client/cleartext-password-tests.js @@ -7,19 +7,19 @@ const suite = new helper.Suite() const { MemoryStream } = helper suite.test('cleartext password auth responds with password', function () { - var client = createClient() + const client = createClient() client.password = '!' client.connection.stream.packets = [] client.connection.emit('authenticationCleartextPassword') - var packets = client.connection.stream.packets + const packets = client.connection.stream.packets assert.lengthIs(packets, 1) - var packet = packets[0] + const packet = packets[0] assert.equalBuffers(packet, [0x70, 0, 0, 0, 6, 33, 0]) }) suite.test('cleartext password auth does not crash with null password using pg-pass', function () { process.env.PGPASSFILE = `${__dirname}/pgpass.file` - var client = new helper.Client({ + const client = new helper.Client({ host: 'foo', port: 5432, database: 'bar', diff --git a/packages/pg/test/unit/client/configuration-tests.js b/packages/pg/test/unit/client/configuration-tests.js index 55e14e143..63d4ea649 100644 --- a/packages/pg/test/unit/client/configuration-tests.js +++ b/packages/pg/test/unit/client/configuration-tests.js @@ -1,17 +1,17 @@ 'use strict' const helper = require('./test-helper') const { Client } = helper -var assert = require('assert') +const assert = require('assert') const suite = new helper.Suite() const test = suite.test.bind(suite) -var pguser = process.env['PGUSER'] || process.env.USER -var pgdatabase = process.env['PGDATABASE'] || process.env.USER -var pgport = process.env['PGPORT'] || 5432 +const pguser = process.env['PGUSER'] || process.env.USER +const pgdatabase = process.env['PGDATABASE'] || process.env.USER +const pgport = process.env['PGPORT'] || 5432 test('client settings', function () { test('defaults', function () { - var client = new Client() + const client = new Client() assert.equal(client.user, pguser) assert.equal(client.database, pgdatabase) assert.equal(client.port, pgport) @@ -19,10 +19,10 @@ test('client settings', function () { }) test('custom', function () { - var user = 'brian' - var database = 'pgjstest' - var password = 'boom' - var client = new Client({ + const user = 'brian' + const database = 'pgjstest' + const password = 'boom' + const client = new Client({ user: user, database: database, port: 321, @@ -38,20 +38,20 @@ test('client settings', function () { }) test('custom ssl default on', function () { - var old = process.env.PGSSLMODE + const old = process.env.PGSSLMODE process.env.PGSSLMODE = 'prefer' - var client = new Client() + const client = new Client() process.env.PGSSLMODE = old assert.equal(client.ssl, true) }) test('custom ssl force off', function () { - var old = process.env.PGSSLMODE + const old = process.env.PGSSLMODE process.env.PGSSLMODE = 'prefer' - var client = new Client({ + const client = new Client({ ssl: false, }) process.env.PGSSLMODE = old @@ -62,7 +62,7 @@ test('client settings', function () { test('initializing from a config string', function () { test('uses connectionString property', function () { - var client = new Client({ + const client = new Client({ connectionString: 'postgres://brian:pass@host1:333/databasename', }) assert.equal(client.user, 'brian') @@ -73,7 +73,7 @@ test('initializing from a config string', function () { }) test('uses the correct values from the config string', function () { - var client = new Client('postgres://brian:pass@host1:333/databasename') + const client = new Client('postgres://brian:pass@host1:333/databasename') assert.equal(client.user, 'brian') assert.equal(client.password, 'pass') assert.equal(client.host, 'host1') @@ -82,7 +82,7 @@ test('initializing from a config string', function () { }) test('uses the correct values from the config string with space in password', function () { - var client = new Client('postgres://brian:pass word@host1:333/databasename') + const client = new Client('postgres://brian:pass word@host1:333/databasename') assert.equal(client.user, 'brian') assert.equal(client.password, 'pass word') assert.equal(client.host, 'host1') @@ -91,7 +91,7 @@ test('initializing from a config string', function () { }) test('when not including all values the defaults are used', function () { - var client = new Client('postgres://host1') + const client = new Client('postgres://host1') assert.equal(client.user, process.env['PGUSER'] || process.env.USER) assert.equal(client.password, process.env['PGPASSWORD'] || null) assert.equal(client.host, 'host1') @@ -100,17 +100,17 @@ test('initializing from a config string', function () { }) test('when not including all values the environment variables are used', function () { - var envUserDefined = process.env['PGUSER'] !== undefined - var envPasswordDefined = process.env['PGPASSWORD'] !== undefined - var envHostDefined = process.env['PGHOST'] !== undefined - var envPortDefined = process.env['PGPORT'] !== undefined - var envDBDefined = process.env['PGDATABASE'] !== undefined - - var savedEnvUser = process.env['PGUSER'] - var savedEnvPassword = process.env['PGPASSWORD'] - var savedEnvHost = process.env['PGHOST'] - var savedEnvPort = process.env['PGPORT'] - var savedEnvDB = process.env['PGDATABASE'] + const envUserDefined = process.env['PGUSER'] !== undefined + const envPasswordDefined = process.env['PGPASSWORD'] !== undefined + const envHostDefined = process.env['PGHOST'] !== undefined + const envPortDefined = process.env['PGPORT'] !== undefined + const envDBDefined = process.env['PGDATABASE'] !== undefined + + const savedEnvUser = process.env['PGUSER'] + const savedEnvPassword = process.env['PGPASSWORD'] + const savedEnvHost = process.env['PGHOST'] + const savedEnvPort = process.env['PGPORT'] + const savedEnvDB = process.env['PGDATABASE'] process.env['PGUSER'] = 'utUser1' process.env['PGPASSWORD'] = 'utPass1' @@ -118,7 +118,7 @@ test('initializing from a config string', function () { process.env['PGPORT'] = 5464 process.env['PGDATABASE'] = 'utDB1' - var client = new Client('postgres://host1') + const client = new Client('postgres://host1') assert.equal(client.user, process.env['PGUSER']) assert.equal(client.password, process.env['PGPASSWORD']) assert.equal(client.host, 'host1') @@ -158,9 +158,9 @@ test('initializing from a config string', function () { }) test('calls connect correctly on connection', function () { - var client = new Client('/tmp') - var usedPort = '' - var usedHost = '' + const client = new Client('/tmp') + let usedPort = '' + let usedHost = '' client.connection.connect = function (port, host) { usedPort = port usedHost = host diff --git a/packages/pg/test/unit/client/early-disconnect-tests.js b/packages/pg/test/unit/client/early-disconnect-tests.js index 5e8880c7e..f62ce62d1 100644 --- a/packages/pg/test/unit/client/early-disconnect-tests.js +++ b/packages/pg/test/unit/client/early-disconnect-tests.js @@ -1,17 +1,17 @@ 'use strict' require('./test-helper') -var net = require('net') -var pg = require('../../../lib/index.js') +const net = require('net') +const pg = require('../../../lib/index.js') const assert = require('assert') /* console.log() messages show up in `make test` output. TODO: fix it. */ -var server = net.createServer(function (c) { +const server = net.createServer(function (c) { c.destroy() server.close() }) server.listen(7777, function () { - var client = new pg.Client('postgres://localhost:7777') + const client = new pg.Client('postgres://localhost:7777') client.connect( assert.calls(function (err) { assert(err) diff --git a/packages/pg/test/unit/client/escape-tests.js b/packages/pg/test/unit/client/escape-tests.js index 2b5f64499..e19ef14be 100644 --- a/packages/pg/test/unit/client/escape-tests.js +++ b/packages/pg/test/unit/client/escape-tests.js @@ -1,43 +1,43 @@ 'use strict' -var helper = require('./test-helper') -var utils = require('../../../lib/utils') +const helper = require('./test-helper') +const utils = require('../../../lib/utils') const assert = require('assert') const { Client, Suite } = helper const suite = new Suite() const test = suite.test.bind(suite) -var testLit = function (testName, input, expected) { +const testLit = function (testName, input, expected) { test(testName, function () { - var client = new Client(helper.config) - var actual = client.escapeLiteral(input) + const client = new Client(helper.config) + const actual = client.escapeLiteral(input) assert.equal(expected, actual) }) test('Client.prototype.' + testName, function () { - var actual = Client.prototype.escapeLiteral(input) + const actual = Client.prototype.escapeLiteral(input) assert.equal(expected, actual) }) test('utils.' + testName, function () { - var actual = utils.escapeLiteral(input) + const actual = utils.escapeLiteral(input) assert.equal(expected, actual) }) } -var testIdent = function (testName, input, expected) { +const testIdent = function (testName, input, expected) { test(testName, function () { - var client = new Client(helper.config) - var actual = client.escapeIdentifier(input) + const client = new Client(helper.config) + const actual = client.escapeIdentifier(input) assert.equal(expected, actual) }) test('Client.prototype.' + testName, function () { - var actual = Client.prototype.escapeIdentifier(input) + const actual = Client.prototype.escapeIdentifier(input) assert.equal(expected, actual) }) test('utils.' + testName, function () { - var actual = utils.escapeIdentifier(input) + const actual = utils.escapeIdentifier(input) assert.equal(expected, actual) }) } diff --git a/packages/pg/test/unit/client/md5-password-tests.js b/packages/pg/test/unit/client/md5-password-tests.js index e4cb9b3e6..8fd2f7c2f 100644 --- a/packages/pg/test/unit/client/md5-password-tests.js +++ b/packages/pg/test/unit/client/md5-password-tests.js @@ -1,22 +1,22 @@ 'use strict' -var helper = require('./test-helper') +const helper = require('./test-helper') const BufferList = require('../../buffer-list') -var crypto = require('../../../lib/crypto/utils') +const crypto = require('../../../lib/crypto/utils') const assert = require('assert') const suite = new helper.Suite() const test = suite.test.bind(suite) test('md5 authentication', async function () { - var client = helper.createClient() + const client = helper.createClient() client.password = '!' - var salt = Buffer.from([1, 2, 3, 4]) + const salt = Buffer.from([1, 2, 3, 4]) await client.connection.emit('authenticationMD5Password', { salt: salt }) setTimeout(() => test('responds', function () { assert.lengthIs(client.connection.stream.packets, 1) test('should have correct encrypted data', async function () { - var password = await crypto.postgresMd5PasswordHash(client.user, client.password, salt) + const password = await crypto.postgresMd5PasswordHash(client.user, client.password, salt) // how do we want to test this? assert.equalBuffers(client.connection.stream.packets[0], new BufferList().addCString(password).join(true, 'p')) }) diff --git a/packages/pg/test/unit/client/notification-tests.js b/packages/pg/test/unit/client/notification-tests.js index 25d0e9f48..55efdbad8 100644 --- a/packages/pg/test/unit/client/notification-tests.js +++ b/packages/pg/test/unit/client/notification-tests.js @@ -1,10 +1,10 @@ 'use strict' -var helper = require('./test-helper') +const helper = require('./test-helper') const assert = require('assert') const suite = new helper.Suite() suite.test('passes connection notification', function () { - var client = helper.client() + const client = helper.client() assert.emits(client, 'notice', function (msg) { assert.equal(msg, 'HAY!!') }) diff --git a/packages/pg/test/unit/client/prepared-statement-tests.js b/packages/pg/test/unit/client/prepared-statement-tests.js index ba080dd59..71f9d094b 100644 --- a/packages/pg/test/unit/client/prepared-statement-tests.js +++ b/packages/pg/test/unit/client/prepared-statement-tests.js @@ -1,13 +1,13 @@ 'use strict' -var helper = require('./test-helper') -var Query = require('../../../lib/query') +const helper = require('./test-helper') +const Query = require('../../../lib/query') const assert = require('assert') -var client = helper.client() +const client = helper.client() const suite = new helper.Suite() const test = suite.test.bind(suite) -var con = client.connection -var parseArg = null +const con = client.connection +let parseArg = null con.parse = function (arg) { parseArg = arg process.nextTick(function () { @@ -15,7 +15,7 @@ con.parse = function (arg) { }) } -var bindArg = null +let bindArg = null con.bind = function (arg) { bindArg = arg process.nextTick(function () { @@ -23,7 +23,7 @@ con.bind = function (arg) { }) } -var executeArg = null +let executeArg = null con.execute = function (arg) { executeArg = arg process.nextTick(function () { @@ -32,7 +32,7 @@ con.execute = function (arg) { }) } -var describeArg = null +let describeArg = null con.describe = function (arg) { describeArg = arg process.nextTick(function () { @@ -40,7 +40,7 @@ con.describe = function (arg) { }) } -var syncCalled = false +let syncCalled = false con.flush = function () {} con.sync = function () { syncCalled = true @@ -53,7 +53,7 @@ test('bound command', function () { test('simple, unnamed bound command', function () { assert.ok(client.connection.emit('readyForQuery')) - var query = client.query( + const query = client.query( new Query({ text: 'select * from X where name = $1', values: ['hi'], @@ -91,15 +91,15 @@ test('bound command', function () { }) }) -var portalClient = helper.client() -var portalCon = portalClient.connection +const portalClient = helper.client() +const portalCon = portalClient.connection portalCon.parse = function (arg) { process.nextTick(function () { portalCon.emit('parseComplete') }) } -var portalBindArg = null +let portalBindArg = null portalCon.bind = function (arg) { portalBindArg = arg process.nextTick(function () { @@ -107,7 +107,7 @@ portalCon.bind = function (arg) { }) } -var portalExecuteArg = null +let portalExecuteArg = null portalCon.execute = function (arg) { portalExecuteArg = arg process.nextTick(function () { @@ -116,7 +116,7 @@ portalCon.execute = function (arg) { }) } -var portalDescribeArg = null +let portalDescribeArg = null portalCon.describe = function (arg) { portalDescribeArg = arg process.nextTick(function () { @@ -134,7 +134,7 @@ portalCon.sync = function () { test('prepared statement with explicit portal', function () { assert.ok(portalClient.connection.emit('readyForQuery')) - var query = portalClient.query( + const query = portalClient.query( new Query({ text: 'select * from X where name = $1', portal: 'myportal', diff --git a/packages/pg/test/unit/client/query-queue-tests.js b/packages/pg/test/unit/client/query-queue-tests.js index ede3293fc..1566afc43 100644 --- a/packages/pg/test/unit/client/query-queue-tests.js +++ b/packages/pg/test/unit/client/query-queue-tests.js @@ -1,21 +1,21 @@ 'use strict' const helper = require('./test-helper') const { Client } = helper -var Connection = require('../../../lib/connection') +const Connection = require('../../../lib/connection') const assert = require('assert') const suite = new helper.Suite() const test = suite.test.bind(suite) test('drain', function () { - var con = new Connection({ stream: 'NO' }) - var client = new Client({ connection: con }) + const con = new Connection({ stream: 'NO' }) + const client = new Client({ connection: con }) con.connect = function () { con.emit('connect') } con.query = function () {} client.connect() - var raisedDrain = false + let raisedDrain = false client.on('drain', function () { raisedDrain = true }) diff --git a/packages/pg/test/unit/client/result-metadata-tests.js b/packages/pg/test/unit/client/result-metadata-tests.js index e37209872..bbc85c7af 100644 --- a/packages/pg/test/unit/client/result-metadata-tests.js +++ b/packages/pg/test/unit/client/result-metadata-tests.js @@ -1,12 +1,12 @@ 'use strict' -var helper = require('./test-helper') +const helper = require('./test-helper') const assert = require('assert') const suite = new helper.Suite() const test = suite.test.bind(suite) -var testForTag = function (tagText, callback) { +const testForTag = function (tagText, callback) { test('includes command tag data for tag ' + tagText, function () { - var client = helper.client() + const client = helper.client() client.connection.emit('readyForQuery') client.query( @@ -26,7 +26,7 @@ var testForTag = function (tagText, callback) { }) } -var check = function (oid, rowCount, command) { +const check = function (oid, rowCount, command) { return function (result) { if (oid != null) { assert.equal(result.oid, oid) diff --git a/packages/pg/test/unit/client/sasl-scram-tests.js b/packages/pg/test/unit/client/sasl-scram-tests.js index 2e1ed6a2f..fca48efb2 100644 --- a/packages/pg/test/unit/client/sasl-scram-tests.js +++ b/packages/pg/test/unit/client/sasl-scram-tests.js @@ -2,7 +2,7 @@ const helper = require('./test-helper') const assert = require('assert') -var sasl = require('../../../lib/crypto/sasl') +const sasl = require('../../../lib/crypto/sasl') const suite = new helper.Suite() diff --git a/packages/pg/test/unit/client/simple-query-tests.js b/packages/pg/test/unit/client/simple-query-tests.js index 3fecc1435..f82c3e661 100644 --- a/packages/pg/test/unit/client/simple-query-tests.js +++ b/packages/pg/test/unit/client/simple-query-tests.js @@ -1,6 +1,6 @@ 'use strict' -var helper = require('./test-helper') -var Query = require('../../../lib/query') +const helper = require('./test-helper') +const Query = require('../../../lib/query') const assert = require('assert') const suite = new helper.Suite() const test = suite.test.bind(suite) @@ -8,7 +8,7 @@ const test = suite.test.bind(suite) test('executing query', function () { test('queing query', function () { test('when connection is ready', function () { - var client = helper.client() + const client = helper.client() assert.empty(client.connection.queries) client.connection.emit('readyForQuery') client.query('yes') @@ -17,7 +17,7 @@ test('executing query', function () { }) test('when connection is not ready', function () { - var client = helper.client() + const client = helper.client() test('query is not sent', function () { client.query('boom') @@ -32,9 +32,9 @@ test('executing query', function () { }) test('multiple in the queue', function () { - var client = helper.client() - var connection = client.connection - var queries = connection.queries + const client = helper.client() + const connection = client.connection + const queries = connection.queries client.query('one') client.query('two') client.query('three') @@ -64,9 +64,9 @@ test('executing query', function () { }) test('query event binding and flow', function () { - var client = helper.client() - var con = client.connection - var query = client.query(new Query('whatever')) + const client = helper.client() + const con = client.connection + const query = client.query(new Query('whatever')) test('has no queries sent before ready', function () { assert.empty(con.queries) @@ -79,7 +79,7 @@ test('executing query', function () { }) test('handles rowDescription message', function () { - var handled = con.emit('rowDescription', { + const handled = con.emit('rowDescription', { fields: [ { name: 'boom', @@ -94,14 +94,14 @@ test('executing query', function () { assert.equal(row['boom'], 'hi') }) - var handled = con.emit('dataRow', { fields: ['hi'] }) + const handled = con.emit('dataRow', { fields: ['hi'] }) assert.ok(handled, 'should have handled first data row message') assert.emits(query, 'row', function (row) { assert.equal(row['boom'], 'bye') }) - var handledAgain = con.emit('dataRow', { fields: ['bye'] }) + const handledAgain = con.emit('dataRow', { fields: ['bye'] }) assert.ok(handledAgain, 'should have handled seciond data row message') }) @@ -119,7 +119,7 @@ test('executing query', function () { }) test('handles errors', function () { - var client = helper.client() + const client = helper.client() test('throws an error when config is null', function () { try { diff --git a/packages/pg/test/unit/client/stream-and-query-error-interaction-tests.js b/packages/pg/test/unit/client/stream-and-query-error-interaction-tests.js index 6f0da6142..8a5e4656c 100644 --- a/packages/pg/test/unit/client/stream-and-query-error-interaction-tests.js +++ b/packages/pg/test/unit/client/stream-and-query-error-interaction-tests.js @@ -1,12 +1,12 @@ 'use strict' const helper = require('./test-helper') -var Connection = require('../../../lib/connection') -var Client = require('../../../lib/client') +const Connection = require('../../../lib/connection') +const Client = require('../../../lib/client') const assert = require('assert') const suite = new helper.Suite() suite.test('emits end when not in query', function () { - var stream = new (require('events').EventEmitter)() + const stream = new (require('events').EventEmitter)() stream.setNoDelay = () => {} stream.connect = function () { // NOOP @@ -15,7 +15,7 @@ suite.test('emits end when not in query', function () { // NOOP } - var client = new Client({ connection: new Connection({ stream: stream }) }) + const client = new Client({ connection: new Connection({ stream: stream }) }) client.connect( assert.calls(function () { client.query( diff --git a/packages/pg/test/unit/client/test-helper.js b/packages/pg/test/unit/client/test-helper.js index 1a89a59f5..3e8f75c31 100644 --- a/packages/pg/test/unit/client/test-helper.js +++ b/packages/pg/test/unit/client/test-helper.js @@ -1,17 +1,17 @@ 'use strict' -var helper = require('../test-helper') -var Connection = require('../../../lib/connection') +const helper = require('../test-helper') +const Connection = require('../../../lib/connection') const { Client } = helper -var makeClient = function () { - var connection = new Connection({ stream: 'no' }) +const makeClient = function () { + const connection = new Connection({ stream: 'no' }) connection.startup = function () {} connection.connect = function () {} connection.query = function (text) { this.queries.push(text) } connection.queries = [] - var client = new Client({ connection: connection }) + const client = new Client({ connection: connection }) client.connect() client.connection.emit('connect') return client diff --git a/packages/pg/test/unit/client/throw-in-type-parser-tests.js b/packages/pg/test/unit/client/throw-in-type-parser-tests.js index cf1a35364..2428a121b 100644 --- a/packages/pg/test/unit/client/throw-in-type-parser-tests.js +++ b/packages/pg/test/unit/client/throw-in-type-parser-tests.js @@ -1,12 +1,12 @@ 'use strict' -var helper = require('./test-helper') -var Query = require('../../../lib/query') -var types = require('pg-types') +const helper = require('./test-helper') +const Query = require('../../../lib/query') +const types = require('pg-types') const assert = require('assert') const suite = new helper.Suite() -var typeParserError = new Error('TEST: Throw in type parsers') +const typeParserError = new Error('TEST: Throw in type parsers') types.setTypeParser('special oid that will throw', function () { throw typeParserError @@ -33,9 +33,9 @@ const emitFakeEvents = (con) => { } suite.test('emits error', function (done) { - var client = helper.client() - var con = client.connection - var query = client.query(new Query('whatever')) + const client = helper.client() + const con = client.connection + const query = client.query(new Query('whatever')) emitFakeEvents(con) assert.emits(query, 'error', function (err) { @@ -45,8 +45,8 @@ suite.test('emits error', function (done) { }) suite.test('calls callback with error', function (done) { - var client = helper.client() - var con = client.connection + const client = helper.client() + const con = client.connection emitFakeEvents(con) client.query('whatever', function (err) { assert.equal(err, typeParserError) @@ -55,8 +55,8 @@ suite.test('calls callback with error', function (done) { }) suite.test('rejects promise with error', function (done) { - var client = helper.client() - var con = client.connection + const client = helper.client() + const con = client.connection emitFakeEvents(con) client.query('whatever').catch((err) => { assert.equal(err, typeParserError) diff --git a/packages/pg/test/unit/connection-parameters/creation-tests.js b/packages/pg/test/unit/connection-parameters/creation-tests.js index 5225b9773..158f1dbeb 100644 --- a/packages/pg/test/unit/connection-parameters/creation-tests.js +++ b/packages/pg/test/unit/connection-parameters/creation-tests.js @@ -6,7 +6,7 @@ const defaults = require('../../../lib').defaults const dns = require('dns') // clear process.env -for (var key in process.env) { +for (const key in process.env) { delete process.env[key] } @@ -18,7 +18,7 @@ suite.test('ConnectionParameters construction', function () { assert.ok(new ConnectionParameters('postgres://localhost/postgres'), 'with connection string') }) -var compare = function (actual, expected, type) { +const compare = function (actual, expected, type) { const expectedDatabase = expected.database === undefined ? expected.user : expected.database assert.equal(actual.user, expected.user, type + ' user') @@ -38,13 +38,13 @@ var compare = function (actual, expected, type) { } suite.test('ConnectionParameters initializing from defaults', function () { - var subject = new ConnectionParameters() + const subject = new ConnectionParameters() compare(subject, defaults, 'defaults') assert.ok(subject.isDomainSocket === false) }) suite.test('ConnectionParameters initializing from defaults with connectionString set', function () { - var config = { + const config = { user: 'brians-are-the-best', database: 'scoobysnacks', port: 7777, @@ -57,18 +57,18 @@ suite.test('ConnectionParameters initializing from defaults with connectionStrin options: '-c geqo=off', } - var original_value = defaults.connectionString + const original_value = defaults.connectionString // Just changing this here doesn't actually work because it's no longer in scope when viewed inside of // of ConnectionParameters() so we have to pass in the defaults explicitly to test it defaults.connectionString = 'postgres://brians-are-the-best:mypassword@foo.bar.net:7777/scoobysnacks?options=-c geqo=off' - var subject = new ConnectionParameters(defaults) + const subject = new ConnectionParameters(defaults) defaults.connectionString = original_value compare(subject, config, 'defaults-connectionString') }) suite.test('ConnectionParameters initializing from config', function () { - var config = { + const config = { user: 'brian', database: 'home', port: 7777, @@ -84,23 +84,23 @@ suite.test('ConnectionParameters initializing from config', function () { idle_in_transaction_session_timeout: 15000, options: '-c geqo=off', } - var subject = new ConnectionParameters(config) + const subject = new ConnectionParameters(config) compare(subject, config, 'config') assert.ok(subject.isDomainSocket === false) }) suite.test('ConnectionParameters initializing from config and config.connectionString', function () { - var subject1 = new ConnectionParameters({ + const subject1 = new ConnectionParameters({ connectionString: 'postgres://test@host/db', }) - var subject2 = new ConnectionParameters({ + const subject2 = new ConnectionParameters({ connectionString: 'postgres://test@host/db?ssl=1', }) - var subject3 = new ConnectionParameters({ + const subject3 = new ConnectionParameters({ connectionString: 'postgres://test@host/db', ssl: true, }) - var subject4 = new ConnectionParameters({ + const subject4 = new ConnectionParameters({ connectionString: 'postgres://test@host/db?ssl=1', ssl: false, }) @@ -112,31 +112,31 @@ suite.test('ConnectionParameters initializing from config and config.connectionS }) suite.test('escape spaces if present', function () { - var subject = new ConnectionParameters('postgres://localhost/post gres') + const subject = new ConnectionParameters('postgres://localhost/post gres') assert.equal(subject.database, 'post gres') }) suite.test('do not double escape spaces', function () { - var subject = new ConnectionParameters('postgres://localhost/post%20gres') + const subject = new ConnectionParameters('postgres://localhost/post%20gres') assert.equal(subject.database, 'post gres') }) suite.test('initializing with unix domain socket', function () { - var subject = new ConnectionParameters('/var/run/') + const subject = new ConnectionParameters('/var/run/') assert.ok(subject.isDomainSocket) assert.equal(subject.host, '/var/run/') assert.equal(subject.database, defaults.user) }) suite.test('initializing with unix domain socket and a specific database, the simple way', function () { - var subject = new ConnectionParameters('/var/run/ mydb') + const subject = new ConnectionParameters('/var/run/ mydb') assert.ok(subject.isDomainSocket) assert.equal(subject.host, '/var/run/') assert.equal(subject.database, 'mydb') }) suite.test('initializing with unix domain socket, the health way', function () { - var subject = new ConnectionParameters('socket:/some path/?db=my[db]&encoding=utf8') + const subject = new ConnectionParameters('socket:/some path/?db=my[db]&encoding=utf8') assert.ok(subject.isDomainSocket) assert.equal(subject.host, '/some path/') assert.equal(subject.database, 'my[db]', 'must to be escaped and unescaped trough "my%5Bdb%5D"') @@ -144,14 +144,14 @@ suite.test('initializing with unix domain socket, the health way', function () { }) suite.test('initializing with unix domain socket, the escaped health way', function () { - var subject = new ConnectionParameters('socket:/some%20path/?db=my%2Bdb&encoding=utf8') + const subject = new ConnectionParameters('socket:/some%20path/?db=my%2Bdb&encoding=utf8') assert.ok(subject.isDomainSocket) assert.equal(subject.host, '/some path/') assert.equal(subject.database, 'my+db') assert.equal(subject.client_encoding, 'utf8') }) -var checkForPart = function (array, part) { +const checkForPart = function (array, part) { assert.ok(array.indexOf(part) > -1, array.join(' ') + ' did not contain ' + part) } @@ -164,19 +164,19 @@ const getDNSHost = async function (host) { } suite.testAsync('builds simple string', async function () { - var config = { + const config = { user: 'brian', password: 'xyz', host: 'localhost', port: 888, database: 'bam', } - var subject = new ConnectionParameters(config) + const subject = new ConnectionParameters(config) const dnsHost = await getDNSHost(config.host) return new Promise((resolve) => { subject.getLibpqConnectionString(function (err, constring) { assert(!err) - var parts = constring.split(' ') + const parts = constring.split(' ') checkForPart(parts, "user='brian'") checkForPart(parts, "password='xyz'") checkForPart(parts, `hostaddr='${dnsHost}'`) @@ -188,18 +188,18 @@ suite.testAsync('builds simple string', async function () { }) suite.test('builds dns string', async function () { - var config = { + const config = { user: 'brian', password: 'asdf', host: 'localhost', port: 5432, } - var subject = new ConnectionParameters(config) + const subject = new ConnectionParameters(config) const dnsHost = await getDNSHost(config.host) return new Promise((resolve) => { subject.getLibpqConnectionString(function (err, constring) { assert(!err) - var parts = constring.split(' ') + const parts = constring.split(' ') checkForPart(parts, "user='brian'") checkForPart(parts, `hostaddr='${dnsHost}'`) resolve() @@ -208,13 +208,13 @@ suite.test('builds dns string', async function () { }) suite.test('error when dns fails', function () { - var config = { + const config = { user: 'brian', password: 'asf', host: 'asdlfkjasldfkksfd#!$!!!!..com', port: 5432, } - var subject = new ConnectionParameters(config) + const subject = new ConnectionParameters(config) subject.getLibpqConnectionString( assert.calls(function (err, constring) { assert.ok(err) @@ -224,17 +224,17 @@ suite.test('error when dns fails', function () { }) suite.test('connecting to unix domain socket', function () { - var config = { + const config = { user: 'brian', password: 'asf', host: '/tmp/', port: 5432, } - var subject = new ConnectionParameters(config) + const subject = new ConnectionParameters(config) subject.getLibpqConnectionString( assert.calls(function (err, constring) { assert(!err) - var parts = constring.split(' ') + const parts = constring.split(' ') checkForPart(parts, "user='brian'") checkForPart(parts, "host='/tmp/'") }) @@ -242,17 +242,17 @@ suite.test('connecting to unix domain socket', function () { }) suite.test('config contains quotes and backslashes', function () { - var config = { + const config = { user: 'not\\brian', password: "bad'chars", host: '/tmp/', port: 5432, } - var subject = new ConnectionParameters(config) + const subject = new ConnectionParameters(config) subject.getLibpqConnectionString( assert.calls(function (err, constring) { assert(!err) - var parts = constring.split(' ') + const parts = constring.split(' ') checkForPart(parts, "user='not\\\\brian'") checkForPart(parts, "password='bad\\'chars'") }) @@ -260,28 +260,28 @@ suite.test('config contains quotes and backslashes', function () { }) suite.test('encoding can be specified by config', function () { - var config = { + const config = { client_encoding: 'utf-8', } - var subject = new ConnectionParameters(config) + const subject = new ConnectionParameters(config) subject.getLibpqConnectionString( assert.calls(function (err, constring) { assert(!err) - var parts = constring.split(' ') + const parts = constring.split(' ') checkForPart(parts, "client_encoding='utf-8'") }) ) }) suite.test('password contains < and/or > characters', function () { - var sourceConfig = { + const sourceConfig = { user: 'brian', password: 'helloe', host: 'localhost', port: 5432, database: 'postgres', } - var connectionString = + const connectionString = 'postgres://' + sourceConfig.user + ':' + @@ -292,15 +292,15 @@ suite.test('password contains < and/or > characters', function () { sourceConfig.port + '/' + sourceConfig.database - var subject = new ConnectionParameters(connectionString) + const subject = new ConnectionParameters(connectionString) assert.equal(subject.password, sourceConfig.password) }) suite.test('username or password contains weird characters', function () { - var defaults = require('../../../lib/defaults') + const defaults = require('../../../lib/defaults') defaults.ssl = true - var strang = 'pg://my f%irst name:is&%awesome!@localhost:9000' - var subject = new ConnectionParameters(strang) + const strang = 'pg://my f%irst name:is&%awesome!@localhost:9000' + const subject = new ConnectionParameters(strang) assert.equal(subject.user, 'my f%irst name') assert.equal(subject.password, 'is&%awesome!') assert.equal(subject.host, 'localhost') @@ -308,8 +308,8 @@ suite.test('username or password contains weird characters', function () { }) suite.test('url is properly encoded', function () { - var encoded = 'pg://bi%25na%25%25ry%20:s%40f%23@localhost/%20u%2520rl' - var subject = new ConnectionParameters(encoded) + const encoded = 'pg://bi%25na%25%25ry%20:s%40f%23@localhost/%20u%2520rl' + const subject = new ConnectionParameters(encoded) assert.equal(subject.user, 'bi%na%%ry ') assert.equal(subject.password, 's@f#') assert.equal(subject.host, 'localhost') @@ -317,10 +317,10 @@ suite.test('url is properly encoded', function () { }) suite.test('ssl is set on client', function () { - var Client = require('../../../lib/client') - var defaults = require('../../../lib/defaults') + const Client = require('../../../lib/client') + const defaults = require('../../../lib/defaults') defaults.ssl = true - var c = new Client('postgres://user:password@host/database') + const c = new Client('postgres://user:password@host/database') assert(c.ssl, 'Client should have ssl enabled via defaults') }) @@ -330,7 +330,7 @@ suite.test('coercing string "true" to boolean', function () { }) suite.test('ssl is set on client', function () { - var sourceConfig = { + const sourceConfig = { user: 'brian', password: 'helloe', host: 'localhost', @@ -344,9 +344,9 @@ suite.test('ssl is set on client', function () { sslrootcert: '/path/root.crt', }, } - var defaults = require('../../../lib/defaults') + const defaults = require('../../../lib/defaults') defaults.ssl = true - var c = new ConnectionParameters(sourceConfig) + const c = new ConnectionParameters(sourceConfig) c.getLibpqConnectionString( assert.calls(function (err, pgCString) { assert(!err) diff --git a/packages/pg/test/unit/connection-parameters/environment-variable-tests.js b/packages/pg/test/unit/connection-parameters/environment-variable-tests.js index e4e08ebd5..068814365 100644 --- a/packages/pg/test/unit/connection-parameters/environment-variable-tests.js +++ b/packages/pg/test/unit/connection-parameters/environment-variable-tests.js @@ -1,13 +1,13 @@ 'use strict' const Suite = require('../../suite') -var assert = require('assert') -var ConnectionParameters = require('../../../lib/connection-parameters') -var defaults = require('../../../lib').defaults +const assert = require('assert') +const ConnectionParameters = require('../../../lib/connection-parameters') +const defaults = require('../../../lib').defaults // clear process.env -var realEnv = {} -for (var key in process.env) { +const realEnv = {} +for (const key in process.env) { realEnv[key] = process.env[key] delete process.env[key] } @@ -16,7 +16,7 @@ const suite = new Suite('ConnectionParameters') const clearEnv = () => { // clear process.env - for (var key in process.env) { + for (const key in process.env) { delete process.env[key] } } @@ -29,7 +29,7 @@ suite.test('ConnectionParameters initialized from environment variables', functi process.env['PGDATABASE'] = 'allyerbase' process.env['PGPASSWORD'] = 'open' - var subject = new ConnectionParameters() + const subject = new ConnectionParameters() assert.equal(subject.host, 'local', 'env host') assert.equal(subject.user, 'bmc2', 'env user') assert.equal(subject.port, 7890, 'env port') @@ -46,7 +46,7 @@ suite.test('ConnectionParameters initialized from mix', function () { process.env['PGPASSWORD'] = 'open' delete process.env['PGPASSWORD'] delete process.env['PGDATABASE'] - var subject = new ConnectionParameters({ + const subject = new ConnectionParameters({ user: 'testing', database: 'zugzug', }) @@ -59,8 +59,8 @@ suite.test('ConnectionParameters initialized from mix', function () { suite.test('connection string parsing', function () { clearEnv() - var string = 'postgres://brian:pw@boom:381/lala' - var subject = new ConnectionParameters(string) + const string = 'postgres://brian:pw@boom:381/lala' + const subject = new ConnectionParameters(string) assert.equal(subject.host, 'boom', 'string host') assert.equal(subject.user, 'brian', 'string user') assert.equal(subject.password, 'pw', 'string password') @@ -72,8 +72,8 @@ suite.test('connection string parsing - ssl', function () { // clear process.env clearEnv() - var string = 'postgres://brian:pw@boom:381/lala?ssl=true' - var subject = new ConnectionParameters(string) + let string = 'postgres://brian:pw@boom:381/lala?ssl=true' + let subject = new ConnectionParameters(string) assert.equal(subject.ssl, true, 'ssl') string = 'postgres://brian:pw@boom:381/lala?ssl=1' @@ -99,15 +99,15 @@ suite.test('connection string parsing - ssl', function () { suite.test('ssl is false by default', function () { clearEnv() - var subject = new ConnectionParameters() + const subject = new ConnectionParameters() assert.equal(subject.ssl, false) }) -var testVal = function (mode, expected) { +const testVal = function (mode, expected) { suite.test('ssl is ' + expected + ' when $PGSSLMODE=' + mode, function () { clearEnv() process.env.PGSSLMODE = mode - var subject = new ConnectionParameters() + const subject = new ConnectionParameters() assert.deepStrictEqual(subject.ssl, expected) }) } @@ -122,6 +122,6 @@ testVal('verify-full', true) testVal('no-verify', { rejectUnauthorized: false }) // restore process.env -for (var key in realEnv) { +for (const key in realEnv) { process.env[key] = realEnv[key] } diff --git a/packages/pg/test/unit/connection/error-tests.js b/packages/pg/test/unit/connection/error-tests.js index b7496aba9..2171a25b6 100644 --- a/packages/pg/test/unit/connection/error-tests.js +++ b/packages/pg/test/unit/connection/error-tests.js @@ -1,14 +1,14 @@ 'use strict' -var helper = require('./test-helper') -var Connection = require('../../../lib/connection') -var net = require('net') +const helper = require('./test-helper') +const Connection = require('../../../lib/connection') +const net = require('net') const assert = require('assert') const suite = new helper.Suite() const { MemoryStream } = helper suite.test('connection emits stream errors', function (done) { - var con = new Connection({ stream: new MemoryStream() }) + const con = new Connection({ stream: new MemoryStream() }) assert.emits(con, 'error', function (err) { assert.equal(err.message, 'OMG!') done() @@ -18,28 +18,28 @@ suite.test('connection emits stream errors', function (done) { }) suite.test('connection emits ECONNRESET errors during normal operation', function (done) { - var con = new Connection({ stream: new MemoryStream() }) + const con = new Connection({ stream: new MemoryStream() }) con.connect() assert.emits(con, 'error', function (err) { assert.equal(err.code, 'ECONNRESET') done() }) - var e = new Error('Connection Reset') + const e = new Error('Connection Reset') e.code = 'ECONNRESET' con.stream.emit('error', e) }) suite.test('connection does not emit ECONNRESET errors during disconnect', function (done) { - var con = new Connection({ stream: new MemoryStream() }) + const con = new Connection({ stream: new MemoryStream() }) con.connect() - var e = new Error('Connection Reset') + const e = new Error('Connection Reset') e.code = 'ECONNRESET' con.end() con.stream.emit('error', e) done() }) -var SSLNegotiationPacketTests = [ +const SSLNegotiationPacketTests = [ { testName: 'connection does not emit ECONNRESET errors during disconnect also when using SSL', errorMessage: null, @@ -63,8 +63,8 @@ var SSLNegotiationPacketTests = [ for (const tc of SSLNegotiationPacketTests) { suite.test(tc.testName, function (done) { // our fake postgres server - var socket - var server = net.createServer(function (c) { + let socket + const server = net.createServer(function (c) { socket = c c.once('data', function (data) { c.write(Buffer.from(tc.response)) @@ -72,7 +72,7 @@ for (const tc of SSLNegotiationPacketTests) { }) server.listen(7778, function () { - var con = new Connection({ ssl: true }) + const con = new Connection({ ssl: true }) con.connect(7778, 'localhost') assert.emits(con, tc.responseType, function (err) { if (tc.errorMessage !== null || err) { diff --git a/packages/pg/test/unit/connection/startup-tests.js b/packages/pg/test/unit/connection/startup-tests.js index eaedfbad2..65cc0c0aa 100644 --- a/packages/pg/test/unit/connection/startup-tests.js +++ b/packages/pg/test/unit/connection/startup-tests.js @@ -1,31 +1,31 @@ 'use strict' const helper = require('./test-helper') const assert = require('assert') -var Connection = require('../../../lib/connection') +const Connection = require('../../../lib/connection') const suite = new helper.Suite() const test = suite.test.bind(suite) const { MemoryStream } = helper test('connection can take existing stream', function () { - var stream = new MemoryStream() - var con = new Connection({ stream: stream }) + const stream = new MemoryStream() + const con = new Connection({ stream: stream }) assert.equal(con.stream, stream) }) test('connection can take stream factory method', function () { - var stream = new MemoryStream() - var connectionOpts = {} - var makeStream = function (opts) { + const stream = new MemoryStream() + const connectionOpts = {} + const makeStream = function (opts) { assert.equal(connectionOpts, opts) return stream } connectionOpts.stream = makeStream - var con = new Connection(connectionOpts) + const con = new Connection(connectionOpts) assert.equal(con.stream, stream) }) test('using any stream', function () { - var makeStream = function () { - var stream = new MemoryStream() + const makeStream = function () { + const stream = new MemoryStream() stream.connect = function (port, host) { this.connectCalled = true this.port = port @@ -34,9 +34,9 @@ test('using any stream', function () { return stream } - var stream = makeStream() + const stream = makeStream() - var con = new Connection({ stream: stream }) + const con = new Connection({ stream: stream }) con.connect(1234, 'bang') @@ -53,7 +53,7 @@ test('using any stream', function () { }) test('after stream connects client emits connected event', function () { - var hit = false + let hit = false con.once('connect', function () { hit = true @@ -64,11 +64,11 @@ test('using any stream', function () { }) test('after stream emits connected event init TCP-keepalive', function () { - var stream = makeStream() - var con = new Connection({ stream: stream, keepAlive: true }) + const stream = makeStream() + const con = new Connection({ stream: stream, keepAlive: true }) con.connect(123, 'test') - var res = false + let res = false stream.setKeepAlive = function (bit) { res = bit diff --git a/packages/pg/test/unit/test-helper.js b/packages/pg/test/unit/test-helper.js index 757c986e7..618866920 100644 --- a/packages/pg/test/unit/test-helper.js +++ b/packages/pg/test/unit/test-helper.js @@ -1,8 +1,8 @@ 'use strict' -var EventEmitter = require('events').EventEmitter +const EventEmitter = require('events').EventEmitter -var helper = require('../test-helper') -var Connection = require('../../lib/connection') +const helper = require('../test-helper') +const Connection = require('../../lib/connection') const { Client } = helper const MemoryStream = function () { @@ -12,7 +12,7 @@ const MemoryStream = function () { helper.sys.inherits(MemoryStream, EventEmitter) -var p = MemoryStream.prototype +const p = MemoryStream.prototype p.connect = function () { // NOOP @@ -36,8 +36,8 @@ p.closed = false p.writable = true const createClient = function () { - var stream = new MemoryStream() - var client = new Client({ + const stream = new MemoryStream() + const client = new Client({ connection: new Connection({ stream: stream }), }) client.connect() diff --git a/packages/pg/test/unit/utils-tests.js b/packages/pg/test/unit/utils-tests.js index d514f5ad8..0e79e6265 100644 --- a/packages/pg/test/unit/utils-tests.js +++ b/packages/pg/test/unit/utils-tests.js @@ -1,21 +1,21 @@ 'use strict' -var helper = require('./test-helper') -var utils = require('./../../lib/utils') -var defaults = require('./../../lib').defaults +const helper = require('./test-helper') +const utils = require('./../../lib/utils') +const defaults = require('./../../lib').defaults const assert = require('assert') const suite = new helper.Suite() const test = suite.test.bind(suite) test('ensure types is exported on root object', function () { - var pg = require('../../lib') + const pg = require('../../lib') assert(pg.types) assert(pg.types.getTypeParser) assert(pg.types.setTypeParser) }) test('normalizing query configs', function () { - var config - var callback = function () {} + let config + const callback = function () {} config = utils.normalizeQueryConfig({ text: 'TEXT' }) assert.same(config, { text: 'TEXT' }) @@ -34,14 +34,14 @@ test('normalizing query configs', function () { }) test('prepareValues: buffer prepared properly', function () { - var buf = Buffer.from('quack') - var out = utils.prepareValue(buf) + const buf = Buffer.from('quack') + const out = utils.prepareValue(buf) assert.strictEqual(buf, out) }) test('prepareValues: Uint8Array prepared properly', function () { - var buf = new Uint8Array([1, 2, 3]).subarray(1, 2) - var out = utils.prepareValue(buf) + const buf = new Uint8Array([1, 2, 3]).subarray(1, 2) + const out = utils.prepareValue(buf) assert.ok(Buffer.isBuffer(out)) assert.equal(out.length, 1) assert.deepEqual(out[0], 2) @@ -50,8 +50,8 @@ test('prepareValues: Uint8Array prepared properly', function () { test('prepareValues: date prepared properly', function () { helper.setTimezoneOffset(-330) - var date = new Date(2014, 1, 1, 11, 11, 1, 7) - var out = utils.prepareValue(date) + const date = new Date(2014, 1, 1, 11, 11, 1, 7) + const out = utils.prepareValue(date) assert.strictEqual(out, '2014-02-01T11:11:01.007+05:30') helper.resetTimezoneOffset() @@ -61,8 +61,8 @@ test('prepareValues: date prepared properly as UTC', function () { defaults.parseInputDatesAsUTC = true // make a date in the local timezone that represents a specific UTC point in time - var date = new Date(Date.UTC(2014, 1, 1, 11, 11, 1, 7)) - var out = utils.prepareValue(date) + const date = new Date(Date.UTC(2014, 1, 1, 11, 11, 1, 7)) + const out = utils.prepareValue(date) assert.strictEqual(out, '2014-02-01T11:11:01.007+00:00') defaults.parseInputDatesAsUTC = false @@ -71,8 +71,8 @@ test('prepareValues: date prepared properly as UTC', function () { test('prepareValues: BC date prepared properly', function () { helper.setTimezoneOffset(-330) - var date = new Date(-3245, 1, 1, 11, 11, 1, 7) - var out = utils.prepareValue(date) + const date = new Date(-3245, 1, 1, 11, 11, 1, 7) + const out = utils.prepareValue(date) assert.strictEqual(out, '3246-02-01T11:11:01.007+05:30 BC') helper.resetTimezoneOffset() @@ -82,104 +82,104 @@ test('prepareValues: 1 BC date prepared properly', function () { helper.setTimezoneOffset(-330) // can't use the multi-argument constructor as year 0 would be interpreted as 1900 - var date = new Date('0000-02-01T11:11:01.007') - var out = utils.prepareValue(date) + const date = new Date('0000-02-01T11:11:01.007') + const out = utils.prepareValue(date) assert.strictEqual(out, '0001-02-01T11:11:01.007+05:30 BC') helper.resetTimezoneOffset() }) test('prepareValues: undefined prepared properly', function () { - var out = utils.prepareValue(void 0) + const out = utils.prepareValue(void 0) assert.strictEqual(out, null) }) test('prepareValue: null prepared properly', function () { - var out = utils.prepareValue(null) + const out = utils.prepareValue(null) assert.strictEqual(out, null) }) test('prepareValue: true prepared properly', function () { - var out = utils.prepareValue(true) + const out = utils.prepareValue(true) assert.strictEqual(out, 'true') }) test('prepareValue: false prepared properly', function () { - var out = utils.prepareValue(false) + const out = utils.prepareValue(false) assert.strictEqual(out, 'false') }) test('prepareValue: number prepared properly', function () { - var out = utils.prepareValue(3.042) + const out = utils.prepareValue(3.042) assert.strictEqual(out, '3.042') }) test('prepareValue: string prepared properly', function () { - var out = utils.prepareValue('big bad wolf') + const out = utils.prepareValue('big bad wolf') assert.strictEqual(out, 'big bad wolf') }) test('prepareValue: simple array prepared properly', function () { - var out = utils.prepareValue([1, null, 3, undefined, [5, 6, 'squ,awk']]) + const out = utils.prepareValue([1, null, 3, undefined, [5, 6, 'squ,awk']]) assert.strictEqual(out, '{"1",NULL,"3",NULL,{"5","6","squ,awk"}}') }) test('prepareValue: complex array prepared properly', function () { - var out = utils.prepareValue([{ x: 42 }, { y: 84 }]) + const out = utils.prepareValue([{ x: 42 }, { y: 84 }]) assert.strictEqual(out, '{"{\\"x\\":42}","{\\"y\\":84}"}') }) test('prepareValue: date array prepared properly', function () { helper.setTimezoneOffset(-330) - var date = new Date(2014, 1, 1, 11, 11, 1, 7) - var out = utils.prepareValue([date]) + const date = new Date(2014, 1, 1, 11, 11, 1, 7) + const out = utils.prepareValue([date]) assert.strictEqual(out, '{"2014-02-01T11:11:01.007+05:30"}') helper.resetTimezoneOffset() }) test('prepareValue: arbitrary objects prepared properly', function () { - var out = utils.prepareValue({ x: 42 }) + const out = utils.prepareValue({ x: 42 }) assert.strictEqual(out, '{"x":42}') }) test('prepareValue: objects with simple toPostgres prepared properly', function () { - var customType = { + const customType = { toPostgres: function () { return 'zomgcustom!' }, } - var out = utils.prepareValue(customType) + const out = utils.prepareValue(customType) assert.strictEqual(out, 'zomgcustom!') }) test('prepareValue: buffer array prepared properly', function () { - var buffer1 = Buffer.from('dead', 'hex') - var buffer2 = Buffer.from('beef', 'hex') - var out = utils.prepareValue([buffer1, buffer2]) + const buffer1 = Buffer.from('dead', 'hex') + const buffer2 = Buffer.from('beef', 'hex') + const out = utils.prepareValue([buffer1, buffer2]) assert.strictEqual(out, '{\\\\xdead,\\\\xbeef}') }) test('prepareValue: Uint8Array array prepared properly', function () { - var buffer1 = Uint8Array.from(Buffer.from('dead', 'hex')) - var buffer2 = Uint8Array.from(Buffer.from('beef', 'hex')) - var out = utils.prepareValue([buffer1, buffer2]) + const buffer1 = Uint8Array.from(Buffer.from('dead', 'hex')) + const buffer2 = Uint8Array.from(Buffer.from('beef', 'hex')) + const out = utils.prepareValue([buffer1, buffer2]) assert.strictEqual(out, '{\\\\xdead,\\\\xbeef}') }) test('prepareValue: objects with complex toPostgres prepared properly', function () { - var customType = { + const customType = { toPostgres: function () { return [1, 2] }, } - var out = utils.prepareValue(customType) + const out = utils.prepareValue(customType) assert.strictEqual(out, '{"1","2"}') }) test('prepareValue: objects with toPostgres receive prepareValue', function () { - var customRange = { + const customRange = { lower: { toPostgres: function () { return 5 @@ -194,12 +194,12 @@ test('prepareValue: objects with toPostgres receive prepareValue', function () { return '[' + prepare(this.lower) + ',' + prepare(this.upper) + ']' }, } - var out = utils.prepareValue(customRange) + const out = utils.prepareValue(customRange) assert.strictEqual(out, '[5,10]') }) test('prepareValue: objects with circular toPostgres rejected', function () { - var customType = { + const customType = { toPostgres: function () { return { toPostgres: function () { @@ -221,19 +221,19 @@ test('prepareValue: objects with circular toPostgres rejected', function () { }) test('prepareValue: can safely be used to map an array of values including those with toPostgres functions', function () { - var customType = { + const customType = { toPostgres: function () { return 'zomgcustom!' }, } - var values = [1, 'test', customType] - var out = values.map(utils.prepareValue) + const values = [1, 'test', customType] + const out = values.map(utils.prepareValue) assert.deepEqual(out, [1, 'test', 'zomgcustom!']) }) -var testEscapeLiteral = function (testName, input, expected) { +const testEscapeLiteral = function (testName, input, expected) { test(testName, function () { - var actual = utils.escapeLiteral(input) + const actual = utils.escapeLiteral(input) assert.equal(expected, actual) }) } @@ -265,9 +265,9 @@ testEscapeLiteral( " E'hello \\\\ '' \" world'" ) -var testEscapeIdentifier = function (testName, input, expected) { +const testEscapeIdentifier = function (testName, input, expected) { test(testName, function () { - var actual = utils.escapeIdentifier(input) + const actual = utils.escapeIdentifier(input) assert.equal(expected, actual) }) } diff --git a/packages/pg/test/worker/src/index.test.js b/packages/pg/test/worker/src/index.test.js index 2bfe50c2a..637c5aec4 100644 --- a/packages/pg/test/worker/src/index.test.js +++ b/packages/pg/test/worker/src/index.test.js @@ -1,11 +1,11 @@ if (parseInt(process.versions.node.split('.')[0]) < 20) { process.exit(0) } -var helper = require('../../test-helper') +const helper = require('../../test-helper') const path = require('path') const { unstable_dev } = require('wrangler') -var suite = new helper.Suite() +const suite = new helper.Suite() const assert = require('assert') suite.testAsync('Can run in Cloudflare Worker?', test()) diff --git a/packages/pg/test/worker/src/index.ts b/packages/pg/test/worker/src/index.ts index 61597c3c2..64f1fd322 100644 --- a/packages/pg/test/worker/src/index.ts +++ b/packages/pg/test/worker/src/index.ts @@ -14,7 +14,7 @@ export default { const params = url.searchParams const ssl = params.has('ssl') - var client = new Client({ + const client = new Client({ user: env.PGUSER || env.USER, password: env.PGPASSWORD, ssl,