From 156c850a0d66e5b4a5812360717b841b76fb0044 Mon Sep 17 00:00:00 2001 From: Vitaly Tomilov Date: Fri, 17 Mar 2023 19:03:11 +0000 Subject: [PATCH] refactor string styles --- .eslintrc.json | 2 +- lib/assert.js | 2 +- lib/connect.js | 34 +- lib/database-pool.js | 10 +- lib/database.js | 74 +- lib/errors/index.js | 8 +- lib/errors/parameterized-query-error.js | 24 +- lib/errors/prepared-statement-error.js | 26 +- lib/errors/query-file-error.js | 20 +- lib/errors/query-result-error.js | 26 +- lib/events.js | 34 +- lib/formatting.js | 138 +-- lib/helpers/column-set.js | 58 +- lib/helpers/column.js | 78 +- lib/helpers/index.js | 8 +- lib/helpers/methods/concat.js | 18 +- lib/helpers/methods/index.js | 10 +- lib/helpers/methods/insert.js | 30 +- lib/helpers/methods/sets.js | 10 +- lib/helpers/methods/update.js | 44 +- lib/helpers/methods/values.js | 20 +- lib/helpers/table-name.js | 14 +- lib/index.js | 6 +- lib/inner-state.js | 6 +- lib/main.js | 64 +- lib/patterns.js | 2 +- lib/promise-adapter.js | 24 +- lib/promise-parser.js | 14 +- lib/query-file.js | 42 +- lib/query.js | 38 +- lib/stream.js | 22 +- lib/task.js | 50 +- lib/text.js | 34 +- lib/tx-mode.js | 28 +- lib/types/index.js | 6 +- lib/types/parameterized-query.js | 32 +- lib/types/prepared-statement.js | 36 +- lib/types/server-formatting.js | 6 +- lib/utils/color.js | 2 +- lib/utils/index.js | 40 +- lib/utils/public.js | 52 +- test/adapter.spec.js | 40 +- test/color.spec.js | 56 +- test/db.spec.js | 1045 +++++++++--------- test/db/capture.js | 4 +- test/db/header.js | 16 +- test/db/init.js | 50 +- test/db/tools.js | 2 +- test/entry.spec.js | 84 +- test/event.spec.js | 250 ++--- test/file.spec.js | 126 +-- test/format.spec.js | 1310 +++++++++++------------ test/generator.spec.js | 14 +- test/help.spec.js | 870 +++++++-------- test/parameterized.spec.js | 138 +-- test/prepared.spec.js | 180 ++-- test/protocol.spec.js | 360 +++---- test/stream.spec.js | 74 +- test/tx-mode.spec.js | 98 +- test/typescript.spec.js | 12 +- test/utils.spec.js | 264 ++--- 61 files changed, 3070 insertions(+), 3115 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index 6ab6199be..0f783fac1 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -33,7 +33,7 @@ ], "quotes": [ "error", - "backtick" + "single" ], "semi": [ "error", diff --git a/lib/assert.js b/lib/assert.js index d7fbf56e8..8aed5ac61 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -1,4 +1,4 @@ -const {assertOptions} = require(`assert-options`); +const {assertOptions} = require('assert-options'); // this to allow override options-related errors globally (for pg-promise) global.pgPromiseAssert = assertOptions; diff --git a/lib/connect.js b/lib/connect.js index b29922773..74ca0c425 100644 --- a/lib/connect.js +++ b/lib/connect.js @@ -7,13 +7,13 @@ * Removal or modification of this copyright notice is prohibited. */ -const {Events} = require(`./events`); -const {ColorConsole} = require(`./utils/color`); +const {Events} = require('./events'); +const {ColorConsole} = require('./utils/color'); const npm = { - utils: require(`./utils`), - text: require(`./text`), - formatting: require(`./formatting`) + utils: require('./utils'), + text: require('./text'), + formatting: require('./formatting') }; function poolConnect(ctx, db, config) { @@ -36,7 +36,7 @@ function poolConnect(ctx, db, config) { }); reject(err); } else { - if (`$useCount` in client) { + if ('$useCount' in client) { // Make sure useCount drops to 1, if it ever reaches maximum integer number; // We do not drop it to zero, to avoid rerun of initialization queries that // usually check for useCount === 0; @@ -47,7 +47,7 @@ function poolConnect(ctx, db, config) { client.$useCount = ++client.$useCount; } } else { - Object.defineProperty(client, `$useCount`, { + Object.defineProperty(client, '$useCount', { value: 0, configurable: false, enumerable: false, @@ -57,7 +57,7 @@ function poolConnect(ctx, db, config) { } setCtx(client, ctx); const end = lockClientEnd(client); - client.on(`error`, onError); + client.on('error', onError); resolve({ client, useCount: client.$useCount, @@ -65,7 +65,7 @@ function poolConnect(ctx, db, config) { client.end = end; client.release(kill || client.$connectionError); Events.disconnect(ctx, client); - client.removeListener(`error`, onError); + client.removeListener('error', onError); } }); Events.connect(ctx, client, client.$useCount); @@ -88,7 +88,7 @@ function directConnect(ctx, config) { setSchema(client, ctx); setCtx(client, ctx); const end = lockClientEnd(client); - client.on(`error`, onError); + client.on('error', onError); resolve({ client, useCount: 0, @@ -96,7 +96,7 @@ function directConnect(ctx, config) { client.end = end; const p = config.promise((res, rej) => client.end().then(res).catch(rej)); Events.disconnect(ctx, client); - client.removeListener(`error`, onError); + client.removeListener('error', onError); return p; } }); @@ -113,7 +113,7 @@ function onError(err) { const ctx = this.$ctx; const cn = npm.utils.getSafeConnection(ctx.cn); Events.error(ctx.options, err, {cn, dc: ctx.dc}); - if (ctx.cnOptions && typeof ctx.cnOptions.onLost === `function` && !ctx.notified) { + if (ctx.cnOptions && typeof ctx.cnOptions.onLost === 'function' && !ctx.notified) { try { ctx.cnOptions.onLost.call(this, err, { cn, @@ -143,7 +143,7 @@ function lockClientEnd(client) { } function setCtx(client, ctx) { - Object.defineProperty(client, `$ctx`, { + Object.defineProperty(client, '$ctx', { value: ctx, writable: true }); @@ -154,14 +154,14 @@ function setSchema(client, ctx) { if (!s) { return; } - if (typeof s === `function`) { + if (typeof s === 'function') { s = s.call(ctx.dc, ctx.dc); } if (Array.isArray(s)) { - s = s.filter(a => a && typeof a === `string`); + s = s.filter(a => a && typeof a === 'string'); } - if (typeof s === `string` || (Array.isArray(s) && s.length)) { - client.query(npm.formatting.as.format(`SET search_path TO $1:name`, [s]), err => { + if (typeof s === 'string' || (Array.isArray(s) && s.length)) { + client.query(npm.formatting.as.format('SET search_path TO $1:name', [s]), err => { // istanbul ignore if; if (err) { // This is unlikely to ever happen, unless the connection is created faulty, diff --git a/lib/database-pool.js b/lib/database-pool.js index 74a864841..004e91a04 100644 --- a/lib/database-pool.js +++ b/lib/database-pool.js @@ -7,10 +7,10 @@ * Removal or modification of this copyright notice is prohibited. */ -const {ColorConsole} = require(`./utils/color`); +const {ColorConsole} = require('./utils/color'); const npm = { - utils: require(`./utils`) + utils: require('./utils') }; /** @@ -26,7 +26,7 @@ class DatabasePool { * @returns {{dbMap: {}, dbs: Array}} */ static get instance() { - const s = Symbol.for(`pgPromiseDatabasePool`); + const s = Symbol.for('pgPromiseDatabasePool'); let scope = global[s]; if (!scope) { scope = { @@ -50,7 +50,7 @@ class DatabasePool { */ static register(db) { const cnKey = DatabasePool.createContextKey(db); - npm.utils.addReadProp(db, `$cnKey`, cnKey, true); + npm.utils.addReadProp(db, '$cnKey', cnKey, true); const {dbMap, dbs} = DatabasePool.instance; if (cnKey in dbMap) { dbMap[cnKey]++; @@ -101,7 +101,7 @@ class DatabasePool { */ static createContextKey(db) { let cn = db.$cn; - if (typeof cn === `object`) { + if (typeof cn === 'object') { const obj = {}, keys = Object.keys(cn).sort(); keys.forEach(name => { obj[name] = cn[name]; diff --git a/lib/database.js b/lib/database.js index 184ac3f56..e674e1efa 100644 --- a/lib/database.js +++ b/lib/database.js @@ -7,20 +7,20 @@ * Removal or modification of this copyright notice is prohibited. */ -const {Events} = require(`./events`); -const {assert} = require(`./assert`); -const {resultQuery, multiResultQuery, streamQuery} = require(`./special-query`); -const {ConnectionContext} = require(`./context`); -const {DatabasePool} = require(`./database-pool`); -const {queryResult} = require(`./query-result`); +const {Events} = require('./events'); +const {assert} = require('./assert'); +const {resultQuery, multiResultQuery, streamQuery} = require('./special-query'); +const {ConnectionContext} = require('./context'); +const {DatabasePool} = require('./database-pool'); +const {queryResult} = require('./query-result'); const npm = { - utils: require(`./utils`), - pubUtils: require(`./utils/public`), - connect: require(`./connect`), - query: require(`./query`), - task: require(`./task`), - text: require(`./text`) + utils: require('./utils'), + pubUtils: require('./utils/public'), + connect: require('./connect'), + query: require('./query'), + task: require('./task'), + text: require('./text') }; /** @@ -123,7 +123,7 @@ function Database(cn, dc, config) { const dbThis = this, $p = config.promise, - poolConnection = typeof cn === `string` ? {connectionString: cn} : cn, + poolConnection = typeof cn === 'string' ? {connectionString: cn} : cn, pool = new config.pgp.pg.Pool(poolConnection), endMethod = pool.end; @@ -135,7 +135,7 @@ function Database(cn, dc, config) { return res; }; - pool.on(`error`, onError); + pool.on('error', onError); /** * @method Database#connect @@ -373,7 +373,7 @@ function Database(cn, dc, config) { * // call either resolve(data) or reject(reason) here * }); */ - npm.utils.addReadProp(this, `$config`, config, true); + npm.utils.addReadProp(this, '$config', config, true); /** * @member {string|object} Database#$cn @@ -385,7 +385,7 @@ function Database(cn, dc, config) { * * @see Database */ - npm.utils.addReadProp(this, `$cn`, cn, true); + npm.utils.addReadProp(this, '$cn', cn, true); /** * @member {*} Database#$dc @@ -397,7 +397,7 @@ function Database(cn, dc, config) { * * @see Database */ - npm.utils.addReadProp(this, `$dc`, dc, true); + npm.utils.addReadProp(this, '$dc', dc, true); /** * @member {external:pg-pool} Database#$pool @@ -428,7 +428,7 @@ function Database(cn, dc, config) { * .finally(db.$pool.end); // shutting down the pool * */ - npm.utils.addReadProp(this, `$pool`, pool, true); + npm.utils.addReadProp(this, '$pool', pool, true); /** * @member {function} Database.$destroy @@ -437,13 +437,13 @@ function Database(cn, dc, config) { * @description * Permanently shuts down the database object. */ - npm.utils.addReadProp(this, `$destroy`, () => { + npm.utils.addReadProp(this, '$destroy', () => { if (!destroyed) { if (!pool.ending) { endMethod.call(pool); } DatabasePool.unregister(dbThis); - pool.removeListener(`error`, onError); + pool.removeListener('error', onError); destroyed = true; } }, true); @@ -458,7 +458,7 @@ function Database(cn, dc, config) { // Optional value-transformation helper: function transform(value, cb, thisArg) { - return typeof cb === `function` ? value.then(data => cb.call(thisArg, data)) : value; + return typeof cb === 'function' ? value.then(data => cb.call(thisArg, data)) : value; } //////////////////////////////////////////////////// @@ -981,7 +981,7 @@ function Database(cn, dc, config) { * {@link Database#proc proc} */ obj.func = function (funcName, values, qrm) { - return obj.query.call(this, {entity: funcName, type: `func`}, values, qrm); + return obj.query.call(this, {entity: funcName, type: 'func'}, values, qrm); }; /** @@ -1020,7 +1020,7 @@ function Database(cn, dc, config) { obj.proc = function (procName, values, cb, thisArg) { const v = obj.query.call(this, { entity: procName, - type: `proc` + type: 'proc' }, values, queryResult.one | queryResult.none); return transform(v, cb, thisArg); }; @@ -1289,7 +1289,7 @@ function Database(cn, dc, config) { */ obj.task = function () { const args = npm.pubUtils.taskArgs(arguments); - assert(args.options, [`tag`]); + assert(args.options, ['tag']); return taskProcessor.call(this, args, false); }; @@ -1347,11 +1347,11 @@ function Database(cn, dc, config) { */ obj.taskIf = function () { const args = npm.pubUtils.taskArgs(arguments); - assert(args.options, [`tag`, `cnd`]); + assert(args.options, ['tag', 'cnd']); try { let cnd = args.options.cnd; - if (`cnd` in args.options) { - cnd = typeof cnd === `function` ? cnd.call(obj, obj) : !!cnd; + if ('cnd' in args.options) { + cnd = typeof cnd === 'function' ? cnd.call(obj, obj) : !!cnd; } else { cnd = !obj.ctx; // create task, if it is the top level } @@ -1456,7 +1456,7 @@ function Database(cn, dc, config) { */ obj.tx = function () { const args = npm.pubUtils.taskArgs(arguments); - assert(args.options, [`tag`, `mode`]); + assert(args.options, ['tag', 'mode']); return taskProcessor.call(this, args, true); }; @@ -1529,18 +1529,18 @@ function Database(cn, dc, config) { */ obj.txIf = function () { const args = npm.pubUtils.taskArgs(arguments); - assert(args.options, [`tag`, `mode`, `cnd`, `reusable`]); + assert(args.options, ['tag', 'mode', 'cnd', 'reusable']); try { let cnd; - if (`cnd` in args.options) { + if ('cnd' in args.options) { cnd = args.options.cnd; - cnd = typeof cnd === `function` ? cnd.call(obj, obj) : !!cnd; + cnd = typeof cnd === 'function' ? cnd.call(obj, obj) : !!cnd; } else { cnd = !obj.ctx || !obj.ctx.inTransaction; } args.options.cnd = cnd; const reusable = args.options.reusable; - args.options.reusable = !cnd && obj.ctx && typeof reusable === `function` ? reusable.call(obj, obj) : !!reusable; + args.options.reusable = !cnd && obj.ctx && typeof reusable === 'function' ? reusable.call(obj, obj) : !!reusable; } catch (e) { return $p.reject(e); } @@ -1551,8 +1551,8 @@ function Database(cn, dc, config) { // Resolves with result from the callback function; function taskProcessor(params, isTX) { - if (typeof params.cb !== `function`) { - return $p.reject(new TypeError(`Callback function is required.`)); + if (typeof params.cb !== 'function') { + return $p.reject(new TypeError('Callback function is required.')); } if (params.options.reusable) { @@ -1577,7 +1577,7 @@ function Database(cn, dc, config) { if (taskCtx.db) { // reuse existing connection; - npm.utils.addReadProp(tsk.ctx, `useCount`, taskCtx.db.useCount); + npm.utils.addReadProp(tsk.ctx, 'useCount', taskCtx.db.useCount); addServerVersion(tsk.ctx, taskCtx.db.client); return config.$npm.task.execute(taskCtx, tsk, isTX, config); } @@ -1586,7 +1586,7 @@ function Database(cn, dc, config) { return config.$npm.connect.pool(taskCtx, dbThis) .then(db => { taskCtx.connect(db); - npm.utils.addReadProp(tsk.ctx, `useCount`, db.useCount); + npm.utils.addReadProp(tsk.ctx, 'useCount', db.useCount); addServerVersion(tsk.ctx, db.client); return config.$npm.task.execute(taskCtx, tsk, isTX, config); }) @@ -1604,7 +1604,7 @@ function Database(cn, dc, config) { // Exclude else-case from coverage, because it can only occur with Native Bindings. // istanbul ignore else if (client.serverVersion) { - npm.utils.addReadProp(target, `serverVersion`, client.serverVersion); + npm.utils.addReadProp(target, 'serverVersion', client.serverVersion); } } diff --git a/lib/errors/index.js b/lib/errors/index.js index 48253294b..a151b32b3 100644 --- a/lib/errors/index.js +++ b/lib/errors/index.js @@ -7,10 +7,10 @@ * Removal or modification of this copyright notice is prohibited. */ -const {QueryResultError, queryResultErrorCode} = require(`./query-result-error`); -const {PreparedStatementError} = require(`./prepared-statement-error`); -const {ParameterizedQueryError} = require(`./parameterized-query-error`); -const {QueryFileError} = require(`./query-file-error`); +const {QueryResultError, queryResultErrorCode} = require('./query-result-error'); +const {PreparedStatementError} = require('./prepared-statement-error'); +const {ParameterizedQueryError} = require('./parameterized-query-error'); +const {QueryFileError} = require('./query-file-error'); /** * @namespace errors diff --git a/lib/errors/parameterized-query-error.js b/lib/errors/parameterized-query-error.js index f51c8b507..29200f223 100644 --- a/lib/errors/parameterized-query-error.js +++ b/lib/errors/parameterized-query-error.js @@ -7,11 +7,11 @@ * Removal or modification of this copyright notice is prohibited. */ -const {QueryFileError} = require(`./query-file-error`); +const {QueryFileError} = require('./query-file-error'); const npm = { - os: require(`os`), - utils: require(`../utils`) + os: require('os'), + utils: require('../utils') }; /** @@ -45,7 +45,7 @@ const npm = { class ParameterizedQueryError extends Error { constructor(error, pq) { const isQueryFileError = error instanceof QueryFileError; - const message = isQueryFileError ? `Failed to initialize 'text' from a QueryFile.` : error; + const message = isQueryFileError ? 'Failed to initialize \'text\' from a QueryFile.' : error; super(message); this.name = this.constructor.name; if (isQueryFileError) { @@ -74,17 +74,17 @@ ParameterizedQueryError.prototype.toString = function (level) { gap1 = npm.utils.messageGap(level + 1), gap2 = npm.utils.messageGap(level + 2), lines = [ - `ParameterizedQueryError {`, - gap1 + `message: "` + this.message + `"`, - gap1 + `result: {`, - gap2 + `text: ` + npm.utils.toJson(this.result.text), - gap2 + `values: ` + npm.utils.toJson(this.result.values), - gap1 + `}` + 'ParameterizedQueryError {', + gap1 + 'message: "' + this.message + '"', + gap1 + 'result: {', + gap2 + 'text: ' + npm.utils.toJson(this.result.text), + gap2 + 'values: ' + npm.utils.toJson(this.result.values), + gap1 + '}' ]; if (this.error) { - lines.push(gap1 + `error: ` + this.error.toString(level + 1)); + lines.push(gap1 + 'error: ' + this.error.toString(level + 1)); } - lines.push(gap0 + `}`); + lines.push(gap0 + '}'); return lines.join(npm.os.EOL); }; diff --git a/lib/errors/prepared-statement-error.js b/lib/errors/prepared-statement-error.js index 9ce9333ef..2a4884301 100644 --- a/lib/errors/prepared-statement-error.js +++ b/lib/errors/prepared-statement-error.js @@ -7,11 +7,11 @@ * Removal or modification of this copyright notice is prohibited. */ -const {QueryFileError} = require(`./query-file-error`); +const {QueryFileError} = require('./query-file-error'); const npm = { - os: require(`os`), - utils: require(`../utils`) + os: require('os'), + utils: require('../utils') }; /** @@ -45,7 +45,7 @@ const npm = { class PreparedStatementError extends Error { constructor(error, ps) { const isQueryFileError = error instanceof QueryFileError; - const message = isQueryFileError ? `Failed to initialize 'text' from a QueryFile.` : error; + const message = isQueryFileError ? 'Failed to initialize \'text\' from a QueryFile.' : error; super(message); this.name = this.constructor.name; if (isQueryFileError) { @@ -74,18 +74,18 @@ PreparedStatementError.prototype.toString = function (level) { gap1 = npm.utils.messageGap(level + 1), gap2 = npm.utils.messageGap(level + 2), lines = [ - `PreparedStatementError {`, - gap1 + `message: "` + this.message + `"`, - gap1 + `result: {`, - gap2 + `name: ` + npm.utils.toJson(this.result.name), - gap2 + `text: ` + npm.utils.toJson(this.result.text), - gap2 + `values: ` + npm.utils.toJson(this.result.values), - gap1 + `}` + 'PreparedStatementError {', + gap1 + 'message: "' + this.message + '"', + gap1 + 'result: {', + gap2 + 'name: ' + npm.utils.toJson(this.result.name), + gap2 + 'text: ' + npm.utils.toJson(this.result.text), + gap2 + 'values: ' + npm.utils.toJson(this.result.values), + gap1 + '}' ]; if (this.error) { - lines.push(gap1 + `error: ` + this.error.toString(level + 1)); + lines.push(gap1 + 'error: ' + this.error.toString(level + 1)); } - lines.push(gap0 + `}`); + lines.push(gap0 + '}'); return lines.join(npm.os.EOL); }; diff --git a/lib/errors/query-file-error.js b/lib/errors/query-file-error.js index 61b5c3142..1739124b7 100644 --- a/lib/errors/query-file-error.js +++ b/lib/errors/query-file-error.js @@ -8,9 +8,9 @@ */ const npm = { - os: require(`os`), - utils: require(`../utils`), - minify: require(`pg-minify`) + os: require('os'), + utils: require('../utils'), + minify: require('pg-minify') }; /** @@ -47,7 +47,7 @@ const npm = { class QueryFileError extends Error { constructor(error, qf) { const isSqlError = error instanceof npm.minify.SQLParsingError; - const message = isSqlError ? `Failed to parse the SQL.` : error.message; + const message = isSqlError ? 'Failed to parse the SQL.' : error.message; super(message); this.name = this.constructor.name; if (isSqlError) { @@ -76,15 +76,15 @@ QueryFileError.prototype.toString = function (level) { const gap0 = npm.utils.messageGap(level), gap1 = npm.utils.messageGap(level + 1), lines = [ - `QueryFileError {`, - gap1 + `message: "` + this.message + `"`, - gap1 + `options: ` + npm.utils.toJson(this.options), - gap1 + `file: "` + this.file + `"` + 'QueryFileError {', + gap1 + 'message: "' + this.message + '"', + gap1 + 'options: ' + npm.utils.toJson(this.options), + gap1 + 'file: "' + this.file + '"' ]; if (this.error) { - lines.push(gap1 + `error: ` + this.error.toString(level + 1)); + lines.push(gap1 + 'error: ' + this.error.toString(level + 1)); } - lines.push(gap0 + `}`); + lines.push(gap0 + '}'); return lines.join(npm.os.EOL); }; diff --git a/lib/errors/query-result-error.js b/lib/errors/query-result-error.js index 1dee46673..09d884f6d 100644 --- a/lib/errors/query-result-error.js +++ b/lib/errors/query-result-error.js @@ -8,9 +8,9 @@ */ const npm = { - os: require(`os`), - utils: require(`../utils`), - text: require(`../text`) + os: require('os'), + utils: require('../utils'), + text: require('../text') }; /** @@ -36,9 +36,9 @@ const queryResultErrorCode = { }; const errorMessages = [ - {name: `noData`, message: npm.text.noData}, - {name: `notEmpty`, message: npm.text.notEmpty}, - {name: `multiple`, message: npm.text.multiple} + {name: 'noData', message: npm.text.noData}, + {name: 'notEmpty', message: npm.text.notEmpty}, + {name: 'multiple', message: npm.text.multiple} ]; /** @@ -154,16 +154,16 @@ QueryResultError.prototype.toString = function (level) { const gap0 = npm.utils.messageGap(level), gap1 = npm.utils.messageGap(level + 1), lines = [ - `QueryResultError {`, - gap1 + `code: queryResultErrorCode.` + errorMessages[this.code].name, - gap1 + `message: "` + this.message + `"`, - gap1 + `received: ` + this.received, - gap1 + `query: ` + (typeof this.query === `string` ? `"` + this.query + `"` : npm.utils.toJson(this.query)) + 'QueryResultError {', + gap1 + 'code: queryResultErrorCode.' + errorMessages[this.code].name, + gap1 + 'message: "' + this.message + '"', + gap1 + 'received: ' + this.received, + gap1 + 'query: ' + (typeof this.query === 'string' ? '"' + this.query + '"' : npm.utils.toJson(this.query)) ]; if (this.values !== undefined) { - lines.push(gap1 + `values: ` + npm.utils.toJson(this.values)); + lines.push(gap1 + 'values: ' + npm.utils.toJson(this.values)); } - lines.push(gap0 + `}`); + lines.push(gap0 + '}'); return lines.join(npm.os.EOL); }; diff --git a/lib/events.js b/lib/events.js index cc49ffbe6..b3846b7d2 100644 --- a/lib/events.js +++ b/lib/events.js @@ -7,11 +7,11 @@ * Removal or modification of this copyright notice is prohibited. */ -const {ColorConsole} = require(`./utils/color`); +const {ColorConsole} = require('./utils/color'); const npm = { - main: require(`./`), - utils: require(`./utils`) + main: require('./'), + utils: require('./utils') }; ///////////////////////////////// @@ -57,14 +57,14 @@ class Events { * }; */ static connect(ctx, client, useCount) { - if (typeof ctx.options.connect === `function`) { + if (typeof ctx.options.connect === 'function') { try { ctx.options.connect({client, dc: ctx.dc, useCount}); } catch (e) { // have to silence errors here; // cannot allow unhandled errors while connecting to the database, // as it will break the connection logic; - Events.unexpected(`connect`, e); + Events.unexpected('connect', e); } } } @@ -99,14 +99,14 @@ class Events { * }; */ static disconnect(ctx, client) { - if (typeof ctx.options.disconnect === `function`) { + if (typeof ctx.options.disconnect === 'function') { try { ctx.options.disconnect({client, dc: ctx.dc}); } catch (e) { // have to silence errors here; // cannot allow unhandled errors while disconnecting from the database, // as it will break the disconnection logic; - Events.unexpected(`disconnect`, e); + Events.unexpected('disconnect', e); } } } @@ -135,7 +135,7 @@ class Events { * }; */ static query(options, context) { - if (typeof options.query === `function`) { + if (typeof options.query === 'function') { try { options.query(context); } catch (e) { @@ -210,7 +210,7 @@ class Events { * } */ static receive(options, data, result, ctx) { - if (typeof options.receive === `function`) { + if (typeof options.receive === 'function') { try { options.receive({data, result, ctx}); } catch (e) { @@ -256,12 +256,12 @@ class Events { * */ static task(options, context) { - if (typeof options.task === `function`) { + if (typeof options.task === 'function') { try { options.task(context); } catch (e) { // silencing the error, to avoid breaking the task; - Events.unexpected(`task`, e); + Events.unexpected('task', e); } } } @@ -301,12 +301,12 @@ class Events { * */ static transact(options, context) { - if (typeof options.transact === `function`) { + if (typeof options.transact === 'function') { try { options.transact(context); } catch (e) { // silencing the error, to avoid breaking the transaction; - Events.unexpected(`transact`, e); + Events.unexpected('transact', e); } } } @@ -352,14 +352,14 @@ class Events { * */ static error(options, err, context) { - if (typeof options.error === `function`) { + if (typeof options.error === 'function') { try { options.error(err, context); } catch (e) { // have to silence errors here; // throwing unhandled errors while handling an error // notification is simply not acceptable. - Events.unexpected(`error`, e); + Events.unexpected('error', e); } } } @@ -450,14 +450,14 @@ class Events { * */ static extend(options, obj, dc) { - if (typeof options.extend === `function`) { + if (typeof options.extend === 'function') { try { options.extend.call(obj, obj, dc); } catch (e) { // have to silence errors here; // the result of throwing unhandled errors while // extending the protocol would be unpredictable. - Events.unexpected(`extend`, e); + Events.unexpected('extend', e); } } } diff --git a/lib/formatting.js b/lib/formatting.js index 883ab7d04..de7e637bf 100644 --- a/lib/formatting.js +++ b/lib/formatting.js @@ -7,12 +7,12 @@ * Removal or modification of this copyright notice is prohibited. */ -const {assert} = require(`./assert`); +const {assert} = require('./assert'); const npm = { - pgUtils: require(`pg/lib/utils`), - patterns: require(`./patterns`), - utils: require(`./utils`) + pgUtils: require('pg/lib/utils'), + patterns: require('./patterns'), + utils: require('./utils') }; // Format Modification Flags; @@ -41,8 +41,8 @@ const fmMap = { // Global symbols for Custom Type Formatting: const ctfSymbols = { - toPostgres: Symbol.for(`ctf.toPostgres`), - rawType: Symbol.for(`ctf.rawType`) + toPostgres: Symbol.for('ctf.toPostgres'), + rawType: Symbol.for('ctf.rawType') }; const maxVariable = 100000; // maximum supported variable is '$100000' @@ -51,7 +51,7 @@ const maxVariable = 100000; // maximum supported variable is '$100000' // Converts a single value into its Postgres format. function formatValue({value, fm, cc, options}) { - if (typeof value === `function`) { + if (typeof value === 'function') { return formatValue({value: resolveFunc(value, cc), fm, cc}); } @@ -81,18 +81,18 @@ function formatValue({value, fm, cc, options}) { if (isNull(value)) { throwIfRaw(isRaw); - return `null`; + return 'null'; } switch (typeof value) { - case `string`: + case 'string': return $to.text(value, isRaw); - case `boolean`: + case 'boolean': return $to.bool(value); - case `number`: - case `bigint`: + case 'number': + case 'bigint': return $to.number(value); - case `symbol`: + case 'symbol': throw new TypeError(`Type Symbol has no meaning for PostgreSQL: ${value.toString()}`); default: if (value instanceof Date) { @@ -117,12 +117,12 @@ function formatValue({value, fm, cc, options}) { // Top-level empty arrays are formatted as literal '{}' to avoid the necessity of explicit type casting, // as the server cannot automatically infer the type of empty non-literal array. function formatArray(array, options) { - const loop = a => `[` + a.map(value => Array.isArray(value) ? loop(value) : formatValue({ + const loop = a => '[' + a.map(value => Array.isArray(value) ? loop(value) : formatValue({ value, options - })).join() + `]`; - const prefix = options && options.capSQL ? `ARRAY` : `array`; - return array.length ? (prefix + loop(array)) : `'{}'`; + })).join() + ']'; + const prefix = options && options.capSQL ? 'ARRAY' : 'array'; + return array.length ? (prefix + loop(array)) : '\'{}\''; } /////////////////////////////////////////////////////////////////// @@ -131,10 +131,10 @@ function formatCSV(values, options) { if (Array.isArray(values)) { return values.map(value => formatValue({value, options})).join(); } - if (typeof values === `object` && values !== null) { + if (typeof values === 'object' && values !== null) { return Object.keys(values).map(v => formatValue({value: values[v], options})).join(); } - return values === undefined ? `` : formatValue({value: values, options}); + return values === undefined ? '' : formatValue({value: values, options}); } /////////////////////////////// @@ -142,9 +142,9 @@ function formatCSV(values, options) { const formatAs = { object({query, obj, raw, options}) { - options = options && typeof options === `object` ? options : {}; + options = options && typeof options === 'object' ? options : {}; return query.replace(npm.patterns.namedParameters, name => { - const v = formatAs.stripName(name.replace(/^\$[{(<[/]|[\s})>\]/]/g, ``), raw), + const v = formatAs.stripName(name.replace(/^\$[{(<[/]|[\s})>\]/]/g, ''), raw), c = npm.utils.getIfHas(obj, v.name); if (!c.valid) { throw new Error(`Invalid property name '${v.name}'.`); @@ -152,11 +152,11 @@ const formatAs = { if (c.has) { return formatValue({value: c.value, fm: v.fm, cc: c.target, options}); } - if (v.name === `this`) { + if (v.name === 'this') { return formatValue({value: obj, fm: v.fm, options}); } - if (`def` in options) { - const d = options.def, value = typeof d === `function` ? d.call(obj, v.name, obj) : d; + if ('def' in options) { + const d = options.def, value = typeof d === 'function' ? d.call(obj, v.name, obj) : d; return formatValue({value, fm: v.fm, cc: obj, options}); } if (options.partial) { @@ -168,7 +168,7 @@ const formatAs = { }, array({query, array, raw, options}) { - options = options && typeof options === `object` ? options : {}; + options = options && typeof options === 'object' ? options : {}; return query.replace(npm.patterns.multipleValues, name => { const v = formatAs.stripName(name.substr(1), raw); const idx = v.name - 1; @@ -178,8 +178,8 @@ const formatAs = { if (idx < array.length) { return formatValue({value: array[idx], fm: v.fm, options}); } - if (`def` in options) { - const d = options.def, value = typeof d === `function` ? d.call(array, idx, array) : d; + if ('def' in options) { + const d = options.def, value = typeof d === 'function' ? d.call(array, idx, array) : d; return formatValue({value, fm: v.fm, options}); } if (options.partial) { @@ -223,13 +223,13 @@ function isNull(value) { function getCTF(value) { if (!isNull(value)) { let toPostgres = value[ctfSymbols.toPostgres], rawType = !!value[ctfSymbols.rawType]; - if (typeof toPostgres !== `function`) { + if (typeof toPostgres !== 'function') { toPostgres = value.toPostgres; rawType = !!value.rawType; } - if (typeof toPostgres === `function`) { - if (toPostgres.constructor.name !== `Function`) { - throw new Error(`CTF does not support asynchronous toPostgres functions.`); + if (typeof toPostgres === 'function') { + if (toPostgres.constructor.name !== 'Function') { + throw new Error('CTF does not support asynchronous toPostgres functions.'); } return {toPostgres, rawType}; } @@ -247,26 +247,26 @@ function wrapText(text) { // Replaces each single-quote symbol ' with two, // for compliance with PostgreSQL strings. function safeText(text) { - return text.replace(/'/g, `''`); + return text.replace(/'/g, '\'\''); } ///////////////////////////////////////////// // Throws an exception, if flag 'raw' is set. function throwIfRaw(raw) { if (raw) { - throw new TypeError(`Values null/undefined cannot be used as raw text.`); + throw new TypeError('Values null/undefined cannot be used as raw text.'); } } ///////////////////////////////////////////////////////////////////////////// // Recursively resolves parameter-function, with an optional Calling Context. function resolveFunc(value, cc) { - while (typeof value === `function`) { - if (value.constructor.name !== `Function`) { + while (typeof value === 'function') { + if (value.constructor.name !== 'Function') { // Constructor name for asynchronous functions have different names: // - 'GeneratorFunction' for ES6 generators // - 'AsyncFunction' for ES7 async functions - throw new Error(`Cannot use asynchronous functions with query formatting.`); + throw new Error('Cannot use asynchronous functions with query formatting.'); } value = value.call(cc, cc); } @@ -282,15 +282,15 @@ function resolveFunc(value, cc) { // and where * is any of the supported open-close pairs: {}, (), [], <>, // // function formatQuery(query, values, raw, options) { - if (typeof query !== `string`) { - throw new TypeError(`Parameter 'query' must be a text string.`); + if (typeof query !== 'string') { + throw new TypeError('Parameter \'query\' must be a text string.'); } const ctf = getCTF(values); if (ctf) { // Custom Type Formatting return formatQuery(query, resolveFunc(ctf.toPostgres, values), raw || ctf.rawType, options); } - if (typeof values === `object` && values !== null) { + if (typeof values === 'object' && values !== null) { if (Array.isArray(values)) { // $1, $2,... formatting to be applied; return formatAs.array({query, array: values, raw, options}); @@ -307,7 +307,7 @@ function formatQuery(query, values, raw, options) { ////////////////////////////////////////////////////// // Formats a function or stored procedure call query; function formatEntity(entity, values, {capSQL, type}) { - let prefix = type === `func` ? `select * from` : `call`; + let prefix = type === 'func' ? 'select * from' : 'call'; if (capSQL) { prefix = prefix.toUpperCase(); } @@ -315,7 +315,7 @@ function formatEntity(entity, values, {capSQL, type}) { } function formatSqlName(name) { - return `"${name.replace(/"/g, `""`)}"`; + return `"${name.replace(/"/g, '""')}"`; } /** @@ -426,9 +426,9 @@ const $as = { value = resolveFunc(value); if (isNull(value)) { throwIfRaw(raw); - return `null`; + return 'null'; } - if (typeof value !== `string`) { + if (typeof value !== 'string') { value = value.toString(); } return $to.text(value, raw); @@ -477,16 +477,16 @@ const $as = { name(name) { name = resolveFunc(name); if (name) { - if (typeof name === `string`) { + if (typeof name === 'string') { return /^\s*\*(\s*)$/.test(name) ? name : formatSqlName(name); } - if (typeof name === `object`) { + if (typeof name === 'object') { const keys = Array.isArray(name) ? name : Object.keys(name); if (!keys.length) { - throw new Error(`Cannot retrieve sql names from an empty array/object.`); + throw new Error('Cannot retrieve sql names from an empty array/object.'); } return keys.map(value => { - if (!value || typeof value !== `string`) { + if (!value || typeof value !== 'string') { throw new Error(`Invalid sql name: ${npm.utils.toJson(value)}`); } return formatSqlName(value); @@ -529,16 +529,16 @@ const $as = { */ alias(name) { name = resolveFunc(name); - if (name && typeof name === `string`) { - return name.split(`.`) + if (name && typeof name === 'string') { + return name.split('.') .filter(f => f) .map(a => { const m = a.match(/^([a-z_][a-z0-9_$]*|[A-Z_][A-Z0-9_$]*)$/); if (m && m[0] === a) { return a; } - return `"${a.replace(/"/g, `""`)}"`; - }).join(`.`); + return `"${a.replace(/"/g, '""')}"`; + }).join('.'); } throw new TypeError(`Invalid sql alias: ${npm.utils.toJson(name)}`); }, @@ -564,7 +564,7 @@ const $as = { value(value) { value = resolveFunc(value); if (isNull(value)) { - throw new TypeError(`Open values cannot be null or undefined.`); + throw new TypeError('Open values cannot be null or undefined.'); } return safeText(formatValue({value, fm: fmFlags.raw})); }, @@ -588,7 +588,7 @@ const $as = { obj = resolveFunc(obj); if (isNull(obj)) { throwIfRaw(raw); - return `null`; + return 'null'; } if (obj instanceof Buffer) { return $to.buffer(obj, raw); @@ -609,7 +609,7 @@ const $as = { bool(value) { value = resolveFunc(value); if (isNull(value)) { - return `null`; + return 'null'; } return $to.bool(value); }, @@ -632,7 +632,7 @@ const $as = { d = resolveFunc(d); if (isNull(d)) { throwIfRaw(raw); - return `null`; + return 'null'; } if (d instanceof Date) { return $to.date(d, raw); @@ -654,10 +654,10 @@ const $as = { number(num) { num = resolveFunc(num); if (isNull(num)) { - return `null`; + return 'null'; } const t = typeof num; - if (t !== `number` && t !== `bigint`) { + if (t !== 'number' && t !== 'bigint') { throw new TypeError(`${wrapText(num)} is not a number.`); } return $to.number(num); @@ -683,10 +683,10 @@ const $as = { * @returns {string} */ array(arr, options) { - options = assert(options, [`capSQL`]); + options = assert(options, ['capSQL']); arr = resolveFunc(arr); if (isNull(arr)) { - return `null`; + return 'null'; } if (Array.isArray(arr)) { return $to.array(arr, options); @@ -737,7 +737,7 @@ const $as = { data = resolveFunc(data); if (isNull(data)) { throwIfRaw(raw); - return `null`; + return 'null'; } return $to.json(data, raw); }, @@ -761,9 +761,9 @@ const $as = { func(func, raw, cc) { if (isNull(func)) { throwIfRaw(raw); - return `null`; + return 'null'; } - if (typeof func !== `function`) { + if (typeof func !== 'function') { throw new TypeError(`${wrapText(func)} is not a function.`); } const fm = raw ? fmFlags.raw : null; @@ -850,7 +850,7 @@ const $as = { * The function will throw an error, if any occurs during formatting. */ format(query, values, options) { - options = assert(options, [`capSQL`, `partial`, `def`]); + options = assert(options, ['capSQL', 'partial', 'def']); const ctf = getCTF(query); if (ctf) { query = ctf.toPostgres.call(query, query); @@ -868,10 +868,10 @@ const $to = { return formatCSV(resolveFunc(values), options); }, bool(value) { - return value ? `true` : `false`; + return value ? 'true' : 'false'; }, buffer(obj, raw) { - const s = `\\x${obj.toString(`hex`)}`; + const s = `\\x${obj.toString('hex')}`; return raw ? s : wrapText(s); }, date(d, raw) { @@ -883,7 +883,7 @@ const $to = { return raw ? s : wrapText(safeText(s)); }, number(num) { - if (typeof num === `bigint` || Number.isFinite(num)) { + if (typeof num === 'bigint' || Number.isFinite(num)) { return num.toString(); } // Converting NaN/+Infinity/-Infinity according to Postgres documentation: @@ -891,12 +891,12 @@ const $to = { // // NOTE: strings for 'NaN'/'+Infinity'/'-Infinity' are not case-sensitive. if (num === Number.POSITIVE_INFINITY) { - return wrapText(`+Infinity`); + return wrapText('+Infinity'); } if (num === Number.NEGATIVE_INFINITY) { - return wrapText(`-Infinity`); + return wrapText('-Infinity'); } - return wrapText(`NaN`); + return wrapText('NaN'); }, text(value, raw) { return raw ? value : wrapText(safeText(value)); diff --git a/lib/helpers/column-set.js b/lib/helpers/column-set.js index cbcf63610..176e8c415 100644 --- a/lib/helpers/column-set.js +++ b/lib/helpers/column-set.js @@ -7,15 +7,15 @@ * Removal or modification of this copyright notice is prohibited. */ -const {InnerState} = require(`../inner-state`); -const {assert} = require(`../assert`); -const {TableName} = require(`./table-name`); -const {Column} = require(`./column`); +const {InnerState} = require('../inner-state'); +const {assert} = require('../assert'); +const {TableName} = require('./table-name'); +const {Column} = require('./column'); const npm = { - os: require(`os`), - utils: require(`../utils`), - formatting: require(`../formatting`) + os: require('os'), + utils: require('../utils'), + formatting: require('../formatting') }; /** @@ -168,11 +168,11 @@ class ColumnSet extends InnerState { constructor(columns, opt) { super(); - if (!columns || typeof columns !== `object`) { - throw new TypeError(`Invalid parameter 'columns' specified.`); + if (!columns || typeof columns !== 'object') { + throw new TypeError('Invalid parameter \'columns\' specified.'); } - opt = assert(opt, [`table`, `inherit`]); + opt = assert(opt, ['table', 'inherit']); if (!npm.utils.isNull(opt.table)) { this.table = (opt.table instanceof TableName) ? opt.table : new TableName(opt.table); @@ -234,7 +234,7 @@ class ColumnSet extends InnerState { const c = this.columns[i]; // ColumnSet is simple when the source objects require no preparation, // and should be used directly: - if (c.prop || c.init || `def` in c) { + if (c.prop || c.init || 'def' in c) { this._inner.isSimple = false; break; } @@ -329,12 +329,12 @@ class ColumnSet extends InnerState { */ ColumnSet.prototype.assign = function (options) { const _i = this._inner; - const hasPrefix = options && options.prefix && typeof options.prefix === `string`; + const hasPrefix = options && options.prefix && typeof options.prefix === 'string'; if (_i.updates && !hasPrefix) { return _i.updates; } let dynamic = hasPrefix; - const hasSource = options && options.source && typeof options.source === `object`; + const hasSource = options && options.source && typeof options.source === 'object'; let list = this.columns.filter(c => { if (c.cnd) { return false; @@ -351,8 +351,8 @@ ColumnSet.prototype.assign = function (options) { return true; }); - const prefix = hasPrefix ? npm.formatting.as.alias(options.prefix) + `.` : ``; - list = list.map(c => prefix + c.escapedName + `=` + c.variable + c.castText).join(); + const prefix = hasPrefix ? npm.formatting.as.alias(options.prefix) + '.' : ''; + list = list.map(c => prefix + c.escapedName + '=' + c.variable + c.castText).join(); if (!dynamic) { _i.updates = list; @@ -400,13 +400,13 @@ ColumnSet.prototype.assign = function (options) { * */ ColumnSet.prototype.assignColumns = function (options) { - options = assert(options, [`from`, `to`, `skip`]); - const skip = (typeof options.skip === `string` && [options.skip]) || ((Array.isArray(options.skip) || typeof options.skip === `function`) && options.skip); - const from = (typeof options.from === `string` && options.from && (npm.formatting.as.alias(options.from) + `.`)) || ``; - const to = (typeof options.to === `string` && options.to && (npm.formatting.as.alias(options.to) + `.`)) || ``; - const iterator = typeof skip === `function` ? c => !skip.call(c, c) : c => skip.indexOf(c.name) === -1; + options = assert(options, ['from', 'to', 'skip']); + const skip = (typeof options.skip === 'string' && [options.skip]) || ((Array.isArray(options.skip) || typeof options.skip === 'function') && options.skip); + const from = (typeof options.from === 'string' && options.from && (npm.formatting.as.alias(options.from) + '.')) || ''; + const to = (typeof options.to === 'string' && options.to && (npm.formatting.as.alias(options.to) + '.')) || ''; + const iterator = typeof skip === 'function' ? c => !skip.call(c, c) : c => skip.indexOf(c.name) === -1; const cols = skip ? this.columns.filter(iterator) : this.columns; - return cols.map(c => to + c.escapedName + `=` + from + c.escapedName).join(); + return cols.map(c => to + c.escapedName + '=' + from + c.escapedName).join(); }; /** @@ -583,7 +583,7 @@ ColumnSet.prototype.prepare = function (source) { if (c.init) { target[a.name] = c.init.call(source, a); } else { - if (a.exists || `def` in c) { + if (a.exists || 'def' in c) { target[a.name] = a.value; } } @@ -600,7 +600,7 @@ function colDesc(column, source) { if (a.exists) { a.value = source[a.name]; } else { - a.value = `def` in column ? column.def : undefined; + a.value = 'def' in column ? column.def : undefined; } return a; } @@ -622,21 +622,21 @@ ColumnSet.prototype.toString = function (level) { const gap0 = npm.utils.messageGap(level), gap1 = npm.utils.messageGap(level + 1), lines = [ - `ColumnSet {` + 'ColumnSet {' ]; if (this.table) { - lines.push(gap1 + `table: ` + this.table); + lines.push(gap1 + 'table: ' + this.table); } if (this.columns.length) { - lines.push(gap1 + `columns: [`); + lines.push(gap1 + 'columns: ['); this.columns.forEach(c => { lines.push(c.toString(2)); }); - lines.push(gap1 + `]`); + lines.push(gap1 + ']'); } else { - lines.push(gap1 + `columns: []`); + lines.push(gap1 + 'columns: []'); } - lines.push(gap0 + `}`); + lines.push(gap0 + '}'); return lines.join(npm.os.EOL); }; diff --git a/lib/helpers/column.js b/lib/helpers/column.js index e4ad176d7..623009b6a 100644 --- a/lib/helpers/column.js +++ b/lib/helpers/column.js @@ -7,14 +7,14 @@ * Removal or modification of this copyright notice is prohibited. */ -const {InnerState} = require(`../inner-state`); -const {assert} = require(`../assert`); +const {InnerState} = require('../inner-state'); +const {assert} = require('../assert'); const npm = { - os: require(`os`), - utils: require(`../utils`), - formatting: require(`../formatting`), - patterns: require(`../patterns`) + os: require('os'), + utils: require('../utils'), + formatting: require('../formatting'), + patterns: require('../patterns') }; /** @@ -132,18 +132,18 @@ class Column extends InnerState { constructor(col) { super(); - if (typeof col === `string`) { + if (typeof col === 'string') { const info = parseColumn(col); this.name = info.name; - if (`mod` in info) { + if ('mod' in info) { this.mod = info.mod; } - if (`cnd` in info) { + if ('cnd' in info) { this.cnd = info.cnd; } } else { - col = assert(col, [`name`, `prop`, `mod`, `cast`, `cnd`, `def`, `init`, `skip`]); - if (`name` in col) { + col = assert(col, ['name', 'prop', 'mod', 'cast', 'cnd', 'def', 'init', 'skip']); + if ('name' in col) { if (!npm.utils.isText(col.name)) { throw new TypeError(`Invalid 'name' value: ${npm.utils.toJson(col.name)}. A non-empty string was expected.`); } @@ -165,7 +165,7 @@ class Column extends InnerState { } } if (!npm.utils.isNull(col.mod)) { - if (typeof col.mod !== `string` || !isValidMod(col.mod)) { + if (typeof col.mod !== 'string' || !isValidMod(col.mod)) { throw new TypeError(`Invalid 'mod' value: ${npm.utils.toJson(col.mod)}.`); } this.mod = col.mod; // optional format modifier; @@ -173,25 +173,25 @@ class Column extends InnerState { if (!npm.utils.isNull(col.cast)) { this.cast = parseCast(col.cast); // optional SQL type casting } - if (`cnd` in col) { + if ('cnd' in col) { this.cnd = !!col.cnd; } - if (`def` in col) { + if ('def' in col) { this.def = col.def; // optional default } - if (typeof col.init === `function`) { + if (typeof col.init === 'function') { this.init = col.init; // optional value override (overrides 'def' also) } - if (typeof col.skip === `function`) { + if (typeof col.skip === 'function') { this.skip = col.skip; } } else { - throw new TypeError(`Invalid column details.`); + throw new TypeError('Invalid column details.'); } } - const variable = `\${` + (this.prop || this.name) + (this.mod || ``) + `}`; - const castText = this.cast ? (`::` + this.cast) : ``; + const variable = '${' + (this.prop || this.name) + (this.mod || '') + '}'; + const castText = this.cast ? ('::' + this.cast) : ''; const escapedName = npm.formatting.as.name(this.name); this.extendState({variable, castText, escapedName}); @@ -251,8 +251,8 @@ class Column extends InnerState { } function parseCast(name) { - if (typeof name === `string`) { - const s = name.replace(/^[:\s]*|\s*$/g, ``); + if (typeof name === 'string') { + const s = name.replace(/^[:\s]*|\s*$/g, ''); if (s) { return s; } @@ -264,7 +264,7 @@ function parseColumn(name) { const m = name.match(npm.patterns.validColumn); if (m && m[0] === name) { const res = {}; - if (name[0] === `?`) { + if (name[0] === '?') { res.cnd = true; name = name.substr(1); } @@ -306,31 +306,31 @@ Column.prototype.toString = function (level) { const gap0 = npm.utils.messageGap(level), gap1 = npm.utils.messageGap(level + 1), lines = [ - gap0 + `Column {`, - gap1 + `name: ` + npm.utils.toJson(this.name) + gap0 + 'Column {', + gap1 + 'name: ' + npm.utils.toJson(this.name) ]; - if (`prop` in this) { - lines.push(gap1 + `prop: ` + npm.utils.toJson(this.prop)); + if ('prop' in this) { + lines.push(gap1 + 'prop: ' + npm.utils.toJson(this.prop)); } - if (`mod` in this) { - lines.push(gap1 + `mod: ` + npm.utils.toJson(this.mod)); + if ('mod' in this) { + lines.push(gap1 + 'mod: ' + npm.utils.toJson(this.mod)); } - if (`cast` in this) { - lines.push(gap1 + `cast: ` + npm.utils.toJson(this.cast)); + if ('cast' in this) { + lines.push(gap1 + 'cast: ' + npm.utils.toJson(this.cast)); } - if (`cnd` in this) { - lines.push(gap1 + `cnd: ` + npm.utils.toJson(this.cnd)); + if ('cnd' in this) { + lines.push(gap1 + 'cnd: ' + npm.utils.toJson(this.cnd)); } - if (`def` in this) { - lines.push(gap1 + `def: ` + npm.utils.toJson(this.def)); + if ('def' in this) { + lines.push(gap1 + 'def: ' + npm.utils.toJson(this.def)); } - if (`init` in this) { - lines.push(gap1 + `init: [Function]`); + if ('init' in this) { + lines.push(gap1 + 'init: [Function]'); } - if (`skip` in this) { - lines.push(gap1 + `skip: [Function]`); + if ('skip' in this) { + lines.push(gap1 + 'skip: [Function]'); } - lines.push(gap0 + `}`); + lines.push(gap0 + '}'); return lines.join(npm.os.EOL); }; diff --git a/lib/helpers/index.js b/lib/helpers/index.js index e0520d564..820f23097 100644 --- a/lib/helpers/index.js +++ b/lib/helpers/index.js @@ -7,10 +7,10 @@ * Removal or modification of this copyright notice is prohibited. */ -const {Column} = require(`./column`); -const {ColumnSet} = require(`./column-set`); -const {TableName} = require(`./table-name`); -const method = require(`./methods`); +const {Column} = require('./column'); +const {ColumnSet} = require('./column-set'); +const {TableName} = require('./table-name'); +const method = require('./methods'); /** * @namespace helpers diff --git a/lib/helpers/methods/concat.js b/lib/helpers/methods/concat.js index aade8d932..a1382f5b6 100644 --- a/lib/helpers/methods/concat.js +++ b/lib/helpers/methods/concat.js @@ -7,10 +7,10 @@ * Removal or modification of this copyright notice is prohibited. */ -const {QueryFile} = require(`../../query-file`); +const {QueryFile} = require('../../query-file'); const npm = { - formatting: require(`../../formatting`) + formatting: require('../../formatting') }; /** @@ -50,22 +50,22 @@ const npm = { */ function concat(queries, capSQL) { if (!Array.isArray(queries)) { - throw new TypeError(`Parameter 'queries' must be an array.`); + throw new TypeError('Parameter \'queries\' must be an array.'); } const fmOptions = {capSQL}; const all = queries.map((q, index) => { - if (typeof q === `string`) { + if (typeof q === 'string') { // a simple query string without parameters: return clean(q); } - if (q && typeof q === `object`) { + if (q && typeof q === 'object') { if (q instanceof QueryFile) { // QueryFile object: return clean(q[npm.formatting.as.ctf.toPostgres]()); } - if (`query` in q) { + if ('query' in q) { // object {query, values, options}: - let opt = q.options && typeof q.options === `object` ? q.options : {}; + let opt = q.options && typeof q.options === 'object' ? q.options : {}; opt = opt.capSQL === undefined ? Object.assign(opt, fmOptions) : opt; return clean(npm.formatting.as.format(q.query, q.values, opt)); } @@ -73,12 +73,12 @@ function concat(queries, capSQL) { throw new Error(`Invalid query element at index ${index}.`); }); - return all.filter(q => q).join(`;`); + return all.filter(q => q).join(';'); } function clean(q) { // removes from the query all leading and trailing symbols ' ', '\t' and ';' - return q.replace(/^[\s;]*|[\s;]*$/g, ``); + return q.replace(/^[\s;]*|[\s;]*$/g, ''); } module.exports = {concat}; diff --git a/lib/helpers/methods/index.js b/lib/helpers/methods/index.js index 4bdb496ca..52a73aa73 100644 --- a/lib/helpers/methods/index.js +++ b/lib/helpers/methods/index.js @@ -1,8 +1,8 @@ -const {concat} = require(`./concat`); -const {insert} = require(`./insert`); -const {update} = require(`./update`); -const {values} = require(`./values`); -const {sets} = require(`./sets`); +const {concat} = require('./concat'); +const {insert} = require('./insert'); +const {update} = require('./update'); +const {values} = require('./values'); +const {sets} = require('./sets'); module.exports = { concat, diff --git a/lib/helpers/methods/insert.js b/lib/helpers/methods/insert.js index fa5f4b23c..ab023a7df 100644 --- a/lib/helpers/methods/insert.js +++ b/lib/helpers/methods/insert.js @@ -7,12 +7,12 @@ * Removal or modification of this copyright notice is prohibited. */ -const {TableName} = require(`../table-name`); -const {ColumnSet} = require(`../column-set`); +const {TableName} = require('../table-name'); +const {ColumnSet} = require('../column-set'); const npm = { - formatting: require(`../../formatting`), - utils: require(`../../utils`) + formatting: require('../../formatting'), + utils: require('../../utils') }; /** @@ -90,14 +90,14 @@ const npm = { */ function insert(data, columns, table, capSQL) { - if (!data || typeof data !== `object`) { - throw new TypeError(`Invalid parameter 'data' specified.`); + if (!data || typeof data !== 'object') { + throw new TypeError('Invalid parameter \'data\' specified.'); } const isArray = Array.isArray(data); if (isArray && !data.length) { - throw new TypeError(`Cannot generate an INSERT from an empty array.`); + throw new TypeError('Cannot generate an INSERT from an empty array.'); } if (columns instanceof ColumnSet) { @@ -106,17 +106,17 @@ function insert(data, columns, table, capSQL) { } } else { if (isArray && npm.utils.isNull(columns)) { - throw new TypeError(`Parameter 'columns' is required when inserting multiple records.`); + throw new TypeError('Parameter \'columns\' is required when inserting multiple records.'); } columns = new ColumnSet(columns || data); } if (!columns.columns.length) { - throw new Error(`Cannot generate an INSERT without any columns.`); + throw new Error('Cannot generate an INSERT without any columns.'); } if (!table) { - throw new Error(`Table name is unknown.`); + throw new Error('Table name is unknown.'); } if (!(table instanceof TableName)) { @@ -131,18 +131,18 @@ function insert(data, columns, table, capSQL) { if (isArray) { return query + data.map((d, index) => { - if (!d || typeof d !== `object`) { + if (!d || typeof d !== 'object') { throw new Error(`Invalid insert object at index ${index}.`); } - return `(` + format(columns.variables, columns.prepare(d), fmOptions) + `)`; + return '(' + format(columns.variables, columns.prepare(d), fmOptions) + ')'; }).join(); } - return query + `(` + format(columns.variables, columns.prepare(data), fmOptions) + `)`; + return query + '(' + format(columns.variables, columns.prepare(data), fmOptions) + ')'; } const sql = { - lowCase: `insert into $1^($2^) values`, - capCase: `INSERT INTO $1^($2^) VALUES` + lowCase: 'insert into $1^($2^) values', + capCase: 'INSERT INTO $1^($2^) VALUES' }; module.exports = {insert}; diff --git a/lib/helpers/methods/sets.js b/lib/helpers/methods/sets.js index 24c2bd622..da1039bf7 100644 --- a/lib/helpers/methods/sets.js +++ b/lib/helpers/methods/sets.js @@ -7,11 +7,11 @@ * Removal or modification of this copyright notice is prohibited. */ -const {ColumnSet} = require(`../column-set`); +const {ColumnSet} = require('../column-set'); const npm = { - format: require(`../../formatting`).as.format, - utils: require(`../../utils`) + format: require('../../formatting').as.format, + utils: require('../../utils') }; /** @@ -66,8 +66,8 @@ const npm = { */ function sets(data, columns, capSQL) { - if (!data || typeof data !== `object` || Array.isArray(data)) { - throw new TypeError(`Invalid parameter 'data' specified.`); + if (!data || typeof data !== 'object' || Array.isArray(data)) { + throw new TypeError('Invalid parameter \'data\' specified.'); } if (!(columns instanceof ColumnSet)) { diff --git a/lib/helpers/methods/update.js b/lib/helpers/methods/update.js index 374590e2c..4cad4a702 100644 --- a/lib/helpers/methods/update.js +++ b/lib/helpers/methods/update.js @@ -7,13 +7,13 @@ * Removal or modification of this copyright notice is prohibited. */ -const {assert} = require(`../../assert`); -const {TableName} = require(`../table-name`); -const {ColumnSet} = require(`../column-set`); +const {assert} = require('../../assert'); +const {TableName} = require('../table-name'); +const {ColumnSet} = require('../column-set'); const npm = { - formatting: require(`../../formatting`), - utils: require(`../../utils`) + formatting: require('../../formatting'), + utils: require('../../utils') }; /** @@ -147,14 +147,14 @@ const npm = { */ function update(data, columns, table, options, capSQL) { - if (!data || typeof data !== `object`) { - throw new TypeError(`Invalid parameter 'data' specified.`); + if (!data || typeof data !== 'object') { + throw new TypeError('Invalid parameter \'data\' specified.'); } const isArray = Array.isArray(data); if (isArray && !data.length) { - throw new TypeError(`Cannot generate an UPDATE from an empty array.`); + throw new TypeError('Cannot generate an UPDATE from an empty array.'); } if (columns instanceof ColumnSet) { @@ -163,20 +163,20 @@ function update(data, columns, table, options, capSQL) { } } else { if (isArray && npm.utils.isNull(columns)) { - throw new TypeError(`Parameter 'columns' is required when updating multiple records.`); + throw new TypeError('Parameter \'columns\' is required when updating multiple records.'); } columns = new ColumnSet(columns || data); } - options = assert(options, [`tableAlias`, `valueAlias`, `emptyUpdate`]); + options = assert(options, ['tableAlias', 'valueAlias', 'emptyUpdate']); const format = npm.formatting.as.format, - useEmptyUpdate = `emptyUpdate` in options, + useEmptyUpdate = 'emptyUpdate' in options, fmOptions = {capSQL}; if (isArray) { - const tableAlias = npm.formatting.as.alias(npm.utils.isNull(options.tableAlias) ? `t` : options.tableAlias); - const valueAlias = npm.formatting.as.alias(npm.utils.isNull(options.valueAlias) ? `v` : options.valueAlias); + const tableAlias = npm.formatting.as.alias(npm.utils.isNull(options.tableAlias) ? 't' : options.tableAlias); + const valueAlias = npm.formatting.as.alias(npm.utils.isNull(options.valueAlias) ? 'v' : options.valueAlias); const q = capSQL ? sql.multi.capCase : sql.multi.lowCase; @@ -188,13 +188,13 @@ function update(data, columns, table, options, capSQL) { checkTable(); - const targetCols = actualColumns.map(c => c.escapedName + `=` + valueAlias + `.` + c.escapedName).join(); + const targetCols = actualColumns.map(c => c.escapedName + '=' + valueAlias + '.' + c.escapedName).join(); const values = data.map((d, index) => { - if (!d || typeof d !== `object`) { + if (!d || typeof d !== 'object') { throw new Error(`Invalid update object at index ${index}.`); } - return `(` + format(columns.variables, columns.prepare(d), fmOptions) + `)`; + return '(' + format(columns.variables, columns.prepare(d), fmOptions) + ')'; }).join(); return format(q, [table.name, tableAlias, targetCols, values, valueAlias, columns.names], fmOptions); @@ -217,7 +217,7 @@ function update(data, columns, table, options, capSQL) { table = new TableName(table); } if (!table) { - throw new Error(`Table name is unknown.`); + throw new Error('Table name is unknown.'); } } @@ -226,19 +226,19 @@ function update(data, columns, table, options, capSQL) { if (useEmptyUpdate) { return true; } - throw new Error(`Cannot generate an UPDATE without any columns.`); + throw new Error('Cannot generate an UPDATE without any columns.'); } } } const sql = { single: { - lowCase: `update $1^ set `, - capCase: `UPDATE $1^ SET ` + lowCase: 'update $1^ set ', + capCase: 'UPDATE $1^ SET ' }, multi: { - lowCase: `update $1^ as $2^ set $3^ from (values$4^) as $5^($6^)`, - capCase: `UPDATE $1^ AS $2^ SET $3^ FROM (VALUES$4^) AS $5^($6^)` + lowCase: 'update $1^ as $2^ set $3^ from (values$4^) as $5^($6^)', + capCase: 'UPDATE $1^ AS $2^ SET $3^ FROM (VALUES$4^) AS $5^($6^)' } }; diff --git a/lib/helpers/methods/values.js b/lib/helpers/methods/values.js index 1c2db12f9..b5da990b8 100644 --- a/lib/helpers/methods/values.js +++ b/lib/helpers/methods/values.js @@ -7,11 +7,11 @@ * Removal or modification of this copyright notice is prohibited. */ -const {ColumnSet} = require(`../column-set`); +const {ColumnSet} = require('../column-set'); const npm = { - formatting: require(`../../formatting`), - utils: require(`../../utils`) + formatting: require('../../formatting'), + utils: require('../../utils') }; /** @@ -81,21 +81,21 @@ const npm = { */ function values(data, columns, capSQL) { - if (!data || typeof data !== `object`) { - throw new TypeError(`Invalid parameter 'data' specified.`); + if (!data || typeof data !== 'object') { + throw new TypeError('Invalid parameter \'data\' specified.'); } const isArray = Array.isArray(data); if (!(columns instanceof ColumnSet)) { if (isArray && npm.utils.isNull(columns)) { - throw new TypeError(`Parameter 'columns' is required when generating multi-row values.`); + throw new TypeError('Parameter \'columns\' is required when generating multi-row values.'); } columns = new ColumnSet(columns || data); } if (!columns.columns.length) { - throw new Error(`Cannot generate values without any columns.`); + throw new Error('Cannot generate values without any columns.'); } const format = npm.formatting.as.format, @@ -103,13 +103,13 @@ function values(data, columns, capSQL) { if (isArray) { return data.map((d, index) => { - if (!d || typeof d !== `object`) { + if (!d || typeof d !== 'object') { throw new Error(`Invalid object at index ${index}.`); } - return `(` + format(columns.variables, columns.prepare(d), fmOptions) + `)`; + return '(' + format(columns.variables, columns.prepare(d), fmOptions) + ')'; }).join(); } - return `(` + format(columns.variables, columns.prepare(data), fmOptions) + `)`; + return '(' + format(columns.variables, columns.prepare(data), fmOptions) + ')'; } module.exports = {values}; diff --git a/lib/helpers/table-name.js b/lib/helpers/table-name.js index 3dd60f9f5..3f5e440dd 100644 --- a/lib/helpers/table-name.js +++ b/lib/helpers/table-name.js @@ -7,11 +7,11 @@ * Removal or modification of this copyright notice is prohibited. */ -const {assert} = require(`../assert`); +const {assert} = require('../assert'); const npm = { - utils: require(`../utils`), - format: require(`../formatting`).as // formatting namespace + utils: require('../utils'), + format: require('../formatting').as // formatting namespace }; /** @@ -62,21 +62,21 @@ const npm = { class TableName { constructor(table) { - if (typeof table === `string`) { + if (typeof table === 'string') { this.table = table; } else { - const config = assert(table, [`table`, `schema`]); + const config = assert(table, ['table', 'schema']); this.table = config.table; if (npm.utils.isText(config.schema)) { this.schema = config.schema; } } if (!npm.utils.isText(this.table)) { - throw new TypeError(`Table name must be a non-empty text string.`); + throw new TypeError('Table name must be a non-empty text string.'); } this.name = npm.format.name(this.table); if (this.schema) { - this.name = npm.format.name(this.schema) + `.` + this.name; + this.name = npm.format.name(this.schema) + '.' + this.name; } Object.freeze(this); } diff --git a/lib/index.js b/lib/index.js index 5621b31e2..aa569e1a9 100644 --- a/lib/index.js +++ b/lib/index.js @@ -8,7 +8,7 @@ */ /* eslint no-var: off */ -var v = process.versions.node.split(`.`), +var v = process.versions.node.split('.'), highVer = +v[0]; // istanbul ignore next @@ -22,7 +22,7 @@ if (highVer < 14) { // Node.js v4.5.0 was supported up to pg-promise v8.7.5 // Node.js v0.10 was supported up to pg-promise v5.5.8 - throw new Error(`Minimum Node.js version supported by pg-promise is 14.0.0`); + throw new Error('Minimum Node.js version supported by pg-promise is 14.0.0'); } -module.exports = require(`./main`); +module.exports = require('./main'); diff --git a/lib/inner-state.js b/lib/inner-state.js index 7039058f6..b29b2c42c 100644 --- a/lib/inner-state.js +++ b/lib/inner-state.js @@ -1,4 +1,4 @@ -const {addReadProp} = require(`./utils`); +const {addReadProp} = require('./utils'); /** * @private @@ -10,8 +10,8 @@ const {addReadProp} = require(`./utils`); class InnerState { constructor(initialState) { - addReadProp(this, `_inner`, {}, true); - if (initialState && typeof initialState === `object`) { + addReadProp(this, '_inner', {}, true); + if (initialState && typeof initialState === 'object') { this.extendState(initialState); } } diff --git a/lib/main.js b/lib/main.js index ef5b148b8..b64601b1a 100644 --- a/lib/main.js +++ b/lib/main.js @@ -7,26 +7,26 @@ * Removal or modification of this copyright notice is prohibited. */ -const {PromiseAdapter} = require(`./promise-adapter`); -const {DatabasePool} = require(`./database-pool`); -const {PreparedStatement, ParameterizedQuery} = require(`./types`); -const {QueryFile} = require(`./query-file`); -const {queryResult} = require(`./query-result`); -const {parsePromise} = require(`./promise-parser`); -const {assert} = require(`./assert`); +const {PromiseAdapter} = require('./promise-adapter'); +const {DatabasePool} = require('./database-pool'); +const {PreparedStatement, ParameterizedQuery} = require('./types'); +const {QueryFile} = require('./query-file'); +const {queryResult} = require('./query-result'); +const {parsePromise} = require('./promise-parser'); +const {assert} = require('./assert'); const npm = { - path: require(`path`), - pg: require(`pg`), - minify: require(`pg-minify`), - formatting: require(`./formatting`), - helpers: require(`./helpers`), - errors: require(`./errors`), - utils: require(`./utils`), - pubUtils: require(`./utils/public`), - mode: require(`./tx-mode`), - package: require(`../package.json`), - text: require(`./text`) + path: require('path'), + pg: require('pg'), + minify: require('pg-minify'), + formatting: require('./formatting'), + helpers: require('./helpers'), + errors: require('./errors'), + utils: require('./utils'), + pubUtils: require('./utils/public'), + mode: require('./tx-mode'), + package: require('../package.json'), + text: require('./text') }; let originalClientConnect; @@ -178,8 +178,8 @@ let originalClientConnect; */ function $main(options) { - options = assert(options, [`pgFormatting`, `pgNative`, `promiseLib`, `capSQL`, `noWarnings`, - `connect`, `disconnect`, `query`, `receive`, `task`, `transact`, `error`, `extend`, `schema`]); + options = assert(options, ['pgFormatting', 'pgNative', 'promiseLib', 'capSQL', 'noWarnings', + 'connect', 'disconnect', 'query', 'receive', 'task', 'transact', 'error', 'extend', 'schema']); let pg = npm.pg; const p = parsePromise(options.promiseLib); @@ -190,11 +190,11 @@ function $main(options) { promise: p.promise }; - npm.utils.addReadProp(config, `$npm`, {}, true); + npm.utils.addReadProp(config, '$npm', {}, true); // Locking properties that cannot be changed later: - npm.utils.addReadProp(options, `promiseLib`, options.promiseLib); - npm.utils.addReadProp(options, `pgNative`, !!options.pgNative); + npm.utils.addReadProp(options, 'promiseLib', options.promiseLib); + npm.utils.addReadProp(options, 'pgNative', !!options.pgNative); config.options = options; @@ -210,24 +210,24 @@ function $main(options) { originalClientConnect = pg.Client.prototype.connect; pg.Client.prototype.connect = function () { const handler = msg => { - if (msg.parameterName === `server_version`) { + if (msg.parameterName === 'server_version') { this.serverVersion = msg.parameterValue; - this.connection.removeListener(`parameterStatus`, handler); + this.connection.removeListener('parameterStatus', handler); } }; - this.connection.on(`parameterStatus`, handler); + this.connection.on('parameterStatus', handler); return originalClientConnect.call(this, ...arguments); }; } } - const Database = require(`./database`)(config); + const Database = require('./database')(config); const inst = (cn, dc) => { - if (npm.utils.isText(cn) || (cn && typeof cn === `object`)) { + if (npm.utils.isText(cn) || (cn && typeof cn === 'object')) { return new Database(cn, dc, config); } - throw new TypeError(`Invalid connection details: ` + npm.utils.toJson(cn)); + throw new TypeError('Invalid connection details: ' + npm.utils.toJson(cn)); }; npm.utils.addReadProperties(inst, rootNameSpace); @@ -258,7 +258,7 @@ function $main(options) { * * For more details see $[Library de-initialization]. */ - npm.utils.addReadProp(inst, `end`, () => { + npm.utils.addReadProp(inst, 'end', () => { DatabasePool.shutDown(); }); @@ -272,7 +272,7 @@ function $main(options) { * * @see {@link helpers}. */ - npm.utils.addReadProp(inst, `helpers`, npm.helpers(config)); + npm.utils.addReadProp(inst, 'helpers', npm.helpers(config)); /** * @member {external:spex} spex @@ -287,7 +287,7 @@ function $main(options) { * {@link Task#page}, * {@link Task#sequence} */ - npm.utils.addReadProp(inst, `spex`, config.$npm.spex); + npm.utils.addReadProp(inst, 'spex', config.$npm.spex); config.pgp = inst; diff --git a/lib/patterns.js b/lib/patterns.js index ee633fe31..499fa8fcf 100644 --- a/lib/patterns.js +++ b/lib/patterns.js @@ -39,5 +39,5 @@ module.exports = { hasValidModifier: /\^|~|#|:raw|:alias|:name|:json|:csv|:list|:value/, // List of all supported formatting modifiers: - validModifiers: [`^`, `~`, `#`, `:raw`, `:alias`, `:name`, `:json`, `:csv`, `:list`, `:value`] + validModifiers: ['^', '~', '#', ':raw', ':alias', ':name', ':json', ':csv', ':list', ':value'] }; diff --git a/lib/promise-adapter.js b/lib/promise-adapter.js index 965a6addf..ebb6a87b6 100644 --- a/lib/promise-adapter.js +++ b/lib/promise-adapter.js @@ -7,7 +7,7 @@ * Removal or modification of this copyright notice is prohibited. */ -const {assert} = require(`./assert`); +const {assert} = require('./assert'); /** * @class PromiseAdapter @@ -54,31 +54,31 @@ const {assert} = require(`./assert`); class PromiseAdapter { constructor(api) { - if (!api || typeof api !== `object`) { - throw new TypeError(`Adapter requires an api configuration object.`); + if (!api || typeof api !== 'object') { + throw new TypeError('Adapter requires an api configuration object.'); } - api = assert(api, [`create`, `resolve`, `reject`, `all`]); + api = assert(api, ['create', 'resolve', 'reject', 'all']); this.create = api.create; this.resolve = api.resolve; this.reject = api.reject; this.all = api.all; - if (typeof this.create !== `function`) { - throw new TypeError(`Function 'create' must be specified.`); + if (typeof this.create !== 'function') { + throw new TypeError('Function \'create\' must be specified.'); } - if (typeof this.resolve !== `function`) { - throw new TypeError(`Function 'resolve' must be specified.`); + if (typeof this.resolve !== 'function') { + throw new TypeError('Function \'resolve\' must be specified.'); } - if (typeof this.reject !== `function`) { - throw new TypeError(`Function 'reject' must be specified.`); + if (typeof this.reject !== 'function') { + throw new TypeError('Function \'reject\' must be specified.'); } - if (typeof this.all !== `function`) { - throw new TypeError(`Function 'all' must be specified.`); + if (typeof this.all !== 'function') { + throw new TypeError('Function \'all\' must be specified.'); } } } diff --git a/lib/promise-parser.js b/lib/promise-parser.js index 8da39023b..161110588 100644 --- a/lib/promise-parser.js +++ b/lib/promise-parser.js @@ -7,7 +7,7 @@ * Removal or modification of this copyright notice is prohibited. */ -const {PromiseAdapter} = require(`./promise-adapter`); +const {PromiseAdapter} = require('./promise-adapter'); ////////////////////////////////////////// // Parses and validates a promise library; @@ -24,22 +24,22 @@ function parse(pl) { return promise; } const t = typeof pl; - if (t === `function` || t === `object`) { - const Root = typeof pl.Promise === `function` ? pl.Promise : pl; + if (t === 'function' || t === 'object') { + const Root = typeof pl.Promise === 'function' ? pl.Promise : pl; promise = function (func) { return new Root(func); }; promise.resolve = Root.resolve; promise.reject = Root.reject; promise.all = Root.all; - if (typeof promise.resolve === `function` && - typeof promise.reject === `function` && - typeof promise.all === `function`) { + if (typeof promise.resolve === 'function' && + typeof promise.reject === 'function' && + typeof promise.all === 'function') { return promise; } } - throw new TypeError(`Invalid promise library specified.`); + throw new TypeError('Invalid promise library specified.'); } function parsePromise(promiseLib) { diff --git a/lib/query-file.js b/lib/query-file.js index 9a700fa2b..b55adda4a 100644 --- a/lib/query-file.js +++ b/lib/query-file.js @@ -7,21 +7,21 @@ * Removal or modification of this copyright notice is prohibited. */ -const {InnerState} = require(`./inner-state`); -const {QueryFileError} = require(`./errors`); -const {assert} = require(`./assert`); -const {ColorConsole} = require(`./utils/color`); +const {InnerState} = require('./inner-state'); +const {QueryFileError} = require('./errors'); +const {assert} = require('./assert'); +const {ColorConsole} = require('./utils/color'); const npm = { - fs: require(`fs`), - os: require(`os`), - path: require(`path`), - minify: require(`pg-minify`), - utils: require(`./utils`), - formatting: require(`./formatting`) + fs: require('fs'), + os: require('os'), + path: require('path'), + minify: require('pg-minify'), + utils: require('./utils'), + formatting: require('./formatting') }; -const file$query = Symbol(`QueryFile.query`); +const file$query = Symbol('QueryFile.query'); /** * @class QueryFile @@ -151,7 +151,7 @@ class QueryFile extends InnerState { * @return {{usedPath: {}}} */ static get instance() { - const s = Symbol.for(`pgPromiseQueryFile`); + const s = Symbol.for('pgPromiseQueryFile'); let scope = global[s]; if (!scope) { scope = { @@ -253,15 +253,15 @@ class QueryFile extends InnerState { return; } try { - i.sql = npm.fs.readFileSync(i.filePath, `utf8`); + i.sql = npm.fs.readFileSync(i.filePath, 'utf8'); i.modTime = lastMod || npm.fs.statSync(i.filePath).mtime.getTime(); - if (options.minify && options.minify !== `after`) { + if (options.minify && options.minify !== 'after') { i.sql = npm.minify(i.sql, {compress: options.compress}); } if (options.params !== undefined) { i.sql = npm.formatting.as.format(i.sql, options.params, {partial: true}); } - if (options.minify && options.minify === `after`) { + if (options.minify && options.minify === 'after') { i.sql = npm.minify(i.sql, {compress: options.compress}); } i.ready = true; @@ -328,17 +328,17 @@ QueryFile.prototype.toString = function (level) { level = level > 0 ? parseInt(level) : 0; const gap = npm.utils.messageGap(level + 1); const lines = [ - `QueryFile {` + 'QueryFile {' ]; this.prepare(); - lines.push(gap + `file: "` + this.file + `"`); - lines.push(gap + `options: ` + npm.utils.toJson(this.options)); + lines.push(gap + 'file: "' + this.file + '"'); + lines.push(gap + 'options: ' + npm.utils.toJson(this.options)); if (this.error) { - lines.push(gap + `error: ` + this.error.toString(level + 1)); + lines.push(gap + 'error: ' + this.error.toString(level + 1)); } else { - lines.push(gap + `query: "` + this[QueryFile.$query] + `"`); + lines.push(gap + 'query: "' + this[QueryFile.$query] + '"'); } - lines.push(npm.utils.messageGap(level) + `}`); + lines.push(npm.utils.messageGap(level) + '}'); return lines.join(npm.os.EOL); }; diff --git a/lib/query.js b/lib/query.js index a266c6796..77c3e8d36 100644 --- a/lib/query.js +++ b/lib/query.js @@ -7,19 +7,19 @@ * Removal or modification of this copyright notice is prohibited. */ -const {Events} = require(`./events`); -const {QueryFile} = require(`./query-file`); -const {ServerFormatting, PreparedStatement, ParameterizedQuery} = require(`./types`); -const {SpecialQuery} = require(`./special-query`); -const {queryResult} = require(`./query-result`); +const {Events} = require('./events'); +const {QueryFile} = require('./query-file'); +const {ServerFormatting, PreparedStatement, ParameterizedQuery} = require('./types'); +const {SpecialQuery} = require('./special-query'); +const {queryResult} = require('./query-result'); const npm = { - util: require(`util`), - utils: require(`./utils`), - formatting: require(`./formatting`), - errors: require(`./errors`), - stream: require(`./stream`), - text: require(`./text`) + util: require('util'), + utils: require('./utils'), + formatting: require('./formatting'), + errors: require('./errors'), + stream: require('./stream'), + text: require('./text') }; const QueryResultError = npm.errors.QueryResultError, @@ -46,7 +46,7 @@ function $query(ctx, query, values, qrm, config) { pgFormatting = opt.pgFormatting, params = pgFormatting ? values : undefined; - if (typeof query === `function`) { + if (typeof query === 'function') { try { query = npm.formatting.resolveFunc(query, values); } catch (e) { @@ -60,7 +60,7 @@ function $query(ctx, query, values, qrm, config) { error = new TypeError(npm.text.invalidQuery); } - if (!error && typeof query === `object`) { + if (!error && typeof query === 'object') { if (query instanceof QueryFile) { query.prepare(); if (query.error) { @@ -70,18 +70,18 @@ function $query(ctx, query, values, qrm, config) { query = query[QueryFile.$query]; } } else { - if (`entity` in query) { + if ('entity' in query) { entityType = query.type; query = query.entity; // query is a function name; } else { if (query instanceof ServerFormatting) { pgFormatting = true; } else { - if (`name` in query) { + if ('name' in query) { query = new PreparedStatement(query); pgFormatting = true; } else { - if (`text` in query) { + if ('text' in query) { query = new ParameterizedQuery(query); pgFormatting = true; } @@ -96,7 +96,7 @@ function $query(ctx, query, values, qrm, config) { if (!error) { if (!pgFormatting && !npm.utils.isText(query)) { - const errTxt = entityType ? (entityType === `func` ? npm.text.invalidFunction : npm.text.invalidProc) : npm.text.invalidQuery; + const errTxt = entityType ? (entityType === 'func' ? npm.text.invalidFunction : npm.text.invalidProc) : npm.text.invalidQuery; error = new TypeError(errTxt); } if (query instanceof ServerFormatting) { @@ -130,11 +130,11 @@ function $query(ctx, query, values, qrm, config) { } } catch (e) { if (entityType) { - let prefix = entityType === `func` ? `select * from` : `call`; + let prefix = entityType === 'func' ? 'select * from' : 'call'; if (capSQL) { prefix = prefix.toUpperCase(); } - query = prefix + ` ` + query + `(...)`; + query = prefix + ' ' + query + '(...)'; } else { params = values; } diff --git a/lib/stream.js b/lib/stream.js index d3b34590e..a34278b36 100644 --- a/lib/stream.js +++ b/lib/stream.js @@ -7,11 +7,11 @@ * Removal or modification of this copyright notice is prohibited. */ -const {Events} = require(`./events`); +const {Events} = require('./events'); const npm = { - utils: require(`./utils`), - text: require(`./text`) + utils: require('./utils'), + text: require('./text') }; //////////////////////////////////////////// @@ -28,7 +28,7 @@ function $stream(ctx, qs, initCB, config) { } // Stream class was renamed again, see the following issue: // https://github.com/brianc/node-postgres/issues/2412 - if (!qs || !qs.constructor || qs.constructor.name !== `QueryStream`) { + if (!qs || !qs.constructor || qs.constructor.name !== 'QueryStream') { // invalid or missing stream object; return $p.reject(new TypeError(npm.text.invalidStream)); } @@ -36,7 +36,7 @@ function $stream(ctx, qs, initCB, config) { // stream object is in the wrong state; return $p.reject(new Error(npm.text.invalidStreamState)); } - if (typeof initCB !== `function`) { + if (typeof initCB !== 'function') { // parameter `initCB` must be passed as the initialization callback; return $p.reject(new TypeError(npm.text.invalidStreamCB)); } @@ -51,9 +51,9 @@ function $stream(ctx, qs, initCB, config) { const stream = ctx.db.client.query(qs); - stream.on(`data`, onData); - stream.on(`error`, onError); - stream.on(`end`, onEnd); + stream.on('data', onData); + stream.on('error', onError); + stream.on('end', onEnd); try { initCB.call(this, stream); // the stream must be initialized during the call; @@ -92,9 +92,9 @@ function $stream(ctx, qs, initCB, config) { } function release() { - stream.removeListener(`data`, onData); - stream.removeListener(`error`, onError); - stream.removeListener(`end`, onEnd); + stream.removeListener('data', onData); + stream.removeListener('error', onError); + stream.removeListener('end', onEnd); } function getError(e) { diff --git a/lib/task.js b/lib/task.js index e9c5abacf..999b65ccf 100644 --- a/lib/task.js +++ b/lib/task.js @@ -7,14 +7,14 @@ * Removal or modification of this copyright notice is prohibited. */ -const {Events} = require(`./events`); +const {Events} = require('./events'); const npm = { - spex: require(`spex`), - utils: require(`./utils`), - mode: require(`./tx-mode`), - query: require(`./query`), - text: require(`./text`) + spex: require('spex'), + utils: require('./utils'), + mode: require('./tx-mode'), + query: require('./query'), + text: require('./text') }; /** @@ -91,23 +91,23 @@ function Task(ctx, tag, isTX, config) { */ this.ctx = ctx.ctx = {}; // task context object; - npm.utils.addReadProp(this.ctx, `isTX`, isTX); + npm.utils.addReadProp(this.ctx, 'isTX', isTX); - if (`context` in ctx) { - npm.utils.addReadProp(this.ctx, `context`, ctx.context); + if ('context' in ctx) { + npm.utils.addReadProp(this.ctx, 'context', ctx.context); } - npm.utils.addReadProp(this.ctx, `connected`, !ctx.db); - npm.utils.addReadProp(this.ctx, `tag`, tag); - npm.utils.addReadProp(this.ctx, `dc`, ctx.dc); - npm.utils.addReadProp(this.ctx, `level`, ctx.level); - npm.utils.addReadProp(this.ctx, `inTransaction`, ctx.inTransaction); + npm.utils.addReadProp(this.ctx, 'connected', !ctx.db); + npm.utils.addReadProp(this.ctx, 'tag', tag); + npm.utils.addReadProp(this.ctx, 'dc', ctx.dc); + npm.utils.addReadProp(this.ctx, 'level', ctx.level); + npm.utils.addReadProp(this.ctx, 'inTransaction', ctx.inTransaction); if (isTX) { - npm.utils.addReadProp(this.ctx, `txLevel`, ctx.txLevel); + npm.utils.addReadProp(this.ctx, 'txLevel', ctx.txLevel); } - npm.utils.addReadProp(this.ctx, `parent`, ctx.parentCtx); + npm.utils.addReadProp(this.ctx, 'parent', ctx.parentCtx); // generic query method; this.query = function (query, values, qrm) { @@ -193,10 +193,10 @@ const callback = (ctx, obj, cb, config) => { let result; try { - if (cb.constructor.name === `GeneratorFunction`) { + if (cb.constructor.name === 'GeneratorFunction') { // v9.0 dropped all support for ES6 generator functions; // Clients should use the new ES7 async/await syntax. - throw new TypeError(`ES6 generator functions are no longer supported!`); + throw new TypeError('ES6 generator functions are no longer supported!'); } result = cb.call(obj, obj); // invoking the callback function; } catch (err) { @@ -207,7 +207,7 @@ const callback = (ctx, obj, cb, config) => { }); return $p.reject(err); // reject with the error; } - if (result && typeof result.then === `function`) { + if (result && typeof result.then === 'function') { return result; // result is a valid promise object; } return $p.resolve(result); @@ -232,7 +232,7 @@ const execute = (ctx, obj, isTX, config) => { function update(start, success, result) { const c = ctx.ctx; if (start) { - npm.utils.addReadProp(c, `start`, new Date()); + npm.utils.addReadProp(c, 'start', new Date()); } else { c.finish = new Date(); c.success = success; @@ -294,22 +294,22 @@ const execute = (ctx, obj, isTX, config) => { function begin() { if (!ctx.txLevel && ctx.mode instanceof npm.mode.TransactionMode) { - return exec(ctx.mode.begin(capSQL), `savepoint`); + return exec(ctx.mode.begin(capSQL), 'savepoint'); } - return exec(`begin`, `savepoint`); + return exec('begin', 'savepoint'); } function commit() { - return exec(`commit`, `release savepoint`); + return exec('commit', 'release savepoint'); } function rollback() { - return exec(`rollback`, `rollback to savepoint`); + return exec('rollback', 'rollback to savepoint'); } function exec(top, nested) { if (ctx.txLevel) { - return obj.none((capSQL ? nested.toUpperCase() : nested) + ` ` + spName); + return obj.none((capSQL ? nested.toUpperCase() : nested) + ' ' + spName); } return obj.none(capSQL ? top.toUpperCase() : top); } diff --git a/lib/text.js b/lib/text.js index c869460c2..5e7ef0dd7 100644 --- a/lib/text.js +++ b/lib/text.js @@ -9,32 +9,32 @@ /* All error messages used in the module */ -const streamVersion = require(`../package.json`) - .devDependencies[`pg-query-stream`]; +const streamVersion = require('../package.json') + .devDependencies['pg-query-stream']; module.exports = { - nativeError: `Failed to initialize Native Bindings.`, + nativeError: 'Failed to initialize Native Bindings.', /* Database errors */ - queryDisconnected: `Cannot execute a query on a disconnected client.`, - invalidQuery: `Invalid query format.`, - invalidFunction: `Invalid function name.`, - invalidProc: `Invalid procedure name.`, - invalidMask: `Invalid Query Result Mask specified.`, - looseQuery: `Querying against a released or lost connection.`, + queryDisconnected: 'Cannot execute a query on a disconnected client.', + invalidQuery: 'Invalid query format.', + invalidFunction: 'Invalid function name.', + invalidProc: 'Invalid procedure name.', + invalidMask: 'Invalid Query Result Mask specified.', + looseQuery: 'Querying against a released or lost connection.', /* result errors */ - notEmpty: `No return data was expected.`, - noData: `No data returned from the query.`, - multiple: `Multiple rows were not expected.`, + notEmpty: 'No return data was expected.', + noData: 'No data returned from the query.', + multiple: 'Multiple rows were not expected.', /* streaming support */ - nativeStreaming: `Streaming doesn't work with Native Bindings.`, + nativeStreaming: 'Streaming doesn\'t work with Native Bindings.', invalidStream: `Invalid or missing stream object: pg-query-stream >= v${streamVersion} was expected`, - invalidStreamState: `Invalid stream state.`, - invalidStreamCB: `Invalid or missing stream initialization callback.`, + invalidStreamState: 'Invalid stream state.', + invalidStreamCB: 'Invalid or missing stream initialization callback.', /* connection errors */ - poolDestroyed: `Connection pool of the database object has been destroyed.`, - clientEnd: `Abnormal client.end() call, due to invalid code or failed server connection.` + poolDestroyed: 'Connection pool of the database object has been destroyed.', + clientEnd: 'Abnormal client.end() call, due to invalid code or failed server connection.' }; diff --git a/lib/tx-mode.js b/lib/tx-mode.js index c3718355a..6963cddac 100644 --- a/lib/tx-mode.js +++ b/lib/tx-mode.js @@ -7,9 +7,9 @@ * Removal or modification of this copyright notice is prohibited. */ -const {InnerState} = require(`./inner-state`); -const {addInspection} = require(`./utils`); -const {assert} = require(`./assert`); +const {InnerState} = require('./inner-state'); +const {addInspection} = require('./utils'); +const {assert} = require('./assert'); /** * @enum {number} @@ -103,42 +103,42 @@ const isolationLevel = { class TransactionMode extends InnerState { constructor(options) { - options = assert(options, [`tiLevel`, `deferrable`, `readOnly`]); + options = assert(options, ['tiLevel', 'deferrable', 'readOnly']); const {readOnly, deferrable} = options; let {tiLevel} = options; - let level, accessMode, deferrableMode, begin = `begin`; + let level, accessMode, deferrableMode, begin = 'begin'; tiLevel = (tiLevel > 0) ? parseInt(tiLevel) : 0; if (tiLevel > 0 && tiLevel < 4) { - const values = [`serializable`, `repeatable read`, `read committed`]; - level = `isolation level ` + values[tiLevel - 1]; + const values = ['serializable', 'repeatable read', 'read committed']; + level = 'isolation level ' + values[tiLevel - 1]; } if (readOnly) { - accessMode = `read only`; + accessMode = 'read only'; } else { if (readOnly !== undefined) { - accessMode = `read write`; + accessMode = 'read write'; } } // From the official documentation: http://www.postgresql.org/docs/9.5/static/sql-set-transaction.html // The DEFERRABLE transaction property has no effect unless the transaction is also SERIALIZABLE and READ ONLY if (tiLevel === isolationLevel.serializable && readOnly) { if (deferrable) { - deferrableMode = `deferrable`; + deferrableMode = 'deferrable'; } else { if (deferrable !== undefined) { - deferrableMode = `not deferrable`; + deferrableMode = 'not deferrable'; } } } if (level) { - begin += ` ` + level; + begin += ' ' + level; } if (accessMode) { - begin += ` ` + accessMode; + begin += ' ' + accessMode; } if (deferrableMode) { - begin += ` ` + deferrableMode; + begin += ' ' + deferrableMode; } super({begin, capBegin: begin.toUpperCase()}); diff --git a/lib/types/index.js b/lib/types/index.js index d822d0429..49a1197f3 100644 --- a/lib/types/index.js +++ b/lib/types/index.js @@ -7,9 +7,9 @@ * Removal or modification of this copyright notice is prohibited. */ -const {ServerFormatting} = require(`./server-formatting`); -const {PreparedStatement} = require(`./prepared-statement`); -const {ParameterizedQuery} = require(`./parameterized-query`); +const {ServerFormatting} = require('./server-formatting'); +const {PreparedStatement} = require('./prepared-statement'); +const {ParameterizedQuery} = require('./parameterized-query'); module.exports = { ServerFormatting, diff --git a/lib/types/parameterized-query.js b/lib/types/parameterized-query.js index a67c4c9a7..96936ade7 100644 --- a/lib/types/parameterized-query.js +++ b/lib/types/parameterized-query.js @@ -7,14 +7,14 @@ * Removal or modification of this copyright notice is prohibited. */ -const {ServerFormatting} = require(`./server-formatting`); -const {ParameterizedQueryError} = require(`../errors`); -const {QueryFile} = require(`../query-file`); -const {assert} = require(`../assert`); +const {ServerFormatting} = require('./server-formatting'); +const {ParameterizedQueryError} = require('../errors'); +const {QueryFile} = require('../query-file'); +const {assert} = require('../assert'); const npm = { - EOL: require(`os`).EOL, - utils: require(`../utils`) + EOL: require('os').EOL, + utils: require('../utils') }; /** @@ -86,12 +86,12 @@ const npm = { */ class ParameterizedQuery extends ServerFormatting { constructor(options) { - if (typeof options === `string` || options instanceof QueryFile) { + if (typeof options === 'string' || options instanceof QueryFile) { options = { text: options }; } else { - options = assert(options, [`text`, `values`, `binary`, `rowMode`]); + options = assert(options, ['text', 'values', 'binary', 'rowMode']); } super(options); } @@ -133,7 +133,7 @@ ParameterizedQuery.prototype.parse = function () { } if (!npm.utils.isText(_i.target.text)) { - errors.push(`Property 'text' must be a non-empty text string.`); + errors.push('Property \'text\' must be a non-empty text string.'); } if (!npm.utils.isNull(values)) { @@ -174,24 +174,24 @@ ParameterizedQuery.prototype.toString = function (level) { const gap = npm.utils.messageGap(level + 1); const pq = this.parse(); const lines = [ - `ParameterizedQuery {` + 'ParameterizedQuery {' ]; if (npm.utils.isText(pq.text)) { - lines.push(gap + `text: "` + pq.text + `"`); + lines.push(gap + 'text: "' + pq.text + '"'); } if (this.values !== undefined) { - lines.push(gap + `values: ` + npm.utils.toJson(this.values)); + lines.push(gap + 'values: ' + npm.utils.toJson(this.values)); } if (this.binary !== undefined) { - lines.push(gap + `binary: ` + npm.utils.toJson(this.binary)); + lines.push(gap + 'binary: ' + npm.utils.toJson(this.binary)); } if (this.rowMode !== undefined) { - lines.push(gap + `rowMode: ` + npm.utils.toJson(this.rowMode)); + lines.push(gap + 'rowMode: ' + npm.utils.toJson(this.rowMode)); } if (this.error !== undefined) { - lines.push(gap + `error: ` + this.error.toString(level + 1)); + lines.push(gap + 'error: ' + this.error.toString(level + 1)); } - lines.push(npm.utils.messageGap(level) + `}`); + lines.push(npm.utils.messageGap(level) + '}'); return lines.join(npm.EOL); }; diff --git a/lib/types/prepared-statement.js b/lib/types/prepared-statement.js index d84adcc0f..21f89d314 100644 --- a/lib/types/prepared-statement.js +++ b/lib/types/prepared-statement.js @@ -7,14 +7,14 @@ * Removal or modification of this copyright notice is prohibited. */ -const {ServerFormatting} = require(`./server-formatting`); -const {PreparedStatementError} = require(`../errors`); -const {QueryFile} = require(`../query-file`); -const {assert} = require(`../assert`); +const {ServerFormatting} = require('./server-formatting'); +const {PreparedStatementError} = require('../errors'); +const {QueryFile} = require('../query-file'); +const {assert} = require('../assert'); const npm = { - EOL: require(`os`).EOL, - utils: require(`../utils`) + EOL: require('os').EOL, + utils: require('../utils') }; /** @@ -89,7 +89,7 @@ const npm = { */ class PreparedStatement extends ServerFormatting { constructor(options) { - options = assert(options, [`name`, `text`, `values`, `binary`, `rowMode`, `rows`]); + options = assert(options, ['name', 'text', 'values', 'binary', 'rowMode', 'rows']); super(options); } @@ -161,7 +161,7 @@ PreparedStatement.prototype.parse = function () { _i.currentError = undefined; if (!npm.utils.isText(_i.target.name)) { - errors.push(`Property 'name' must be a non-empty text string.`); + errors.push('Property \'name\' must be a non-empty text string.'); } if (qf) { @@ -173,7 +173,7 @@ PreparedStatement.prototype.parse = function () { } } if (!npm.utils.isText(_i.target.text)) { - errors.push(`Property 'text' must be a non-empty text string.`); + errors.push('Property \'text\' must be a non-empty text string.'); } if (!npm.utils.isNull(values)) { @@ -218,28 +218,28 @@ PreparedStatement.prototype.toString = function (level) { const gap = npm.utils.messageGap(level + 1); const ps = this.parse(); const lines = [ - `PreparedStatement {`, - gap + `name: ` + npm.utils.toJson(this.name) + 'PreparedStatement {', + gap + 'name: ' + npm.utils.toJson(this.name) ]; if (npm.utils.isText(ps.text)) { - lines.push(gap + `text: "` + ps.text + `"`); + lines.push(gap + 'text: "' + ps.text + '"'); } if (this.values !== undefined) { - lines.push(gap + `values: ` + npm.utils.toJson(this.values)); + lines.push(gap + 'values: ' + npm.utils.toJson(this.values)); } if (this.binary !== undefined) { - lines.push(gap + `binary: ` + npm.utils.toJson(this.binary)); + lines.push(gap + 'binary: ' + npm.utils.toJson(this.binary)); } if (this.rowMode !== undefined) { - lines.push(gap + `rowMode: ` + npm.utils.toJson(this.rowMode)); + lines.push(gap + 'rowMode: ' + npm.utils.toJson(this.rowMode)); } if (this.rows !== undefined) { - lines.push(gap + `rows: ` + npm.utils.toJson(this.rows)); + lines.push(gap + 'rows: ' + npm.utils.toJson(this.rows)); } if (this.error) { - lines.push(gap + `error: ` + this.error.toString(level + 1)); + lines.push(gap + 'error: ' + this.error.toString(level + 1)); } - lines.push(npm.utils.messageGap(level) + `}`); + lines.push(npm.utils.messageGap(level) + '}'); return lines.join(npm.EOL); }; diff --git a/lib/types/server-formatting.js b/lib/types/server-formatting.js index ecc924572..dc1ea06ab 100644 --- a/lib/types/server-formatting.js +++ b/lib/types/server-formatting.js @@ -1,6 +1,6 @@ -const {InnerState} = require(`../inner-state`); -const {addInspection} = require(`../utils`); -const utils = require(`../utils`); +const {InnerState} = require('../inner-state'); +const {addInspection} = require('../utils'); +const utils = require('../utils'); /** * @private diff --git a/lib/utils/color.js b/lib/utils/color.js index 25f145199..64e54dc73 100644 --- a/lib/utils/color.js +++ b/lib/utils/color.js @@ -1,4 +1,4 @@ -const util = require(`util`); +const util = require('util'); class ColorConsole { diff --git a/lib/utils/index.js b/lib/utils/index.js index 35a4a37b5..30a984817 100644 --- a/lib/utils/index.js +++ b/lib/utils/index.js @@ -8,9 +8,9 @@ */ const npm = { - path: require(`path`), - util: require(`util`), - patterns: require(`../patterns`) + path: require('path'), + util: require('util'), + patterns: require('../patterns') }; //////////////////////////////////////////// @@ -22,7 +22,7 @@ function isNull(value) { //////////////////////////////////////////////////////// // Verifies parameter for being a non-empty text string; function isText(txt) { - return txt && typeof txt === `string` && /\S/.test(txt); + return txt && typeof txt === 'string' && /\S/.test(txt); } /////////////////////////////////////////////////////////// @@ -31,8 +31,8 @@ function isText(txt) { // Proper configuration is having NODE_ENV = 'development', but this // method only checks for 'dev' being present, and regardless of the case. function isDev() { - const env = global.process.env.NODE_ENV || ``; - return env.toLowerCase().indexOf(`dev`) !== -1; + const env = global.process.env.NODE_ENV || ''; + return env.toLowerCase().indexOf('dev') !== -1; } ///////////////////////////////////////////// @@ -59,13 +59,13 @@ function addReadProp(obj, name, value, hidden) { // Converts a connection string or object into its safe copy: // if password is present, it is masked with symbol '#'. function getSafeConnection(cn) { - const maskPassword = cs => cs.replace(/:(?![/])([^@]+)/, (_, m) => `:` + new Array(m.length + 1).join(`#`)); - if (typeof cn === `object`) { + const maskPassword = cs => cs.replace(/:(?![/])([^@]+)/, (_, m) => ':' + new Array(m.length + 1).join('#')); + if (typeof cn === 'object') { const copy = Object.assign({}, cn); - if (typeof copy.password === `string`) { - copy.password = copy.password.replace(/./g, `#`); + if (typeof copy.password === 'string') { + copy.password = copy.password.replace(/./g, '#'); } - if (typeof copy.connectionString === `string`) { + if (typeof copy.connectionString === 'string') { copy.connectionString = maskPassword(copy.connectionString); } return copy; @@ -76,7 +76,7 @@ function getSafeConnection(cn) { /////////////////////////////////////////// // Returns a space gap for console output; function messageGap(level) { - return ` `.repeat(level * 4); + return ' '.repeat(level * 4); } ///////////////////////////////////////// @@ -92,10 +92,10 @@ function getLocalStack(startIdx, maxLines) { startIdx = startIdx || 0; const endIdx = maxLines > 0 ? startIdx + maxLines : undefined; return new Error().stack - .split(`\n`) + .split('\n') .filter(line => line.match(/\(.+\)/)) .slice(startIdx, endIdx) - .join(`\n`); + .join('\n'); } ////////////////////////////// @@ -113,14 +113,14 @@ function InternalError(error) { // - value - the value; set when 'has' = true function getIfHas(obj, prop) { const result = {valid: true}; - if (prop.indexOf(`.`) === -1) { + if (prop.indexOf('.') === -1) { result.has = prop in obj; result.target = obj; if (result.has) { result.value = obj[prop]; } } else { - const names = prop.split(`.`); + const names = prop.split('.'); let missing, target; for (let i = 0; i < names.length; i++) { const n = names[i]; @@ -147,7 +147,7 @@ function getIfHas(obj, prop) { ///////////////////////////////////////////////////////////////////////// // Checks if the property exists in the object or value or its prototype; function hasProperty(value, prop) { - return (value && typeof value === `object` && prop in value) || + return (value && typeof value === 'object' && prop in value) || value !== null && value !== undefined && value[prop] !== undefined; } @@ -161,10 +161,10 @@ function addInspection(type, cb) { // Identifies a general connectivity error, after which no more queries can be executed. // This is for detecting when to skip executing ROLLBACK for a failed transaction. function isConnectivityError(err) { - const code = err && typeof err.code === `string` && err.code; + const code = err && typeof err.code === 'string' && err.code; const cls = code && code.substr(0, 2); // Error Class // istanbul ignore next (we cannot test-cover all error cases): - return code === `ECONNRESET` || (cls === `08` && code !== `08P01`) || (cls === `57` && code !== `57014`); + return code === 'ECONNRESET' || (cls === '08' && code !== '08P01') || (cls === '57' && code !== '57014'); // Code 'ECONNRESET' - Connectivity issue handled by the driver. // Class 08 - Connection Exception (except for 08P01, for protocol violation). // Class 57 - Operator Intervention (except for 57014, for cancelled queries). @@ -176,7 +176,7 @@ function isConnectivityError(err) { // Does JSON.stringify, with support for BigInt (irreversible) function toJson(data) { if (data !== undefined) { - return JSON.stringify(data, (_, v) => typeof v === `bigint` ? `${v}#bigint` : v) + return JSON.stringify(data, (_, v) => typeof v === 'bigint' ? `${v}#bigint` : v) .replace(/"(-?\d+)#bigint"/g, (_, a) => a); } } diff --git a/lib/utils/public.js b/lib/utils/public.js index 518925227..4ffebd280 100644 --- a/lib/utils/public.js +++ b/lib/utils/public.js @@ -7,13 +7,13 @@ * Removal or modification of this copyright notice is prohibited. */ -const {assert} = require(`../assert`); +const {assert} = require('../assert'); const npm = { - fs: require(`fs`), - path: require(`path`), - utils: require(`./`), - package: require(`../../package.json`) + fs: require('fs'), + path: require('path'), + utils: require('./'), + package: require('../../package.json') }; /** @@ -38,7 +38,7 @@ const npm = { * */ function camelize(text) { - text = text.replace(/[-_\s.]+(.)?/g, (_, c) => c ? c.toUpperCase() : ``); + text = text.replace(/[-_\s.]+(.)?/g, (_, c) => c ? c.toUpperCase() : ''); return text.substr(0, 1).toLowerCase() + text.substr(1); } @@ -65,7 +65,7 @@ function camelize(text) { * */ function camelizeVar(text) { - text = text.replace(/[^a-zA-Z0-9$_\-\s.]/g, ``).replace(/^[0-9_\-\s.]+/, ``); + text = text.replace(/[^a-zA-Z0-9$_\-\s.]/g, '').replace(/^[0-9_\-\s.]+/, ''); return camelize(text); } @@ -89,28 +89,28 @@ function _enumSql(dir, options, cb, namePath) { if (stat.isDirectory()) { if (options.recursive) { const dirName = camelizeVar(file); - const np = namePath ? (namePath + `.` + dirName) : dirName; + const np = namePath ? (namePath + '.' + dirName) : dirName; const t = _enumSql(fullPath, options, cb, np); if (Object.keys(t).length) { if (!dirName.length || dirName in tree) { if (!options.ignoreErrors) { - throw new Error(`Empty or duplicate camelized folder name: ` + fullPath); + throw new Error('Empty or duplicate camelized folder name: ' + fullPath); } } tree[dirName] = t; } } } else { - if (npm.path.extname(file).toLowerCase() === `.sql`) { - const name = camelizeVar(file.replace(/\.[^/.]+$/, ``)); + if (npm.path.extname(file).toLowerCase() === '.sql') { + const name = camelizeVar(file.replace(/\.[^/.]+$/, '')); if (!name.length || name in tree) { if (!options.ignoreErrors) { - throw new Error(`Empty or duplicate camelized file name: ` + fullPath); + throw new Error('Empty or duplicate camelized file name: ' + fullPath); } } tree[name] = fullPath; if (cb) { - const result = cb(fullPath, name, namePath ? (namePath + `.` + name) : name); + const result = cb(fullPath, name, namePath ? (namePath + '.' + name) : name); if (result !== undefined) { tree[name] = result; } @@ -185,11 +185,11 @@ function _enumSql(dir, options, cb, namePath) { */ function enumSql(dir, options, cb) { if (!npm.utils.isText(dir)) { - throw new TypeError(`Parameter 'dir' must be a non-empty text string.`); + throw new TypeError('Parameter \'dir\' must be a non-empty text string.'); } - options = assert(options, [`recursive`, `ignoreErrors`]); - cb = (typeof cb === `function`) ? cb : null; - return _enumSql(dir, options, cb, ``); + options = assert(options, ['recursive', 'ignoreErrors']); + cb = (typeof cb === 'function') ? cb : null; + return _enumSql(dir, options, cb, ''); } /** @@ -236,26 +236,26 @@ function enumSql(dir, options, cb) { */ function taskArgs(args) { - if (!args || typeof args.length !== `number`) { - throw new TypeError(`Parameter 'args' must be an array-like object of arguments.`); + if (!args || typeof args.length !== 'number') { + throw new TypeError('Parameter \'args\' must be an array-like object of arguments.'); } let options = args[0], cb; - if (typeof options === `function`) { + if (typeof options === 'function') { cb = options; options = {}; if (cb.name) { options.tag = cb.name; } } else { - if (typeof args[1] === `function`) { + if (typeof args[1] === 'function') { cb = args[1]; } - if (typeof options === `string` || typeof options === `number`) { + if (typeof options === 'string' || typeof options === 'number') { options = {tag: options}; } else { - options = (typeof options === `object` && options) || {}; - if (!(`tag` in options) && cb && cb.name) { + options = (typeof options === 'object' && options) || {}; + if (!('tag' in options) && cb && cb.name) { options.tag = cb.name; } } @@ -263,7 +263,7 @@ function taskArgs(args) { const res = [options, cb]; - Object.defineProperty(res, `options`, { + Object.defineProperty(res, 'options', { get: function () { return this[0]; }, @@ -273,7 +273,7 @@ function taskArgs(args) { enumerable: true }); - Object.defineProperty(res, `cb`, { + Object.defineProperty(res, 'cb', { get: function () { return this[1]; }, diff --git a/test/adapter.spec.js b/test/adapter.spec.js index 21459dc67..27c19ad64 100644 --- a/test/adapter.spec.js +++ b/test/adapter.spec.js @@ -1,14 +1,14 @@ -const pgp = require(`../lib/index`); +const pgp = require('../lib/index'); const {PromiseAdapter} = pgp; const dummy = () => { }; -describe(`Adapter`, () => { +describe('Adapter', () => { - describe(`with invalid parameters`, () => { - const error = `Adapter requires an api configuration object.`; - it(`must throw an error`, () => { + describe('with invalid parameters', () => { + const error = 'Adapter requires an api configuration object.'; + it('must throw an error', () => { expect(() => { new PromiseAdapter(); }).toThrow(error); @@ -19,45 +19,45 @@ describe(`Adapter`, () => { new PromiseAdapter(123); }).toThrow(error); expect(() => { - new PromiseAdapter(`test`); + new PromiseAdapter('test'); }).toThrow(error); }); }); - describe(`with invalid 'create'`, () => { - it(`must throw an error`, () => { + describe('with invalid \'create\'', () => { + it('must throw an error', () => { expect(() => { new PromiseAdapter({}); - }).toThrow(`Function 'create' must be specified.`); + }).toThrow('Function \'create\' must be specified.'); }); }); - describe(`with invalid 'resolve'`, () => { - it(`must throw an error`, () => { + describe('with invalid \'resolve\'', () => { + it('must throw an error', () => { expect(() => { new PromiseAdapter({create: dummy}); - }).toThrow(`Function 'resolve' must be specified.`); + }).toThrow('Function \'resolve\' must be specified.'); }); }); - describe(`with invalid 'reject'`, () => { - it(`must throw an error`, () => { + describe('with invalid \'reject\'', () => { + it('must throw an error', () => { expect(() => { new PromiseAdapter({create: dummy, resolve: dummy}); - }).toThrow(`Function 'reject' must be specified.`); + }).toThrow('Function \'reject\' must be specified.'); }); }); - describe(`with invalid 'all'`, () => { - it(`must throw an error`, () => { + describe('with invalid \'all\'', () => { + it('must throw an error', () => { expect(() => { new PromiseAdapter({create: dummy, resolve: dummy, reject: dummy}); - }).toThrow(`Function 'all' must be specified.`); + }).toThrow('Function \'all\' must be specified.'); }); }); - describe(`with all valid parameters`, () => { - it(`must be successful`, () => { + describe('with all valid parameters', () => { + it('must be successful', () => { const adapter = new PromiseAdapter({create: dummy, resolve: dummy, reject: dummy, all: dummy}); expect(adapter instanceof PromiseAdapter).toBe(true); }); diff --git a/test/color.spec.js b/test/color.spec.js index fc1e220e6..b2d6a6385 100644 --- a/test/color.spec.js +++ b/test/color.spec.js @@ -1,38 +1,38 @@ -const {ColorConsole} = require(`../lib/utils/color`); +const {ColorConsole} = require('../lib/utils/color'); -describe(`protocol`, () => { - it(`must have the right signature`, () => { - expect(typeof ColorConsole).toBe(`function`); - expect(typeof ColorConsole.log).toBe(`function`); - expect(typeof ColorConsole.log.bright).toBe(`function`); - expect(typeof ColorConsole.info).toBe(`function`); - expect(typeof ColorConsole.info.bright).toBe(`function`); - expect(typeof ColorConsole.warn).toBe(`function`); - expect(typeof ColorConsole.warn.bright).toBe(`function`); - expect(typeof ColorConsole.error).toBe(`function`); - expect(typeof ColorConsole.error.bright).toBe(`function`); - expect(typeof ColorConsole.success).toBe(`function`); - expect(typeof ColorConsole.success.bright).toBe(`function`); +describe('protocol', () => { + it('must have the right signature', () => { + expect(typeof ColorConsole).toBe('function'); + expect(typeof ColorConsole.log).toBe('function'); + expect(typeof ColorConsole.log.bright).toBe('function'); + expect(typeof ColorConsole.info).toBe('function'); + expect(typeof ColorConsole.info.bright).toBe('function'); + expect(typeof ColorConsole.warn).toBe('function'); + expect(typeof ColorConsole.warn.bright).toBe('function'); + expect(typeof ColorConsole.error).toBe('function'); + expect(typeof ColorConsole.error.bright).toBe('function'); + expect(typeof ColorConsole.success).toBe('function'); + expect(typeof ColorConsole.success.bright).toBe('function'); }); }); -describe(`text`, () => { - it(`must match`, () => { - expect(invoke(ColorConsole.log, `log`)).toEqual([`log`]); - expect(invoke(ColorConsole.log.bright, [`one`, `two`])).toEqual([`one`, `two`]); - expect(invoke(ColorConsole.info, `info`)).toEqual([`info`]); - expect(invoke(ColorConsole.info.bright, [`one`, `two`])).toEqual([`one`, `two`]); - expect(invoke(ColorConsole.warn, `warning`)).toEqual([`warning`]); - expect(invoke(ColorConsole.warn.bright, [`one`, `two`])).toEqual([`one`, `two`]); - expect(invoke(ColorConsole.success, `success`)).toEqual([`success`]); - expect(invoke(ColorConsole.success.bright, [`one`, `two`])).toEqual([`one`, `two`]); - expect(invoke(ColorConsole.error, `error`, true)).toEqual([`error`]); - expect(invoke(ColorConsole.error.bright, [`one`, `two`], true)).toEqual([`one`, `two`]); +describe('text', () => { + it('must match', () => { + expect(invoke(ColorConsole.log, 'log')).toEqual(['log']); + expect(invoke(ColorConsole.log.bright, ['one', 'two'])).toEqual(['one', 'two']); + expect(invoke(ColorConsole.info, 'info')).toEqual(['info']); + expect(invoke(ColorConsole.info.bright, ['one', 'two'])).toEqual(['one', 'two']); + expect(invoke(ColorConsole.warn, 'warning')).toEqual(['warning']); + expect(invoke(ColorConsole.warn.bright, ['one', 'two'])).toEqual(['one', 'two']); + expect(invoke(ColorConsole.success, 'success')).toEqual(['success']); + expect(invoke(ColorConsole.success.bright, ['one', 'two'])).toEqual(['one', 'two']); + expect(invoke(ColorConsole.error, 'error', true)).toEqual(['error']); + expect(invoke(ColorConsole.error.bright, ['one', 'two'], true)).toEqual(['one', 'two']); }); function invoke(method, text, isErr) { text = Array.isArray(text) ? text : [text]; - const name = isErr ? `error` : `log`; + const name = isErr ? 'error' : 'log'; const old = console[name]; // eslint-disable-line no-console let res; console[name] = function () { // eslint-disable-line no-console @@ -46,5 +46,5 @@ describe(`text`, () => { function removeColors(text) { /*eslint no-control-regex: 0*/ - return text.replace(/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g, ``); + return text.replace(/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g, ''); } diff --git a/test/db.spec.js b/test/db.spec.js index b183b1e1c..9ea2c9ce1 100644 --- a/test/db.spec.js +++ b/test/db.spec.js @@ -1,15 +1,15 @@ const npm = { - util: require(`util`), - platform: require(`os`).platform() + util: require('util'), + platform: require('os').platform() }; -const capture = require(`./db/capture`); -const pgResult = require(`pg/lib/result`); -const header = require(`./db/header`); -const tools = require(`./db/tools`); +const capture = require('./db/capture'); +const pgResult = require('pg/lib/result'); +const header = require('./db/header'); +const tools = require('./db/tools'); -const isMac = npm.platform === `darwin`; -const isWindows = npm.platform === `win32`; +const isMac = npm.platform === 'darwin'; +const isWindows = npm.platform === 'win32'; const promise = header.defPromise; const options = { @@ -34,62 +34,61 @@ function isResult(value) { return value instanceof pgResult; } -const $text = require(`../lib/text`); +const $text = require('../lib/text'); -describe(`Database Instantiation`, () => { - it(`must throw an invalid connection passed`, () => { - const errBody = `Invalid connection details: `; - expect(pgp).toThrow(errBody + `undefined`); +describe('Database Instantiation', () => { + it('must throw an invalid connection passed', () => { + const errBody = 'Invalid connection details: '; + expect(pgp).toThrow(errBody + 'undefined'); expect(() => { pgp(null); - }).toThrow(errBody + `null`); + }).toThrow(errBody + 'null'); expect(() => { - pgp(``); - }).toThrow(errBody + `""`); + pgp(''); + }).toThrow(errBody + '""'); expect(() => { - pgp(` `); - }).toThrow(errBody + `" "`); + pgp(' '); + }).toThrow(errBody + '" "'); expect(() => { pgp(123); - }).toThrow(errBody + `123`); + }).toThrow(errBody + '123'); }); }); -describe(`Connection`, () => { +describe('Connection', () => { - describe(`with default parameters`, () => { - let status = `connecting`, error, doneRes; + describe('with default parameters', () => { + let status = 'connecting', error, doneRes; beforeEach(done => { db.connect() .then(obj => { - status = `success`; + status = 'success'; doneRes = obj.done(); // release connection; }, reason => { error = reason; - status = `failed`;//reason.error; + status = 'failed';//reason.error; }) .catch(err => { error = err; - status = `exception`; + status = 'exception'; }) .finally(done); }); - it(`must be successful`, () => { - expect(status).toBe(`success`); + it('must be successful', () => { + expect(status).toBe('success'); expect(error).toBeUndefined(); expect(doneRes).toBeUndefined(); }); }); - describe(`for regular queries`, () => { + describe('for regular queries', () => { let result, sco; beforeEach(done => { db.connect() .then(obj => { sco = obj; - return sco.one(`select count(*) - from users`); + return sco.one('select count(*) from users'); }) .catch(reason => { result = null; @@ -108,21 +107,20 @@ describe(`Connection`, () => { done(); }); }); - it(`must provide functioning context`, () => { + it('must provide functioning context', () => { expect(result).toBeDefined(); expect(result.count > 0).toBe(true); - expect(typeof sco.tx).toBe(`function`); // just a protocol check; + expect(typeof sco.tx).toBe('function'); // just a protocol check; }); }); - describe(`for raw queries`, () => { + describe('for raw queries', () => { let result, sco; beforeEach(done => { db.connect() .then(obj => { sco = obj; - return sco.result(`select * - from users`); + return sco.result('select * from users'); }) .catch(reason => { result = null; @@ -141,27 +139,27 @@ describe(`Connection`, () => { done(); }); }); - it(`must provide functioning context`, () => { + it('must provide functioning context', () => { expect(isResult(result)).toBe(true); expect(result.rows.length > 0).toBe(true); - expect(typeof result.rowCount).toBe(`number`); - expect(typeof result.duration).toBe(`number`); + expect(typeof result.rowCount).toBe('number'); + expect(typeof result.duration).toBe('number'); expect(result.rows.length === result.rowCount).toBe(true); }); }); - describe(`for invalid port`, () => { + describe('for invalid port', () => { let errCN, dbErr, result, log; beforeEach(() => { errCN = JSON.parse(JSON.stringify(dbHeader.cn)); // dumb connection cloning; errCN.port = 9999; - errCN.password = `########`; + errCN.password = '########'; dbErr = pgp(errCN); options.error = function (err, e) { log = {err, e}; }; }); - describe(`using connect()`, () => { + describe('using connect()', () => { beforeEach(done => { dbErr.connect() .catch(error => { @@ -169,19 +167,19 @@ describe(`Connection`, () => { }) .finally(done); }); - it(`must report the right error`, () => { + it('must report the right error', () => { expect(log.e.cn).toEqual(errCN); expect(result instanceof Error).toBe(true); if (options.pgNative) { - expect(result.message).toContain(`could not connect to server`); + expect(result.message).toContain('could not connect to server'); } else { - expect(result.message).toContain(`connect ECONNREFUSED`); + expect(result.message).toContain('connect ECONNREFUSED'); } }); }); - describe(`with transaction connection`, () => { + describe('with transaction connection', () => { beforeEach(done => { dbErr.tx(dummy) .catch(error => { @@ -189,12 +187,12 @@ describe(`Connection`, () => { }) .finally(done); }); - it(`must report the right error`, () => { + it('must report the right error', () => { expect(result instanceof Error).toBe(true); if (options.pgNative) { - expect(result.message).toContain(`could not connect to server`); + expect(result.message).toContain('could not connect to server'); } else { - expect(result.message).toContain(`connect ECONNREFUSED`); + expect(result.message).toContain('connect ECONNREFUSED'); } }); }); @@ -203,9 +201,9 @@ describe(`Connection`, () => { }); }); - describe(`for an invalid port`, () => { + describe('for an invalid port', () => { const errCN = JSON.parse(JSON.stringify(dbHeader.cn)); // dumb connection cloning; - errCN.port = `12345`; + errCN.port = '12345'; const dbErr = pgp(errCN); let result; beforeEach(done => { @@ -215,17 +213,17 @@ describe(`Connection`, () => { }) .finally(done); }); - it(`must report the right error`, () => { + it('must report the right error', () => { expect(result instanceof Error).toBe(true); if (options.pgNative) { - expect(result.message).toContain(`could not connect to server`); + expect(result.message).toContain('could not connect to server'); } else { - expect(result.message).toContain(`connect ECONNREFUSED`); + expect(result.message).toContain('connect ECONNREFUSED'); } }); }); - describe(`direct end() call`, () => { + describe('direct end() call', () => { let txt; beforeEach(done => { db.connect() @@ -237,7 +235,7 @@ describe(`Connection`, () => { }) .finally(done); }); - it(`must be reported into the console`, () => { + it('must be reported into the console', () => { expect(txt).toContain($text.clientEnd); }); }); @@ -246,8 +244,8 @@ describe(`Connection`, () => { /* Disabled this test on 14/11/2020, since it started showing crypto-related issues on Windows; */ - describe(`for invalid connection`, () => { - const dbErr = pgp(`bla-bla`); + describe('for invalid connection', () => { + const dbErr = pgp('bla-bla'); let error; beforeEach(done => { dbErr.connect() @@ -256,14 +254,14 @@ describe(`Connection`, () => { }) .finally(done); }); - it(`must report the right error`, () => { - const oldStyleError = `database "bla-bla" does not exist`; // Before PostgreSQL v.10 - const newStyleError = `role ` + JSON.stringify(pgp.pg.defaults.user) + ` does not exist`; + it('must report the right error', () => { + const oldStyleError = 'database "bla-bla" does not exist'; // Before PostgreSQL v.10 + const newStyleError = 'role ' + JSON.stringify(pgp.pg.defaults.user) + ' does not exist'; expect(error instanceof Error).toBe(true); if (isMac) { expect(error.message.indexOf(oldStyleError) >= 0 || error.message.indexOf(newStyleError) >= 0).toBe(true); } else { - expect(error.message).toContain(`password authentication failed for user`); + expect(error.message).toContain('password authentication failed for user'); } }); }); @@ -273,9 +271,9 @@ describe(`Connection`, () => { /* Disabled this test on 14/11/2020, since it started showing crypto-related issues on Windows; */ - describe(`for invalid user name`, () => { + describe('for invalid user name', () => { const errCN = JSON.parse(JSON.stringify(dbHeader.cn)); // dumb connection cloning; - errCN.user = `somebody`; + errCN.user = 'somebody'; const dbErr = pgp(errCN); let error; beforeEach(done => { @@ -285,11 +283,11 @@ describe(`Connection`, () => { }) .finally(done); }); - it(`must report the right error`, () => { + it('must report the right error', () => { expect(error instanceof Error).toBe(true); - const reportError = `password authentication failed for user "somebody"`; + const reportError = 'password authentication failed for user "somebody"'; if (isMac) { - expect(error.message).toContain(`role "somebody" does not exist`); + expect(error.message).toContain('role "somebody" does not exist'); } else { expect(error.message).toContain(reportError); } @@ -297,7 +295,7 @@ describe(`Connection`, () => { }); } - describe(`on repeated disconnection`, () => { + describe('on repeated disconnection', () => { let error; beforeEach(done => { db.connect() @@ -314,13 +312,13 @@ describe(`Connection`, () => { }) .finally(done); }); - it(`must throw the right error`, () => { + it('must throw the right error', () => { expect(error instanceof Error).toBe(true); expect(error.message).toBe($text.looseQuery); }); }); - describe(`when executing a disconnected query`, () => { + describe('when executing a disconnected query', () => { let error; beforeEach(done => { db.connect() @@ -333,14 +331,14 @@ describe(`Connection`, () => { }) .finally(done); }); - it(`must throw the right error`, () => { + it('must throw the right error', () => { expect(error instanceof Error).toBe(true); expect(error.message).toBe($text.queryDisconnected); }); }); - describe(`external closing of the connection pool`, () => { - const tmpDB = pgp(`postgres://postgres:password@localhost:5432/invalidDB`); + describe('external closing of the connection pool', () => { + const tmpDB = pgp('postgres://postgres:password@localhost:5432/invalidDB'); let error; beforeEach(done => { tmpDB.$pool.end(); @@ -350,7 +348,7 @@ describe(`Connection`, () => { }) .finally(done); }); - it(`must be handled`, () => { + it('must be handled', () => { expect(error).toEqual(new Error($text.poolDestroyed)); }); }); @@ -360,7 +358,7 @@ describe(`Connection`, () => { This test has been known to be very flaky, especially on Windows, and keeps getting in the way of testing the framework locally. */ - describe(`db side closing of the connection pool`, () => { + describe('db side closing of the connection pool', () => { const singleCN = JSON.parse(JSON.stringify(dbHeader.cn)); // dumb connection cloning; singleCN.max = 1; const dbSingleCN = pgp(singleCN); @@ -370,20 +368,18 @@ describe(`Connection`, () => { beforeEach(done => { dbSingleCN.connect() .then(obj => { - obj.func(`pg_backend_pid`) + obj.func('pg_backend_pid') .then(res => { const pid = res[0].pg_backend_pid; return promise.all([ - obj.func(`pg_sleep`, [2]) + obj.func('pg_sleep', [2]) .catch(reason => { error = reason; }), // Terminate connection after a short delay, before the query finishes promise.delay(1000) .then(() => - db.one(`SELECT pg_terminate_backend(pid) - FROM pg_stat_activity - WHERE pid = $1`, pid) + db.one('SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid = $1', pid) ) ]) .finally(() => { @@ -394,16 +390,16 @@ describe(`Connection`, () => { }); }); - it(`returns the postgres error`, () => { + it('returns the postgres error', () => { expect(error instanceof Error).toBe(true); - expect(error.code).toEqual(`57P01`); - expect(error.message).toEqual(`terminating connection due to administrator command`); + expect(error.code).toEqual('57P01'); + expect(error.message).toEqual('terminating connection due to administrator command'); }); - it(`releases the client from the pool`, done => { + it('releases the client from the pool', done => { let result, singleError; - dbSingleCN.one(`SELECT 1 as test`) + dbSingleCN.one('SELECT 1 as test') .then(data => { result = data; }) @@ -420,9 +416,9 @@ describe(`Connection`, () => { } }); -describe(`Direct Connection`, () => { +describe('Direct Connection', () => { - describe(`successful connection`, () => { + describe('successful connection', () => { let sco, doneRes; beforeEach(done => { db.connect({direct: true}) @@ -432,13 +428,13 @@ describe(`Direct Connection`, () => { done(); }); }); - it(`must connect correctly`, () => { - expect(typeof sco).toBe(`object`); - expect(doneRes && typeof doneRes.then === `function`).toBe(true); + it('must connect correctly', () => { + expect(typeof sco).toBe('object'); + expect(doneRes && typeof doneRes.then === 'function').toBe(true); }); }); - describe(`direct end() call`, () => { + describe('direct end() call', () => { let txt; beforeEach(done => { db.connect({direct: true}) @@ -449,14 +445,14 @@ describe(`Direct Connection`, () => { done(); }); }); - it(`must be reported into the console`, () => { + it('must be reported into the console', () => { expect(txt).toContain($text.clientEnd); }); }); - describe(`for an invalid port`, () => { + describe('for an invalid port', () => { const errCN = JSON.parse(JSON.stringify(dbHeader.cn)); // dumb connection cloning; - errCN.port = `12345`; + errCN.port = '12345'; const dbErr = pgp(errCN); let result; beforeEach(done => { @@ -469,19 +465,19 @@ describe(`Direct Connection`, () => { }) .finally(done); }); - it(`must report the right error`, () => { + it('must report the right error', () => { expect(result instanceof Error).toBe(true); if (options.pgNative) { - expect(result.message).toContain(`could not connect to server`); + expect(result.message).toContain('could not connect to server'); } else { - expect(result.message).toContain(`connect ECONNREFUSED`); + expect(result.message).toContain('connect ECONNREFUSED'); } }); }); }); -describe(`Masked Connection Log`, () => { +describe('Masked Connection Log', () => { let cn; beforeEach(() => { @@ -489,12 +485,12 @@ describe(`Masked Connection Log`, () => { cn = e.cn; }; }); - describe(`as an object`, () => { + describe('as an object', () => { const connection = { - host: `localhost`, + host: 'localhost', port: 123, - user: `unknown`, - password: `123` + user: 'unknown', + password: '123' }; beforeEach(done => { const errDB = pgp(connection); @@ -503,34 +499,34 @@ describe(`Masked Connection Log`, () => { done(); }); }); - it(`must report the password masked correctly`, () => { - expect(cn.password).toEqual(`###`); + it('must report the password masked correctly', () => { + expect(cn.password).toEqual('###'); }); }); - describe(`as a string`, () => { + describe('as a string', () => { beforeEach(done => { - const errDB = pgp(`postgres://postgres:password@localhost:123/unknown`); + const errDB = pgp('postgres://postgres:password@localhost:123/unknown'); errDB.connect() .catch(() => { done(); }); }); - it(`must report the password masked correctly`, () => { - expect(cn).toBe(`postgres://postgres:########@localhost:123/unknown`); + it('must report the password masked correctly', () => { + expect(cn).toBe('postgres://postgres:########@localhost:123/unknown'); }); }); - describe(`as a config string`, () => { + describe('as a config string', () => { beforeEach(done => { - const errDB = pgp({connectionString: `postgres://postgres:password@localhost:123/unknown`}); + const errDB = pgp({connectionString: 'postgres://postgres:password@localhost:123/unknown'}); errDB.connect() .catch(() => { done(); }); }); - it(`must report the password masked correctly`, () => { - expect(cn).toEqual({connectionString: `postgres://postgres:########@localhost:123/unknown`}); + it('must report the password masked correctly', () => { + expect(cn).toEqual({connectionString: 'postgres://postgres:########@localhost:123/unknown'}); }); }); @@ -540,12 +536,12 @@ describe(`Masked Connection Log`, () => { }); }); -describe(`Method 'map'`, () => { +describe('Method \'map\'', () => { - describe(`positive:`, () => { + describe('positive:', () => { let pValue, pIndex, pArr, pData; beforeEach(done => { - db.map(`SELECT 1 as value`, null, (value, index, arr) => { + db.map('SELECT 1 as value', null, (value, index, arr) => { pValue = value; pIndex = index; pArr = arr; @@ -556,7 +552,7 @@ describe(`Method 'map'`, () => { done(); }); }); - it(`must resolve with the right value`, () => { + it('must resolve with the right value', () => { expect(pValue).toEqual({value: 1}); expect(pIndex).toBe(0); expect(pArr).toEqual([{value: 1}]); @@ -564,48 +560,48 @@ describe(`Method 'map'`, () => { }); }); - describe(`negative:`, () => { + describe('negative:', () => { - describe(`with invalid parameters`, () => { + describe('with invalid parameters', () => { let err; beforeEach(done => { - db.map(`SELECT 1`) + db.map('SELECT 1') .catch(error => { err = error; }) .finally(done); }); - it(`must reject with an error`, () => { + it('must reject with an error', () => { expect(err instanceof TypeError).toBe(true); - expect(err.message).toContain(`is not a function`); + expect(err.message).toContain('is not a function'); }); }); - describe(`with error thrown inside the callback`, () => { + describe('with error thrown inside the callback', () => { let err; beforeEach(done => { - db.map(`SELECT 1`, null, () => { - throw new Error(`Ops!`); + db.map('SELECT 1', null, () => { + throw new Error('Ops!'); }) .catch(error => { err = error; }) .finally(done); }); - it(`must reject with an error`, () => { - expect(err).toEqual(new Error(`Ops!`)); + it('must reject with an error', () => { + expect(err).toEqual(new Error('Ops!')); }); }); }); }); -describe(`Method 'each'`, () => { +describe('Method \'each\'', () => { - describe(`positive:`, () => { + describe('positive:', () => { let pValue, pIndex, pArr, pData; beforeEach(done => { - db.each(`SELECT 1 as value`, null, (value, index, arr) => { + db.each('SELECT 1 as value', null, (value, index, arr) => { pValue = value; pIndex = index; pArr = arr; @@ -616,7 +612,7 @@ describe(`Method 'each'`, () => { done(); }); }); - it(`must resolve with the right value`, () => { + it('must resolve with the right value', () => { expect(pValue).toEqual({value: 2}); expect(pIndex).toBe(0); expect(pArr).toEqual([{value: 2}]); @@ -624,49 +620,47 @@ describe(`Method 'each'`, () => { }); }); - describe(`negative:`, () => { + describe('negative:', () => { - describe(`with invalid parameters`, () => { + describe('with invalid parameters', () => { let err; beforeEach(done => { - db.each(`SELECT 1`) + db.each('SELECT 1') .catch(error => { err = error; }) .finally(done); }); - it(`must reject with an error`, () => { + it('must reject with an error', () => { expect(err instanceof TypeError).toBe(true); - expect(err.message).toContain(`is not a function`); + expect(err.message).toContain('is not a function'); }); }); - describe(`with error thrown inside the callback`, () => { + describe('with error thrown inside the callback', () => { let err; beforeEach(done => { - db.each(`SELECT 1`, null, () => { - throw new Error(`Ops!`); + db.each('SELECT 1', null, () => { + throw new Error('Ops!'); }) .catch(error => { err = error; }) .finally(done); }); - it(`must reject with an error`, () => { - expect(err).toEqual(new Error(`Ops!`)); + it('must reject with an error', () => { + expect(err).toEqual(new Error('Ops!')); }); }); }); }); -describe(`Method 'none'`, () => { +describe('Method \'none\'', () => { - it(`must resolve with 'null'`, () => { + it('must resolve with \'null\'', () => { let result, error, finished; - db.none(`select * - from users - where id = $1`, 12345678) + db.none('select * from users where id = $1', 12345678) .then(data => { result = data; }) @@ -676,19 +670,18 @@ describe(`Method 'none'`, () => { .finally(() => { finished = true; }); - waitsFor(() => finished === true, `Query timed out`, 5000); + waitsFor(() => finished === true, 'Query timed out', 5000); runs(() => { expect(error).toBeUndefined(); expect(result).toBe(null); }); }); - describe(`when any data is returned`, () => { + describe('when any data is returned', () => { - it(`must reject for a single query`, () => { + it('must reject for a single query', () => { let result, error, finished; - db.none(`select * - from users`) + db.none('select * from users') .then(data => { result = data; }) @@ -698,7 +691,7 @@ describe(`Method 'none'`, () => { .finally(() => { finished = true; }); - waitsFor(() => finished === true, `Query timed out`, 5000); + waitsFor(() => finished === true, 'Query timed out', 5000); runs(() => { expect(result).toBeUndefined(); expect(error instanceof pgp.errors.QueryResultError).toBe(true); @@ -708,11 +701,9 @@ describe(`Method 'none'`, () => { }); }); - it(`must reject for multi-queries`, () => { + it('must reject for multi-queries', () => { let result, error, finished; - db.none(`select 1; - select * - from users`) + db.none('select 1; select * from users') .then(data => { result = data; }) @@ -722,7 +713,7 @@ describe(`Method 'none'`, () => { .finally(() => { finished = true; }); - waitsFor(() => finished === true, `Query timed out`, 5000); + waitsFor(() => finished === true, 'Query timed out', 5000); runs(() => { expect(result).toBeUndefined(); expect(error instanceof pgp.errors.QueryResultError).toBe(true); @@ -736,11 +727,11 @@ describe(`Method 'none'`, () => { }); -describe(`Method 'one'`, () => { +describe('Method \'one\'', () => { - it(`must resolve with one object`, () => { + it('must resolve with one object', () => { let result, error; - db.one(`select 123 as value`) + db.one('select 123 as value') .then(data => { result = data; }) @@ -750,21 +741,20 @@ describe(`Method 'one'`, () => { }); waitsFor(() => { return result !== undefined; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(error).toBeUndefined(); - expect(typeof result).toBe(`object`); + expect(typeof result).toBe('object'); expect(result.value).toBe(123); }); }); - describe(`value transformation`, () => { + describe('value transformation', () => { let result, context; beforeEach(done => { - db.one(`select count(*) - from users`, null, function (value) { + db.one('select count(*) from users', null, function (value) { 'use strict'; - // NOTE: Outside of strict mode, only objects can be passed in as this context + // NOTE: Outside the strict mode, only objects can be passed in as this context context = this; return parseInt(value.count); }, 123) @@ -773,20 +763,18 @@ describe(`Method 'one'`, () => { done(); }); }); - it(`must resolve with the new value`, () => { - expect(typeof result).toBe(`number`); + it('must resolve with the new value', () => { + expect(typeof result).toBe('number'); expect(result > 0).toBe(true); expect(context).toBe(123); }); }); - describe(`when no data found`, () => { + describe('when no data found', () => { - it(`must reject for a single query`, () => { + it('must reject for a single query', () => { let result, error, finished; - db.one(`select * - from users - where id = $1`, 12345678) + db.one('select * from users where id = $1', 12345678) .then(data => { result = data; }) @@ -796,7 +784,7 @@ describe(`Method 'one'`, () => { .finally(() => { finished = true; }); - waitsFor(() => finished === true, `Query timed out`, 5000); + waitsFor(() => finished === true, 'Query timed out', 5000); runs(() => { expect(result).toBeUndefined(); expect(error instanceof pgp.errors.QueryResultError).toBe(true); @@ -805,12 +793,9 @@ describe(`Method 'one'`, () => { }); }); - it(`must reject for a multi-query`, () => { + it('must reject for a multi-query', () => { let result, error, finished; - db.one(`select 1; - select * - from users - where id = $1`, 12345678) + db.one('select 1; select * from users where id = $1', 12345678) .then(data => { result = data; }) @@ -820,7 +805,7 @@ describe(`Method 'one'`, () => { .finally(() => { finished = true; }); - waitsFor(() => finished === true, `Query timed out`, 5000); + waitsFor(() => finished === true, 'Query timed out', 5000); runs(() => { expect(result).toBeUndefined(); expect(error instanceof pgp.errors.QueryResultError).toBe(true); @@ -831,11 +816,10 @@ describe(`Method 'one'`, () => { }); - describe(`When multiple rows are found`, () => { - it(`must reject for a single query`, () => { + describe('When multiple rows are found', () => { + it('must reject for a single query', () => { let result, error, finished; - db.one(`select * - from users`) + db.one('select * from users') .then(data => { result = data; }) @@ -845,7 +829,7 @@ describe(`Method 'one'`, () => { .finally(() => { finished = true; }); - waitsFor(() => finished === true, `Query timed out`, 5000); + waitsFor(() => finished === true, 'Query timed out', 5000); runs(() => { expect(result).toBeUndefined(); expect(error instanceof pgp.errors.QueryResultError).toBe(true); @@ -853,11 +837,9 @@ describe(`Method 'one'`, () => { expect(error.result.rows.length).toBeGreaterThan(0); }); }); - it(`must reject for a multi-query`, () => { + it('must reject for a multi-query', () => { let result, error, finished; - db.one(`select 1; - select * - from users`) + db.one('select 1; select * from users') .then(data => { result = data; }) @@ -867,7 +849,7 @@ describe(`Method 'one'`, () => { .finally(() => { finished = true; }); - waitsFor(() => finished === true, `Query timed out`, 5000); + waitsFor(() => finished === true, 'Query timed out', 5000); runs(() => { expect(result).toBeUndefined(); expect(error instanceof pgp.errors.QueryResultError).toBe(true); @@ -880,13 +862,11 @@ describe(`Method 'one'`, () => { }); -describe(`Method 'oneOrNone'`, () => { +describe('Method \'oneOrNone\'', () => { - it(`must resolve with one object when found`, () => { + it('must resolve with one object when found', () => { let result, error; - db.oneOrNone(`select * - from users - where id = $1`, 1) + db.oneOrNone('select * from users where id = $1', 1) .then(data => { result = data; }) @@ -896,19 +876,17 @@ describe(`Method 'oneOrNone'`, () => { }); waitsFor(() => { return result !== undefined; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(error).toBeUndefined(); - expect(typeof result).toBe(`object`); + expect(typeof result).toBe('object'); expect(result.id).toBe(1); }); }); - it(`must resolve with null when no data found`, () => { + it('must resolve with null when no data found', () => { let result, error, finished; - db.oneOrNone(`select * - from users - where id = $1`, 12345678) + db.oneOrNone('select * from users where id = $1', 12345678) .then(data => { result = data; finished = true; @@ -918,20 +896,19 @@ describe(`Method 'oneOrNone'`, () => { }); waitsFor(() => { return finished === true; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(error).toBeUndefined(); expect(result).toBeNull(); }); }); - describe(`value transformation`, () => { + describe('value transformation', () => { let result, context; beforeEach(done => { - db.oneOrNone(`select count(*) - from users`, null, function (value) { + db.oneOrNone('select count(*) from users', null, function (value) { 'use strict'; - // NOTE: Outside of strict mode, only objects can be passed in as this context + // NOTE: Outside strict mode, only objects can be passed in as this context context = this; return parseInt(value.count); }, 123) @@ -940,17 +917,16 @@ describe(`Method 'oneOrNone'`, () => { done(); }); }); - it(`must resolve with the new value`, () => { - expect(typeof result).toBe(`number`); + it('must resolve with the new value', () => { + expect(typeof result).toBe('number'); expect(result > 0).toBe(true); expect(context).toBe(123); }); }); - it(`must reject when multiple rows are found`, () => { + it('must reject when multiple rows are found', () => { let result, error, finished; - db.oneOrNone(`select * - from users`) + db.oneOrNone('select * from users') .then(data => { result = data; finished = true; @@ -960,7 +936,7 @@ describe(`Method 'oneOrNone'`, () => { }); waitsFor(() => { return finished === true; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(result).toBeUndefined(); expect(error instanceof pgp.errors.QueryResultError).toBe(true); @@ -970,12 +946,11 @@ describe(`Method 'oneOrNone'`, () => { }); -describe(`Method 'many'`, () => { +describe('Method \'many\'', () => { - it(`must resolve with array of objects`, () => { + it('must resolve with array of objects', () => { let result, error; - db.many(`select * - from users`) + db.many('select * from users') .then(data => { result = data; }, reason => { @@ -984,7 +959,7 @@ describe(`Method 'many'`, () => { }); waitsFor(() => { return result !== undefined; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(error).toBeUndefined(); expect(Array.isArray(result)).toBe(true); @@ -992,11 +967,9 @@ describe(`Method 'many'`, () => { }); }); - it(`must reject when no data found`, () => { + it('must reject when no data found', () => { let result, error, finished; - db.many(`select * - from users - where id = $1`, 12345678) + db.many('select * from users where id = $1', 12345678) .then(data => { result = data; finished = true; @@ -1006,7 +979,7 @@ describe(`Method 'many'`, () => { }); waitsFor(() => { return finished === true; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(result).toBeUndefined(); expect(error instanceof pgp.errors.QueryResultError).toBe(true); @@ -1016,12 +989,11 @@ describe(`Method 'many'`, () => { }); -describe(`Method 'manyOrNone'`, () => { +describe('Method \'manyOrNone\'', () => { - it(`must resolve with array of objects`, () => { + it('must resolve with array of objects', () => { let result, error; - db.manyOrNone(`select * - from users`) + db.manyOrNone('select * from users') .then(data => { result = data; }, reason => { @@ -1030,7 +1002,7 @@ describe(`Method 'manyOrNone'`, () => { }); waitsFor(() => { return result !== undefined; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(error).toBeUndefined(); expect(Array.isArray(result)).toBe(true); @@ -1038,11 +1010,9 @@ describe(`Method 'manyOrNone'`, () => { }); }); - it(`must resolve with an empty array when no data found`, () => { + it('must resolve with an empty array when no data found', () => { let result, error, finished; - db.manyOrNone(`select * - from users - where id = $1`, 12345678) + db.manyOrNone('select * from users where id = $1', 12345678) .then(data => { result = data; finished = true; @@ -1052,7 +1022,7 @@ describe(`Method 'manyOrNone'`, () => { }); waitsFor(() => { return finished === true; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(error).toBeUndefined(); expect(Array.isArray(result)).toBe(true); @@ -1062,15 +1032,15 @@ describe(`Method 'manyOrNone'`, () => { }); -describe(`Executing method query`, () => { +describe('Executing method query', () => { - describe(`with invalid query as parameter`, () => { + describe('with invalid query as parameter', () => { let result; beforeEach(done => { promise.any([ db.query(), - db.query(``), - db.query(` `), + db.query(''), + db.query(' '), db.query({}), db.query(1), db.query(null)]) @@ -1079,7 +1049,7 @@ describe(`Executing method query`, () => { }) .finally(done); }); - it(`must throw an error`, () => { + it('must throw an error', () => { expect(result.length).toBe(6); expect(result[0].message).toBe($text.invalidQuery); // reject to an undefined query; expect(result[1].message).toBe($text.invalidQuery); // reject to an empty-string query; @@ -1090,26 +1060,26 @@ describe(`Executing method query`, () => { }); }); - describe(`with invalid qrm as parameter`, () => { + describe('with invalid qrm as parameter', () => { let result; beforeEach(done => { promise.any([ - db.query(`something`, undefined, ``), - db.query(`something`, undefined, `2`), - db.query(`something`, undefined, -1), - db.query(`something`, undefined, 0), - db.query(`something`, undefined, 100), - db.query(`something`, undefined, NaN), - db.query(`something`, undefined, 1 / 0), - db.query(`something`, undefined, -1 / 0), - db.query(`something`, undefined, 2.45)]) + db.query('something', undefined, ''), + db.query('something', undefined, '2'), + db.query('something', undefined, -1), + db.query('something', undefined, 0), + db.query('something', undefined, 100), + db.query('something', undefined, NaN), + db.query('something', undefined, 1 / 0), + db.query('something', undefined, -1 / 0), + db.query('something', undefined, 2.45)]) .catch(err => { result = err; }) .finally(done); }); - it(`must throw an error`, () => { - const error = `Invalid Query Result Mask specified.`; + it('must throw an error', () => { + const error = 'Invalid Query Result Mask specified.'; expect(result.length).toBe(9); for (let i = 0; i < 9; i++) { expect(result[i] instanceof TypeError).toBe(true); @@ -1118,14 +1088,14 @@ describe(`Executing method query`, () => { }); }); - describe(`with query as function`, () => { - describe(`for normal functions`, () => { + describe('with query as function', () => { + describe('for normal functions', () => { const context = []; - const getQuery1 = () => `select 123 as value`; + const getQuery1 = () => 'select 123 as value'; function getQuery2(values) { context.push(this); - return pgp.as.format(`select $1 as value`, values); + return pgp.as.format('select $1 as value', values); } const getQuery3 = () => getQuery2; @@ -1143,16 +1113,16 @@ describe(`Executing method query`, () => { }) .finally(done); }); - it(`must return the right result`, () => { + it('must return the right result', () => { expect(result[0]).toEqual({value: 123}); expect(result[1]).toEqual({value: 456}); // test that values are passing in correctly; expect(result[2]).toEqual({value: 789});// must pass values through recursive functions expect(context).toEqual([456, 789]); // this context must be passed in correctly }); }); - describe(`for error-throwing functions`, () => { + describe('for error-throwing functions', () => { function throwError() { - throw new Error(`Ops!`); + throw new Error('Ops!'); } let error, query, params; @@ -1167,10 +1137,10 @@ describe(`Executing method query`, () => { }) .finally(done); }); - it(`must reject with the error`, () => { - expect(error.message).toBe(`Ops!`); + it('must reject with the error', () => { + expect(error.message).toBe('Ops!'); }); - it(`must notify with the right query and params`, () => { + it('must notify with the right query and params', () => { expect(query).toBe(npm.util.inspect(throwError)); expect(params).toBe(123); }); @@ -1178,7 +1148,7 @@ describe(`Executing method query`, () => { delete options.error; }); }); - describe(`for async functions`, () => { + describe('for async functions', () => { async function invalidFunc() { } @@ -1194,10 +1164,10 @@ describe(`Executing method query`, () => { }) .finally(done); }); - it(`must reject with the right error`, () => { - expect(error.message).toBe(`Cannot use asynchronous functions with query formatting.`); + it('must reject with the right error', () => { + expect(error.message).toBe('Cannot use asynchronous functions with query formatting.'); }); - it(`must notify with the right query and params`, () => { + it('must notify with the right query and params', () => { expect(query).toBe(npm.util.inspect(invalidFunc)); expect(params).toBe(123); }); @@ -1208,34 +1178,28 @@ describe(`Executing method query`, () => { }); }); -describe(`Transactions`, () => { +describe('Transactions', () => { // NOTE: The same test for 100,000 inserts works also the same. // Inserting just 10,000 records to avoid exceeding memory quota on the test server. // Also, the client shouldn't execute more than 10,000 queries within a single transaction, // huge transactions should be throttled into smaller chunks. - describe(`A complex transaction with 10,000 inserts`, () => { + describe('A complex transaction with 10,000 inserts', () => { let result, error, context, THIS, tag; beforeEach(done => { - db.tx(`complex`, function (t) { + db.tx('complex', function (t) { tag = t.ctx.tag; THIS = this; context = t; const queries = [ - this.none(`drop table if exists test`), - this.none(`create table test - ( - id serial, - name text - )`) + this.none('drop table if exists test'), + this.none('create table test(id serial, name text)') ]; for (let i = 1; i <= 10000; i++) { - queries.push(this.none(`insert into test(name) - values ($1)`, `name-` + i)); + queries.push(this.none('insert into test(name) values ($1)', 'name-' + i)); } - queries.push(this.one(`select count(*) - from test`)); + queries.push(this.one('select count(*) from test')); return this.batch(queries); }) .then(data => { @@ -1244,19 +1208,19 @@ describe(`Transactions`, () => { }); }, 20000); - it(`must not fail`, () => { + it('must not fail', () => { expect(THIS === context).toBe(true); expect(error).toBeUndefined(); expect(Array.isArray(result)).toBe(true); expect(result.length).toBe(10003); // drop + create + insert x 10000 + select; const last = result[result.length - 1]; // result from the select; - expect(typeof last).toBe(`object`); - expect(last.count).toBe(`10000`); // last one must be the counter (as text); - expect(tag).toBe(`complex`); + expect(typeof last).toBe('object'); + expect(last.count).toBe('10000'); // last one must be the counter (as text); + expect(tag).toBe('complex'); }); }); - describe(`When a nested transaction fails`, () => { + describe('When a nested transaction fails', () => { let error, THIS, context, ctx; beforeEach(done => { options.capSQL = true; @@ -1264,12 +1228,10 @@ describe(`Transactions`, () => { THIS = this; context = t; return this.batch([ - this.none(`update users - set login=$1 - where id = $2`, [`TestName`, 1]), + this.none('update users set login=$1 where id = $2', ['TestName', 1]), this.tx(function () { ctx = this.ctx; - throw new Error(`Nested TX failure`); + throw new Error('Nested TX failure'); }) ]); }) @@ -1278,10 +1240,10 @@ describe(`Transactions`, () => { }) .finally(done); }); - it(`must return error from the nested transaction`, () => { + it('must return error from the nested transaction', () => { expect(THIS === context).toBe(true); expect(error instanceof Error).toBe(true); - expect(error.message).toBe(`Nested TX failure`); + expect(error.message).toBe('Nested TX failure'); expect(ctx.level).toBe(1); expect(ctx.txLevel).toBe(1); }); @@ -1290,7 +1252,7 @@ describe(`Transactions`, () => { }); }); - describe(`Detached Transaction`, () => { + describe('Detached Transaction', () => { let error; beforeEach(done => { db.tx(t => { @@ -1298,36 +1260,33 @@ describe(`Transactions`, () => { }) .then(obj => { // cannot use transaction context outside of transaction callback: - return obj.query(`select 123`); + return obj.query('select 123'); }) .catch(err => { error = err; }) .finally(done); }); - it(`must reject when querying after the callback`, () => { + it('must reject when querying after the callback', () => { expect(error instanceof Error).toBe(true); expect(error.message).toBe($text.looseQuery); }); }); - describe(`bottom-level failure`, () => { + describe('bottom-level failure', () => { let result, nestError, THIS1, THIS2, context1, context2; beforeEach(done => { db.tx(function (t1) { THIS1 = this; context1 = t1; return this.batch([ - this.none(`update users - set login=$1`, `External`), + this.none('update users set login=$1', 'External'), this.tx(function (t2) { THIS2 = this; context2 = t2; return this.batch([ - this.none(`update users - set login=$1`, `Internal`), - this.one(`select * - from unknownTable`) // emulating a bad query; + this.none('update users set login=$1', 'Internal'), + this.one('select * from unknownTable') // emulating a bad query; ]); }) ]); @@ -1335,12 +1294,8 @@ describe(`Transactions`, () => { .then(dummy, reason => { nestError = reason.data[1].result.data[1].result; return promise.all([ - db.one(`select count(*) - from users - where login = $1`, `External`), // 0 is expected; - db.one(`select count(*) - from users - where login = $1`, `Internal`) // 0 is expected; + db.one('select count(*) from users where login = $1', 'External'), // 0 is expected; + db.one('select count(*) from users where login = $1', 'Internal') // 0 is expected; ]); }) .then(data => { @@ -1348,7 +1303,7 @@ describe(`Transactions`, () => { }) .finally(done); }); - it(`must rollback everything`, () => { + it('must rollback everything', () => { expect(THIS1 && THIS2 && context1 && context2).toBeTruthy(); expect(THIS1 === context1).toBe(true); expect(THIS2 === context2).toBe(true); @@ -1356,40 +1311,40 @@ describe(`Transactions`, () => { expect(THIS1.ctx.inTransaction).toBe(true); expect(THIS2.ctx.inTransaction).toBe(true); expect(nestError instanceof Error).toBe(true); - expect(nestError.message).toContain(`relation "unknowntable" does not exist`); + expect(nestError.message).toContain('relation "unknowntable" does not exist'); expect(Array.isArray(result)).toBe(true); expect(result.length).toBe(2); - expect(result[0].count).toBe(`0`); // no changes within parent transaction; - expect(result[1].count).toBe(`0`); // no changes within nested transaction; + expect(result[0].count).toBe('0'); // no changes within parent transaction; + expect(result[1].count).toBe('0'); // no changes within nested transaction; }); }); - describe(`top-level failure`, () => { + describe('top-level failure', () => { let result; beforeEach(done => { db.tx(function () { return this.batch([ this.none(`update users set login=$1 - where id = 1`, `Test`), + where id = 1`, 'Test'), this.tx(function () { return this.none(`update person set name=$1 - where id = 1`, `Test`); + where id = 1`, 'Test'); }) ]) .then(() => { - return promise.reject(new Error(`ops!`)); + return promise.reject(new Error('ops!')); }); }) .then(dummy, () => { return promise.all([ db.one(`select count(*) from users - where login = $1`, `Test`), // 0 is expected; + where login = $1`, 'Test'), // 0 is expected; db.one(`select count(*) from person - where name = $1`, `Test`) // 0 is expected; + where name = $1`, 'Test') // 0 is expected; ]); }) .then(data => { @@ -1397,16 +1352,16 @@ describe(`Transactions`, () => { done(); }); }); - it(`must rollback everything`, () => { + it('must rollback everything', () => { expect(Array.isArray(result)).toBe(true); expect(result.length).toBe(2); - expect(result[0].count).toBe(`0`); // no changes within parent transaction; - expect(result[1].count).toBe(`0`); // no changes within nested transaction; + expect(result[0].count).toBe('0'); // no changes within parent transaction; + expect(result[1].count).toBe('0'); // no changes within nested transaction; }); }); - describe(`Calling without a callback`, () => { - describe(`for a transaction`, () => { + describe('Calling without a callback', () => { + describe('for a transaction', () => { let error; beforeEach(done => { db.tx() @@ -1415,12 +1370,12 @@ describe(`Transactions`, () => { }) .finally(done); }); - it(`must reject`, () => { + it('must reject', () => { expect(error instanceof TypeError).toBe(true); - expect(error.message).toBe(`Callback function is required.`); + expect(error.message).toBe('Callback function is required.'); }); }); - describe(`for a task`, () => { + describe('for a task', () => { let error; beforeEach(done => { db.task() @@ -1429,15 +1384,15 @@ describe(`Transactions`, () => { }) .finally(done); }); - it(`must reject`, () => { + it('must reject', () => { expect(error instanceof TypeError).toBe(true); - expect(error.message).toBe(`Callback function is required.`); + expect(error.message).toBe('Callback function is required.'); }); }); }); - describe(`A nested transaction (10 levels)`, () => { + describe('A nested transaction (10 levels)', () => { let result, THIS, context; const ctx = []; beforeEach(done => { @@ -1455,7 +1410,7 @@ describe(`Transactions`, () => { return this.tx(5, function () { ctx.push(this.ctx); return this.batch([ - this.one(`select 'Hello' as word`), + this.one('select \'Hello\' as word'), this.tx(6, function () { ctx.push(this.ctx); return this.tx(7, function () { @@ -1466,7 +1421,7 @@ describe(`Transactions`, () => { ctx.push(this.ctx); THIS = this; context = t; - return this.one(`select 'World!' as word`); + return this.one('select \'World!\' as word'); }); }); }); @@ -1483,10 +1438,10 @@ describe(`Transactions`, () => { done(); }); }); - it(`must work the same no matter how many levels`, () => { + it('must work the same no matter how many levels', () => { expect(THIS && context && THIS === context).toBeTruthy(); expect(Array.isArray(result)).toBe(true); - expect(result).toEqual([{word: `Hello`}, {word: `World!`}]); + expect(result).toEqual([{word: 'Hello'}, {word: 'World!'}]); for (let i = 0; i < 10; i++) { expect(ctx[i].tag).toBe(i); expect(ctx[i].inTransaction).toBe(true); @@ -1507,7 +1462,7 @@ describe(`Transactions`, () => { }); }); - describe(`Closing after a regular issue`, () => { + describe('Closing after a regular issue', () => { let error, query; beforeEach(done => { options.query = e => { @@ -1515,7 +1470,7 @@ describe(`Transactions`, () => { }; db.tx(() => { throw { - code: `something` + code: 'something' }; }) .catch(e => { @@ -1523,38 +1478,38 @@ describe(`Transactions`, () => { done(); }); }); - it(`Must end with ROLLBACK`, () => { - expect(error).toEqual({code: `something`}); - expect(query).toBe(`rollback`); + it('Must end with ROLLBACK', () => { + expect(error).toEqual({code: 'something'}); + expect(query).toBe('rollback'); }); afterEach(() => { delete options.query; }); }); - describe(`Closing after a protocol violation`, () => { + describe('Closing after a protocol violation', () => { let error, value; beforeEach(done => { db.task(task => - task.tx(tx => tx.one(`select '\u0000'`)) + task.tx(tx => tx.one('select \'\u0000\'')) .then(() => { - throw new Error(`expected error`); + throw new Error('expected error'); }, () => { }) - .then(() => task.tx(tx => tx.one(`select 'hi' as v`))) + .then(() => task.tx(tx => tx.one('select \'hi\' as v'))) ).then(row => { value = row.v; }, e => { error = e; }).then(done); }); - it(`Must not have an error`, () => { - expect(value).toEqual(`hi`); + it('Must not have an error', () => { + expect(value).toEqual('hi'); expect(error).toEqual(undefined); }); }); - describe(`Closing after a connectivity issue`, () => { + describe('Closing after a connectivity issue', () => { let error, query; beforeEach(done => { options.query = e => { @@ -1562,7 +1517,7 @@ describe(`Transactions`, () => { }; db.tx(() => { throw { - code: `ECONNRESET` + code: 'ECONNRESET' }; }) .catch(e => { @@ -1570,25 +1525,25 @@ describe(`Transactions`, () => { done(); }); }); - it(`must still execute ROLLBACK`, () => { - expect(error).toEqual({code: `ECONNRESET`}); - expect(query).toBe(`rollback`); + it('must still execute ROLLBACK', () => { + expect(error).toEqual({code: 'ECONNRESET'}); + expect(query).toBe('rollback'); }); afterEach(() => { delete options.query; }); }); - describe(`db side closing of the connection during slow-verify`, () => { + describe('db side closing of the connection during slow-verify', () => { // dumb connection cloning; const singleCN = JSON.parse(JSON.stringify(dbHeader.cn)); singleCN.max = 1; // simulate a slow verify call; singleCN.verify = (client, done) => { - client.on(`error`, () => { + client.on('error', () => { // Ignore }); - client.query(`SELECT pg_sleep(3);`, done); + client.query('SELECT pg_sleep(3);', done); }; const dbSingleCN = pgp(singleCN); @@ -1617,25 +1572,25 @@ describe(`Transactions`, () => { }); }); - it(`returns the postgres error`, () => { + it('returns the postgres error', () => { expect(error instanceof Error).toBe(true); if (options.pgNative) { // we do not test it for native bindings } else { - if (error.code.includes(`ECONNRESET`)) { - expect(error.code).toBe(`ECONNRESET`); - expect(error.message).toBe(`read ECONNRESET`); + if (error.code.includes('ECONNRESET')) { + expect(error.code).toBe('ECONNRESET'); + expect(error.message).toBe('read ECONNRESET'); } else { - expect(error.code).toBe(`57P01`); - expect(error.message).toBe(`terminating connection due to administrator command`); + expect(error.code).toBe('57P01'); + expect(error.message).toBe('terminating connection due to administrator command'); } } }); }); }); -describe(`Conditional Transaction`, () => { - describe(`with default parameters`, () => { +describe('Conditional Transaction', () => { + describe('with default parameters', () => { let firstCtx, secondCtx; beforeEach(done => { db.txIf(t => { @@ -1646,14 +1601,14 @@ describe(`Conditional Transaction`, () => { }) .finally(done); }); - it(`must execute a transaction on the top level`, () => { + it('must execute a transaction on the top level', () => { expect(firstCtx.isTX).toBe(true); }); - it(`must execute a task on lower levels`, () => { + it('must execute a task on lower levels', () => { expect(secondCtx.isTX).toBe(false); }); }); - describe(`with condition simple override`, () => { + describe('with condition simple override', () => { let firstCtx, secondCtx; beforeEach(done => { db.txIf({cnd: false}, t => { @@ -1664,12 +1619,12 @@ describe(`Conditional Transaction`, () => { }) .finally(done); }); - it(`must change the nested transaction logic`, () => { + it('must change the nested transaction logic', () => { expect(firstCtx.isTX).toBe(false); expect(secondCtx.isTX).toBe(true); }); }); - describe(`with successful condition-function override`, () => { + describe('with successful condition-function override', () => { let firstCtx, secondCtx; beforeEach(done => { db.txIf({cnd: () => false}, t => { @@ -1680,15 +1635,15 @@ describe(`Conditional Transaction`, () => { }) .finally(done); }); - it(`must change the nested transaction logic`, () => { + it('must change the nested transaction logic', () => { expect(firstCtx.isTX).toBe(false); expect(secondCtx.isTX).toBe(true); }); }); - describe(`with error condition-function override`, () => { + describe('with error condition-function override', () => { function errorCondition() { - throw new Error(`Ops!`); + throw new Error('Ops!'); } let error; @@ -1700,14 +1655,14 @@ describe(`Conditional Transaction`, () => { }) .finally(done); }); - it(`must reject with the right error`, () => { - expect(error.message).toBe(`Ops!`); + it('must reject with the right error', () => { + expect(error.message).toBe('Ops!'); }); }); }); -describe(`Reusable Transaction`, () => { - describe(`as value with default condition`, () => { +describe('Reusable Transaction', () => { + describe('as value with default condition', () => { let ctx1, ctx2; beforeEach(done => { db.tx(t1 => { @@ -1718,29 +1673,29 @@ describe(`Reusable Transaction`, () => { }) .finally(done); }); - it(`must reuse context`, () => { + it('must reuse context', () => { expect(ctx1).toBe(ctx2); }); }); - describe(`as value with true condition`, () => { + describe('as value with true condition', () => { let ctx1, ctx2; beforeEach(done => { - db.tx(`first`, t1 => { + db.tx('first', t1 => { ctx1 = t1.ctx; - return t1.txIf({tag: `second`, cnd: true, reusable: false}, t2 => { + return t1.txIf({tag: 'second', cnd: true, reusable: false}, t2 => { ctx2 = t2.ctx; }); }) .finally(done); }); - it(`must create a new sub-transaction context`, () => { + it('must create a new sub-transaction context', () => { expect(ctx1).not.toBe(ctx2); - expect(ctx1.tag).toBe(`first`); - expect(ctx2.tag).toBe(`second`); + expect(ctx1.tag).toBe('first'); + expect(ctx2.tag).toBe('second'); }); }); - describe(`as successful function`, () => { + describe('as successful function', () => { function getReusable() { return true; } @@ -1755,13 +1710,13 @@ describe(`Reusable Transaction`, () => { }) .finally(done); }); - it(`must reuse context`, () => { + it('must reuse context', () => { expect(ctx1).toBe(ctx2); }); }); - describe(`as error function`, () => { + describe('as error function', () => { function getReusable() { - throw new Error(`Ops!`); + throw new Error('Ops!'); } let error; @@ -1775,14 +1730,14 @@ describe(`Reusable Transaction`, () => { }) .finally(done); }); - it(`must reject with the right error`, () => { - expect(error.message).toBe(`Ops!`); + it('must reject with the right error', () => { + expect(error.message).toBe('Ops!'); }); }); }); -describe(`Conditional Task`, () => { - describe(`with default parameters`, () => { +describe('Conditional Task', () => { + describe('with default parameters', () => { let firstCtx, secondCtx; beforeEach(done => { db.taskIf(t => { @@ -1793,11 +1748,11 @@ describe(`Conditional Task`, () => { }) .finally(done); }); - it(`must reuse the task`, () => { + it('must reuse the task', () => { expect(secondCtx).toBe(firstCtx); }); }); - describe(`with successful condition-function override`, () => { + describe('with successful condition-function override', () => { let firstCtx, secondCtx; beforeEach(done => { db.taskIf({cnd: true}, t1 => { @@ -1808,14 +1763,14 @@ describe(`Conditional Task`, () => { }) .finally(done); }); - it(`must create new task as required`, () => { + it('must create new task as required', () => { expect(firstCtx).toBe(secondCtx); }); }); - describe(`with error condition-function override`, () => { + describe('with error condition-function override', () => { function errorCondition() { - throw new Error(`Ops!`); + throw new Error('Ops!'); } let error; @@ -1827,36 +1782,36 @@ describe(`Conditional Task`, () => { }) .finally(done); }); - it(`must reject with the right error`, () => { - expect(error.message).toBe(`Ops!`); + it('must reject with the right error', () => { + expect(error.message).toBe('Ops!'); }); }); }); -describe(`Return data from a query must match the request type`, () => { +describe('Return data from a query must match the request type', () => { - describe(`when no data returned`, () => { + describe('when no data returned', () => { let error; beforeEach(done => { db.none(`select * from person - where name = $1`, `John`) + where name = $1`, 'John') .catch(err => { error = err; done(); }); }); - it(`method 'none' must return an error`, () => { + it('method \'none\' must return an error', () => { expect(error instanceof pgp.errors.QueryResultError).toBe(true); expect(error.message).toBe($text.notEmpty); }); }); - it(`method 'one' must throw an error when there was no data returned`, () => { + it('method \'one\' must throw an error when there was no data returned', () => { let result, error; db.one(`select * from person - where name = $1`, `Unknown`) + where name = $1`, 'Unknown') .then(data => { result = data; }, reason => { @@ -1865,7 +1820,7 @@ describe(`Return data from a query must match the request type`, () => { }); waitsFor(() => { return result !== undefined; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(result).toBeNull(); expect(error instanceof pgp.errors.QueryResultError).toBe(true); @@ -1873,7 +1828,7 @@ describe(`Return data from a query must match the request type`, () => { }); }); - it(`method 'one' must throw an error when more than one row was returned`, () => { + it('method \'one\' must throw an error when more than one row was returned', () => { let result, error; db.one(`select * from person`) @@ -1885,7 +1840,7 @@ describe(`Return data from a query must match the request type`, () => { }); waitsFor(() => { return result !== undefined; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(result).toBeNull(); expect(error instanceof pgp.errors.QueryResultError).toBe(true); @@ -1893,27 +1848,27 @@ describe(`Return data from a query must match the request type`, () => { }); }); - it(`method 'oneOrNone' must resolve into null when no data returned`, () => { + it('method \'oneOrNone\' must resolve into null when no data returned', () => { let result, error; db.oneOrNone(`select * from person - where name = $1`, `Unknown`) + where name = $1`, 'Unknown') .then(data => { result = data; }, reason => { - result = `whatever`; + result = 'whatever'; error = reason; }); waitsFor(() => { return result !== undefined; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(error).toBeUndefined(); expect(result).toBeNull(); }); }); - it(`method 'any' must return an empty array when no records found`, () => { + it('method \'any\' must return an empty array when no records found', () => { let result, error; db.any(`select * from person @@ -1926,7 +1881,7 @@ describe(`Return data from a query must match the request type`, () => { }); waitsFor(() => { return result !== undefined; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(error).toBeUndefined(); expect(Array.isArray(result)).toBe(true); @@ -1936,8 +1891,8 @@ describe(`Return data from a query must match the request type`, () => { }); -describe(`Queries must not allow invalid QRM (Query Request Mask) combinations`, () => { - it(`method 'query' must throw an error when mask is one+many`, () => { +describe('Queries must not allow invalid QRM (Query Request Mask) combinations', () => { + it('method \'query\' must throw an error when mask is one+many', () => { let result, error; db.query(`select * from person`, undefined, pgp.queryResult.one | pgp.queryResult.many) @@ -1949,14 +1904,14 @@ describe(`Queries must not allow invalid QRM (Query Request Mask) combinations`, }); waitsFor(() => { return result !== undefined; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(result).toBeNull(); expect(error instanceof TypeError).toBe(true); - expect(error.message).toBe(`Invalid Query Result Mask specified.`); + expect(error.message).toBe('Invalid Query Result Mask specified.'); }); }); - it(`method 'query' must throw an error when QRM is > 6`, () => { + it('method \'query\' must throw an error when QRM is > 6', () => { let result, error; db.query(`select * from person`, undefined, 7) @@ -1968,14 +1923,14 @@ describe(`Queries must not allow invalid QRM (Query Request Mask) combinations`, }); waitsFor(() => { return result !== undefined; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(result).toBeNull(); expect(error instanceof TypeError).toBe(true); - expect(error.message).toBe(`Invalid Query Result Mask specified.`); + expect(error.message).toBe('Invalid Query Result Mask specified.'); }); }); - it(`method 'query' must throw an error when QRM is < 1`, () => { + it('method \'query\' must throw an error when QRM is < 1', () => { let result, error; db.query(`select * from person`, undefined, 0) @@ -1988,18 +1943,18 @@ describe(`Queries must not allow invalid QRM (Query Request Mask) combinations`, }); waitsFor(() => { return result !== undefined; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(result).toBeNull(); expect(error instanceof TypeError).toBe(true); - expect(error.message).toBe(`Invalid Query Result Mask specified.`); + expect(error.message).toBe('Invalid Query Result Mask specified.'); }); }); - it(`method 'query' must throw an error when QRM is of the wrong type`, () => { + it('method \'query\' must throw an error when QRM is of the wrong type', () => { let result, error; db.query(`select * - from person`, undefined, `wrong qrm`) + from person`, undefined, 'wrong qrm') .then(data => { result = data; }) @@ -2009,71 +1964,71 @@ describe(`Queries must not allow invalid QRM (Query Request Mask) combinations`, }); waitsFor(() => { return result !== undefined; - }, `Query timed out`, 5000); + }, 'Query timed out', 5000); runs(() => { expect(result).toBeNull(); expect(error instanceof TypeError).toBe(true); - expect(error.message).toBe(`Invalid Query Result Mask specified.`); + expect(error.message).toBe('Invalid Query Result Mask specified.'); }); }); }); -describe(`Method 'result'`, () => { +describe('Method \'result\'', () => { - describe(`for a single query`, () => { + describe('for a single query', () => { let result; beforeEach(done => { - db.result(`select 1 as one`) + db.result('select 1 as one') .then(data => { result = data; done(); }); }); - it(`must resolve with a single Result object`, () => { + it('must resolve with a single Result object', () => { expect(isResult(result)).toBe(true); expect(result.rows).toEqual([{one: 1}]); - expect(typeof result.duration).toBe(`number`); + expect(typeof result.duration).toBe('number'); }); }); - describe(`for a multi-query`, () => { + describe('for a multi-query', () => { let result; beforeEach(done => { - db.result(`select 1 as one;select 2 as two`) + db.result('select 1 as one;select 2 as two') .then(data => { result = data; done(); }); }); - it(`must resolve with the last Result object`, () => { + it('must resolve with the last Result object', () => { expect(isResult(result)).toBe(true); expect(result.rows).toEqual([{two: 2}]); - expect(`duration` in result).toBe(false); // must be present in multi-query results + expect('duration' in result).toBe(false); // must be present in multi-query results }); }); }); -describe(`Method 'multiResult'`, () => { +describe('Method \'multiResult\'', () => { - describe(`for a single query`, () => { + describe('for a single query', () => { let result; beforeEach(done => { - db.multiResult(`select 1 as one`) + db.multiResult('select 1 as one') .then(data => { result = data; done(); }); }); - it(`must resolve with one-element array of Result`, () => { + it('must resolve with one-element array of Result', () => { expect(Array.isArray(result)).toBe(true); expect(result.length).toBe(1); expect(result[0].rows).toEqual([{one: 1}]); }); }); - describe(`for a multi-query`, () => { + describe('for a multi-query', () => { let result; beforeEach(done => { db.multiResult(`select 1 as one; @@ -2086,7 +2041,7 @@ describe(`Method 'multiResult'`, () => { done(); }); }); - it(`must resolve with an array of Results`, () => { + it('must resolve with an array of Results', () => { expect(Array.isArray(result)).toBe(true); expect(result.length).toBe(3); expect(result[0].rows).toEqual([{one: 1}]); @@ -2097,25 +2052,25 @@ describe(`Method 'multiResult'`, () => { }); -describe(`Method 'multi'`, () => { +describe('Method \'multi\'', () => { - describe(`for a single query`, () => { + describe('for a single query', () => { let result; beforeEach(done => { - db.multi(`select 1 as one`) + db.multi('select 1 as one') .then(data => { result = data; done(); }); }); - it(`must resolve with one-element array`, () => { + it('must resolve with one-element array', () => { expect(Array.isArray(result)).toBe(true); expect(result.length).toBe(1); expect(result[0]).toEqual([{one: 1}]); }); }); - describe(`for a multi-query`, () => { + describe('for a multi-query', () => { let result; beforeEach(done => { db.multi(`select 1 as one; @@ -2128,7 +2083,7 @@ describe(`Method 'multi'`, () => { done(); }); }); - it(`must resolve with an array of arrays`, () => { + it('must resolve with an array of arrays', () => { expect(Array.isArray(result)).toBe(true); expect(result.length).toBe(3); expect(result[0]).toEqual([{one: 1}]); @@ -2139,19 +2094,19 @@ describe(`Method 'multi'`, () => { }); -describe(`Querying an entity`, () => { +describe('Querying an entity', () => { - describe(`multi-row function`, () => { + describe('multi-row function', () => { let result; beforeEach(done => { options.capSQL = true; - db.func(`get_users`) + db.func('get_users') .then(data => { result = data; }) .finally(done); }); - it(`must return all rows`, () => { + it('must return all rows', () => { expect(Array.isArray(result)).toBe(true); expect(result.length >= 4).toBe(true); }); @@ -2160,39 +2115,39 @@ describe(`Querying an entity`, () => { }); }); - describe(`single-row function`, () => { + describe('single-row function', () => { let result; beforeEach(done => { - db.func(`findUser`, 1, pgp.queryResult.one) + db.func('findUser', 1, pgp.queryResult.one) .then(data => { result = data; }) .finally(done); }); - it(`must return one object`, () => { - expect(typeof result).toBe(`object`); - expect(`id` in result && `login` in result && `active` in result).toBe(true); + it('must return one object', () => { + expect(typeof result).toBe('object'); + expect('id' in result && 'login' in result && 'active' in result).toBe(true); }); }); - describe(`with invalid parameters`, () => { + describe('with invalid parameters', () => { let result; beforeEach(done => { promise.any([ db.func(), // undefined function name; - db.func(``), // empty-string function name; - db.func(` `), // white-space string for function name; + db.func(''), // empty-string function name; + db.func(' '), // white-space string for function name; db.func(1), // invalid-type function name; db.func(null), // null function name; // query function overrides: db.query({ - entity: null, type: `func` + entity: null, type: 'func' }), db.query({ - entity: ``, type: `func` + entity: '', type: 'func' }), db.query({ - entity: ` `, type: `func` + entity: ' ', type: 'func' }) ]) .catch(reason => { @@ -2200,7 +2155,7 @@ describe(`Querying an entity`, () => { }) .finally(done); }); - it(`must reject with the right error`, () => { + it('must reject with the right error', () => { expect(result.length).toBe(8); for (let i = 0; i < result.length; i++) { expect(result[i] instanceof Error).toBe(true); @@ -2209,76 +2164,76 @@ describe(`Querying an entity`, () => { }); }); - describe(`proc with bad parameters`, () => { + describe('proc with bad parameters', () => { let result, errCtx; beforeEach(done => { options.error = function (err, e) { errCtx = e; }; - db.proc(`camelCase`, [() => { - throw new Error(`bad proc params`); + db.proc('camelCase', [() => { + throw new Error('bad proc params'); }]) .catch(reason => { result = reason; }) .finally(done); }); - it(`must throw an error`, () => { + it('must throw an error', () => { expect(result instanceof Error).toBe(true); - expect(result.message).toBe(`bad proc params`); + expect(result.message).toBe('bad proc params'); // NOTE: camel-case ignored within the error query; - expect(errCtx.query).toBe(`call camelCase(...)`); + expect(errCtx.query).toBe('call camelCase(...)'); }); afterEach(() => { delete options.error; }); }); - describe(`func with bad parameters`, () => { + describe('func with bad parameters', () => { let result, errCtx; beforeEach(done => { options.error = function (err, e) { errCtx = e; }; - db.func(`camelCase`, [() => { - throw new Error(`bad func params`); + db.func('camelCase', [() => { + throw new Error('bad func params'); }]) .catch(reason => { result = reason; }) .finally(done); }); - it(`must throw an error`, () => { + it('must throw an error', () => { expect(result instanceof Error).toBe(true); - expect(result.message).toBe(`bad func params`); + expect(result.message).toBe('bad func params'); // NOTE: camel-case ignored within the error query; - expect(errCtx.query).toBe(`select * from camelCase(...)`); + expect(errCtx.query).toBe('select * from camelCase(...)'); }); afterEach(() => { delete options.error; }); }); - describe(`with bad proc params + caps`, () => { + describe('with bad proc params + caps', () => { let result, errCtx; beforeEach(done => { options.error = function (err, e) { errCtx = e; }; options.capSQL = true; - db.proc(`camelCase`, () => { - throw new Error(`bad proc name`); + db.proc('camelCase', () => { + throw new Error('bad proc name'); }) .catch(reason => { result = reason; }) .finally(done); }); - it(`must throw an error`, () => { + it('must throw an error', () => { expect(result instanceof Error).toBe(true); - expect(result.message).toBe(`bad proc name`); + expect(result.message).toBe('bad proc name'); // NOTE: camel-case ignored within the error query; - expect(errCtx.query).toBe(`CALL camelCase(...)`); + expect(errCtx.query).toBe('CALL camelCase(...)'); }); afterEach(() => { delete options.error; @@ -2286,23 +2241,23 @@ describe(`Querying an entity`, () => { }); }); - describe(`stored procedures`, () => { - describe(`normal call`, () => { - it(`must resolve with null`, async () => { - const res = await db.proc(`empty_proc`); + describe('stored procedures', () => { + describe('normal call', () => { + it('must resolve with null', async () => { + const res = await db.proc('empty_proc'); expect(res).toBeNull(); }); - it(`must support output values`, async () => { - const res = await db.proc(`output_proc`, [null, `world`]); - expect(res).toEqual({output1: true, output2: `world-hello!`}); + it('must support output values', async () => { + const res = await db.proc('output_proc', [null, 'world']); + expect(res).toEqual({output1: true, output2: 'world-hello!'}); }); - it(`must support transformation`, async () => { - const res = await db.proc(`output_proc`, [null, `world`], a => a.output2); - expect(res).toBe(`world-hello!`); + it('must support transformation', async () => { + const res = await db.proc('output_proc', [null, 'world'], a => a.output2); + expect(res).toBe('world-hello!'); }); }); - describe(`with invalid name`, () => { + describe('with invalid name', () => { let err; beforeEach(done => { db.proc() @@ -2311,17 +2266,17 @@ describe(`Querying an entity`, () => { done(); }); }); - it(`must throw error`, () => { - expect(err).toBe(`Invalid procedure name.`); + it('must throw error', () => { + expect(err).toBe('Invalid procedure name.'); }); }); }); }); -describe(`Task`, () => { +describe('Task', () => { - describe(`with detached connection`, () => { + describe('with detached connection', () => { let error, tsk; beforeEach(done => { db.task(async function () { @@ -2329,14 +2284,14 @@ describe(`Task`, () => { }) .then(() => { // try use the task connection context outside of the task callback; - return tsk.query(`select 'test'`); + return tsk.query('select \'test\''); }) .catch(err => { error = err; }) .finally(done); }); - it(`must throw an error on any query request`, () => { + it('must throw an error on any query request', () => { expect(error instanceof Error).toBe(true); expect(error.message).toBe($text.looseQuery); expect(tsk.ctx.level).toBe(0); @@ -2346,7 +2301,7 @@ describe(`Task`, () => { }); }); - describe(`inside a transaction`, () => { + describe('inside a transaction', () => { let context; beforeEach(done => { db.tx(tx => { @@ -2356,12 +2311,12 @@ describe(`Task`, () => { }) .finally(done); }); - it(`must know it is in transaction`, () => { + it('must know it is in transaction', () => { expect(context.ctx.inTransaction).toBe(true); }); }); - describe(`with a callback that returns nothing`, () => { + describe('with a callback that returns nothing', () => { let result; beforeEach(done => { db.task(dummy) @@ -2370,12 +2325,12 @@ describe(`Task`, () => { }) .finally(done); }); - it(`must resolve with undefined`, () => { + it('must resolve with undefined', () => { expect(result).toBeUndefined(); }); }); - describe(`with a callback that returns a value`, () => { + describe('with a callback that returns a value', () => { let result; beforeEach(done => { db.task(() => { @@ -2386,66 +2341,66 @@ describe(`Task`, () => { }) .finally(done); }); - it(`must resolve with the value`, () => { + it('must resolve with the value', () => { expect(result).toBe(123); }); }); - describe(`with the callback throwing an error`, () => { + describe('with the callback throwing an error', () => { let result; beforeEach(done => { db.task(() => { - throw new Error(`test`); + throw new Error('test'); }) .catch(reason => { result = reason; }) .finally(done); }); - it(`must reject with the error thrown`, () => { + it('must reject with the error thrown', () => { expect(result instanceof Error).toBe(true); - expect(result.message).toBe(`test`); + expect(result.message).toBe('test'); }); }); - describe(`with a simple promise result`, () => { + describe('with a simple promise result', () => { let result, context, THIS; beforeEach(done => { db.task(async function (t) { THIS = this; context = t; - return `Ok`; + return 'Ok'; }) .then(data => { result = data; }) .finally(done); }); - it(`must resolve with that result`, () => { - expect(result).toBe(`Ok`); + it('must resolve with that result', () => { + expect(result).toBe('Ok'); }); - it(`must provide correct connection context`, () => { - expect(context && typeof context === `object`).toBeTruthy(); + it('must provide correct connection context', () => { + expect(context && typeof context === 'object').toBeTruthy(); expect(context === THIS).toBe(true); }); }); - describe(`with a notification error`, () => { + describe('with a notification error', () => { let result, event, counter = 0; beforeEach(done => { options.task = e => { if (counter) { - throw `ops!`; + throw 'ops!'; } counter++; event = e; }; async function myTask() { - return `success`; + return 'success'; } - db.task(`testTag`, myTask) + db.task('testTag', myTask) .then(data => { result = data; }) @@ -2454,53 +2409,53 @@ describe(`Task`, () => { afterEach(() => { delete options.task; }); - it(`that must be ignored`, () => { - expect(result).toBe(`success`); + it('that must be ignored', () => { + expect(result).toBe('success'); expect(counter).toBe(1); // successful notification 'Start', failed for 'Finish'; - expect(event && event.ctx && typeof event.ctx === `object`).toBeTruthy(); - expect(event.ctx.tag).toBe(`testTag`); + expect(event && event.ctx && typeof event.ctx === 'object').toBeTruthy(); + expect(event.ctx.tag).toBe('testTag'); }); }); }); -describe(`negative query formatting`, () => { +describe('negative query formatting', () => { - describe(`with invalid property name`, () => { + describe('with invalid property name', () => { let error; beforeEach(done => { - db.one(`select \${invalid}`, {}) + db.one('select ${invalid}', {}) .catch(e => { error = e; }) .finally(done); }); - it(`must reject with correct error`, () => { + it('must reject with correct error', () => { expect(error instanceof Error).toBe(true); - expect(error.message).toBe(`Property 'invalid' doesn't exist.`); + expect(error.message).toBe('Property \'invalid\' doesn\'t exist.'); }); }); - describe(`with invalid variable index`, () => { + describe('with invalid variable index', () => { let error; beforeEach(done => { - db.one(`select $1`, []) + db.one('select $1', []) .catch(e => { error = e; }) .finally(done); }); - it(`must reject with correct error`, () => { + it('must reject with correct error', () => { expect(error instanceof RangeError).toBe(true); - expect(error.message).toBe(`Variable $1 out of range. Parameters array length: 0`); + expect(error.message).toBe('Variable $1 out of range. Parameters array length: 0'); }); }); - describe(`with formatting parameter throwing error`, () => { + describe('with formatting parameter throwing error', () => { let error; - const err = new Error(`ops!`); + const err = new Error('ops!'); beforeEach(done => { - db.one(`select $1`, [() => { + db.one('select $1', [() => { throw err; }]) .catch(e => { @@ -2508,17 +2463,17 @@ describe(`negative query formatting`, () => { }) .finally(done); }); - it(`must reject with correct error`, () => { + it('must reject with correct error', () => { expect(error instanceof Error).toBe(true); expect(error).toBe(err); }); }); - describe(`with formatting parameter throwing a non-error`, () => { + describe('with formatting parameter throwing a non-error', () => { let error; - const err = `ops!`; + const err = 'ops!'; beforeEach(done => { - db.one(`select $1`, [() => { + db.one('select $1', [() => { throw err; }]) .catch(e => { @@ -2526,7 +2481,7 @@ describe(`negative query formatting`, () => { }) .finally(done); }); - it(`must reject with correct error`, () => { + it('must reject with correct error', () => { expect(error instanceof Error).toBe(false); expect(error).toBe(err); }); @@ -2534,22 +2489,22 @@ describe(`negative query formatting`, () => { }); -describe(`Multi-result queries`, () => { +describe('Multi-result queries', () => { let result; beforeEach(done => { - db.one(`select 1 as one;select 2 as two`) + db.one('select 1 as one;select 2 as two') .then(data => { result = data; }) .finally(done); }); - it(`must return the first result`, () => { + it('must return the first result', () => { expect(result).toEqual({two: 2}); }); }); -describe(`Dynamic Schema`, () => { - describe(`for an invalid value`, () => { +describe('Dynamic Schema', () => { + describe('for an invalid value', () => { let result; beforeEach(done => { const innerDb = header({schema: 123, noWarnings: true, promiseLib: promise}).db; @@ -2560,15 +2515,15 @@ describe(`Dynamic Schema`, () => { done(); }); }); - it(`must not try change the schema`, () => { + it('must not try change the schema', () => { expect(result.length).toBeGreaterThan(1); }); }); - describe(`for a single schema`, () => { + describe('for a single schema', () => { let result; beforeEach(done => { - const innerDb = header({schema: `test`, noWarnings: true, promiseLib: promise}).db; + const innerDb = header({schema: 'test', noWarnings: true, promiseLib: promise}).db; innerDb.any(`select * from users`) .catch(error => { @@ -2576,14 +2531,14 @@ describe(`Dynamic Schema`, () => { }) .finally(done); }); - it(`must change the default schema`, () => { - expect(result && result.message).toBe(`relation "users" does not exist`); + it('must change the default schema', () => { + expect(result && result.message).toBe('relation "users" does not exist'); }); }); - describe(`for multiple schemas`, () => { + describe('for multiple schemas', () => { let result; beforeEach(done => { - const innerDb = header({schema: [`first`, `second`, `public`], noWarnings: true, promiseLib: promise}).db; + const innerDb = header({schema: ['first', 'second', 'public'], noWarnings: true, promiseLib: promise}).db; innerDb.any(`select * from users`) .then(data => { @@ -2591,14 +2546,14 @@ describe(`Dynamic Schema`, () => { }) .finally(done); }); - it(`must change the default schemas`, () => { + it('must change the default schemas', () => { expect(result && result.length).toBeGreaterThan(0); }); }); - describe(`for a callback`, () => { + describe('for a callback', () => { let result; beforeEach(done => { - const schema = () => [`first`, `second`, `public`]; + const schema = () => ['first', 'second', 'public']; const innerDb = header({schema, noWarnings: true, promiseLib: promise}).db; innerDb.any(`select * from users`) @@ -2607,7 +2562,7 @@ describe(`Dynamic Schema`, () => { }) .finally(done); }); - it(`must change the default schemas`, () => { + it('must change the default schemas', () => { expect(result && result.length).toBeGreaterThan(0); }); }); diff --git a/test/db/capture.js b/test/db/capture.js index 52a05d406..04dfa8ab0 100644 --- a/test/db/capture.js +++ b/test/db/capture.js @@ -25,11 +25,11 @@ function hookConsole(callback) { // removes color elements from text; function removeColors(text) { - return text.replace(/\\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g, ``); + return text.replace(/\\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g, ''); } function capture() { - let text = ``; + let text = ''; const hook = hookConsole(s => { if (!text) { text = s; diff --git a/test/db/header.js b/test/db/header.js index b78c71469..7167c65b7 100644 --- a/test/db/header.js +++ b/test/db/header.js @@ -2,8 +2,8 @@ // Database connection header used in every test; ////////////////////////////////////////////////// -const pgpLib = require(`../../lib/index`); -const defPromise = require(`bluebird`); // default promise library; +const pgpLib = require('../../lib/index'); +const defPromise = require('bluebird'); // default promise library; defPromise.config({ warnings: false @@ -13,19 +13,19 @@ defPromise.config({ // or the other way round - change the details to match your local configuration. const cn = { allowExitOnIdle: true, - host: process.env.POSTGRES_HOST || `localhost`, // server name or IP address; + host: process.env.POSTGRES_HOST || 'localhost', // server name or IP address; port: 5432, // default port; - database: process.env.POSTGRES_DB || `pg_promise_test`, // local database name for testing; - user: process.env.POSTGRES_USER || `postgres`, // username; - password: process.env.POSTGRES_PASSWORD || `postgres` //- add password, if needed; + database: process.env.POSTGRES_DB || 'pg_promise_test', // local database name for testing; + user: process.env.POSTGRES_USER || 'postgres', // username; + password: process.env.POSTGRES_PASSWORD || 'postgres' //- add password, if needed; }; pgpLib.suppressErrors = true; // suppress console output for error messages; function main(options, dc) { const pgNative = eval(process.env.PG_NATIVE); if (pgNative) { - if (options && typeof options === `object`) { - if (!(`pgNative` in options)) { + if (options && typeof options === 'object') { + if (!('pgNative' in options)) { options.pgNative = true; } } else { diff --git a/test/db/init.js b/test/db/init.js index 3ebbb3cf4..47e4d16af 100644 --- a/test/db/init.js +++ b/test/db/init.js @@ -2,9 +2,9 @@ // Initialization scripts for the test database; //////////////////////////////////////////////// -const dbHeader = require(`./header`); +const dbHeader = require('./header'); const promise = dbHeader.defPromise; -const {ColorConsole} = require(`../../lib/utils/color`); +const {ColorConsole} = require('../../lib/utils/color'); const header = dbHeader({ query(e) { @@ -23,39 +23,39 @@ const db = header.db; await db.tx(async t => { // drop all functions; - await t.none(`DROP FUNCTION IF EXISTS "findUser"(int)`); - await t.none(`DROP FUNCTION IF EXISTS get_users()`); + await t.none('DROP FUNCTION IF EXISTS "findUser"(int)'); + await t.none('DROP FUNCTION IF EXISTS get_users()'); // drop all tables; - await t.none(`DROP TABLE IF EXISTS audit`); - await t.none(`DROP TABLE IF EXISTS person`); - await t.none(`DROP TABLE IF EXISTS users`); - await t.none(`DROP TABLE IF EXISTS images`); + await t.none('DROP TABLE IF EXISTS audit'); + await t.none('DROP TABLE IF EXISTS person'); + await t.none('DROP TABLE IF EXISTS users'); + await t.none('DROP TABLE IF EXISTS images'); // create all tables; - await t.none(`CREATE TABLE audit(id serial, event text, created timestamptz, ref int)`); - await t.none(`CREATE TABLE person(id serial, name text, dob date)`); - await t.none(`CREATE TABLE users(id serial, login text, active boolean)`); - await t.none(`CREATE TABLE images(id serial, name text, data bytea)`); + await t.none('CREATE TABLE audit(id serial, event text, created timestamptz, ref int)'); + await t.none('CREATE TABLE person(id serial, name text, dob date)'); + await t.none('CREATE TABLE users(id serial, login text, active boolean)'); + await t.none('CREATE TABLE images(id serial, name text, data bytea)'); // insert records into 'users'; - await t.none(`INSERT INTO users(login, active) VALUES($1, $2)`, [`user-1`, true]); - await t.none(`INSERT INTO users(login, active) VALUES($1, $2)`, [`user-2`, true]); - await t.none(`INSERT INTO users(login, active) VALUES($1, $2)`, [`user-3`, false]); - await t.none(`INSERT INTO users(login, active) VALUES($1, $2)`, [`user-4`, false]); + await t.none('INSERT INTO users(login, active) VALUES($1, $2)', ['user-1', true]); + await t.none('INSERT INTO users(login, active) VALUES($1, $2)', ['user-2', true]); + await t.none('INSERT INTO users(login, active) VALUES($1, $2)', ['user-3', false]); + await t.none('INSERT INTO users(login, active) VALUES($1, $2)', ['user-4', false]); // insert records into 'person'; - await t.none(`INSERT INTO person(name, dob) VALUES($1, $2)`, [`David`, new Date(1995, 8, 7)]); - await t.none(`INSERT INTO person(name, dob) VALUES($1, $2)`, [`John`, new Date(1980, 3, 20)]); - await t.none(`INSERT INTO person(name, dob) VALUES($1, $2)`, [`Mark`, new Date(1973, 5, 12)]); - await t.none(`INSERT INTO person(name, dob) VALUES($1, $2)`, [`Peter`, new Date(1992, 11, 3)]); + await t.none('INSERT INTO person(name, dob) VALUES($1, $2)', ['David', new Date(1995, 8, 7)]); + await t.none('INSERT INTO person(name, dob) VALUES($1, $2)', ['John', new Date(1980, 3, 20)]); + await t.none('INSERT INTO person(name, dob) VALUES($1, $2)', ['Mark', new Date(1973, 5, 12)]); + await t.none('INSERT INTO person(name, dob) VALUES($1, $2)', ['Peter', new Date(1992, 11, 3)]); // adding functions: - await t.none(`CREATE OR REPLACE FUNCTION "findUser"(userId int) RETURNS SETOF users AS $$ SELECT * FROM users WHERE id = userId $$ language 'sql'`); - await t.none(`CREATE OR REPLACE FUNCTION get_users() RETURNS SETOF users AS $$ SELECT * FROM users $$ language 'sql'`); + await t.none('CREATE OR REPLACE FUNCTION "findUser"(userId int) RETURNS SETOF users AS $$ SELECT * FROM users WHERE id = userId $$ language \'sql\''); + await t.none('CREATE OR REPLACE FUNCTION get_users() RETURNS SETOF users AS $$ SELECT * FROM users $$ language \'sql\''); // adding procedures: - await t.none(`CREATE OR REPLACE PROCEDURE empty_proc() LANGUAGE SQL AS $$ $$;`); + await t.none('CREATE OR REPLACE PROCEDURE empty_proc() LANGUAGE SQL AS $$ $$;'); await t.none(`CREATE OR REPLACE PROCEDURE output_proc(INOUT output1 boolean, INOUT output2 text) LANGUAGE plpgsql AS $$ BEGIN @@ -65,11 +65,11 @@ const db = header.db; }) .then(() => { // eslint-disable-next-line no-console - ColorConsole.success.bright(`*** SUCCESS ***`); + ColorConsole.success.bright('*** SUCCESS ***'); }) .catch(error => { // eslint-disable-next-line no-console - ColorConsole.error.bright(`FAILED:`, error); + ColorConsole.error.bright('FAILED:', error); }) .finally(pgp.end); }()); diff --git a/test/db/tools.js b/test/db/tools.js index e1367efb6..963193a49 100644 --- a/test/db/tools.js +++ b/test/db/tools.js @@ -1,4 +1,4 @@ -const util = require(`util`); +const util = require('util'); function inspect(obj) { return obj[util.inspect.custom](); diff --git a/test/entry.spec.js b/test/entry.spec.js index a98a36bf2..0ff5f56d2 100644 --- a/test/entry.spec.js +++ b/test/entry.spec.js @@ -1,7 +1,7 @@ -const {PromiseAdapter} = require(`../lib/index`); -const supportsPromise = typeof Promise !== `undefined`; +const {PromiseAdapter} = require('../lib/index'); +const supportsPromise = typeof Promise !== 'undefined'; -const header = require(`./db/header`); +const header = require('./db/header'); const promise = header.defPromise; const options = { promiseLib: promise, @@ -16,22 +16,22 @@ const BatchError = pgp.spex.errors.BatchError; function dummy() { } -describe(`Library entry function`, () => { +describe('Library entry function', () => { - describe(`without any promise override`, () => { - it(`must return a valid library object`, () => { + describe('without any promise override', () => { + it('must return a valid library object', () => { if (supportsPromise) { const lib = header({noWarnings: true}); - expect(typeof lib.pgp).toBe(`function`); + expect(typeof lib.pgp).toBe('function'); } else { expect(() => { header(); - }).toThrow(`Promise library must be specified.`); + }).toThrow('Promise library must be specified.'); } }); }); - describe(`with PromiseAdapter override`, () => { + describe('with PromiseAdapter override', () => { const P = header.defPromise; function create(func) { @@ -51,7 +51,7 @@ describe(`Library entry function`, () => { } const adapter = new PromiseAdapter({create, resolve, reject, all}); - it(`must accept custom promise`, () => { + it('must accept custom promise', () => { const lib = header({ promiseLib: adapter, noWarnings: true @@ -59,44 +59,44 @@ describe(`Library entry function`, () => { expect(lib.pgp instanceof Function).toBe(true); }); - describe(`using PromiseAdapter`, () => { + describe('using PromiseAdapter', () => { let result; beforeEach(done => { const lib = header({ promiseLib: adapter, noWarnings: true }); - lib.db.one(`select 1 as value`) + lib.db.one('select 1 as value') .then(data => { result = data; }) .finally(done); }); - it(`must return successfully`, () => { + it('must return successfully', () => { expect(result.value).toBe(1); }); }); }); if (supportsPromise) { - describe(`without any options`, () => { + describe('without any options', () => { let result; beforeEach(done => { const db1 = header({noWarnings: true, promiseLib: promise}).db; - db1.query(`select * from users`) + db1.query('select * from users') .then(data => { result = data; }) .finally(done); }); - it(`must be able to execute queries`, () => { + it('must be able to execute queries', () => { expect(Array.isArray(result)).toBe(true); }); }); } - describe(`with a valid promise library-object override`, () => { - it(`must return a valid library object`, () => { + describe('with a valid promise library-object override', () => { + it('must return a valid library object', () => { const lib = header( { promiseLib: { @@ -106,12 +106,12 @@ describe(`Library entry function`, () => { }, noWarnings: true }); - expect(typeof lib.pgp).toBe(`function`); + expect(typeof lib.pgp).toBe('function'); }); }); - describe(`with a valid promise library-function override`, () => { - it(`must return a valid library object`, () => { + describe('with a valid promise library-function override', () => { + it('must return a valid library object', () => { function fakePromiseLib() { } @@ -122,16 +122,16 @@ describe(`Library entry function`, () => { promiseLib: fakePromiseLib, noWarnings: true }); - expect(typeof lib.pgp).toBe(`function`); + expect(typeof lib.pgp).toBe('function'); }); }); - describe(`with invalid promise override`, () => { - const error = `Invalid promise library specified.`; - it(`must throw the correct error`, () => { + describe('with invalid promise override', () => { + const error = 'Invalid promise library specified.'; + it('must throw the correct error', () => { expect(() => { header({ - promiseLib: `test` + promiseLib: 'test' }); }) .toThrow(error); @@ -144,31 +144,31 @@ describe(`Library entry function`, () => { }); }); - describe(`with invalid options parameter`, () => { - const errBody = `Invalid "options" parameter: `; - it(`must throw an error`, () => { + describe('with invalid options parameter', () => { + const errBody = 'Invalid "options" parameter: '; + it('must throw an error', () => { expect(() => { header(123); - }).toThrow(errBody + `123`); + }).toThrow(errBody + '123'); expect(() => { - header(`hello`); - }).toThrow(errBody + `"hello"`); + header('hello'); + }).toThrow(errBody + '"hello"'); }); }); - describe(`multi-init`, () => { + describe('multi-init', () => { const PromiseOne = { create: cb => new promise.Promise(cb), resolve: data => promise.resolve(data), - reject: () => promise.reject(`reject-one`), + reject: () => promise.reject('reject-one'), all: data => promise.all(data) }; const PromiseTwo = { create: cb => new promise.Promise(cb), resolve: data => promise.resolve(data), - reject: () => promise.reject(`reject-two`), + reject: () => promise.reject('reject-two'), all: data => promise.all(data) }; @@ -181,7 +181,7 @@ describe(`Library entry function`, () => { const pg2 = header({promiseLib: two, noWarnings: true}), db2 = pg2.db; db.task(t => { return t.batch([ - db1.query(`select $1`, []), db2.query(`select $1`, []) + db1.query('select $1', []), db2.query('select $1', []) ]); }) .catch(error => { @@ -190,24 +190,24 @@ describe(`Library entry function`, () => { .finally(done); }); - it(`must be supported`, () => { + it('must be supported', () => { expect(result instanceof BatchError).toBe(true); expect(result.data).toEqual([ { success: false, - result: `reject-one` + result: 'reject-one' }, { success: false, - result: `reject-two` + result: 'reject-two' } ]); }); }); - describe(`Taking no initialization options`, () => { - it(`must be supported`, () => { - expect(typeof dbHeader.pgpLib()).toBe(`function`); + describe('Taking no initialization options', () => { + it('must be supported', () => { + expect(typeof dbHeader.pgpLib()).toBe('function'); }); }); }); diff --git a/test/event.spec.js b/test/event.spec.js index 7f84a8cec..30fdadbd6 100644 --- a/test/event.spec.js +++ b/test/event.spec.js @@ -1,10 +1,10 @@ -const QueryStream = require(`pg-query-stream`); -const JSONStream = require(`JSONStream`); +const QueryStream = require('pg-query-stream'); +const JSONStream = require('JSONStream'); -const pgResult = require(`pg/lib/result`); -const pgClient = require(`pg/lib/client`); +const pgResult = require('pg/lib/result'); +const pgClient = require('pg/lib/client'); -const header = require(`./db/header`); +const header = require('./db/header'); const promise = header.defPromise; const options = { @@ -12,13 +12,13 @@ const options = { noWarnings: true }; -const testDC = `test_DC_123`; +const testDC = 'test_DC_123'; const dbHeader = header(options, testDC); const pgp = dbHeader.pgp; const db = dbHeader.db; -const $text = require(`../lib/text`); +const $text = require('../lib/text'); function isResult(value) { if (options.pgNative) { @@ -34,9 +34,9 @@ function isResult(value) { const dummy = () => { }; -describe(`Connect/Disconnect events`, () => { +describe('Connect/Disconnect events', () => { - describe(`during a query`, () => { + describe('during a query', () => { const ctx1 = {}, ctx2 = {}; let connect = 0, disconnect = 0; beforeEach(done => { @@ -45,15 +45,15 @@ describe(`Connect/Disconnect events`, () => { ctx1.client = e.client; ctx1.useCount = e.useCount; connect++; - throw new Error(`### Testing error output in 'connect'. Please ignore. ###`); + throw new Error('### Testing error output in \'connect\'. Please ignore. ###'); }; options.disconnect = (e) => { ctx2.dc = e.dc; ctx2.client = e.client; disconnect++; - throw new Error(`### Testing error output in 'disconnect'. Please ignore. ###`); + throw new Error('### Testing error output in \'disconnect\'. Please ignore. ###'); }; - db.query(`select 'test'`) + db.query('select \'test\'') .then(dummy, dummy) .finally(done); }); @@ -61,7 +61,7 @@ describe(`Connect/Disconnect events`, () => { options.connect = null; options.disconnect = null; }); - it(`must be sent correctly`, () => { + it('must be sent correctly', () => { expect(connect).toBe(1); expect(disconnect).toBe(1); if (!options.pgNative) { @@ -69,13 +69,13 @@ describe(`Connect/Disconnect events`, () => { expect(ctx2.client instanceof pgClient).toBe(true); } expect(ctx1.dc).toBe(testDC); - expect(typeof ctx1.useCount).toBe(`number`); + expect(typeof ctx1.useCount).toBe('number'); expect(ctx1.useCount >= 0).toBe(true); expect(ctx2.dc).toBe(testDC); }); }); - describe(`during a transaction`, () => { + describe('during a transaction', () => { const obj1 = {}, obj2 = {}; let ctx, connect = 0, disconnect = 0; beforeEach(done => { @@ -93,9 +93,9 @@ describe(`Connect/Disconnect events`, () => { db.tx(function (t) { ctx = t.ctx; return this.batch([ - t.query(`select 'one'`), - t.query(`select 'two'`), - t.query(`select 'three'`) + t.query('select \'one\''), + t.query('select \'two\''), + t.query('select \'three\'') ]); }) .then(dummy, dummy) @@ -105,7 +105,7 @@ describe(`Connect/Disconnect events`, () => { options.connect = null; options.disconnect = null; }); - it(`must be sent correctly`, () => { + it('must be sent correctly', () => { expect(connect).toBe(1); expect(disconnect).toBe(1); if (!options.pgNative) { @@ -119,58 +119,58 @@ describe(`Connect/Disconnect events`, () => { }); }); -describe(`Query event`, () => { +describe('Query event', () => { - describe(`positive`, () => { + describe('positive', () => { let param, counter = 0; beforeEach(done => { options.query = e => { counter++; param = e; }; - db.query(`select $1`, [123]) + db.query('select $1', [123]) .finally(done); }); - it(`must pass query and parameters correctly`, () => { + it('must pass query and parameters correctly', () => { expect(counter).toBe(1); - expect(param.query).toBe(`select 123`); + expect(param.query).toBe('select 123'); expect(param.params).toBeUndefined(); expect(param.dc).toBe(testDC); }); }); - describe(`negative, with an error object`, () => { + describe('negative, with an error object', () => { let result; - const errMsg = `Throwing a new Error during 'query' notification.`; + const errMsg = 'Throwing a new Error during \'query\' notification.'; beforeEach(done => { options.query = () => { throw new Error(errMsg); }; - db.query(`select $1`, [123]) + db.query('select $1', [123]) .catch(error => { result = error; }) .finally(done); }); - it(`must reject with the right error`, () => { + it('must reject with the right error', () => { expect(result).toEqual(new Error(errMsg)); }); }); - describe(`negative, with undefined`, () => { + describe('negative, with undefined', () => { let result, handled; beforeEach(done => { options.query = () => { throw undefined; }; - db.query(`select $1`, [123]) + db.query('select $1', [123]) .catch(error => { handled = true; result = error; }) .finally(done); }); - it(`must reject with undefined`, () => { + it('must reject with undefined', () => { expect(handled).toBe(true); expect(result).toBeUndefined(); }); @@ -182,7 +182,7 @@ describe(`Query event`, () => { }); -describe(`Start/Finish transaction events`, () => { +describe('Start/Finish transaction events', () => { let result, tag, ctx, e1, e2, start = 0, finish = 0; beforeEach(done => { options.transact = e => { @@ -195,9 +195,9 @@ describe(`Start/Finish transaction events`, () => { tag = e.ctx.tag; e2 = e; } - throw `### Testing error output in 'transact'. Please ignore. ###`; + throw '### Testing error output in \'transact\'. Please ignore. ###'; }; - db.tx(`myTransaction`, async () => `SUCCESS`) + db.tx('myTransaction', async () => 'SUCCESS') .then(data => { result = data; }) @@ -207,11 +207,11 @@ describe(`Start/Finish transaction events`, () => { options.transact = null; }); - it(`must execute correctly`, () => { - expect(result).toBe(`SUCCESS`); + it('must execute correctly', () => { + expect(result).toBe('SUCCESS'); expect(start).toBe(1); expect(finish).toBe(1); - expect(tag).toBe(`myTransaction`); + expect(tag).toBe('myTransaction'); expect(ctx.success).toBe(true); expect(ctx.isTX).toBe(true); expect(ctx.dc).toBe(testDC); @@ -220,32 +220,32 @@ describe(`Start/Finish transaction events`, () => { }); }); -describe(`Error event`, () => { +describe('Error event', () => { - describe(`from transaction callbacks`, () => { + describe('from transaction callbacks', () => { let r, error, context, counter = 0; beforeEach(done => { options.error = (err, e) => { counter++; error = err; context = e; - throw new Error(`### Testing error output in 'error'. Please ignore. ###`); + throw new Error('### Testing error output in \'error\'. Please ignore. ###'); }; - db.tx(`Error Transaction`, () => { - throw new Error(`Test Error`); + db.tx('Error Transaction', () => { + throw new Error('Test Error'); }) .catch(reason => { r = reason; }) .finally(done); }); - it(`must report errors`, () => { + it('must report errors', () => { expect(r instanceof Error).toBe(true); - expect(r.message).toBe(`Test Error`); + expect(r.message).toBe('Test Error'); expect(error instanceof Error).toBe(true); - expect(error.message).toBe(`Test Error`); + expect(error.message).toBe('Test Error'); expect(counter).toBe(1); - expect(context.ctx.tag).toBe(`Error Transaction`); + expect(context.ctx.tag).toBe('Error Transaction'); expect(context.dc).toBe(testDC); if (!options.pgNative) { expect(context.client instanceof pgClient).toBe(true); @@ -253,7 +253,7 @@ describe(`Error event`, () => { }); }); - describe(`for null-queries`, () => { + describe('for null-queries', () => { let error, context, counter = 0; beforeEach(done => { options.error = (err, e) => { @@ -265,7 +265,7 @@ describe(`Error event`, () => { .then(dummy, dummy) .finally(done); }); - it(`must fail correctly`, () => { + it('must fail correctly', () => { expect(error instanceof TypeError).toBe(true); expect(error.message).toBe($text.invalidQuery); expect(context.params).toBeUndefined(); @@ -276,7 +276,7 @@ describe(`Error event`, () => { }); }); - describe(`for incorrect QRM`, () => { + describe('for incorrect QRM', () => { let error, context, counter = 0; beforeEach(done => { options.error = (err, e) => { @@ -284,14 +284,14 @@ describe(`Error event`, () => { error = err; context = e; }; - db.query(`Bla-Bla`, undefined, 42) + db.query('Bla-Bla', undefined, 42) .then(dummy, dummy) .finally(done); }); - it(`must reject with correct error`, () => { + it('must reject with correct error', () => { expect(error instanceof TypeError).toBe(true); - expect(error.message).toBe(`Invalid Query Result Mask specified.`); - expect(context.query).toBe(`Bla-Bla`); + expect(error.message).toBe('Invalid Query Result Mask specified.'); + expect(context.query).toBe('Bla-Bla'); expect(context.params).toBeUndefined(); if (!options.pgNative) { expect(context.client instanceof pgClient).toBe(true); @@ -300,7 +300,7 @@ describe(`Error event`, () => { }); }); - describe(`for single-row requests`, () => { + describe('for single-row requests', () => { let errTxt, context, counter = 0; beforeEach(done => { options.error = (err, e) => { @@ -308,14 +308,14 @@ describe(`Error event`, () => { errTxt = err; context = e; }; - db.one(`select * from users`) + db.one('select * from users') .then(dummy, dummy) .finally(done); }); - it(`must reject with correct error`, () => { + it('must reject with correct error', () => { expect(errTxt instanceof pgp.errors.QueryResultError).toBe(true); - expect(errTxt.message).toBe(`Multiple rows were not expected.`); - expect(context.query).toBe(`select * from users`); + expect(errTxt.message).toBe('Multiple rows were not expected.'); + expect(context.query).toBe('select * from users'); expect(context.params).toBeUndefined(); if (!options.pgNative) { expect(context.client instanceof pgClient).toBe(true); @@ -324,7 +324,7 @@ describe(`Error event`, () => { }); }); - describe(`for no-row requests`, () => { + describe('for no-row requests', () => { let errTxt, context, counter = 0; beforeEach(done => { options.error = (err, e) => { @@ -332,14 +332,14 @@ describe(`Error event`, () => { errTxt = err; context = e; }; - db.none(`select * from users`) + db.none('select * from users') .then(dummy, dummy) .finally(done); }); - it(`must reject with correct error`, () => { + it('must reject with correct error', () => { expect(errTxt instanceof pgp.errors.QueryResultError).toBe(true); expect(errTxt.message).toBe($text.notEmpty); - expect(context.query).toBe(`select * from users`); + expect(context.query).toBe('select * from users'); expect(context.params).toBeUndefined(); if (!options.pgNative) { expect(context.client instanceof pgClient).toBe(true); @@ -348,7 +348,7 @@ describe(`Error event`, () => { }); }); - describe(`for empty requests`, () => { + describe('for empty requests', () => { let errTxt, context, counter = 0; beforeEach(done => { options.error = (err, e) => { @@ -356,14 +356,14 @@ describe(`Error event`, () => { errTxt = err; context = e; }; - db.many(`select * from users where id > $1`, 1000) + db.many('select * from users where id > $1', 1000) .then(dummy, dummy) .finally(done); }); - it(`must reject with correct error`, () => { + it('must reject with correct error', () => { expect(errTxt instanceof pgp.errors.QueryResultError).toBe(true); - expect(errTxt.message).toBe(`No data returned from the query.`); - expect(context.query).toBe(`select * from users where id > 1000`); + expect(errTxt.message).toBe('No data returned from the query.'); + expect(context.query).toBe('select * from users where id > 1000'); expect(context.params).toBeUndefined(); if (!options.pgNative) { expect(context.client instanceof pgClient).toBe(true); @@ -372,7 +372,7 @@ describe(`Error event`, () => { }); }); - describe(`for loose query requests`, () => { + describe('for loose query requests', () => { let error, r, context, counter = 0; beforeEach(done => { options.error = (err, e) => { @@ -384,7 +384,7 @@ describe(`Error event`, () => { db.connect() .then(obj => { sco = obj; - query = sco.query(`select * from users where($1)`, false); + query = sco.query('select * from users where($1)', false); return null; }) .finally(() => { @@ -396,12 +396,12 @@ describe(`Error event`, () => { .finally(done); }); }); - it(`must notify with correct error`, () => { + it('must notify with correct error', () => { expect(error instanceof Error).toBe(true); expect(error.message).toBe($text.looseQuery); expect(r instanceof Error).toBe(true); expect(r.message).toBe($text.looseQuery); - expect(context.query).toBe(`select * from users where(false)`); + expect(context.query).toBe('select * from users where(false)'); expect(context.client).toBeUndefined(); expect(context.params).toBeUndefined(); expect(counter).toBe(1); @@ -409,17 +409,17 @@ describe(`Error event`, () => { }); if (!options.pgNative) { - describe(`for loose stream requests`, () => { + describe('for loose stream requests', () => { let r, sco; beforeEach(done => { - const qs = new QueryStream(`select * from users`); + const qs = new QueryStream('select * from users'); db.connect() .then(obj => { sco = obj; return sco.stream(qs, s => { s.pipe(JSONStream.stringify()); obj.done(); - throw new Error(`Something went wrong here`); + throw new Error('Something went wrong here'); }); }) .catch(reason => { @@ -427,14 +427,14 @@ describe(`Error event`, () => { }) .finally(done); }); - it(`must notify with correct error`, () => { + it('must notify with correct error', () => { expect(r instanceof Error).toBe(true); expect(r.message).toBe($text.looseQuery); }); }); } - describe(`for invalid parameters`, () => { + describe('for invalid parameters', () => { let error, context, counter = 0; const params = {}; beforeEach(done => { @@ -443,14 +443,14 @@ describe(`Error event`, () => { error = err; context = e; }; - db.query(`\${test}`, params) + db.query('${test}', params) .then(dummy, dummy) .finally(done); }); - it(`must report the parameters correctly`, () => { + it('must report the parameters correctly', () => { expect(error instanceof Error).toBe(true); - expect(error.message).toBe(`Property 'test' doesn't exist.`); - expect(context.query).toBe(`\${test}`); + expect(error.message).toBe('Property \'test\' doesn\'t exist.'); + expect(context.query).toBe('${test}'); expect(context.params).toBe(params); if (!options.pgNative) { expect(context.client instanceof pgClient).toBe(true); @@ -465,9 +465,9 @@ describe(`Error event`, () => { }); -describe(`Receive event`, () => { +describe('Receive event', () => { - describe(`query positive`, () => { + describe('query positive', () => { let ctx, data, res, counter = 0; beforeEach(done => { options.receive = (e) => { @@ -476,23 +476,23 @@ describe(`Receive event`, () => { res = e.result; ctx = e.ctx; }; - db.one(`select $1 as value`, [123]) + db.one('select $1 as value', [123]) .finally(done); }); - it(`must pass in correct data and context`, () => { + it('must pass in correct data and context', () => { expect(counter).toBe(1); - expect(ctx.query).toBe(`select 123 as value`); + expect(ctx.query).toBe('select 123 as value'); expect(ctx.params).toBeUndefined(); expect(ctx.dc).toBe(testDC); expect(data).toEqual([{ value: 123 }]); expect(isResult(res)).toBe(true); - expect(typeof res.duration).toBe(`number`); + expect(typeof res.duration).toBe('number'); }); }); - describe(`for empty queries`, () => { + describe('for empty queries', () => { let ctx, data, res, counter = 0; beforeEach(done => { options.receive = function (e) { @@ -501,87 +501,87 @@ describe(`Receive event`, () => { res = e.result; ctx = e.ctx; }; - db.none(`delete from users where id = $1`, 1234567890) + db.none('delete from users where id = $1', 1234567890) .finally(done); }); - it(`must pass in correct empty data and context`, () => { + it('must pass in correct empty data and context', () => { expect(counter).toBe(1); - expect(ctx.query).toBe(`delete from users where id = 1234567890`); + expect(ctx.query).toBe('delete from users where id = 1234567890'); expect(ctx.params).toBeUndefined(); expect(ctx.dc).toBe(testDC); expect(data).toEqual([]); expect(isResult(res)).toBe(true); - expect(typeof res.duration).toBe(`number`); + expect(typeof res.duration).toBe('number'); }); }); - describe(`positive for multi-queries`, () => { + describe('positive for multi-queries', () => { const data = []; beforeEach(done => { options.receive = (e) => { data.push(e); }; - db.multiResult(`select 1 as one;select 2 as two`) + db.multiResult('select 1 as one;select 2 as two') .then(() => { done(); }); }); - it(`must send the event for each result`, () => { + it('must send the event for each result', () => { expect(data.length).toBe(2); expect(data[0].data).toEqual([{one: 1}]); expect(data[1].data).toEqual([{two: 2}]); }); }); - describe(`negative for multi-queries`, () => { + describe('negative for multi-queries', () => { let result; beforeEach(done => { options.receive = () => { - throw new Error(`Ops!`); + throw new Error('Ops!'); }; - db.multiResult(`select 1 as one;select 2 as two`) + db.multiResult('select 1 as one;select 2 as two') .catch(error => { result = error; }) .finally(done); }); - it(`must reject with the error`, () => { + it('must reject with the error', () => { expect(result instanceof Error).toBe(true); }); }); - describe(`query negative`, () => { + describe('query negative', () => { let result; - const error = `ops!`; + const error = 'ops!'; beforeEach(done => { options.receive = () => { throw error; }; - db.one(`select $1 as value`, [123]) + db.one('select $1 as value', [123]) .catch(reason => { result = reason; }) .finally(done); }); - it(`must reject with the right error`, () => { + it('must reject with the right error', () => { expect(result).toBe(error); }); }); - describe(`query negative, undefined`, () => { + describe('query negative, undefined', () => { let result, handled; beforeEach(done => { options.receive = () => { throw undefined; }; - db.one(`select $1 as value`, [123]) + db.one('select $1 as value', [123]) .catch(error => { handled = true; result = error; }) .finally(done); }); - it(`must reject with undefined`, () => { + it('must reject with undefined', () => { expect(handled).toBe(true); expect(result).toBeUndefined(); }); @@ -590,7 +590,7 @@ describe(`Receive event`, () => { if (!options.pgNative) { // Cannot test streams against native bindings; - describe(`stream positive`, () => { + describe('stream positive', () => { let ctx, data, res, counter = 0; beforeEach(done => { options.receive = (e) => { @@ -599,7 +599,7 @@ describe(`Receive event`, () => { res = e.result; ctx = e.ctx; }; - const qs = new QueryStream(`select $1::int as value`, [123]); + const qs = new QueryStream('select $1::int as value', [123]); db.stream(qs, s => { s.pipe(JSONStream.stringify()); }) @@ -607,10 +607,10 @@ describe(`Receive event`, () => { done(); }); }); - it(`must pass in correct data and context`, () => { + it('must pass in correct data and context', () => { expect(counter).toBe(1); - expect(ctx.query).toBe(`select $1::int as value`); - expect(ctx.params).toEqual([`123`]); + expect(ctx.query).toBe('select $1::int as value'); + expect(ctx.params).toEqual(['123']); expect(data).toEqual([{ value: 123 }]); @@ -618,13 +618,13 @@ describe(`Receive event`, () => { }); }); - describe(`for paged streaming`, () => { + describe('for paged streaming', () => { let result, counter = 0; beforeEach(done => { options.receive = e => { counter += e.data.length; }; - const qs = new QueryStream(`select * from users`, [], {batchSize: 2}); + const qs = new QueryStream('select * from users', [], {batchSize: 2}); db.stream(qs, s => { s.pipe(JSONStream.stringify()); }) @@ -633,19 +633,19 @@ describe(`Receive event`, () => { done(); }); }); - it(`must get all the rows`, () => { + it('must get all the rows', () => { expect(counter).toBe(result.processed); }); }); - describe(`stream negative`, () => { + describe('stream negative', () => { let result; - const err = new Error(`Ops!`); + const err = new Error('Ops!'); beforeEach(done => { options.receive = () => { throw err; }; - const qs = new QueryStream(`select $1::int as value`, [123]); + const qs = new QueryStream('select $1::int as value', [123]); db.stream(qs, s => { s.pipe(JSONStream.stringify()); }) @@ -654,7 +654,7 @@ describe(`Receive event`, () => { }) .finally(done); }); - it(`must reject with the right error`, () => { + it('must reject with the right error', () => { expect(result).toBe(err); }); }); @@ -666,7 +666,7 @@ describe(`Receive event`, () => { }); -describe(`pgFormatting`, () => { +describe('pgFormatting', () => { let result; beforeEach(() => { result = undefined; @@ -675,15 +675,15 @@ describe(`pgFormatting`, () => { afterEach(() => { options.pgFormatting = false; }); - describe(`query event`, () => { + describe('query event', () => { const ctx = []; beforeEach(done => { options.query = e => { ctx.push(e); }; promise.all([ - db.func(`findUser`, [1]), - db.one(`select * from users where id=$1`, [1]) + db.func('findUser', [1]), + db.one('select * from users where id=$1', [1]) ]) .then(data => { result = data; @@ -693,7 +693,7 @@ describe(`pgFormatting`, () => { afterEach(() => { options.query = null; }); - it(`must affect formatting accordingly`, () => { + it('must affect formatting accordingly', () => { expect(Array.isArray(result)).toBe(true); expect(ctx.length).toBe(2); // params will be passed back only because the formatting @@ -704,12 +704,12 @@ describe(`pgFormatting`, () => { }); }); - describe(`empty / null query`, () => { + describe('empty / null query', () => { let err; beforeEach(done => { promise.any([ db.query(), - db.query(``), + db.query(''), db.query(null), db.query(0) ]) @@ -718,7 +718,7 @@ describe(`pgFormatting`, () => { }) .finally(done); }); - it(`must provide the original pg response`, () => { + it('must provide the original pg response', () => { if (!options.pgNative) { expect(err.length).toBe(4); for (let i = 0; i < 4; i++) { diff --git a/test/file.spec.js b/test/file.spec.js index 79b6dc203..ae3f8f3bd 100644 --- a/test/file.spec.js +++ b/test/file.spec.js @@ -1,8 +1,8 @@ -const path = require(`path`); -const fs = require(`fs`); -const header = require(`./db/header`); -const utils = require(`../lib/utils`); -const tools = require(`./db/tools`); +const path = require('path'); +const fs = require('fs'); +const header = require('./db/header'); +const utils = require('../lib/utils'); +const tools = require('./db/tools'); const promise = header.defPromise; const options = { @@ -20,57 +20,57 @@ const getPath = file => { return path.join(__dirname, file); }; -const sqlSimple = getPath(`./sql/simple.sql`); -const sqlUsers = getPath(`./sql/allUsers.sql`); -const sqlUnknown = getPath(`./sql/unknown.sql`); -const sqlInvalid = getPath(`./sql/invalid.sql`); -const sqlParams = getPath(`./sql/params.sql`); -const sqlTemp = getPath(`./sql/temp.sql`); +const sqlSimple = getPath('./sql/simple.sql'); +const sqlUsers = getPath('./sql/allUsers.sql'); +const sqlUnknown = getPath('./sql/unknown.sql'); +const sqlInvalid = getPath('./sql/invalid.sql'); +const sqlParams = getPath('./sql/params.sql'); +const sqlTemp = getPath('./sql/temp.sql'); -describe(`QueryFile / Positive:`, () => { +describe('QueryFile / Positive:', () => { - describe(`without options`, () => { + describe('without options', () => { const qf = new QueryFile(sqlSimple, {noWarnings: true}); - it(`must not minify`, () => { - expect(qf[QueryFile.$query]).toBe(`select 1; --comment`); + it('must not minify', () => { + expect(qf[QueryFile.$query]).toBe('select 1; --comment'); }); }); - describe(`with minify=true && debug=true`, () => { + describe('with minify=true && debug=true', () => { const qf = new QueryFile(sqlUsers, {debug: true, minify: true, noWarnings: true}); - it(`must return minified query`, () => { - expect(qf[QueryFile.$query]).toBe(`select * from users`); + it('must return minified query', () => { + expect(qf[QueryFile.$query]).toBe('select * from users'); }); }); - describe(`default with params`, () => { + describe('default with params', () => { const params = { - schema: `public`, - table: `users` + schema: 'public', + table: 'users' }; const qf = new QueryFile(sqlParams, {minify: true, params, noWarnings: true}); - it(`must return pre-formatted query`, () => { - expect(qf[QueryFile.$query]).toBe(`SELECT \${column~} FROM "public"."users"`); + it('must return pre-formatted query', () => { + expect(qf[QueryFile.$query]).toBe('SELECT ${column~} FROM "public"."users"'); }); }); - describe(`compression with params`, () => { + describe('compression with params', () => { const params = { - schema: `public`, - table: `users`, - column: `col` + schema: 'public', + table: 'users', + column: 'col' }; const qf1 = new QueryFile(sqlParams, {minify: true, compress: true, params, noWarnings: true}); - it(`must return uncompressed replacements by default`, () => { - expect(qf1[QueryFile.$query]).toBe(`SELECT "col" FROM "public"."users"`); + it('must return uncompressed replacements by default', () => { + expect(qf1[QueryFile.$query]).toBe('SELECT "col" FROM "public"."users"'); }); - const qf2 = new QueryFile(sqlParams, {minify: `after`, compress: true, params, noWarnings: true}); - it(`must return compressed replacements for 'after'`, () => { - expect(qf2[QueryFile.$query]).toBe(`SELECT"col"FROM"public"."users"`); + const qf2 = new QueryFile(sqlParams, {minify: 'after', compress: true, params, noWarnings: true}); + it('must return compressed replacements for \'after\'', () => { + expect(qf2[QueryFile.$query]).toBe('SELECT"col"FROM"public"."users"'); }); }); - describe(`non-minified query`, () => { + describe('non-minified query', () => { let result; beforeEach(done => { db.query(new QueryFile(sqlUsers, {noWarnings: true})) @@ -79,13 +79,13 @@ describe(`QueryFile / Positive:`, () => { }) .finally(done); }); - it(`must resolve with data`, () => { + it('must resolve with data', () => { expect(Array.isArray(result)).toBe(true); expect(result.length > 0).toBe(true); }); }); - describe(`minified query`, () => { + describe('minified query', () => { let result; beforeEach(done => { db.query(new QueryFile(sqlUsers, {minify: true, noWarnings: true})) @@ -94,13 +94,13 @@ describe(`QueryFile / Positive:`, () => { }) .finally(done); }); - it(`must resolve with data`, () => { + it('must resolve with data', () => { expect(Array.isArray(result)).toBe(true); expect(result.length > 0).toBe(true); }); }); - describe(`compressed query`, () => { + describe('compressed query', () => { let result, sql; beforeEach(done => { sql = new QueryFile(sqlUsers, {compress: true, noWarnings: true}); @@ -110,14 +110,14 @@ describe(`QueryFile / Positive:`, () => { }) .finally(done); }); - it(`must resolve with data`, () => { - expect(sql[QueryFile.$query]).toBe(`select*from users`); + it('must resolve with data', () => { + expect(sql[QueryFile.$query]).toBe('select*from users'); expect(Array.isArray(result)).toBe(true); expect(result.length > 0).toBe(true); }); }); - describe(`property options`, () => { + describe('property options', () => { const options1 = { debug: utils.isDev(), noWarnings: true @@ -133,33 +133,33 @@ describe(`QueryFile / Positive:`, () => { compress: true, noWarnings: true }; - it(`must be consistent with the settings`, () => { + it('must be consistent with the settings', () => { expect(new QueryFile(sqlSimple, {noWarnings: true}).options).toEqual(options1); expect(new QueryFile(sqlSimple, options2).options).toEqual(options3); }); }); - describe(`inspect`, () => { + describe('inspect', () => { const qf = new QueryFile(sqlSimple, {noWarnings: true}); - it(`must return the query`, () => { + it('must return the query', () => { expect(tools.inspect(qf)).toBe(qf.toString()); }); }); - describe(`custom-type formatting`, () => { + describe('custom-type formatting', () => { const qf = new QueryFile(sqlSimple, {noWarnings: true}); const toPostgres = pgp.as.ctf.toPostgres; - it(`must return the full name`, () => { + it('must return the full name', () => { expect(qf[toPostgres](qf)).toBe(qf[QueryFile.$query]); expect(qf[toPostgres].call(null, qf)).toBe(qf[QueryFile.$query]); expect(qf[toPostgres]()).toBe(qf[QueryFile.$query]); }); }); - describe(`modified file`, () => { - const q1 = `select 1`; - const q2 = `select 2`; - it(`must be read again`, () => { + describe('modified file', () => { + const q1 = 'select 1'; + const q2 = 'select 2'; + it('must be read again', () => { fs.writeFileSync(sqlTemp, q1); const qf = new QueryFile(sqlTemp, {debug: true}); expect(qf[QueryFile.$query]).toBe(q1); @@ -175,20 +175,20 @@ describe(`QueryFile / Positive:`, () => { }); }); - describe(`repeated read`, () => { + describe('repeated read', () => { // this is just for code coverage; - it(`must not read again`, () => { + it('must not read again', () => { const qf = new QueryFile(sqlSimple, {debug: false, minify: true, noWarnings: true}); qf.prepare(); qf.prepare(); - expect(qf[QueryFile.$query]).toBe(`select 1;`); + expect(qf[QueryFile.$query]).toBe('select 1;'); }); }); }); -describe(`QueryFile / Negative:`, () => { +describe('QueryFile / Negative:', () => { - describe(`non-minified query`, () => { + describe('non-minified query', () => { let error; beforeEach(done => { db.query(new QueryFile(sqlUnknown)) @@ -197,24 +197,24 @@ describe(`QueryFile / Negative:`, () => { }) .finally(done); }); - it(`must reject with an error`, () => { + it('must reject with an error', () => { expect(error instanceof Error).toBe(true); }); }); - describe(`inspect`, () => { + describe('inspect', () => { const qf = new QueryFile(sqlInvalid, {minify: true, noWarnings: true}); - it(`must return the error`, () => { + it('must return the error', () => { expect(tools.inspect(qf) != qf.toString(1)).toBe(true); expect(qf.error instanceof QueryFileError).toBe(true); expect(tools.inspect(qf.error)).toBe(qf.error.toString()); }); }); - describe(`accessing a temporary file`, () => { + describe('accessing a temporary file', () => { let error; - const query = `select 123 as value`; - it(`must result in error once deleted`, () => { + const query = 'select 123 as value'; + it('must result in error once deleted', () => { fs.writeFileSync(sqlTemp, query); const qf = new QueryFile(sqlTemp, {debug: true, noWarnings: true}); expect(qf[QueryFile.$query]).toBe(query); @@ -225,7 +225,7 @@ describe(`QueryFile / Negative:`, () => { expect(qf.error instanceof Error).toBe(true); }); - it(`must throw when preparing`, () => { + it('must throw when preparing', () => { fs.writeFileSync(sqlTemp, query); const qf = new QueryFile(sqlTemp, {debug: true, noWarnings: true}); expect(qf[QueryFile.$query]).toBe(query); @@ -242,8 +242,8 @@ describe(`QueryFile / Negative:`, () => { }); - describe(`invalid sql`, () => { - it(`must throw an error`, () => { + describe('invalid sql', () => { + it('must throw an error', () => { const qf = new QueryFile(sqlInvalid, {minify: true, noWarnings: true}); expect(qf.error instanceof QueryFileError).toBe(true); expect(qf.error.file).toBe(sqlInvalid); diff --git a/test/format.spec.js b/test/format.spec.js index 549dfd52e..f7f5e66ff 100644 --- a/test/format.spec.js +++ b/test/format.spec.js @@ -1,19 +1,19 @@ -const path = require(`path`); -const pgp = require(`../lib/index`); +const path = require('path'); +const pgp = require('../lib/index'); -const $pgUtils = require(`pg/lib/utils`); +const $pgUtils = require('pg/lib/utils'); const dateSample = new Date(); // common error messages; const errors = { - rawNull: () => `Values null/undefined cannot be used as raw text.`, + rawNull: () => 'Values null/undefined cannot be used as raw text.', range: (variable, length) => `Variable ${variable} out of range. Parameters array length: ${length}`, buffer: value => `'${value}' is not a Buffer object.` }; -const sqlSimple = getPath(`./sql/simple.sql`); -const sqlParams = getPath(`./sql/params.sql`); +const sqlSimple = getPath('./sql/simple.sql'); +const sqlParams = getPath('./sql/params.sql'); function getPath(file) { return path.join(__dirname, file); @@ -23,55 +23,55 @@ const dummy = () => { }; const userObj = { - name: `John O'Connor`, + name: 'John O\'Connor', dob: new Date(1980, 5, 15), active: true }; -describe(`Method as.buffer`, () => { +describe('Method as.buffer', () => { - describe(`Positive:`, () => { + describe('Positive:', () => { const data = Buffer.from([1, 2, 3]); - const hex = `\\x010203`; + const hex = '\\x010203'; - it(`must hex-format data`, () => { + it('must hex-format data', () => { expect(pgp.as.buffer(data)).toBe(`'${hex}'`); expect(pgp.as.buffer(data, true)).toBe(hex); }); - it(`must format null/undefined correctly`, () => { - expect(pgp.as.buffer()).toBe(`null`); - expect(pgp.as.buffer(null)).toBe(`null`); + it('must format null/undefined correctly', () => { + expect(pgp.as.buffer()).toBe('null'); + expect(pgp.as.buffer(null)).toBe('null'); }); - it(`must format values correctly`, () => { - expect(pgp.as.format(`$1`, data)).toBe(`'${hex}'`); - expect(pgp.as.format(`$1`, [data])).toBe(`'${hex}'`); + it('must format values correctly', () => { + expect(pgp.as.format('$1', data)).toBe(`'${hex}'`); + expect(pgp.as.format('$1', [data])).toBe(`'${hex}'`); }); - it(`must format raw values correctly`, () => { - expect(pgp.as.format(`$1^`, data)).toBe(hex); - expect(pgp.as.format(`$1^`, [data])).toBe(hex); + it('must format raw values correctly', () => { + expect(pgp.as.format('$1^', data)).toBe(hex); + expect(pgp.as.format('$1^', [data])).toBe(hex); }); - it(`must format open values correctly`, () => { - expect(pgp.as.format(`$1#`, data)).toBe(hex); - expect(pgp.as.format(`$1:value`, [data])).toBe(hex); + it('must format open values correctly', () => { + expect(pgp.as.format('$1#', data)).toBe(hex); + expect(pgp.as.format('$1:value', [data])).toBe(hex); }); - it(`must work in any other context`, () => { - const input = [23, Buffer.from([1, 2, 3]), `Hello`], output = `23,'\\x010203','Hello'`, + it('must work in any other context', () => { + const input = [23, Buffer.from([1, 2, 3]), 'Hello'], output = '23,\'\\x010203\',\'Hello\'', simple = Buffer.from([1, 2, 3]); - expect(pgp.as.csv(simple)).toBe(`1,2,3`); - expect(pgp.as.format(`$1:json`, [simple])).toEqual(`'${JSON.stringify(simple)}'`); + expect(pgp.as.csv(simple)).toBe('1,2,3'); + expect(pgp.as.format('$1:json', [simple])).toEqual(`'${JSON.stringify(simple)}'`); expect(pgp.as.csv(input)).toBe(output); - expect(pgp.as.format(`$1,$2,$3`, input)).toBe(output); - expect(pgp.as.format(`$1:csv`, [input])).toBe(output); + expect(pgp.as.format('$1,$2,$3', input)).toBe(output); + expect(pgp.as.format('$1:csv', [input])).toBe(output); }); }); - describe(`Negative:`, () => { - it(`must throw error on invalid data`, () => { + describe('Negative:', () => { + it('must throw error on invalid data', () => { expect(() => { pgp.as.buffer(123); }).toThrow(errors.buffer(123)); @@ -89,54 +89,54 @@ describe(`Method as.buffer`, () => { }); }); -describe(`Method as.bool`, () => { +describe('Method as.bool', () => { - it(`must correctly convert any boolean-like value`, () => { - expect(pgp.as.bool()).toBe(`null`); - expect(pgp.as.bool(null)).toBe(`null`); - expect(pgp.as.bool(0)).toBe(`false`); - expect(pgp.as.bool(false)).toBe(`false`); - expect(pgp.as.bool(1)).toBe(`true`); - expect(pgp.as.bool(true)).toBe(`true`); - expect(pgp.as.bool(10)).toBe(`true`); - expect(pgp.as.bool(-10)).toBe(`true`); - expect(pgp.as.bool([])).toBe(`true`); - expect(pgp.as.bool({})).toBe(`true`); - expect(pgp.as.bool(`false`)).toBe(`true`); + it('must correctly convert any boolean-like value', () => { + expect(pgp.as.bool()).toBe('null'); + expect(pgp.as.bool(null)).toBe('null'); + expect(pgp.as.bool(0)).toBe('false'); + expect(pgp.as.bool(false)).toBe('false'); + expect(pgp.as.bool(1)).toBe('true'); + expect(pgp.as.bool(true)).toBe('true'); + expect(pgp.as.bool(10)).toBe('true'); + expect(pgp.as.bool(-10)).toBe('true'); + expect(pgp.as.bool([])).toBe('true'); + expect(pgp.as.bool({})).toBe('true'); + expect(pgp.as.bool('false')).toBe('true'); }); - it(`must correctly resolve functions`, () => { - expect(pgp.as.bool(dummy)).toBe(`null`); - expect(pgp.as.bool(() => null)).toBe(`null`); - expect(pgp.as.bool(() => true)).toBe(`true`); - expect(pgp.as.bool(() => false)).toBe(`false`); + it('must correctly resolve functions', () => { + expect(pgp.as.bool(dummy)).toBe('null'); + expect(pgp.as.bool(() => null)).toBe('null'); + expect(pgp.as.bool(() => true)).toBe('true'); + expect(pgp.as.bool(() => false)).toBe('false'); }); }); -describe(`Method as.number`, () => { - - it(`must correctly convert any number`, () => { - expect(pgp.as.number()).toBe(`null`); - expect(pgp.as.number(null)).toBe(`null`); - expect(pgp.as.number(0)).toBe(`0`); - expect(pgp.as.number(1)).toBe(`1`); - expect(pgp.as.number(1234567890)).toBe(`1234567890`); - expect(pgp.as.number(-123.456)).toBe(`-123.456`); - expect(pgp.as.number(NaN)).toBe(`'NaN'`); - expect(pgp.as.number(Number.NaN)).toBe(`'NaN'`); - expect(pgp.as.number(1 / 0)).toBe(`'+Infinity'`); - expect(pgp.as.number(Number.POSITIVE_INFINITY)).toBe(`'+Infinity'`); - expect(pgp.as.number(-1 / 0)).toBe(`'-Infinity'`); - expect(pgp.as.number(Number.NEGATIVE_INFINITY)).toBe(`'-Infinity'`); - }); - - it(`must correctly resolve functions`, () => { - expect(pgp.as.number(dummy)).toBe(`null`); - expect(pgp.as.number(() => null)).toBe(`null`); - expect(pgp.as.number(() => 123)).toBe(`123`); - expect(pgp.as.number(() => 0)).toBe(`0`); - expect(pgp.as.number(() => -1 / 0)).toBe(`'-Infinity'`); +describe('Method as.number', () => { + + it('must correctly convert any number', () => { + expect(pgp.as.number()).toBe('null'); + expect(pgp.as.number(null)).toBe('null'); + expect(pgp.as.number(0)).toBe('0'); + expect(pgp.as.number(1)).toBe('1'); + expect(pgp.as.number(1234567890)).toBe('1234567890'); + expect(pgp.as.number(-123.456)).toBe('-123.456'); + expect(pgp.as.number(NaN)).toBe('\'NaN\''); + expect(pgp.as.number(Number.NaN)).toBe('\'NaN\''); + expect(pgp.as.number(1 / 0)).toBe('\'+Infinity\''); + expect(pgp.as.number(Number.POSITIVE_INFINITY)).toBe('\'+Infinity\''); + expect(pgp.as.number(-1 / 0)).toBe('\'-Infinity\''); + expect(pgp.as.number(Number.NEGATIVE_INFINITY)).toBe('\'-Infinity\''); + }); + + it('must correctly resolve functions', () => { + expect(pgp.as.number(dummy)).toBe('null'); + expect(pgp.as.number(() => null)).toBe('null'); + expect(pgp.as.number(() => 123)).toBe('123'); + expect(pgp.as.number(() => 0)).toBe('0'); + expect(pgp.as.number(() => -1 / 0)).toBe('\'-Infinity\''); // deep-call test: expect(pgp.as.number(() => { @@ -145,14 +145,14 @@ describe(`Method as.number`, () => { return 123; }; }; - })).toBe(`123`); + })).toBe('123'); }); - it(`must reject for invalid parameters`, () => { + it('must reject for invalid parameters', () => { - const err = ` is not a number.`; + const err = ' is not a number.'; expect(() => { - pgp.as.number(``); + pgp.as.number(''); }).toThrow(`''${err}`); expect(() => { @@ -162,58 +162,58 @@ describe(`Method as.number`, () => { }); -describe(`Method as.text`, () => { - it(`must correctly convert any text`, () => { +describe('Method as.text', () => { + it('must correctly convert any text', () => { - expect(pgp.as.text()).toBe(`null`); - expect(pgp.as.text(null)).toBe(`null`); + expect(pgp.as.text()).toBe('null'); + expect(pgp.as.text(null)).toBe('null'); - expect(pgp.as.text(``)).toBe(`''`); - expect(pgp.as.text(``, true)).toBe(``); // raw-text test; + expect(pgp.as.text('')).toBe('\'\''); + expect(pgp.as.text('', true)).toBe(''); // raw-text test; - expect(pgp.as.text(`some text`)).toBe(`'some text'`); - expect(pgp.as.text(`some text`, true)).toBe(`some text`); // raw-text test; + expect(pgp.as.text('some text')).toBe('\'some text\''); + expect(pgp.as.text('some text', true)).toBe('some text'); // raw-text test; - expect(pgp.as.text(`'starts with quote`)).toBe(`'''starts with quote'`); - expect(pgp.as.text(`'starts with quote`, true)).toBe(`'starts with quote`); // raw-text test; + expect(pgp.as.text('\'starts with quote')).toBe('\'\'\'starts with quote\''); + expect(pgp.as.text('\'starts with quote', true)).toBe('\'starts with quote'); // raw-text test; - expect(pgp.as.text(`ends with quote'`)).toBe(`'ends with quote'''`); - expect(pgp.as.text(`ends with quote'`, true)).toBe(`ends with quote'`); // raw-text test; + expect(pgp.as.text('ends with quote\'')).toBe('\'ends with quote\'\'\''); + expect(pgp.as.text('ends with quote\'', true)).toBe('ends with quote\''); // raw-text test; - expect(pgp.as.text(`has '' two quotes`)).toBe(`'has '''' two quotes'`); - expect(pgp.as.text(`has '' two quotes`, true)).toBe(`has '' two quotes`); // raw-text test; + expect(pgp.as.text('has \'\' two quotes')).toBe('\'has \'\'\'\' two quotes\''); + expect(pgp.as.text('has \'\' two quotes', true)).toBe('has \'\' two quotes'); // raw-text test; - expect(pgp.as.text(`'`)).toBe(`''''`); - expect(pgp.as.text(`'`, true)).toBe(`'`); // raw-text test; + expect(pgp.as.text('\'')).toBe('\'\'\'\''); + expect(pgp.as.text('\'', true)).toBe('\''); // raw-text test; - expect(pgp.as.text(`''`)).toBe(`''''''`); - expect(pgp.as.text(`''`, true)).toBe(`''`); // raw-text test; + expect(pgp.as.text('\'\'')).toBe('\'\'\'\'\'\''); + expect(pgp.as.text('\'\'', true)).toBe('\'\''); // raw-text test; - expect(pgp.as.text(-123.456)).toBe(`'-123.456'`); - expect(pgp.as.text(true)).toBe(`'true'`); - expect(pgp.as.text(false)).toBe(`'false'`); + expect(pgp.as.text(-123.456)).toBe('\'-123.456\''); + expect(pgp.as.text(true)).toBe('\'true\''); + expect(pgp.as.text(false)).toBe('\'false\''); expect(pgp.as.text(dateSample)).toBe(`'${dateSample.toString()}'`); - expect(pgp.as.text([])).toBe(`''`); - expect(pgp.as.text([], true)).toBe(``); // raw-text test; + expect(pgp.as.text([])).toBe('\'\''); + expect(pgp.as.text([], true)).toBe(''); // raw-text test; - expect(pgp.as.text([1, `hello`])).toBe(`'1,hello'`); // converts string as is; - expect(pgp.as.text([1, `hello`], true)).toBe(`1,hello`); // converts string as is; + expect(pgp.as.text([1, 'hello'])).toBe('\'1,hello\''); // converts string as is; + expect(pgp.as.text([1, 'hello'], true)).toBe('1,hello'); // converts string as is; - expect(pgp.as.text({})).toBe(`'[object Object]'`); + expect(pgp.as.text({})).toBe('\'[object Object]\''); }); - it(`must correctly resolve functions`, () => { + it('must correctly resolve functions', () => { - expect(pgp.as.text(dummy)).toBe(`null`); + expect(pgp.as.text(dummy)).toBe('null'); - expect(pgp.as.text(() => null)).toBe(`null`); + expect(pgp.as.text(() => null)).toBe('null'); - expect(pgp.as.text(() => `hello`)).toBe(`'hello'`); + expect(pgp.as.text(() => 'hello')).toBe('\'hello\''); }); - it(`must correctly respond to invalid raw-text requests`, () => { + it('must correctly respond to invalid raw-text requests', () => { expect(() => { pgp.as.text(undefined, true); }).toThrow(errors.rawNull()); @@ -226,54 +226,54 @@ describe(`Method as.text`, () => { }); -describe(`Method as.value`, () => { - it(`must correctly convert any type`, () => { - expect(pgp.as.value(1)).toBe(`1`); - expect(pgp.as.value(true)).toBe(`true`); +describe('Method as.value', () => { + it('must correctly convert any type', () => { + expect(pgp.as.value(1)).toBe('1'); + expect(pgp.as.value(true)).toBe('true'); }); - it(`must correctly escape text`, () => { - expect(pgp.as.value(`text`)).toBe(`text`); - expect(pgp.as.value(`te'xt`)).toBe(`te''xt`); + it('must correctly escape text', () => { + expect(pgp.as.value('text')).toBe('text'); + expect(pgp.as.value('te\'xt')).toBe('te\'\'xt'); }); - it(`must correctly format values`, () => { - expect(pgp.as.format(`$1:value`, `val`)).toBe(`val`); - expect(pgp.as.format(`$1#`, `val`)).toBe(`val`); - expect(pgp.as.format(`$1#`, `val'ue`)).toBe(`val''ue`); + it('must correctly format values', () => { + expect(pgp.as.format('$1:value', 'val')).toBe('val'); + expect(pgp.as.format('$1#', 'val')).toBe('val'); + expect(pgp.as.format('$1#', 'val\'ue')).toBe('val\'\'ue'); }); - it(`must throw on null/undefined`, () => { - const err = `Open values cannot be null or undefined.`; + it('must throw on null/undefined', () => { + const err = 'Open values cannot be null or undefined.'; expect(() => { pgp.as.value(); }).toThrow(err); expect(() => { - pgp.as.format(`$1#`, [null]); + pgp.as.format('$1#', [null]); }).toThrow(err); expect(() => { - pgp.as.format(`$1#`, [undefined]); + pgp.as.format('$1#', [undefined]); }).toThrow(err); }); }); -describe(`Method as.date`, () => { - it(`must correctly convert any date`, () => { - expect(pgp.as.date()).toBe(`null`); - expect(pgp.as.date(null)).toBe(`null`); +describe('Method as.date', () => { + it('must correctly convert any date', () => { + expect(pgp.as.date()).toBe('null'); + expect(pgp.as.date(null)).toBe('null'); expect(pgp.as.date(dateSample)).toBe(`'${$pgUtils.prepareValue(dateSample)}'`); expect(pgp.as.date(dateSample, true)).toBe($pgUtils.prepareValue(dateSample)); }); - it(`must correctly resolve functions`, () => { - expect(pgp.as.date(dummy)).toBe(`null`); - expect(pgp.as.date(() => null)).toBe(`null`); + it('must correctly resolve functions', () => { + expect(pgp.as.date(dummy)).toBe('null'); + expect(pgp.as.date(() => null)).toBe('null'); expect(pgp.as.date(() => dateSample, true)).toBe($pgUtils.prepareValue(dateSample)); }); - it(`must correctly reject invalid requests`, () => { + it('must correctly reject invalid requests', () => { expect(() => { pgp.as.date(undefined, true); @@ -284,108 +284,108 @@ describe(`Method as.date`, () => { }).toThrow(errors.rawNull()); expect(() => { - pgp.as.date(``); - }).toThrow(`'' is not a Date object.`); + pgp.as.date(''); + }).toThrow('\'\' is not a Date object.'); expect(() => { - pgp.as.date(`bla-bla`); - }).toThrow(`'bla-bla' is not a Date object.`); + pgp.as.date('bla-bla'); + }).toThrow('\'bla-bla\' is not a Date object.'); expect(() => { pgp.as.date(123); - }).toThrow(`'123' is not a Date object.`); + }).toThrow('\'123\' is not a Date object.'); expect(() => { pgp.as.date([]); - }).toThrow(`'' is not a Date object.`); + }).toThrow('\'\' is not a Date object.'); expect(() => { pgp.as.date({}); - }).toThrow(`'[object Object]' is not a Date object.`); + }).toThrow('\'[object Object]\' is not a Date object.'); }); }); -describe(`Method as.csv`, () => { +describe('Method as.csv', () => { - it(`must correctly convert any parameters into CSV`, () => { + it('must correctly convert any parameters into CSV', () => { const obj = { first: 123, - second: `test` + second: 'test' }; - expect(pgp.as.csv()).toBe(``); // test undefined; - expect(pgp.as.csv([])).toBe(``); // test empty array; - expect(pgp.as.csv([[]])).toBe(`'{}'`); // test empty array; - expect(pgp.as.csv(null)).toBe(`null`); // test null; - expect(pgp.as.csv([null])).toBe(`null`); // test null in array; - expect(pgp.as.csv([undefined])).toBe(`null`); // test undefined in array; - expect(pgp.as.csv([null, undefined])).toBe(`null,null`); // test combination of null + undefined in array; + expect(pgp.as.csv()).toBe(''); // test undefined; + expect(pgp.as.csv([])).toBe(''); // test empty array; + expect(pgp.as.csv([[]])).toBe('\'{}\''); // test empty array; + expect(pgp.as.csv(null)).toBe('null'); // test null; + expect(pgp.as.csv([null])).toBe('null'); // test null in array; + expect(pgp.as.csv([undefined])).toBe('null'); // test undefined in array; + expect(pgp.as.csv([null, undefined])).toBe('null,null'); // test combination of null + undefined in array; - expect(pgp.as.csv(0)).toBe(`0`); // test zero; - expect(pgp.as.csv([0])).toBe(`0`); // test zero in array; - expect(pgp.as.csv(-123.456)).toBe(`-123.456`); // test a float; - expect(pgp.as.csv([-123.456])).toBe(`-123.456`); // test a float in array; + expect(pgp.as.csv(0)).toBe('0'); // test zero; + expect(pgp.as.csv([0])).toBe('0'); // test zero in array; + expect(pgp.as.csv(-123.456)).toBe('-123.456'); // test a float; + expect(pgp.as.csv([-123.456])).toBe('-123.456'); // test a float in array; - expect(pgp.as.csv(true)).toBe(`true`); // test boolean True; - expect(pgp.as.csv([true])).toBe(`true`); // test boolean True in array; + expect(pgp.as.csv(true)).toBe('true'); // test boolean True; + expect(pgp.as.csv([true])).toBe('true'); // test boolean True in array; - expect(pgp.as.csv(false)).toBe(`false`); // test boolean False; - expect(pgp.as.csv([false])).toBe(`false`); // test boolean False in array; + expect(pgp.as.csv(false)).toBe('false'); // test boolean False; + expect(pgp.as.csv([false])).toBe('false'); // test boolean False in array; - expect(pgp.as.csv(``)).toBe(`''`); // empty text; - expect(pgp.as.csv([``])).toBe(`''`); // empty text in array; - expect(pgp.as.csv(`simple text`)).toBe(`'simple text'`); // simple text; - expect(pgp.as.csv(`don't break`)).toBe(`'don''t break'`); // text with one single-quote symbol; - expect(pgp.as.csv(`test ''`)).toBe(`'test '''''`); // text with two single-quote symbols; + expect(pgp.as.csv('')).toBe('\'\''); // empty text; + expect(pgp.as.csv([''])).toBe('\'\''); // empty text in array; + expect(pgp.as.csv('simple text')).toBe('\'simple text\''); // simple text; + expect(pgp.as.csv('don\'t break')).toBe('\'don\'\'t break\''); // text with one single-quote symbol; + expect(pgp.as.csv('test \'\'')).toBe('\'test \'\'\'\'\''); // text with two single-quote symbols; - expect(pgp.as.csv(dateSample)).toBe(``); // test date; + expect(pgp.as.csv(dateSample)).toBe(''); // test date; expect(pgp.as.csv([dateSample])).toBe(`'${$pgUtils.prepareValue(dateSample)}'`); // test date in array; expect(pgp.as.csv([userObj])).toBe(pgp.as.text(JSON.stringify(userObj))); // test a combination of all possible types; - expect(pgp.as.csv([12.34, true, `don't break`, null, undefined, userObj, dateSample, [1, 2]])) - .toBe(`12.34,true,'don''t break',null,null,` + pgp.as.text(JSON.stringify(userObj)) + `,'` + $pgUtils.prepareValue(dateSample) + `',array[1,2]`); + expect(pgp.as.csv([12.34, true, 'don\'t break', null, undefined, userObj, dateSample, [1, 2]])) + .toBe('12.34,true,\'don\'\'t break\',null,null,' + pgp.as.text(JSON.stringify(userObj)) + ',\'' + $pgUtils.prepareValue(dateSample) + '\',array[1,2]'); // test array-type as a parameter; - expect(pgp.as.csv([1, [2, 3], 4])).toBe(`1,array[2,3],4`); - expect(pgp.as.csv([1, [[`two`], [`three`]], 4])).toBe(`1,array[['two'],['three']],4`); + expect(pgp.as.csv([1, [2, 3], 4])).toBe('1,array[2,3],4'); + expect(pgp.as.csv([1, [['two'], ['three']], 4])).toBe('1,array[[\'two\'],[\'three\']],4'); - expect(pgp.as.csv(obj)).toBe(`123,'test'`); + expect(pgp.as.csv(obj)).toBe('123,\'test\''); }); - it(`must correctly resolve functions`, () => { + it('must correctly resolve functions', () => { - expect(pgp.as.csv(dummy)).toBe(``); + expect(pgp.as.csv(dummy)).toBe(''); - expect(pgp.as.csv(() => null)).toBe(`null`); + expect(pgp.as.csv(() => null)).toBe('null'); - expect(pgp.as.csv(() => `one`)).toBe(`'one'`); + expect(pgp.as.csv(() => 'one')).toBe('\'one\''); - expect(pgp.as.csv(() => [`one`, `two`, [1, 2, 3]])).toBe(`'one','two',array[1,2,3]`); + expect(pgp.as.csv(() => ['one', 'two', [1, 2, 3]])).toBe('\'one\',\'two\',array[1,2,3]'); }); }); -describe(`Method as.json`, () => { +describe('Method as.json', () => { - it(`must correctly convert any object into JSON`, () => { - expect(pgp.as.json()).toBe(`null`); - expect(pgp.as.json(null)).toBe(`null`); + it('must correctly convert any object into JSON', () => { + expect(pgp.as.json()).toBe('null'); + expect(pgp.as.json(null)).toBe('null'); expect(pgp.as.json({})).toBe(`'${JSON.stringify({})}'`); expect(pgp.as.json(userObj)).toBe(pgp.as.text(JSON.stringify(userObj))); }); - it(`must correctly resolve functions`, () => { - expect(pgp.as.json(dummy)).toBe(`null`); - expect(pgp.as.json(() => null)).toBe(`null`); + it('must correctly resolve functions', () => { + expect(pgp.as.json(dummy)).toBe('null'); + expect(pgp.as.json(() => null)).toBe('null'); expect(pgp.as.json(() => userObj)).toBe(pgp.as.text(JSON.stringify(userObj))); }); - it(`must correctly reject invalid requests`, () => { + it('must correctly reject invalid requests', () => { expect(() => { pgp.as.json(null, true); }).toThrow(errors.rawNull()); @@ -395,76 +395,76 @@ describe(`Method as.json`, () => { }); }); -describe(`Method as.array`, () => { +describe('Method as.array', () => { - it(`must correctly convert an empty array or value`, () => { - expect(pgp.as.array()).toBe(`null`); - expect(pgp.as.array(null)).toBe(`null`); - expect(pgp.as.array([])).toBe(`'{}'`); + it('must correctly convert an empty array or value', () => { + expect(pgp.as.array()).toBe('null'); + expect(pgp.as.array(null)).toBe('null'); + expect(pgp.as.array([])).toBe('\'{}\''); }); - it(`must correctly convert nested arrays`, () => { - expect(pgp.as.array([[]])).toBe(`array[[]]`); - expect(pgp.as.array([[1, 2], [`three`, `four`, [], [5, `six`, true]]])) - .toBe(`array[[1,2],['three','four',[],[5,'six',true]]]`); + it('must correctly convert nested arrays', () => { + expect(pgp.as.array([[]])).toBe('array[[]]'); + expect(pgp.as.array([[1, 2], ['three', 'four', [], [5, 'six', true]]])) + .toBe('array[[1,2],[\'three\',\'four\',[],[5,\'six\',true]]]'); }); // 20-dimension test; - it(`must correctly convert arrays of any depth`, () => { + it('must correctly convert arrays of any depth', () => { expect(pgp.as.array([[[[[[[[[[[[[[[[[[[[20]]]]]]]]]]]]]]]]]]]])) - .toBe(`array[[[[[[[[[[[[[[[[[[[[20]]]]]]]]]]]]]]]]]]]]`); + .toBe('array[[[[[[[[[[[[[[[[[[[[20]]]]]]]]]]]]]]]]]]]]'); }); - it(`must correctly resolve functions`, () => { - expect(pgp.as.array(dummy)).toBe(`null`); - expect(pgp.as.array(() => null)).toBe(`null`); - expect(pgp.as.array(() => [1, 2, 3])).toBe(`array[1,2,3]`); + it('must correctly resolve functions', () => { + expect(pgp.as.array(dummy)).toBe('null'); + expect(pgp.as.array(() => null)).toBe('null'); + expect(pgp.as.array(() => [1, 2, 3])).toBe('array[1,2,3]'); }); - it(`must correctly reject invalid requests`, () => { + it('must correctly reject invalid requests', () => { - const err = ` is not an Array object.`; + const err = ' is not an Array object.'; expect(() => { pgp.as.array(123); }).toThrow(`'123'${err}`); expect(() => { - pgp.as.array(``); + pgp.as.array(''); }).toThrow(`''${err}`); }); - it(`must capitalize the output when required`, () => { + it('must capitalize the output when required', () => { const a = pgp.as.array([1, 2], {capSQL: true}); - expect(a).toBe(`ARRAY[1,2]`); + expect(a).toBe('ARRAY[1,2]'); }); - it(`should throw on invalid options`, () => { + it('should throw on invalid options', () => { expect(() => { pgp.as.array([], {bla: 1}); - }).toThrow(`Option "bla" is not recognized.`); + }).toThrow('Option "bla" is not recognized.'); }); }); -describe(`Method as.func`, () => { +describe('Method as.func', () => { - it(`must correctly convert any function return`, () => { - expect(pgp.as.func()).toBe(`null`); - expect(pgp.as.func(null)).toBe(`null`); - expect(pgp.as.func(() => 1)).toBe(`1`); - expect(pgp.as.func(() => [1, 2, 3])).toBe(`array[1,2,3]`); + it('must correctly convert any function return', () => { + expect(pgp.as.func()).toBe('null'); + expect(pgp.as.func(null)).toBe('null'); + expect(pgp.as.func(() => 1)).toBe('1'); + expect(pgp.as.func(() => [1, 2, 3])).toBe('array[1,2,3]'); expect(pgp.as.func(() => { - })).toBe(`null`); + })).toBe('null'); - expect(pgp.as.func(() => null)).toBe(`null`); - expect(pgp.as.func(() => `hello`, true)).toBe(`hello`); + expect(pgp.as.func(() => null)).toBe('null'); + expect(pgp.as.func(() => 'hello', true)).toBe('hello'); expect(pgp.as.func(() => { return () => { return () => { }; }; - })).toBe(`null`); + })).toBe('null'); expect(pgp.as.func(() => { return () => { @@ -472,23 +472,23 @@ describe(`Method as.func`, () => { return true; }; }; - })).toBe(`true`); + })).toBe('true'); - expect(pgp.as.format(`$1,$1^`, () => { + expect(pgp.as.format('$1,$1^', () => { return () => { - return `one`; + return 'one'; }; - })).toBe(`'one',one`); + })).toBe('\'one\',one'); // testing function-object context; - expect(pgp.as.format(`\${summ1} + \${summ2}`, { + expect(pgp.as.format('${summ1} + ${summ2}', { val1: 1, val2: 2, summ1: function () { return this.val1 + this.val2; // `this` must work here; }, summ2: a => a.val2 * 3 - })).toBe(`3 + 6`); + })).toBe('3 + 6'); // the same object context must be // passed into every sub-function; @@ -499,196 +499,196 @@ describe(`Method as.func`, () => { }; }; }, false, { - test: `Hello!` - })).toBe(`'Hello!'`); + test: 'Hello!' + })).toBe('\'Hello!\''); - expect(pgp.as.func(dummy, false, ``)).toBe(`null`); + expect(pgp.as.func(dummy, false, '')).toBe('null'); - expect(pgp.as.func(a => a, false, 123)).toBe(`123`); + expect(pgp.as.func(a => a, false, 123)).toBe('123'); ///////////////////////////// // negative tests; expect(() => { pgp.as.func(1); - }).toThrow(`'1' is not a function.`); + }).toThrow('\'1\' is not a function.'); expect(() => { pgp.as.func(undefined, true); - }).toThrow(`Values null/undefined cannot be used as raw text.`); + }).toThrow('Values null/undefined cannot be used as raw text.'); expect(() => { pgp.as.func(null, true); - }).toThrow(`Values null/undefined cannot be used as raw text.`); + }).toThrow('Values null/undefined cannot be used as raw text.'); expect(() => { pgp.as.func(() => { - throw `internal error`; + throw 'internal error'; }); - }).toThrow(`internal error`); + }).toThrow('internal error'); }); }); -describe(`Method as.name`, () => { +describe('Method as.name', () => { - describe(`with an empty or non-string`, () => { - it(`must throw na error`, () => { + describe('with an empty or non-string', () => { + it('must throw na error', () => { expect(() => { pgp.as.name(); - }).toThrow(`Invalid sql name: undefined`); + }).toThrow('Invalid sql name: undefined'); expect(() => { pgp.as.name(null); - }).toThrow(`Invalid sql name: null`); + }).toThrow('Invalid sql name: null'); expect(() => { pgp.as.name(123); - }).toThrow(`Invalid sql name: 123`); + }).toThrow('Invalid sql name: 123'); expect(() => { - pgp.as.name(``); - }).toThrow(`Invalid sql name: ""`); + pgp.as.name(''); + }).toThrow('Invalid sql name: ""'); }); }); - describe(`with regular names`, () => { - it(`must return the right name`, () => { - expect(pgp.as.name(`a`)).toBe(`"a"`); - expect(pgp.as.name(` `)).toBe(`" "`); - expect(pgp.as.name(`\t`)).toBe(`"\t"`); - expect(pgp.as.name(`"`)).toBe(`""""`); - expect(pgp.as.name(`""`)).toBe(`""""""`); + describe('with regular names', () => { + it('must return the right name', () => { + expect(pgp.as.name('a')).toBe('"a"'); + expect(pgp.as.name(' ')).toBe('" "'); + expect(pgp.as.name('\t')).toBe('"\t"'); + expect(pgp.as.name('"')).toBe('""""'); + expect(pgp.as.name('""')).toBe('""""""'); }); }); - describe(`with a function`, () => { + describe('with a function', () => { function getName() { - return `name`; + return 'name'; } - it(`must use the function value`, () => { - expect(pgp.as.name(getName)).toBe(`"name"`); + it('must use the function value', () => { + expect(pgp.as.name(getName)).toBe('"name"'); }); }); - describe(`with *`, () => { - it(`must return the original string`, () => { - expect(pgp.as.name(`*`)).toBe(`*`); - expect(pgp.as.name(` \t *\t `)).toBe(` \t *\t `); + describe('with *', () => { + it('must return the original string', () => { + expect(pgp.as.name('*')).toBe('*'); + expect(pgp.as.name(' \t *\t ')).toBe(' \t *\t '); }); }); }); -describe(`Method as.alias`, () => { +describe('Method as.alias', () => { - describe(`with an empty or non-string`, () => { - it(`must throw na error`, () => { + describe('with an empty or non-string', () => { + it('must throw na error', () => { expect(() => { pgp.as.alias(); - }).toThrow(`Invalid sql alias: undefined`); + }).toThrow('Invalid sql alias: undefined'); expect(() => { pgp.as.alias(null); - }).toThrow(`Invalid sql alias: null`); + }).toThrow('Invalid sql alias: null'); expect(() => { pgp.as.alias(123); - }).toThrow(`Invalid sql alias: 123`); + }).toThrow('Invalid sql alias: 123'); expect(() => { - pgp.as.alias(``); - }).toThrow(`Invalid sql alias: ""`); - }); - }); - - describe(`with regular names`, () => { - it(`must return the right name`, () => { - expect(pgp.as.alias(`Aa`)).toBe(`"Aa"`); - expect(pgp.as.alias(`1a`)).toBe(`"1a"`); - expect(pgp.as.alias(` `)).toBe(`" "`); - expect(pgp.as.alias(`\t`)).toBe(`"\t"`); - expect(pgp.as.alias(`"`)).toBe(`""""`); - expect(pgp.as.alias(`""`)).toBe(`""""""`); - expect(pgp.as.alias(`1`)).toBe(`"1"`); - expect(pgp.as.alias(`0A`)).toBe(`"0A"`); - expect(pgp.as.alias(`0abc`)).toBe(`"0abc"`); - expect(pgp.as.alias(`$`)).toBe(`"$"`); - }); - it(`must skip quotes for simple names`, () => { - expect(pgp.as.alias(`a`)).toBe(`a`); - expect(pgp.as.alias(`aaa`)).toBe(`aaa`); - expect(pgp.as.alias(`A`)).toBe(`A`); - expect(pgp.as.alias(`AAA`)).toBe(`AAA`); - expect(pgp.as.alias(`a1`)).toBe(`a1`); - expect(pgp.as.alias(`a_123_$`)).toBe(`a_123_$`); - expect(pgp.as.alias(`_`)).toBe(`_`); - expect(pgp.as.alias(`___`)).toBe(`___`); - expect(pgp.as.alias(`_a_`)).toBe(`_a_`); - expect(pgp.as.alias(`__a_b__`)).toBe(`__a_b__`); - expect(pgp.as.alias(`_A_`)).toBe(`_A_`); - expect(pgp.as.alias(`__A_B__`)).toBe(`__A_B__`); - expect(pgp.as.alias(`a$`)).toBe(`a$`); - expect(pgp.as.alias(`_0`)).toBe(`_0`); - expect(pgp.as.alias(`___0`)).toBe(`___0`); - expect(pgp.as.alias(`_$`)).toBe(`_$`); - expect(pgp.as.alias(`_0$_`)).toBe(`_0$_`); - }); - }); - - describe(`with a function`, () => { + pgp.as.alias(''); + }).toThrow('Invalid sql alias: ""'); + }); + }); + + describe('with regular names', () => { + it('must return the right name', () => { + expect(pgp.as.alias('Aa')).toBe('"Aa"'); + expect(pgp.as.alias('1a')).toBe('"1a"'); + expect(pgp.as.alias(' ')).toBe('" "'); + expect(pgp.as.alias('\t')).toBe('"\t"'); + expect(pgp.as.alias('"')).toBe('""""'); + expect(pgp.as.alias('""')).toBe('""""""'); + expect(pgp.as.alias('1')).toBe('"1"'); + expect(pgp.as.alias('0A')).toBe('"0A"'); + expect(pgp.as.alias('0abc')).toBe('"0abc"'); + expect(pgp.as.alias('$')).toBe('"$"'); + }); + it('must skip quotes for simple names', () => { + expect(pgp.as.alias('a')).toBe('a'); + expect(pgp.as.alias('aaa')).toBe('aaa'); + expect(pgp.as.alias('A')).toBe('A'); + expect(pgp.as.alias('AAA')).toBe('AAA'); + expect(pgp.as.alias('a1')).toBe('a1'); + expect(pgp.as.alias('a_123_$')).toBe('a_123_$'); + expect(pgp.as.alias('_')).toBe('_'); + expect(pgp.as.alias('___')).toBe('___'); + expect(pgp.as.alias('_a_')).toBe('_a_'); + expect(pgp.as.alias('__a_b__')).toBe('__a_b__'); + expect(pgp.as.alias('_A_')).toBe('_A_'); + expect(pgp.as.alias('__A_B__')).toBe('__A_B__'); + expect(pgp.as.alias('a$')).toBe('a$'); + expect(pgp.as.alias('_0')).toBe('_0'); + expect(pgp.as.alias('___0')).toBe('___0'); + expect(pgp.as.alias('_$')).toBe('_$'); + expect(pgp.as.alias('_0$_')).toBe('_0$_'); + }); + }); + + describe('with a function', () => { function getName() { - return `name`; + return 'name'; } - it(`must support the function value`, () => { - expect(pgp.as.alias(getName)).toBe(`name`); + it('must support the function value', () => { + expect(pgp.as.alias(getName)).toBe('name'); }); }); - describe(`with dots in the name`, () => { - expect(pgp.as.alias(`one.two`)).toBe(`one.two`); - expect(pgp.as.alias(`one.two.three`)).toBe(`one.two.three`); - expect(pgp.as.alias(`One.two.thrEe`)).toBe(`"One".two."thrEe"`); - expect(pgp.as.alias(`..one..`)).toBe(`one`); - expect(pgp.as.alias(`..one..two..`)).toBe(`one.two`); - expect(pgp.as.alias(`..one. .two..`)).toBe(`one." ".two`); + describe('with dots in the name', () => { + expect(pgp.as.alias('one.two')).toBe('one.two'); + expect(pgp.as.alias('one.two.three')).toBe('one.two.three'); + expect(pgp.as.alias('One.two.thrEe')).toBe('"One".two."thrEe"'); + expect(pgp.as.alias('..one..')).toBe('one'); + expect(pgp.as.alias('..one..two..')).toBe('one.two'); + expect(pgp.as.alias('..one. .two..')).toBe('one." ".two'); }); }); -describe(`Method as.format`, () => { +describe('Method as.format', () => { - it(`must return a correctly formatted string`, () => { + it('must return a correctly formatted string', () => { - expect(pgp.as.format(``, [])).toBe(``); + expect(pgp.as.format('', [])).toBe(''); - expect(pgp.as.format(`$1`)).toBe(`$1`); - expect(pgp.as.format(`$1`, null)).toBe(`null`); + expect(pgp.as.format('$1')).toBe('$1'); + expect(pgp.as.format('$1', null)).toBe('null'); - expect(pgp.as.format(`$1`, [undefined])).toBe(`null`); + expect(pgp.as.format('$1', [undefined])).toBe('null'); - expect(pgp.as.format(`$1`, `one`)).toBe(`'one'`); - expect(pgp.as.format(`$1^`, `one`)).toBe(`one`); - expect(pgp.as.format(`$1:raw`, `one`)).toBe(`one`); + expect(pgp.as.format('$1', 'one')).toBe('\'one\''); + expect(pgp.as.format('$1^', 'one')).toBe('one'); + expect(pgp.as.format('$1:raw', 'one')).toBe('one'); - expect(pgp.as.format(`$1`, [`one`])).toBe(`'one'`); - expect(pgp.as.format(`$1^`, [`one`])).toBe(`one`); - expect(pgp.as.format(`$1:raw`, [`one`])).toBe(`one`); + expect(pgp.as.format('$1', ['one'])).toBe('\'one\''); + expect(pgp.as.format('$1^', ['one'])).toBe('one'); + expect(pgp.as.format('$1:raw', ['one'])).toBe('one'); - expect(pgp.as.format(`$1, $1`, `one`)).toBe(`'one', 'one'`); + expect(pgp.as.format('$1, $1', 'one')).toBe('\'one\', \'one\''); - expect(pgp.as.format(`$1$1`, `one`)).toBe(`'one''one'`); - expect(pgp.as.format(`$1^$1^`, `one`)).toBe(`oneone`); + expect(pgp.as.format('$1$1', 'one')).toBe('\'one\'\'one\''); + expect(pgp.as.format('$1^$1^', 'one')).toBe('oneone'); - expect(pgp.as.format(`$1`, [userObj])).toBe(pgp.as.text(JSON.stringify(userObj))); - expect(pgp.as.format(`$1^`, [userObj])).toBe(JSON.stringify(userObj)); + expect(pgp.as.format('$1', [userObj])).toBe(pgp.as.text(JSON.stringify(userObj))); + expect(pgp.as.format('$1^', [userObj])).toBe(JSON.stringify(userObj)); - expect(pgp.as.format(`$1, $2, $3, $4`, [true, -12.34, `text`, dateSample])).toBe(`true, -12.34, 'text', '${$pgUtils.prepareValue(dateSample)}'`); + expect(pgp.as.format('$1, $2, $3, $4', [true, -12.34, 'text', dateSample])).toBe(`true, -12.34, 'text', '${$pgUtils.prepareValue(dateSample)}'`); - expect(pgp.as.format(`$1 $1, $2 $2, $1`, [1, `two`])).toBe(`1 1, 'two' 'two', 1`); // test for repeated variables; + expect(pgp.as.format('$1 $1, $2 $2, $1', [1, 'two'])).toBe('1 1, \'two\' \'two\', 1'); // test for repeated variables; - expect(pgp.as.format(`Test: $1`, [`don't break quotes!`])).toBe(`Test: 'don''t break quotes!'`); + expect(pgp.as.format('Test: $1', ['don\'t break quotes!'])).toBe('Test: \'don\'\'t break quotes!\''); // testing with lots of variables; - let source = ``, dest = ``; + let source = '', dest = ''; const params = []; for (let i = 1; i <= 1000; i++) { - source += `$` + i; + source += '$' + i; dest += i; params.push(i); } @@ -699,99 +699,99 @@ describe(`Method as.format`, () => { // - variables not defined; // - variables are repeated; // - long variable names present; - expect(pgp.as.format(`$1$2,$3,$4,$5,$6,$7,$8,$9,$10$11,$12,$13,$14,$15,$1,$3`, [1, 2, `C`, `DDD`, `E`, `F`, `G`, `H`, `I`, 88, 99, `LLL`], {partial: true})) - .toBe(`12,'C','DDD','E','F','G','H','I',8899,'LLL',$13,$14,$15,1,'C'`); + expect(pgp.as.format('$1$2,$3,$4,$5,$6,$7,$8,$9,$10$11,$12,$13,$14,$15,$1,$3', [1, 2, 'C', 'DDD', 'E', 'F', 'G', 'H', 'I', 88, 99, 'LLL'], {partial: true})) + .toBe('12,\'C\',\'DDD\',\'E\',\'F\',\'G\',\'H\',\'I\',8899,\'LLL\',$13,$14,$15,1,\'C\''); // test that variable names are not confused for longer ones; - expect(pgp.as.format(`$11, $1, $111, $1`, 123)).toBe(`$11, 123, $111, 123`); + expect(pgp.as.format('$11, $1, $111, $1', 123)).toBe('$11, 123, $111, 123'); // test that variable names are not confused for longer ones, // even when they are right next to each other; - expect(pgp.as.format(`$11$1$111$1`, 123)).toBe(`$11123$111123`); + expect(pgp.as.format('$11$1$111$1', 123)).toBe('$11123$111123'); - expect(pgp.as.format(`$1, $2`, [ - `one`, [2, 3] - ])).toBe(`'one', array[2,3]`); + expect(pgp.as.format('$1, $2', [ + 'one', [2, 3] + ])).toBe('\'one\', array[2,3]'); // check that gaps are handled correctly; - expect(pgp.as.format(`$2, $4, $6`, [1, 2, 3, 4, 5], {partial: true})).toBe(`2, 4, $6`); + expect(pgp.as.format('$2, $4, $6', [1, 2, 3, 4, 5], {partial: true})).toBe('2, 4, $6'); /////////////////////////////////////////////////// // test that inserting strings with variable names - // in them doesn't effect formatting; + // in them doesn't affect formatting; // a) for regular variables; - expect(pgp.as.format(`$1, $2, $3^, $4`, [`$2`, `$3`, `$2,$3`], {partial: true})).toBe(`'$2', '$3', $2,$3, $4`); + expect(pgp.as.format('$1, $2, $3^, $4', ['$2', '$3', '$2,$3'], {partial: true})).toBe('\'$2\', \'$3\', $2,$3, $4'); // b) for the Named Parameters; - expect(pgp.as.format(`\${one}, \${two}, \${three^}, $four`, { - one: `\${two}`, - two: `\${three}`, - three: `\${two},\${three}` - })).toBe(`'\${two}', '\${three}', \${two},\${three}, $four`); + expect(pgp.as.format('${one}, ${two}, ${three^}, $four', { + one: '${two}', + two: '${three}', + three: '${two},${three}' + })).toBe('\'${two}\', \'${three}\', ${two},${three}, $four'); }); - it(`must correctly inject raw-text variables`, () => { + it('must correctly inject raw-text variables', () => { - expect(pgp.as.format(`\${name},\${name^},\${name},\${name^}`, { - name: `me` - })).toBe(`'me',me,'me',me`); + expect(pgp.as.format('${name},${name^},${name},${name^}', { + name: 'me' + })).toBe('\'me\',me,\'me\',me'); - expect(pgp.as.format(`$1,$1^,$1,$1^`, `hello`)).toBe(`'hello',hello,'hello',hello`); + expect(pgp.as.format('$1,$1^,$1,$1^', 'hello')).toBe('\'hello\',hello,\'hello\',hello'); - expect(pgp.as.format(`$1,$2,$1^,$2^`, [`one`, `two`])) - .toBe(`'one','two',one,two`); + expect(pgp.as.format('$1,$2,$1^,$2^', ['one', 'two'])) + .toBe('\'one\',\'two\',one,two'); - expect(pgp.as.format(`$1^ $2^ $1`, [`Don't break`, `this`])) - .toBe(`Don't break this 'Don''t break'`); + expect(pgp.as.format('$1^ $2^ $1', ['Don\'t break', 'this'])) + .toBe('Don\'t break this \'Don\'\'t break\''); - expect(pgp.as.format(`$1^,$1`, dateSample)) - .toBe($pgUtils.prepareValue(dateSample) + `,'` + $pgUtils.prepareValue(dateSample) + `'`); + expect(pgp.as.format('$1^,$1', dateSample)) + .toBe($pgUtils.prepareValue(dateSample) + ',\'' + $pgUtils.prepareValue(dateSample) + '\''); }); - it(`must correctly reject invalid requests`, () => { + it('must correctly reject invalid requests', () => { - const errEmptyString = `Parameter 'query' must be a text string.`; + const errEmptyString = 'Parameter \'query\' must be a text string.'; expect(() => pgp.as.format()).toThrow(errEmptyString); expect(() => pgp.as.format(null)).toThrow(errEmptyString); expect(() => pgp.as.format(null, [1, 2, 3])).toThrow(errEmptyString); expect(() => pgp.as.format(123)).toThrow(errEmptyString); - expect(() => pgp.as.format(() => ``, dummy)).toThrow(errEmptyString); - expect(() => pgp.as.format(`$1^`, null)).toThrow(errors.rawNull()); - expect(() => pgp.as.format(`$1^`, [null])).toThrow(errors.rawNull()); - expect(() => pgp.as.format(`$1^`, [undefined])).toThrow(errors.rawNull()); - expect(() => pgp.as.format(`$1`, [])).toThrow(errors.range(`$1`, 0)); - expect(() => pgp.as.format(`$3`, [1, 2])).toThrow(errors.range(`$3`, 2)); - expect(() => pgp.as.format(`$100001`, [])).toThrow(`Variable $100001 exceeds supported maximum of $100000`); + expect(() => pgp.as.format(() => '', dummy)).toThrow(errEmptyString); + expect(() => pgp.as.format('$1^', null)).toThrow(errors.rawNull()); + expect(() => pgp.as.format('$1^', [null])).toThrow(errors.rawNull()); + expect(() => pgp.as.format('$1^', [undefined])).toThrow(errors.rawNull()); + expect(() => pgp.as.format('$1', [])).toThrow(errors.range('$1', 0)); + expect(() => pgp.as.format('$3', [1, 2])).toThrow(errors.range('$3', 2)); + expect(() => pgp.as.format('$100001', [])).toThrow('Variable $100001 exceeds supported maximum of $100000'); }); - it(`must throw on type Symbol`, () => { + it('must throw on type Symbol', () => { - const value = Symbol(`one.two`); - const symbolError = `Type Symbol has no meaning for PostgreSQL: ` + value.toString(); + const value = Symbol('one.two'); + const symbolError = 'Type Symbol has no meaning for PostgreSQL: ' + value.toString(); - expect(() => pgp.as.format(`$1`, value)).toThrow(symbolError); - expect(() => pgp.as.format(`$1`, [value])).toThrow(symbolError); + expect(() => pgp.as.format('$1', value)).toThrow(symbolError); + expect(() => pgp.as.format('$1', [value])).toThrow(symbolError); }); - describe(`formatting options`, () => { + describe('formatting options', () => { - describe(`partial`, () => { - it(`must skip missing variables`, () => { - expect(pgp.as.format(`$1`, [], {partial: true})).toBe(`$1`); - expect(pgp.as.format(`$1^`, [], {partial: true})).toBe(`$1^`); - expect(pgp.as.format(`$1:raw`, [], {partial: true})).toBe(`$1:raw`); + describe('partial', () => { + it('must skip missing variables', () => { + expect(pgp.as.format('$1', [], {partial: true})).toBe('$1'); + expect(pgp.as.format('$1^', [], {partial: true})).toBe('$1^'); + expect(pgp.as.format('$1:raw', [], {partial: true})).toBe('$1:raw'); }); }); - describe(`default`, () => { - it(`must replace missing variables`, () => { - expect(pgp.as.format(`$1, $2`, [1], {def: undefined})).toBe(`1, null`); - expect(pgp.as.format(`$1, $2`, [1], {def: null})).toBe(`1, null`); - expect(pgp.as.format(`\${present}, \${missing}`, {present: 1}, {def: 2})).toBe(`1, 2`); + describe('default', () => { + it('must replace missing variables', () => { + expect(pgp.as.format('$1, $2', [1], {def: undefined})).toBe('1, null'); + expect(pgp.as.format('$1, $2', [1], {def: null})).toBe('1, null'); + expect(pgp.as.format('${present}, ${missing}', {present: 1}, {def: 2})).toBe('1, 2'); }); - it(`must invoke a callback correctly`, () => { + it('must invoke a callback correctly', () => { let value, context, param; function cb(v, p) { @@ -801,62 +801,62 @@ describe(`Method as.format`, () => { return 123; } - const arr = [`hi`]; - expect(pgp.as.format(`$1, $2`, arr, {def: cb})).toBe(`'hi', 123`); + const arr = ['hi']; + expect(pgp.as.format('$1, $2', arr, {def: cb})).toBe('\'hi\', 123'); expect(context === arr).toBe(true); expect(param === arr).toBe(true); expect(value).toBe(1); - const obj = {first: `f`}; - expect(pgp.as.format(`\${first}, \${ second^ \t}`, obj, {def: cb})).toBe(`'f', 123`); + const obj = {first: 'f'}; + expect(pgp.as.format('${first}, ${ second^ \t}', obj, {def: cb})).toBe('\'f\', 123'); expect(context === obj).toBe(true); expect(param === obj).toBe(true); - expect(value).toBe(`second`); + expect(value).toBe('second'); }); }); - it(`must propagate options through all types`, () => { - const a1 = pgp.as.format(`$1`, [[1, 2]]); - const a2 = pgp.as.format(`$1`, [[1, 2]], {capSQL: true}); - const a3 = pgp.as.format(`\${first:csv}`, {first: [1, 2, [3, 4]]}, {capSQL: true}); - expect(a1).toBe(`array[1,2]`); - expect(a2).toBe(`ARRAY[1,2]`); - expect(a3).toBe(`1,2,ARRAY[3,4]`); + it('must propagate options through all types', () => { + const a1 = pgp.as.format('$1', [[1, 2]]); + const a2 = pgp.as.format('$1', [[1, 2]], {capSQL: true}); + const a3 = pgp.as.format('${first:csv}', {first: [1, 2, [3, 4]]}, {capSQL: true}); + expect(a1).toBe('array[1,2]'); + expect(a2).toBe('ARRAY[1,2]'); + expect(a3).toBe('1,2,ARRAY[3,4]'); }); }); - describe(`QueryFile - positive`, () => { - it(`must format the object`, () => { + describe('QueryFile - positive', () => { + it('must format the object', () => { const qf = new pgp.QueryFile(sqlParams, {debug: false, minify: true, noWarnings: true}); expect(pgp.as.format(qf, { - column: `col`, - schema: `sc`, - table: `tab` - })).toBe(`SELECT "col" FROM "sc"."tab"`); + column: 'col', + schema: 'sc', + table: 'tab' + })).toBe('SELECT "col" FROM "sc"."tab"'); }); - it(`must format the type as a parameter`, () => { + it('must format the type as a parameter', () => { const qf = new pgp.QueryFile(sqlSimple, {debug: false, minify: true, noWarnings: true}); - expect(pgp.as.format(`$1`, [qf])).toBe(`select 1;`); - expect(pgp.as.format(`$1^`, qf)).toBe(`select 1;`); - expect(pgp.as.format(`$1#`, qf)).toBe(`select 1;`); + expect(pgp.as.format('$1', [qf])).toBe('select 1;'); + expect(pgp.as.format('$1^', qf)).toBe('select 1;'); + expect(pgp.as.format('$1#', qf)).toBe('select 1;'); }); }); - describe(`QueryFile - negative`, () => { - it(`must throw QueryFileError`, () => { + describe('QueryFile - negative', () => { + it('must throw QueryFileError', () => { let error1, error2; - const qf = new pgp.QueryFile(`bla-bla`); + const qf = new pgp.QueryFile('bla-bla'); try { pgp.as.format(qf); } catch (e) { error1 = e; } try { - pgp.as.format(`$1`, [qf]); + pgp.as.format('$1', [qf]); } catch (e) { error2 = e; } @@ -867,28 +867,28 @@ describe(`Method as.format`, () => { }); -describe(`Named Parameters`, () => { +describe('Named Parameters', () => { - it(`must recognize all supported symbols`, () => { - expect(pgp.as.format(`\${one},$(two),$[three],$,$/five/`, { + it('must recognize all supported symbols', () => { + expect(pgp.as.format('${one},$(two),$[three],$,$/five/', { one: 1, two: 2, three: 3, four: 4, five: 5 - })).toBe(`1,2,3,4,5`); + })).toBe('1,2,3,4,5'); }); - it(`must ignore mixed open-close symbols`, () => { - const openers = `{([/`; + it('must ignore mixed open-close symbols', () => { + const openers = '{([/'; for (let i = 0; i < openers.length; i++) { for (let k = 0; k < closers.length; k++) { - const txt = `$` + openers[i] + `value` + closers[k]; + const txt = '$' + openers[i] + 'value' + closers[k]; const s = pgp.as.format(txt, { - value: `hello` + value: 'hello' }); if (i === k) { - expect(s).toBe(`'hello'`); + expect(s).toBe('\'hello\''); } else { expect(s).toBe(txt); } @@ -897,164 +897,164 @@ describe(`Named Parameters`, () => { }); - it(`must ignore internal spaces`, () => { - expect(pgp.as.format(`\${ one },$( two ),$[ three ],$< four >,$/ five /`, { + it('must ignore internal spaces', () => { + expect(pgp.as.format('${ one },$( two ),$[ three ],$< four >,$/ five /', { one: 1, two: 2, three: 3, four: 4, five: 5 - })).toBe(`1,2,3,4,5`); + })).toBe('1,2,3,4,5'); }); - it(`must support short property names`, () => { - expect(pgp.as.format(`\${$}$(_)$[a]$< _$>$/$$ /`, { + it('must support short property names', () => { + expect(pgp.as.format('${$}$(_)$[a]$< _$>$/$$ /', { $: 1, _: 2, a: 3, _$: 4, $$: 5 - })).toBe(`12345`); + })).toBe('12345'); }); - it(`must support digit-only property names`, () => { - expect(pgp.as.format(`\${1}, $(2), $[5^]`, { - 1: `one`, - 2: `two`, - 5: `five` - })).toBe(`'one', 'two', five`); + it('must support digit-only property names', () => { + expect(pgp.as.format('${1}, $(2), $[5^]', { + 1: 'one', + 2: 'two', + 5: 'five' + })).toBe('\'one\', \'two\', five'); }); - it(`must recognize case difference`, () => { - expect(pgp.as.format(`\${value},$(Value),$[VALUE],$,$/vaLue/`, { + it('must recognize case difference', () => { + expect(pgp.as.format('${value},$(Value),$[VALUE],$,$/vaLue/', { value: 1, Value: 2, VALUE: 3, valuE: 4, vaLue: 5 - })).toBe(`1,2,3,4,5`); + })).toBe('1,2,3,4,5'); // Negative; expect(() => { - pgp.as.format(`$/propName/$(PropName)`, { + pgp.as.format('$/propName/$(PropName)', { propName: undefined }); - }).toThrow(`Property 'PropName' doesn't exist.`); + }).toThrow('Property \'PropName\' doesn\'t exist.'); }); - it(`must allow partial replacements`, () => { - expect(pgp.as.format(`\${first}, \${ second }, \${third}`, + it('must allow partial replacements', () => { + expect(pgp.as.format('${first}, ${ second }, ${third}', { - first: `one`, - third: `three` + first: 'one', + third: 'three' }, {partial: true})) - .toBe(`'one', \${ second }, 'three'`); + .toBe('\'one\', ${ second }, \'three\''); }); - it(`must ignore invalid-formatted variables`, () => { - expect(pgp.as.format(`$()`, {})).toBe(`$()`); - expect(pgp.as.format(`$((test))`, {})).toBe(`$((test))`); - expect(pgp.as.format(`\${{test}}`, {})).toBe(`\${{test}}`); - expect(pgp.as.format(`$({test})`, {})).toBe(`$({test})`); - expect(pgp.as.format(`$(^test)`, {})).toBe(`$(^test)`); - expect(pgp.as.format(`\${^test}`, {})).toBe(`\${^test}`); - expect(pgp.as.format(`$(test^^)`, {})).toBe(`$(test^^)`); - expect(pgp.as.format(`\${test^^}`, {})).toBe(`\${test^^}`); + it('must ignore invalid-formatted variables', () => { + expect(pgp.as.format('$()', {})).toBe('$()'); + expect(pgp.as.format('$((test))', {})).toBe('$((test))'); + expect(pgp.as.format('${{test}}', {})).toBe('${{test}}'); + expect(pgp.as.format('$({test})', {})).toBe('$({test})'); + expect(pgp.as.format('$(^test)', {})).toBe('$(^test)'); + expect(pgp.as.format('${^test}', {})).toBe('${^test}'); + expect(pgp.as.format('$(test^^)', {})).toBe('$(test^^)'); + expect(pgp.as.format('${test^^}', {})).toBe('${test^^}'); }); - it(`must convert all types correctly`, () => { - expect(pgp.as.format(`\${one},$(two),$[three],$,$/five/`, { + it('must convert all types correctly', () => { + expect(pgp.as.format('${one},$(two),$[three],$,$/five/', { one: undefined, two: true, three: -123.45, four: dateSample, - five: () => `text` - })).toBe(`null,true,-123.45,'` + $pgUtils.prepareValue(dateSample) + `','text'`); + five: () => 'text' + })).toBe('null,true,-123.45,\'' + $pgUtils.prepareValue(dateSample) + '\',\'text\''); }); - it(`must treat null and undefined values equally`, () => { + it('must treat null and undefined values equally', () => { // Both null and undefined properties are formatted as null; - expect(pgp.as.format(`\${empty1}, $(empty2)`, { + expect(pgp.as.format('${empty1}, $(empty2)', { empty1: null, empty2: undefined - })).toBe(`null, null`); + })).toBe('null, null'); }); - it(`must throw error when property doesn't exist`, () => { - const err = name => `Property '` + name + `' doesn't exist.`; - expect(() => pgp.as.format(`\${abc}`, {})).toThrow(err(`abc`)); - expect(() => pgp.as.format(`\${a.b}`, {a: {}})).toThrow(err(`a.b`)); + it('must throw error when property doesn\'t exist', () => { + const err = name => 'Property \'' + name + '\' doesn\'t exist.'; + expect(() => pgp.as.format('${abc}', {})).toThrow(err('abc')); + expect(() => pgp.as.format('${a.b}', {a: {}})).toThrow(err('a.b')); }); - it(`must throw error for invalid properties`, () => { + it('must throw error for invalid properties', () => { const err = name => `Invalid property name '${name}'.`; - expect(() => pgp.as.format(`\${.}`, {})).toThrow(err(`.`)); - expect(() => pgp.as.format(`\${ a. }`, {})).toThrow(err(`a.`)); - expect(() => pgp.as.format(`\${.b}`, {})).toThrow(err(`.b`)); + expect(() => pgp.as.format('${.}', {})).toThrow(err('.')); + expect(() => pgp.as.format('${ a. }', {})).toThrow(err('a.')); + expect(() => pgp.as.format('${.b}', {})).toThrow(err('.b')); }); - describe(`'this' formatting`, () => { + describe('\'this\' formatting', () => { - it(`must recognize 'this'`, () => { + it('must recognize \'this\'', () => { const obj = { val1: 123, - val2: `hello` + val2: 'hello' }; - expect(pgp.as.format(`\${this}`, obj)).toEqual(`'${JSON.stringify(obj)}'`); + expect(pgp.as.format('${this}', obj)).toEqual(`'${JSON.stringify(obj)}'`); }); - it(`must recognize 'this^'`, () => { + it('must recognize \'this^\'', () => { const obj = { val1: 123, - val2: `hello` + val2: 'hello' }; - expect(pgp.as.format(`\${this^}`, obj)).toEqual(JSON.stringify(obj)); + expect(pgp.as.format('${this^}', obj)).toEqual(JSON.stringify(obj)); }); - it(`must ignore 'this' when property exists`, () => { + it('must ignore \'this\' when property exists', () => { const obj = { - this: `self`, + this: 'self', val1: 123, - val2: `hello` + val2: 'hello' }; - expect(pgp.as.format(`\${this^}`, obj)).toBe(`self`); + expect(pgp.as.format('${this^}', obj)).toBe('self'); }); }); }); -describe(`Nested Named Parameters`, () => { +describe('Nested Named Parameters', () => { - describe(`basic variables`, () => { - it(`must be formatted correctly`, () => { - expect(pgp.as.format(`\${a.b}`, {a: {b: 123}})).toBe(`123`); - expect(pgp.as.format(`\${_.$.123}`, {_: {$: {123: 111}}})).toBe(`111`); + describe('basic variables', () => { + it('must be formatted correctly', () => { + expect(pgp.as.format('${a.b}', {a: {b: 123}})).toBe('123'); + expect(pgp.as.format('${_.$.123}', {_: {$: {123: 111}}})).toBe('111'); }); }); - describe(`prototype variables`, () => { + describe('prototype variables', () => { beforeEach(() => { - Number.prototype.msg = `hello!`; + Number.prototype.msg = 'hello!'; }); afterEach(() => { delete Number.prototype.msg; }); - it(`must be discoverable`, () => { - expect(pgp.as.format(`\${value.msg}`, {value: 10})).toBe(`'hello!'`); + it('must be discoverable', () => { + expect(pgp.as.format('${value.msg}', {value: 10})).toBe('\'hello!\''); }); }); - describe(`default values`, () => { - it(`must be formatted correctly`, () => { - expect(pgp.as.format(`\${one.two.three}`, {}, {def: 123})).toBe(`123`); + describe('default values', () => { + it('must be formatted correctly', () => { + expect(pgp.as.format('${one.two.three}', {}, {def: 123})).toBe('123'); }); }); - describe(`calling context`, () => { - describe(`for functions`, () => { - it(`must represent the container`, () => { + describe('calling context', () => { + describe('for functions', () => { + it('must represent the container', () => { const obj = { first: { second: { @@ -1066,13 +1066,13 @@ describe(`Nested Named Parameters`, () => { } } }; - expect(pgp.as.format(`\${first.second.test1}`, obj)).toBe(`123`); - expect(pgp.as.format(`\${first.second.test2}`, obj)).toBe(`123`); + expect(pgp.as.format('${first.second.test1}', obj)).toBe('123'); + expect(pgp.as.format('${first.second.test2}', obj)).toBe('123'); }); }); - describe(`for CTF`, () => { - it(`must represent the container`, () => { + describe('for CTF', () => { + it('must represent the container', () => { const obj = { first: { second: { @@ -1087,13 +1087,13 @@ describe(`Nested Named Parameters`, () => { } } }; - expect(pgp.as.format(`\${first.second}`, obj)).toBe(`123`); - expect(pgp.as.format(`\${first.second.test}`, obj)).toBe(`456`); + expect(pgp.as.format('${first.second}', obj)).toBe('123'); + expect(pgp.as.format('${first.second.test}', obj)).toBe('456'); }); }); - describe(`for "def" values`, () => { - it(`must represent the source object`, () => { + describe('for "def" values', () => { + it('must represent the source object', () => { const obj = { value: 1, one: { @@ -1103,15 +1103,15 @@ describe(`Nested Named Parameters`, () => { } } }; - expect(pgp.as.format(`\${one.two.three}`, obj, {def: (name, o) => o.value})).toBe(`1`); - expect(pgp.as.format(`\${one.two.three}`, obj, { + expect(pgp.as.format('${one.two.three}', obj, {def: (name, o) => o.value})).toBe('1'); + expect(pgp.as.format('${one.two.three}', obj, { def: function () { return this.value; } - })).toBe(`1`); + })).toBe('1'); }); - it(`must pass in the full property name`, () => { - expect(pgp.as.format(`\${one.two.three}`, {}, {def: name => name})).toBe(`'one.two.three'`); + it('must pass in the full property name', () => { + expect(pgp.as.format('${one.two.three}', {}, {def: name => name})).toBe('\'one.two.three\''); }); }); @@ -1119,100 +1119,100 @@ describe(`Nested Named Parameters`, () => { }); -describe(`Format Modifiers`, () => { +describe('Format Modifiers', () => { function SimpleValue() { this.toPostgres = () => { - return `hello`; + return 'hello'; }; } function RawValue() { this.rawType = true; this.toPostgres = () => { - return `experiment`; + return 'experiment'; }; } - describe(`json modifier`, () => { - it(`must replace any value with json`, () => { - expect(pgp.as.format(`$1:json`, `hello`)).toBe(`'"hello"'`); - expect(pgp.as.format(`$1:json`, [`hello`])).toBe(`'"hello"'`); - expect(pgp.as.format(`\${data:json}`, {data: [1, `two`]})).toBe(`'[1,"two"]'`); + describe('json modifier', () => { + it('must replace any value with json', () => { + expect(pgp.as.format('$1:json', 'hello')).toBe('\'"hello"\''); + expect(pgp.as.format('$1:json', ['hello'])).toBe('\'"hello"\''); + expect(pgp.as.format('${data:json}', {data: [1, 'two']})).toBe('\'[1,"two"]\''); }); - it(`must ignore invalid flags`, () => { - expect(pgp.as.format(`$1 :json`, `hello`)).toBe(`'hello' :json`); - expect(pgp.as.format(`$1: json`, `hello`)).toBe(`'hello': json`); + it('must ignore invalid flags', () => { + expect(pgp.as.format('$1 :json', 'hello')).toBe('\'hello\' :json'); + expect(pgp.as.format('$1: json', 'hello')).toBe('\'hello\': json'); }); - it(`must resolve custom types`, () => { - expect(pgp.as.format(`$1:json`, [new SimpleValue()])).toBe(`'"hello"'`); + it('must resolve custom types', () => { + expect(pgp.as.format('$1:json', [new SimpleValue()])).toBe('\'"hello"\''); }); - it(`must resolve custom raw types inside array`, () => { - expect(pgp.as.format(`$1:json`, [new RawValue()])).toBe(`"experiment"`); + it('must resolve custom raw types inside array', () => { + expect(pgp.as.format('$1:json', [new RawValue()])).toBe('"experiment"'); }); - it(`must resolve custom raw types directly`, () => { - expect(pgp.as.format(`$1:json`, new RawValue())).toBe(`"experiment"`); + it('must resolve custom raw types directly', () => { + expect(pgp.as.format('$1:json', new RawValue())).toBe('"experiment"'); }); }); function SimpleArray() { this.toPostgres = () => { - return [1, `two`]; + return [1, 'two']; }; } function RawArray() { this.rawType = true; this.toPostgres = () => { - return [1, `two`]; + return [1, 'two']; }; } - describe(`csv modifier`, () => { - it(`must replace any value with csv`, () => { - expect(pgp.as.format(`$1:csv`, `hello`)).toBe(`'hello'`); - expect(pgp.as.format(`\${data:csv}`, {data: [1, `two`]})).toBe(`1,'two'`); + describe('csv modifier', () => { + it('must replace any value with csv', () => { + expect(pgp.as.format('$1:csv', 'hello')).toBe('\'hello\''); + expect(pgp.as.format('${data:csv}', {data: [1, 'two']})).toBe('1,\'two\''); }); - it(`must ignore invalid flags`, () => { - expect(pgp.as.format(`$1 :csv`, `hello`)).toBe(`'hello' :csv`); - expect(pgp.as.format(`$1: csv`, `hello`)).toBe(`'hello': csv`); + it('must ignore invalid flags', () => { + expect(pgp.as.format('$1 :csv', 'hello')).toBe('\'hello\' :csv'); + expect(pgp.as.format('$1: csv', 'hello')).toBe('\'hello\': csv'); }); - it(`must resolve custom types`, () => { - expect(pgp.as.format(`$1:csv`, [new SimpleArray()])).toBe(`1,'two'`); + it('must resolve custom types', () => { + expect(pgp.as.format('$1:csv', [new SimpleArray()])).toBe('1,\'two\''); }); - it(`must resolve custom raw types`, () => { - expect(pgp.as.format(`$1:csv`, [new RawArray()])).toBe(`1,'two'`); + it('must resolve custom raw types', () => { + expect(pgp.as.format('$1:csv', [new RawArray()])).toBe('1,\'two\''); }); }); - describe(`list modifier`, () => { - it(`must replace any value with list`, () => { - expect(pgp.as.format(`$1:list`, `hello`)).toBe(`'hello'`); - expect(pgp.as.format(`\${data:list}`, {data: [1, `two`]})).toBe(`1,'two'`); + describe('list modifier', () => { + it('must replace any value with list', () => { + expect(pgp.as.format('$1:list', 'hello')).toBe('\'hello\''); + expect(pgp.as.format('${data:list}', {data: [1, 'two']})).toBe('1,\'two\''); }); - it(`must ignore invalid flags`, () => { - expect(pgp.as.format(`$1 :list`, `hello`)).toBe(`'hello' :list`); - expect(pgp.as.format(`$1: list`, `hello`)).toBe(`'hello': list`); + it('must ignore invalid flags', () => { + expect(pgp.as.format('$1 :list', 'hello')).toBe('\'hello\' :list'); + expect(pgp.as.format('$1: list', 'hello')).toBe('\'hello\': list'); }); - it(`must resolve custom types`, () => { - expect(pgp.as.format(`$1:list`, [new SimpleArray()])).toBe(`1,'two'`); + it('must resolve custom types', () => { + expect(pgp.as.format('$1:list', [new SimpleArray()])).toBe('1,\'two\''); }); - it(`must resolve custom raw types`, () => { - expect(pgp.as.format(`$1:list`, [new RawArray()])).toBe(`1,'two'`); + it('must resolve custom raw types', () => { + expect(pgp.as.format('$1:list', [new RawArray()])).toBe('1,\'two\''); }); }); - describe(`alias modifier`, () => { - it(`must replace any value correctly`, () => { - expect(pgp.as.format(`$1:alias`, `name`)).toBe(`name`); - expect(pgp.as.format(`$1:alias`, `*`)).toBe(`"*"`); - expect(pgp.as.format(`\${name:alias}`, {name: `hello`})).toBe(`hello`); + describe('alias modifier', () => { + it('must replace any value correctly', () => { + expect(pgp.as.format('$1:alias', 'name')).toBe('name'); + expect(pgp.as.format('$1:alias', '*')).toBe('"*"'); + expect(pgp.as.format('${name:alias}', {name: 'hello'})).toBe('hello'); }); }); }); -describe(`Custom Type Formatting`, () => { +describe('Custom Type Formatting', () => { function MyType1(v) { this.value = v; @@ -1231,27 +1231,27 @@ describe(`Custom Type Formatting`, () => { const test1 = new MyType1(12.3); const test2 = new MyType2(56.7); - describe(`as formatting type`, () => { - it(`must pass the values in correctly`, () => { - expect(pgp.as.format(test2)).toBe(`56.70`); + describe('as formatting type', () => { + it('must pass the values in correctly', () => { + expect(pgp.as.format(test2)).toBe('56.70'); }); }); - describe(`as array value`, () => { - it(`must convert correctly`, () => { - expect(pgp.as.format(`$1`, [test1])).toBe(`12.3000`); - expect(pgp.as.format(`$1`, [test2])).toBe(`56.70`); + describe('as array value', () => { + it('must convert correctly', () => { + expect(pgp.as.format('$1', [test1])).toBe('12.3000'); + expect(pgp.as.format('$1', [test2])).toBe('56.70'); }); }); - describe(`as one value`, () => { - it(`must covert correctly`, () => { - expect(pgp.as.format(`$1`, test1)).toBe(`12.3000`); - expect(pgp.as.format(`$1`, test2)).toBe(`56.70`); + describe('as one value', () => { + it('must covert correctly', () => { + expect(pgp.as.format('$1', test1)).toBe('12.3000'); + expect(pgp.as.format('$1', test2)).toBe('56.70'); }); }); - describe(`for Date override`, () => { + describe('for Date override', () => { beforeEach(() => { Date.prototype.toPostgres = () => { function subLevel() { @@ -1262,31 +1262,31 @@ describe(`Custom Type Formatting`, () => { }; }); const today = new Date(); - it(`must covert correctly`, () => { - expect(pgp.as.format(`$1`, today)).toBe(today.getFullYear().toString()); + it('must covert correctly', () => { + expect(pgp.as.format('$1', today)).toBe(today.getFullYear().toString()); }); afterEach(() => { delete Date.prototype.toPostgres; }); }); - describe(`for Array override`, () => { + describe('for Array override', () => { beforeEach(() => { Array.prototype.toPostgres = () => { return new MyType1(88); // testing recursive conversion; }; }); - it(`must covert correctly`, () => { - expect(pgp.as.format(`$1^`, [1, 2, 3])).toBe(`88.0000`); + it('must covert correctly', () => { + expect(pgp.as.format('$1^', [1, 2, 3])).toBe('88.0000'); }); afterEach(() => { delete Array.prototype.toPostgres; }); }); - describe(`with custom object - formatter`, () => { + describe('with custom object - formatter', () => { const values = { - test: `hello` + test: 'hello' }; function CustomFormatter() { @@ -1295,113 +1295,113 @@ describe(`Custom Type Formatting`, () => { }; } - it(`must redirect to named formatting`, () => { - expect(pgp.as.format(`\${test}`, new CustomFormatter())).toBe(`'hello'`); + it('must redirect to named formatting', () => { + expect(pgp.as.format('${test}', new CustomFormatter())).toBe('\'hello\''); }); }); - describe(`with a simple value`, () => { + describe('with a simple value', () => { function SimpleFormatter() { - this.toPostgres = () => `value`; + this.toPostgres = () => 'value'; } - it(`must return the simple value`, () => { - expect(pgp.as.format(`$1`, [new SimpleFormatter()])).toBe(`'value'`); + it('must return the simple value', () => { + expect(pgp.as.format('$1', [new SimpleFormatter()])).toBe('\'value\''); }); }); - describe(`raw inheritance/mutation`, () => { + describe('raw inheritance/mutation', () => { const obj = { // raw flag here must apply to every value of the array returned; rawType: true, toPostgres() { - return [`first`, `second`]; + return ['first', 'second']; } }; - it(`must work`, () => { - expect(pgp.as.format(`$1, $2`, obj)).toBe(`first, second`); + it('must work', () => { + expect(pgp.as.format('$1, $2', obj)).toBe('first, second'); }); }); - describe(`for simple type`, () => { - it(`Boolean`, () => { + describe('for simple type', () => { + it('Boolean', () => { Boolean.prototype.toPostgres = self => self + 1; const a = true; - expect(pgp.as.format(`$1`, a)).toBe(`2`); - expect(pgp.as.format(`$1`, [a])).toBe(`2`); + expect(pgp.as.format('$1', a)).toBe('2'); + expect(pgp.as.format('$1', [a])).toBe('2'); delete Boolean.prototype.toPostgres; }); - it(`Number`, () => { + it('Number', () => { const a = 2; Number.prototype.toPostgres = self => (self + 3).toString(); Number.prototype.rawType = true; - expect(pgp.as.format(`$1`, a)).toBe(`5`); - expect(pgp.as.format(`$1`, [a])).toBe(`5`); + expect(pgp.as.format('$1', a)).toBe('5'); + expect(pgp.as.format('$1', [a])).toBe('5'); delete Number.prototype.toPostgres; delete Number.prototype.rawType; }); - it(`String`, () => { - const a = `true`; - String.prototype.toPostgres = self => self === `true` ? true : self; - expect(pgp.as.format(`$1`, a)).toBe(`true`); - expect(pgp.as.format(`$1`, [a])).toBe(`true`); + it('String', () => { + const a = 'true'; + String.prototype.toPostgres = self => self === 'true' ? true : self; + expect(pgp.as.format('$1', a)).toBe('true'); + expect(pgp.as.format('$1', [a])).toBe('true'); delete String.prototype.toPostgres; }); }); - describe(`for pre-defined ctf symbols`, () => { + describe('for pre-defined ctf symbols', () => { const ctf = pgp.as.ctf; - it(`must recognize symbolic ctf`, () => { - expect(pgp.as.format(`$1`, {[ctf.toPostgres]: () => `ok`})).toBe(`'ok'`); + it('must recognize symbolic ctf', () => { + expect(pgp.as.format('$1', {[ctf.toPostgres]: () => 'ok'})).toBe('\'ok\''); }); - it(`must recognize symbolic ctf for simple types`, () => { + it('must recognize symbolic ctf for simple types', () => { const value = 0; - Number.prototype[ctf.toPostgres] = () => `ok`; - expect(pgp.as.format(`$1`, value)).toBe(`'ok'`); + Number.prototype[ctf.toPostgres] = () => 'ok'; + expect(pgp.as.format('$1', value)).toBe('\'ok\''); delete Number.prototype[ctf.toPostgres]; }); - it(`must support symbolic rawType`, () => { - expect(pgp.as.format(`$1`, {[ctf.toPostgres]: () => `ok`, [ctf.rawType]: true})).toBe(`ok`); + it('must support symbolic rawType', () => { + expect(pgp.as.format('$1', {[ctf.toPostgres]: () => 'ok', [ctf.rawType]: true})).toBe('ok'); }); - it(`must ignore explicit rawType for symbolic ctf`, () => { - expect(pgp.as.format(`$1`, {[ctf.toPostgres]: () => `ok`, rawType: true})).toBe(`'ok'`); + it('must ignore explicit rawType for symbolic ctf', () => { + expect(pgp.as.format('$1', {[ctf.toPostgres]: () => 'ok', rawType: true})).toBe('\'ok\''); }); - it(`must ignore symbolic rawType for explicit ctf`, () => { - expect(pgp.as.format(`$1`, {toPostgres: () => `ok`, [ctf.rawType]: true})).toBe(`'ok'`); + it('must ignore symbolic rawType for explicit ctf', () => { + expect(pgp.as.format('$1', {toPostgres: () => 'ok', [ctf.rawType]: true})).toBe('\'ok\''); }); }); - describe(`for global ctf symbols`, () => { + describe('for global ctf symbols', () => { const ctf = pgp.as.ctf; - it(`must be equal the pre-defined symbols`, () => { - expect(Symbol.for(`ctf.toPostgres`)).toBe(ctf.toPostgres); - expect(Symbol.for(`ctf.rawType`)).toBe(ctf.rawType); + it('must be equal the pre-defined symbols', () => { + expect(Symbol.for('ctf.toPostgres')).toBe(ctf.toPostgres); + expect(Symbol.for('ctf.rawType')).toBe(ctf.rawType); }); }); - describe(`for asynchronous functions`, () => { - const errMsg = `CTF does not support asynchronous toPostgres functions.`; - it(`must throw an error`, () => { + describe('for asynchronous functions', () => { + const errMsg = 'CTF does not support asynchronous toPostgres functions.'; + it('must throw an error', () => { expect(() => { - pgp.as.format(`$1`, { + pgp.as.format('$1', { toPostgres: function* () { } }); }).toThrow(errMsg); expect(() => { - pgp.as.format(`$1`, { + pgp.as.format('$1', { toPostgres: async function () { } }); }).toThrow(errMsg); expect(() => { - pgp.as.format(`$1`, { + pgp.as.format('$1', { [pgp.as.ctf.toPostgres]: function* () { } }); }).toThrow(errMsg); expect(() => { - pgp.as.format(`$1`, { + pgp.as.format('$1', { [pgp.as.ctf.toPostgres]: async function () { } }); @@ -1410,27 +1410,27 @@ describe(`Custom Type Formatting`, () => { }); }); -describe(`SQL Names`, () => { +describe('SQL Names', () => { - describe(`direct`, () => { - it(`must format correctly`, () => { - expect(pgp.as.format(`$1~`, `name`)).toBe(`"name"`); - expect(pgp.as.format(`$1~`, `"name"`)).toBe(`"""name"""`); - expect(pgp.as.format(`\${name~}`, {name: `hello`})).toBe(`"hello"`); + describe('direct', () => { + it('must format correctly', () => { + expect(pgp.as.format('$1~', 'name')).toBe('"name"'); + expect(pgp.as.format('$1~', '"name"')).toBe('"""name"""'); + expect(pgp.as.format('${name~}', {name: 'hello'})).toBe('"hello"'); }); }); - describe(`from a function`, () => { + describe('from a function', () => { function getName() { - return `hello`; + return 'hello'; } - it(`must use the function result`, () => { - expect(pgp.as.format(`$1:name`, getName)).toBe(`"hello"`); + it('must use the function result', () => { + expect(pgp.as.format('$1:name', getName)).toBe('"hello"'); }); }); - describe(`from a mixed type`, () => { + describe('from a mixed type', () => { function CS(name) { this.name = name; @@ -1439,74 +1439,74 @@ describe(`SQL Names`, () => { }; } - const csTest = new CS(`customType`); + const csTest = new CS('customType'); function getName() { return csTest; } - it(`must resolve the mixed type`, () => { - expect(pgp.as.format(`$1~`, getName)).toBe(`"customType"`); + it('must resolve the mixed type', () => { + expect(pgp.as.format('$1~', getName)).toBe('"customType"'); }); }); - describe(`with an object`, () => { - it(`must enumerate properties`, () => { - expect(pgp.as.format(`$1~`, [{one: 1, two: 2}])).toBe(`"one","two"`); + describe('with an object', () => { + it('must enumerate properties', () => { + expect(pgp.as.format('$1~', [{one: 1, two: 2}])).toBe('"one","two"'); }); }); - describe(`with an array`, () => { - it(`must enumerate properties`, () => { - expect(pgp.as.format(`$1~`, [[`one`, `two`]])).toBe(`"one","two"`); + describe('with an array', () => { + it('must enumerate properties', () => { + expect(pgp.as.format('$1~', [['one', 'two']])).toBe('"one","two"'); }); }); - describe(`Negative`, () => { + describe('Negative', () => { - describe(`with the wrong object type`, () => { - it(`must reject the object with an error`, () => { + describe('with the wrong object type', () => { + it('must reject the object with an error', () => { expect(() => { - pgp.as.format(`$1~`, [123]); - }).toThrow(`Invalid sql name: 123`); + pgp.as.format('$1~', [123]); + }).toThrow('Invalid sql name: 123'); expect(() => { - pgp.as.format(`$1~`, [true]); - }).toThrow(`Invalid sql name: true`); + pgp.as.format('$1~', [true]); + }).toThrow('Invalid sql name: true'); expect(() => { - pgp.as.format(`$1~`, [``]); - }).toThrow(`Invalid sql name: ""`); + pgp.as.format('$1~', ['']); + }).toThrow('Invalid sql name: ""'); }); }); - describe(`with an empty object`, () => { - it(`must reject the object with an error`, () => { + describe('with an empty object', () => { + it('must reject the object with an error', () => { expect(() => { - pgp.as.format(`$1~`, [{}]); - }).toThrow(`Cannot retrieve sql names from an empty array/object.`); + pgp.as.format('$1~', [{}]); + }).toThrow('Cannot retrieve sql names from an empty array/object.'); }); }); - describe(`with an empty array`, () => { - it(`must reject the array with an error`, () => { + describe('with an empty array', () => { + it('must reject the array with an error', () => { expect(() => { - pgp.as.format(`$1~`, [[]]); - }).toThrow(`Cannot retrieve sql names from an empty array/object.`); + pgp.as.format('$1~', [[]]); + }).toThrow('Cannot retrieve sql names from an empty array/object.'); }); }); - describe(`with invalid property`, () => { - it(`must reject the property`, () => { + describe('with invalid property', () => { + it('must reject the property', () => { expect(() => { - pgp.as.format(`$1~`, [{'': 1}]); - }).toThrow(`Invalid sql name: ""`); + pgp.as.format('$1~', [{'': 1}]); + }).toThrow('Invalid sql name: ""'); }); }); - describe(`with invalid array value`, () => { - it(`must reject the value`, () => { + describe('with invalid array value', () => { + it('must reject the value', () => { expect(() => { - pgp.as.format(`$1~`, [[1]]); - }).toThrow(`Invalid sql name: 1`); + pgp.as.format('$1~', [[1]]); + }).toThrow('Invalid sql name: 1'); }); }); diff --git a/test/generator.spec.js b/test/generator.spec.js index ffcfcd9ec..3ed6888e0 100644 --- a/test/generator.spec.js +++ b/test/generator.spec.js @@ -1,4 +1,4 @@ -const header = require(`./db/header`); +const header = require('./db/header'); const promise = header.defPromise; const options = { @@ -9,14 +9,14 @@ const options = { const dbHeader = header(options); const db = dbHeader.db; -describe(`ES6 Generators`, () => { +describe('ES6 Generators', () => { // v9.0 dropped all generators support, and now it throws an error, // if someone still tries to use them. - const errMsg = `ES6 generator functions are no longer supported!`; + const errMsg = 'ES6 generator functions are no longer supported!'; - describe(`for tasks`, () => { + describe('for tasks', () => { let error; beforeEach(done => { db.task(function* () { @@ -26,13 +26,13 @@ describe(`ES6 Generators`, () => { }) .finally(done); }); - it(`must reject`, () => { + it('must reject', () => { expect(error instanceof TypeError).toBe(true); expect(error.message).toBe(errMsg); }); }); - describe(`for transactions`, () => { + describe('for transactions', () => { let error; beforeEach(done => { db.tx(function* () { @@ -42,7 +42,7 @@ describe(`ES6 Generators`, () => { }) .finally(done); }); - it(`must reject`, () => { + it('must reject', () => { expect(error instanceof TypeError).toBe(true); expect(error.message).toBe(errMsg); }); diff --git a/test/help.spec.js b/test/help.spec.js index 82e2db583..49dc4029a 100644 --- a/test/help.spec.js +++ b/test/help.spec.js @@ -1,5 +1,5 @@ -const header = require(`./db/header`); -const tools = require(`./db/tools`); +const header = require('./db/header'); +const tools = require('./db/tools'); const promise = header.defPromise; const options = { @@ -9,70 +9,70 @@ const options = { }; const pgp = header(options).pgp; -const os = require(`os`); -const path = require(`path`); -const utils = require(`../lib/utils`); +const os = require('os'); +const path = require('path'); +const utils = require('../lib/utils'); const helpers = pgp.helpers; const QueryFile = pgp.QueryFile; const dataSingle = { val: 123, - msg: `test` + msg: 'test' }; const dataMulti = [{ id: 1, val: 123, - msg: `hello` + msg: 'hello' }, { id: 2, val: 456, - msg: `world` + msg: 'world' }]; -describe(`INSERT`, () => { +describe('INSERT', () => { - describe(`single:`, () => { - describe(`direct data`, () => { - it(`must return all data properties as columns`, () => { - expect(helpers.insert(dataSingle, null, `table`)).toBe(`insert into "table"("val","msg") values(123,'test')`); + describe('single:', () => { + describe('direct data', () => { + it('must return all data properties as columns', () => { + expect(helpers.insert(dataSingle, null, 'table')).toBe('insert into "table"("val","msg") values(123,\'test\')'); }); }); }); - describe(`multi:`, () => { - describe(`direct data`, () => { - it(`must return all data columns`, () => { - expect(helpers.insert(dataMulti, [`val`, `msg`], `table`)).toBe(`insert into "table"("val","msg") values(123,'hello'),(456,'world')`); + describe('multi:', () => { + describe('direct data', () => { + it('must return all data columns', () => { + expect(helpers.insert(dataMulti, ['val', 'msg'], 'table')).toBe('insert into "table"("val","msg") values(123,\'hello\'),(456,\'world\')'); }); }); }); - describe(`setting table name`, () => { - const cs = new helpers.ColumnSet(dataSingle, {table: `external`}); - it(`must use its own table when specified`, () => { - expect(helpers.insert(dataSingle, cs, `internal`)).toBe(`insert into "internal"("val","msg") values(123,'test')`); + describe('setting table name', () => { + const cs = new helpers.ColumnSet(dataSingle, {table: 'external'}); + it('must use its own table when specified', () => { + expect(helpers.insert(dataSingle, cs, 'internal')).toBe('insert into "internal"("val","msg") values(123,\'test\')'); }); - it(`must use ColumnSet table when not locally specified`, () => { - expect(helpers.insert(dataSingle, cs)).toBe(`insert into "external"("val","msg") values(123,'test')`); + it('must use ColumnSet table when not locally specified', () => { + expect(helpers.insert(dataSingle, cs)).toBe('insert into "external"("val","msg") values(123,\'test\')'); }); }); - describe(`generating sql in upper case`, () => { + describe('generating sql in upper case', () => { beforeEach(() => { options.capSQL = true; }); - it(`must return a capitalized query`, () => { - expect(helpers.insert(dataSingle, null, `table`)).toBe(`INSERT INTO "table"("val","msg") VALUES(123,'test')`); + it('must return a capitalized query', () => { + expect(helpers.insert(dataSingle, null, 'table')).toBe('INSERT INTO "table"("val","msg") VALUES(123,\'test\')'); }); afterEach(() => { options.capSQL = false; }); }); - describe(`negative`, () => { - it(`must throw on invalid data`, () => { - const error = `Invalid parameter 'data' specified.`; + describe('negative', () => { + it('must throw on invalid data', () => { + const error = 'Invalid parameter \'data\' specified.'; expect(() => { helpers.insert(); }).toThrow(error); @@ -80,116 +80,116 @@ describe(`INSERT`, () => { helpers.insert(123); }).toThrow(error); }); - it(`must throw on an empty array`, () => { - const error = `Cannot generate an INSERT from an empty array.`; + it('must throw on an empty array', () => { + const error = 'Cannot generate an INSERT from an empty array.'; expect(() => { helpers.insert([]); }).toThrow(error); }); - it(`must throw for an array without columns specified`, () => { - const error = `Parameter 'columns' is required when inserting multiple records.`; + it('must throw for an array without columns specified', () => { + const error = 'Parameter \'columns\' is required when inserting multiple records.'; expect(() => { helpers.insert([{}]); }).toThrow(error); }); - it(`must throw for an empty column set`, () => { - const error = `Cannot generate an INSERT without any columns.`; + it('must throw for an empty column set', () => { + const error = 'Cannot generate an INSERT without any columns.'; expect(() => { helpers.insert({}, []); }).toThrow(error); }); - it(`must throw when table is not specified`, () => { - const error = `Table name is unknown.`; + it('must throw when table is not specified', () => { + const error = 'Table name is unknown.'; expect(() => { - helpers.insert({}, [`test`]); + helpers.insert({}, ['test']); }).toThrow(error); }); - it(`must throw on invalid array data`, () => { - const error = `Invalid insert object at index 0.`; + it('must throw on invalid array data', () => { + const error = 'Invalid insert object at index 0.'; expect(() => { - helpers.insert([null], [`test`], `table`); + helpers.insert([null], ['test'], 'table'); }).toThrow(error); }); }); }); -describe(`UPDATE`, () => { +describe('UPDATE', () => { - describe(`single:`, () => { - describe(`direct data`, () => { - it(`must return all properties correctly`, () => { - const cs = [`?val`, {name: `msg`, cast: `text`}, {name: `extra`, def: 555}]; - expect(helpers.update(dataSingle, cs, `table`)).toBe(`update "table" set "msg"='test'::text,"extra"=555`); - expect(helpers.update(dataSingle, null, `table`)).toBe(`update "table" set "val"=123,"msg"='test'`); + describe('single:', () => { + describe('direct data', () => { + it('must return all properties correctly', () => { + const cs = ['?val', {name: 'msg', cast: 'text'}, {name: 'extra', def: 555}]; + expect(helpers.update(dataSingle, cs, 'table')).toBe('update "table" set "msg"=\'test\'::text,"extra"=555'); + expect(helpers.update(dataSingle, null, 'table')).toBe('update "table" set "val"=123,"msg"=\'test\''); }); }); - describe(`skipping columns`, () => { - const cs = [`val`, {name: `msg`, skip: () => true}]; - it(`must work`, () => { - expect(helpers.update(dataSingle, cs, `table`)).toBe(`update "table" set "val"=123`); + describe('skipping columns', () => { + const cs = ['val', {name: 'msg', skip: () => true}]; + it('must work', () => { + expect(helpers.update(dataSingle, cs, 'table')).toBe('update "table" set "val"=123'); }); }); }); - describe(`multi:`, () => { - describe(`direct data`, () => { - it(`must return all data columns`, () => { - expect(helpers.update(dataMulti, [`?id`, `val`, { - name: `msg`, - cast: `text` - }], `table`)).toBe(`update "table" as t set "val"=v."val","msg"=v."msg" from (values(1,123,'hello'::text),(2,456,'world'::text)) as v("id","val","msg")`); + describe('multi:', () => { + describe('direct data', () => { + it('must return all data columns', () => { + expect(helpers.update(dataMulti, ['?id', 'val', { + name: 'msg', + cast: 'text' + }], 'table')).toBe('update "table" as t set "val"=v."val","msg"=v."msg" from (values(1,123,\'hello\'::text),(2,456,\'world\'::text)) as v("id","val","msg")'); }); }); }); - describe(`setting table name`, () => { - const cs = new helpers.ColumnSet(dataSingle, {table: `external`}); - it(`must use its own table when specified`, () => { - expect(helpers.update(dataSingle, cs, `internal`)).toBe(`update "internal" set "val"=123,"msg"='test'`); + describe('setting table name', () => { + const cs = new helpers.ColumnSet(dataSingle, {table: 'external'}); + it('must use its own table when specified', () => { + expect(helpers.update(dataSingle, cs, 'internal')).toBe('update "internal" set "val"=123,"msg"=\'test\''); }); - it(`must use ColumnSet table when not locally specified`, () => { - expect(helpers.update(dataSingle, cs)).toBe(`update "external" set "val"=123,"msg"='test'`); + it('must use ColumnSet table when not locally specified', () => { + expect(helpers.update(dataSingle, cs)).toBe('update "external" set "val"=123,"msg"=\'test\''); }); }); - describe(`generating sql in upper case`, () => { - const cs = new helpers.ColumnSet([`?id`, `val`, `msg`], {table: `table`}); + describe('generating sql in upper case', () => { + const cs = new helpers.ColumnSet(['?id', 'val', 'msg'], {table: 'table'}); beforeEach(() => { options.capSQL = true; }); - it(`must return a capitalized query for a single data`, () => { - expect(helpers.update(dataSingle, cs)).toBe(`UPDATE "table" SET "val"=123,"msg"='test'`); + it('must return a capitalized query for a single data', () => { + expect(helpers.update(dataSingle, cs)).toBe('UPDATE "table" SET "val"=123,"msg"=\'test\''); }); - it(`must return a capitalized query for multi-row data`, () => { - expect(helpers.update(dataMulti, cs)).toBe(`UPDATE "table" AS t SET "val"=v."val","msg"=v."msg" FROM (VALUES(1,123,'hello'),(2,456,'world')) AS v("id","val","msg")`); + it('must return a capitalized query for multi-row data', () => { + expect(helpers.update(dataMulti, cs)).toBe('UPDATE "table" AS t SET "val"=v."val","msg"=v."msg" FROM (VALUES(1,123,\'hello\'),(2,456,\'world\')) AS v("id","val","msg")'); }); afterEach(() => { options.capSQL = false; }); }); - describe(`options`, () => { - const cs = new helpers.ColumnSet([`?id`, `val`, `msg`], {table: `table`}); - const opt = {tableAlias: `X`, valueAlias: `Y`}; - it(`must use the options`, () => { - expect(helpers.update(dataMulti, cs, null, opt)).toBe(`update "table" as X set "val"=Y."val","msg"=Y."msg" from (values(1,123,'hello'),(2,456,'world')) as Y("id","val","msg")`); + describe('options', () => { + const cs = new helpers.ColumnSet(['?id', 'val', 'msg'], {table: 'table'}); + const opt = {tableAlias: 'X', valueAlias: 'Y'}; + it('must use the options', () => { + expect(helpers.update(dataMulti, cs, null, opt)).toBe('update "table" as X set "val"=Y."val","msg"=Y."msg" from (values(1,123,\'hello\'),(2,456,\'world\')) as Y("id","val","msg")'); }); - it(`must ignore empty options`, () => { - expect(helpers.update(dataMulti, cs, null, {})).toBe(`update "table" as t set "val"=v."val","msg"=v."msg" from (values(1,123,'hello'),(2,456,'world')) as v("id","val","msg")`); + it('must ignore empty options', () => { + expect(helpers.update(dataMulti, cs, null, {})).toBe('update "table" as t set "val"=v."val","msg"=v."msg" from (values(1,123,\'hello\'),(2,456,\'world\')) as v("id","val","msg")'); }); }); - describe(`emptyUpdate`, () => { - const cs = new helpers.ColumnSet([`?id`, `?val`, `?msg`], {table: `table`}); - it(`must return the option value`, () => { + describe('emptyUpdate', () => { + const cs = new helpers.ColumnSet(['?id', '?val', '?msg'], {table: 'table'}); + it('must return the option value', () => { expect(helpers.update(dataSingle, cs, null, {emptyUpdate: 123})).toBe(123); expect(helpers.update(dataMulti, cs, null, {emptyUpdate: 123})).toBe(123); }); }); - describe(`negative`, () => { - it(`must throw on invalid data`, () => { - const error = `Invalid parameter 'data' specified.`; + describe('negative', () => { + it('must throw on invalid data', () => { + const error = 'Invalid parameter \'data\' specified.'; expect(() => { helpers.update(); }).toThrow(error); @@ -197,87 +197,87 @@ describe(`UPDATE`, () => { helpers.update(123); }).toThrow(error); }); - it(`must throw on an empty array`, () => { - const error = `Cannot generate an UPDATE from an empty array.`; + it('must throw on an empty array', () => { + const error = 'Cannot generate an UPDATE from an empty array.'; expect(() => { helpers.update([]); }).toThrow(error); }); - it(`must throw for an array without columns specified`, () => { - const error = `Parameter 'columns' is required when updating multiple records.`; + it('must throw for an array without columns specified', () => { + const error = 'Parameter \'columns\' is required when updating multiple records.'; expect(() => { helpers.update([{}]); }).toThrow(error); }); - it(`must throw for an empty column set`, () => { - const error = `Cannot generate an UPDATE without any columns.`; + it('must throw for an empty column set', () => { + const error = 'Cannot generate an UPDATE without any columns.'; expect(() => { helpers.update({}, []); }).toThrow(error); }); - it(`must throw when table is not specified for an array`, () => { - const error = `Table name is unknown.`; + it('must throw when table is not specified for an array', () => { + const error = 'Table name is unknown.'; expect(() => { - helpers.update({}, [`test`]); - helpers.update([{}], [`test`]); + helpers.update({}, ['test']); + helpers.update([{}], ['test']); }).toThrow(error); }); - it(`must throw on invalid array data`, () => { - const error = `Invalid update object at index 0.`; + it('must throw on invalid array data', () => { + const error = 'Invalid update object at index 0.'; expect(() => { - helpers.update([null], [`test`], `table`); + helpers.update([null], ['test'], 'table'); }).toThrow(error); }); }); }); -describe(`TableName`, () => { +describe('TableName', () => { - describe(`Negative`, () => { + describe('Negative', () => { - describe(`invalid 'table' parameter`, () => { - const error = `Table name must be a non-empty text string.`; - it(`must throw an error`, () => { + describe('invalid \'table\' parameter', () => { + const error = 'Table name must be a non-empty text string.'; + it('must throw an error', () => { expect(() => { new helpers.TableName(); }).toThrow(error); expect(() => { new helpers.TableName(123); - }).toThrow(`Invalid "options" parameter: 123`); + }).toThrow('Invalid "options" parameter: 123'); expect(() => { - new helpers.TableName(``); + new helpers.TableName(''); }).toThrow(error); expect(() => { - new helpers.TableName(` `); + new helpers.TableName(' '); }).toThrow(error); }); }); }); - describe(`options`, () => { - it(`must find the options correctly`, () => { - const t = new helpers.TableName({table: `table`, schema: `schema`}); - expect(t.table).toBe(`table`); - expect(t.schema).toBe(`schema`); + describe('options', () => { + it('must find the options correctly', () => { + const t = new helpers.TableName({table: 'table', schema: 'schema'}); + expect(t.table).toBe('table'); + expect(t.schema).toBe('schema'); }); - it(`must skip an empty schema`, () => { - const t = new helpers.TableName({table: `table`, schema: ``}); - expect(`schema` in t).toBe(false); + it('must skip an empty schema', () => { + const t = new helpers.TableName({table: 'table', schema: ''}); + expect('schema' in t).toBe(false); }); }); - describe(`console output`, () => { - it(`must be formatted`, () => { - const t = new helpers.TableName({table: `table`, schema: `schema`}); - expect(t.toString()).toBe(`"schema"."table"`); + describe('console output', () => { + it('must be formatted', () => { + const t = new helpers.TableName({table: 'table', schema: 'schema'}); + expect(t.toString()).toBe('"schema"."table"'); expect(t.toString()).toBe(tools.inspect(t)); }); }); - describe(`custom-type formatting`, () => { - const t = new helpers.TableName({table: `table`, schema: `schema`}); - it(`must return the full name`, () => { + describe('custom-type formatting', () => { + const t = new helpers.TableName({table: 'table', schema: 'schema'}); + it('must return the full name', () => { const toPostgres = pgp.as.ctf.toPostgres; expect(t[toPostgres](t)).toBe(t.name); expect(t[toPostgres].call(null, t)).toBe(t.name); @@ -286,196 +286,196 @@ describe(`TableName`, () => { }); }); -describe(`Column`, () => { +describe('Column', () => { - describe(`set all`, () => { - it(`must set all values`, () => { + describe('set all', () => { + it('must set all values', () => { const col = new helpers.Column({ - name: `_colName`, - prop: `$propName01`, + name: '_colName', + prop: '$propName01', def: 123, cnd: true, - cast: `int`, - mod: `^`, + cast: 'int', + mod: '^', init() { }, skip() { } }); - expect(col.name).toBe(`_colName`); - expect(col.prop).toBe(`$propName01`); + expect(col.name).toBe('_colName'); + expect(col.prop).toBe('$propName01'); expect(col.def).toBe(123); expect(col.cnd).toBe(true); - expect(col.cast).toBe(`int`); - expect(col.mod).toBe(`^`); - expect(typeof col.init).toBe(`function`); - expect(typeof col.skip).toBe(`function`); + expect(col.cast).toBe('int'); + expect(col.mod).toBe('^'); + expect(typeof col.init).toBe('function'); + expect(typeof col.skip).toBe('function'); expect(col.toString()).toBe(tools.inspect(col)); }); }); - describe(`set defaults`, () => { - it(`must set all values`, () => { + describe('set defaults', () => { + it('must set all values', () => { const col = new helpers.Column({ - name: `name`, + name: 'name', prop: null, cast: null, mod: null }); - expect(col.name).toBe(`name`); - expect(`prop` in col).toBe(false); - expect(`cast` in col).toBe(false); - expect(`mod` in col).toBe(false); + expect(col.name).toBe('name'); + expect('prop' in col).toBe(false); + expect('cast' in col).toBe(false); + expect('mod' in col).toBe(false); }); }); - describe(`cast`, () => { + describe('cast', () => { const cols = [ new helpers.Column({ - name: `name`, - cast: `::int` + name: 'name', + cast: '::int' }), new helpers.Column({ - name: `name`, - cast: ` : : \t : int` + name: 'name', + cast: ' : : \t : int' }), new helpers.Column({ - name: `name`, - cast: `: : int: \t: ` + name: 'name', + cast: ': : int: \t: ' }), new helpers.Column({ - name: `name`, - cast: `:a:` + name: 'name', + cast: ':a:' }) ]; - it(`must strip the cast`, () => { - expect(cols[0].cast).toBe(`int`); - expect(cols[1].cast).toBe(`int`); - expect(cols[2].cast).toBe(`int: \t:`); - expect(cols[3].cast).toBe(`a:`); + it('must strip the cast', () => { + expect(cols[0].cast).toBe('int'); + expect(cols[1].cast).toBe('int'); + expect(cols[2].cast).toBe('int: \t:'); + expect(cols[3].cast).toBe('a:'); }); }); - describe(`prop`, () => { + describe('prop', () => { const col = new helpers.Column({ - name: `testName`, - prop: `testName` + name: 'testName', + prop: 'testName' }); - it(`must not be set if matches 'name'`, () => { - expect(col.name).toBe(`testName`); - expect(`prop` in col).toBe(false); + it('must not be set if matches \'name\'', () => { + expect(col.name).toBe('testName'); + expect('prop' in col).toBe(false); }); - it(`must throw on invalid property names`, () => { + it('must throw on invalid property names', () => { expect(() => new helpers.Column({ - name: `name`, - prop: `-test` - })).toThrow(`Invalid 'prop' syntax: "-test".`); + name: 'name', + prop: '-test' + })).toThrow('Invalid \'prop\' syntax: "-test".'); }); }); - describe(`mod`, () => { - it(`must strip the mod`, () => { - const col = new helpers.Column(`name^`); - expect(col.name).toBe(`name`); - expect(col.mod).toBe(`^`); + describe('mod', () => { + it('must strip the mod', () => { + const col = new helpers.Column('name^'); + expect(col.name).toBe('name'); + expect(col.mod).toBe('^'); }); - it(`must set the mod`, () => { + it('must set the mod', () => { const col = new helpers.Column({ - name: `name`, - mod: `^` + name: 'name', + mod: '^' }); - expect(col.mod).toBe(`^`); + expect(col.mod).toBe('^'); }); }); - describe(`Negative`, () => { - it(`must throw on invalid construction`, () => { - const error = `Invalid column details.`; + describe('Negative', () => { + it('must throw on invalid construction', () => { + const error = 'Invalid column details.'; expect(() => { new helpers.Column(); }).toThrow(error); expect(() => { new helpers.Column(123); - }).toThrow(`Invalid "options" parameter: 123`); + }).toThrow('Invalid "options" parameter: 123'); }); - it(`must throw on invalid input name`, () => { + it('must throw on invalid input name', () => { expect(() => { - new helpers.Column(``); - }).toThrow(`Invalid column syntax: "".`); + new helpers.Column(''); + }).toThrow('Invalid column syntax: "".'); expect(() => { - new helpers.Column(` `); - }).toThrow(`Invalid column syntax: " ".`); + new helpers.Column(' '); + }).toThrow('Invalid column syntax: " ".'); expect(() => { - new helpers.Column(`name.bla`); - }).toThrow(`Invalid column syntax: "name.bla".`); + new helpers.Column('name.bla'); + }).toThrow('Invalid column syntax: "name.bla".'); }); - it(`must throw on invalid property 'name'`, () => { + it('must throw on invalid property \'name\'', () => { expect(() => { - new helpers.Column({name: ``}); - }).toThrow(`Invalid 'name' value: "". A non-empty string was expected.`); + new helpers.Column({name: ''}); + }).toThrow('Invalid \'name\' value: "". A non-empty string was expected.'); expect(() => { - new helpers.Column({name: ` `}); - }).toThrow(`Invalid 'name' value: " ". A non-empty string was expected.`); + new helpers.Column({name: ' '}); + }).toThrow('Invalid \'name\' value: " ". A non-empty string was expected.'); expect(() => { new helpers.Column({name: 123}); - }).toThrow(`Invalid 'name' value: 123. A non-empty string was expected.`); + }).toThrow('Invalid \'name\' value: 123. A non-empty string was expected.'); expect(() => { - new helpers.Column({name: `name.first`}); - }).toThrow(`Invalid 'name' syntax: "name.first".`); + new helpers.Column({name: 'name.first'}); + }).toThrow('Invalid \'name\' syntax: "name.first".'); }); - it(`must throw on invalid property 'prop'`, () => { + it('must throw on invalid property \'prop\'', () => { expect(() => { - new helpers.Column({name: `name`, prop: 123}); - }).toThrow(`Invalid 'prop' value: 123. A non-empty string was expected.`); + new helpers.Column({name: 'name', prop: 123}); + }).toThrow('Invalid \'prop\' value: 123. A non-empty string was expected.'); expect(() => { - new helpers.Column({name: `name`, prop: ``}); - }).toThrow(`Invalid 'prop' value: "". A non-empty string was expected.`); + new helpers.Column({name: 'name', prop: ''}); + }).toThrow('Invalid \'prop\' value: "". A non-empty string was expected.'); expect(() => { - new helpers.Column({name: `name`, prop: ` `}); - }).toThrow(`Invalid 'prop' value: " ". A non-empty string was expected.`); + new helpers.Column({name: 'name', prop: ' '}); + }).toThrow('Invalid \'prop\' value: " ". A non-empty string was expected.'); expect(() => { - new helpers.Column({name: `name`, prop: `one.two`}); - }).toThrow(`Invalid 'prop' syntax: "one.two".`); + new helpers.Column({name: 'name', prop: 'one.two'}); + }).toThrow('Invalid \'prop\' syntax: "one.two".'); }); - it(`must throw on invalid property 'cast'`, () => { + it('must throw on invalid property \'cast\'', () => { expect(() => { - new helpers.Column({name: `name`, cast: 123}); - }).toThrow(`Invalid 'cast' value: 123.`); + new helpers.Column({name: 'name', cast: 123}); + }).toThrow('Invalid \'cast\' value: 123.'); expect(() => { - new helpers.Column({name: `name`, cast: ``}); - }).toThrow(`Invalid 'cast' value: "".`); + new helpers.Column({name: 'name', cast: ''}); + }).toThrow('Invalid \'cast\' value: "".'); expect(() => { - new helpers.Column({name: `name`, cast: ` `}); - }).toThrow(`Invalid 'cast' value: " ".`); + new helpers.Column({name: 'name', cast: ' '}); + }).toThrow('Invalid \'cast\' value: " ".'); }); - it(`must throw on invalid property 'mod'`, () => { + it('must throw on invalid property \'mod\'', () => { expect(() => { - new helpers.Column({name: `name`, mod: 123}); - }).toThrow(`Invalid 'mod' value: 123.`); + new helpers.Column({name: 'name', mod: 123}); + }).toThrow('Invalid \'mod\' value: 123.'); expect(() => { - new helpers.Column({name: `name`, mod: ``}); - }).toThrow(`Invalid 'mod' value: "".`); + new helpers.Column({name: 'name', mod: ''}); + }).toThrow('Invalid \'mod\' value: "".'); expect(() => { - new helpers.Column({name: `name`, mod: ` `}); - }).toThrow(`Invalid 'mod' value: " ".`); + new helpers.Column({name: 'name', mod: ' '}); + }).toThrow('Invalid \'mod\' value: " ".'); }); }); }); -describe(`ColumnSet`, () => { +describe('ColumnSet', () => { - describe(`options`, () => { - it(`must ignore empty options`, () => { - const cs = new helpers.ColumnSet([`nameName`], {}); - expect(`table` in cs).toBe(false); + describe('options', () => { + it('must ignore empty options', () => { + const cs = new helpers.ColumnSet(['nameName'], {}); + expect('table' in cs).toBe(false); }); - it(`must set table correctly`, () => { - const t = new helpers.TableName(`table`); - const cs = new helpers.ColumnSet([`name`], {table: t}); - expect(cs.table.toString()).toBe(`"table"`); + it('must set table correctly', () => { + const t = new helpers.TableName('table'); + const cs = new helpers.ColumnSet(['name'], {table: t}); + expect(cs.table.toString()).toBe('"table"'); }); - it(`must support inherited properties`, () => { + it('must support inherited properties', () => { function A() { } @@ -492,202 +492,202 @@ describe(`ColumnSet`, () => { const cs1 = new helpers.ColumnSet(obj); const cs2 = new helpers.ColumnSet(obj, {inherit: true}); expect(cs1.columns.length).toBe(1); - expect(cs1.columns[0].name).toBe(`second`); + expect(cs1.columns[0].name).toBe('second'); expect(cs2.columns.length).toBe(2); - expect(cs2.columns[0].name).toBe(`second`); - expect(cs2.columns[1].name).toBe(`first`); + expect(cs2.columns[0].name).toBe('second'); + expect(cs2.columns[1].name).toBe('first'); }); }); - describe(`initialization`, () => { - it(`must accept a Column directly`, () => { - const col = new helpers.Column(`colName`); + describe('initialization', () => { + it('must accept a Column directly', () => { + const col = new helpers.Column('colName'); const cs = new helpers.ColumnSet(col); expect(cs.columns.length).toBe(1); expect(cs.columns[0]).toBe(col); }); - it(`must accept a Column from array directly`, () => { - const col = new helpers.Column(`colName`); + it('must accept a Column from array directly', () => { + const col = new helpers.Column('colName'); const cs = new helpers.ColumnSet([col]); expect(cs.columns.length).toBe(1); expect(cs.columns[0]).toBe(col); }); - it(`must enumerate an object properties`, () => { + it('must enumerate an object properties', () => { const cs = new helpers.ColumnSet(dataSingle); expect(cs.columns.length).toBe(2); - expect(cs.columns[0].name).toBe(`val`); - expect(cs.columns[1].name).toBe(`msg`); + expect(cs.columns[0].name).toBe('val'); + expect(cs.columns[1].name).toBe('msg'); }); }); - describe(`property 'names'`, () => { - const cs = new helpers.ColumnSet([`name1`, `name2`]); + describe('property \'names\'', () => { + const cs = new helpers.ColumnSet(['name1', 'name2']); const csEmpty = new helpers.ColumnSet([]); - it(`must return the right string`, () => { - expect(cs.names).toBe(`"name1","name2"`); - expect(csEmpty.names).toBe(``); + it('must return the right string', () => { + expect(cs.names).toBe('"name1","name2"'); + expect(csEmpty.names).toBe(''); }); - it(`must reuse the data`, () => { - expect(cs.names).toBe(`"name1","name2"`); + it('must reuse the data', () => { + expect(cs.names).toBe('"name1","name2"'); }); }); - describe(`property 'variables'`, () => { - const cs = new helpers.ColumnSet([`id^`, {name: `cells`, cast: `int[]`}, `doc:json`]); + describe('property \'variables\'', () => { + const cs = new helpers.ColumnSet(['id^', {name: 'cells', cast: 'int[]'}, 'doc:json']); const csEmpty = new helpers.ColumnSet([]); - it(`must return the right string`, () => { - expect(cs.variables).toBe(`\${id^},\${cells}::int[],\${doc:json}`); - expect(csEmpty.variables).toBe(``); + it('must return the right string', () => { + expect(cs.variables).toBe('${id^},${cells}::int[],${doc:json}'); + expect(csEmpty.variables).toBe(''); }); - it(`must reuse the data`, () => { - expect(cs.variables).toBe(`\${id^},\${cells}::int[],\${doc:json}`); + it('must reuse the data', () => { + expect(cs.variables).toBe('${id^},${cells}::int[],${doc:json}'); }); }); - describe(`method 'assign'`, () => { + describe('method \'assign\'', () => { const cs = new helpers.ColumnSet(dataSingle); const csEmpty = new helpers.ColumnSet([]); - it(`must return the right update string`, () => { - expect(cs.assign({source: dataSingle})).toBe(`"val"=\${val},"msg"=\${msg}`); - expect(csEmpty.assign({source: dataSingle})).toBe(``); - }); - it(`must return the right string without source`, () => { - const specialCS = new helpers.ColumnSet([{name: `val`, skip: () => false}, `msg`]); - expect(specialCS.assign()).toBe(`"val"=\${val},"msg"=\${msg}`); - expect(specialCS.assign(null)).toBe(`"val"=\${val},"msg"=\${msg}`); - expect(specialCS.assign(123)).toBe(`"val"=\${val},"msg"=\${msg}`); - }); - it(`must reuse the data`, () => { - expect(cs.assign({source: dataSingle})).toBe(`"val"=\${val},"msg"=\${msg}`); - }); - it(`must handle cnd and skip`, () => { - const cs1 = new helpers.ColumnSet([`?val`, `msg`]); - const cs2 = new helpers.ColumnSet([`val`, { - name: `msg`, skip() { + it('must return the right update string', () => { + expect(cs.assign({source: dataSingle})).toBe('"val"=${val},"msg"=${msg}'); + expect(csEmpty.assign({source: dataSingle})).toBe(''); + }); + it('must return the right string without source', () => { + const specialCS = new helpers.ColumnSet([{name: 'val', skip: () => false}, 'msg']); + expect(specialCS.assign()).toBe('"val"=${val},"msg"=${msg}'); + expect(specialCS.assign(null)).toBe('"val"=${val},"msg"=${msg}'); + expect(specialCS.assign(123)).toBe('"val"=${val},"msg"=${msg}'); + }); + it('must reuse the data', () => { + expect(cs.assign({source: dataSingle})).toBe('"val"=${val},"msg"=${msg}'); + }); + it('must handle cnd and skip', () => { + const cs1 = new helpers.ColumnSet(['?val', 'msg']); + const cs2 = new helpers.ColumnSet(['val', { + name: 'msg', skip() { } }]); - const cs3 = new helpers.ColumnSet([`val`, { - name: `msg`, skip() { + const cs3 = new helpers.ColumnSet(['val', { + name: 'msg', skip() { return true; } }]); - expect(cs1.assign({source: dataSingle})).toBe(`"msg"=\${msg}`); - expect(cs2.assign({source: dataSingle})).toBe(`"val"=\${val},"msg"=\${msg}`); - expect(cs3.assign({source: dataSingle})).toBe(`"val"=\${val}`); + expect(cs1.assign({source: dataSingle})).toBe('"msg"=${msg}'); + expect(cs2.assign({source: dataSingle})).toBe('"val"=${val},"msg"=${msg}'); + expect(cs3.assign({source: dataSingle})).toBe('"val"=${val}'); }); - describe(`with prefix`, () => { - const cs1 = new helpers.ColumnSet([`val`, `msg`]); - it(`must correctly escape as alias`, () => { + describe('with prefix', () => { + const cs1 = new helpers.ColumnSet(['val', 'msg']); + it('must correctly escape as alias', () => { expect(cs1.assign({ source: dataSingle, - prefix: `a b c` - })).toBe(`"a b c"."val"=\${val},"a b c"."msg"=\${msg}`); + prefix: 'a b c' + })).toBe('"a b c"."val"=${val},"a b c"."msg"=${msg}'); }); }); }); - describe(`method assignColumns`, () => { - const cs = new helpers.ColumnSet([`?id`, `name`, `title`]); - describe(`without options`, () => { - it(`must provide default processing`, () => { - expect(cs.assignColumns()).toBe(`"id"="id","name"="name","title"="title"`); + describe('method assignColumns', () => { + const cs = new helpers.ColumnSet(['?id', 'name', 'title']); + describe('without options', () => { + it('must provide default processing', () => { + expect(cs.assignColumns()).toBe('"id"="id","name"="name","title"="title"'); }); }); - describe(`option "skip"`, () => { - it(`must skip the columns`, () => { - expect(cs.assignColumns({skip: ``})).toBe(`"id"="id","name"="name","title"="title"`); - expect(cs.assignColumns({skip: `id`})).toBe(`"name"="name","title"="title"`); - expect(cs.assignColumns({skip: [`id`]})).toBe(`"name"="name","title"="title"`); - expect(cs.assignColumns({skip: c => c.cnd})).toBe(`"name"="name","title"="title"`); + describe('option "skip"', () => { + it('must skip the columns', () => { + expect(cs.assignColumns({skip: ''})).toBe('"id"="id","name"="name","title"="title"'); + expect(cs.assignColumns({skip: 'id'})).toBe('"name"="name","title"="title"'); + expect(cs.assignColumns({skip: ['id']})).toBe('"name"="name","title"="title"'); + expect(cs.assignColumns({skip: c => c.cnd})).toBe('"name"="name","title"="title"'); }); }); - describe(`option "from"`, () => { - it(`must append to the source columns`, () => { - expect(cs.assignColumns({from: ``})).toBe(`"id"="id","name"="name","title"="title"`); - expect(cs.assignColumns({from: `source`})).toBe(`"id"=source."id","name"=source."name","title"=source."title"`); + describe('option "from"', () => { + it('must append to the source columns', () => { + expect(cs.assignColumns({from: ''})).toBe('"id"="id","name"="name","title"="title"'); + expect(cs.assignColumns({from: 'source'})).toBe('"id"=source."id","name"=source."name","title"=source."title"'); }); }); - describe(`option "to"`, () => { - it(`must append to the target columns`, () => { - expect(cs.assignColumns({to: ``})).toBe(`"id"="id","name"="name","title"="title"`); - expect(cs.assignColumns({to: `dest`})).toBe(`dest."id"="id",dest."name"="name",dest."title"="title"`); + describe('option "to"', () => { + it('must append to the target columns', () => { + expect(cs.assignColumns({to: ''})).toBe('"id"="id","name"="name","title"="title"'); + expect(cs.assignColumns({to: 'dest'})).toBe('dest."id"="id",dest."name"="name",dest."title"="title"'); }); }); - describe(`in a complex scenario`, () => { - it(`must allow all combinations`, () => { + describe('in a complex scenario', () => { + it('must allow all combinations', () => { expect(cs.assignColumns({ - from: `EXCLUDED`, - to: `Target`, - skip: `id` - })).toBe(`"Target"."name"=EXCLUDED."name","Target"."title"=EXCLUDED."title"`); + from: 'EXCLUDED', + to: 'Target', + skip: 'id' + })).toBe('"Target"."name"=EXCLUDED."name","Target"."title"=EXCLUDED."title"'); }); }); }); - describe(`method 'prepare'`, () => { - it(`must replicate full objects`, () => { + describe('method \'prepare\'', () => { + it('must replicate full objects', () => { const cs = new helpers.ColumnSet(dataSingle); const obj = cs.prepare(dataSingle); expect(obj).toEqual(dataSingle); }); - it(`must set defaults for missing properties`, () => { - const cs = new helpers.ColumnSet([`val`, + it('must set defaults for missing properties', () => { + const cs = new helpers.ColumnSet(['val', { - name: `msg`, + name: 'msg', init: col => { - return col.value + `-init`; + return col.value + '-init'; } }, { - name: `one`, - def: `def-test` + name: 'one', + def: 'def-test' }, { - name: `first`, + name: 'first', init() { - return `init-test`; + return 'init-test'; } }, - `wrong`]); + 'wrong']); const obj = cs.prepare(dataSingle); expect(obj).toEqual({ val: dataSingle.val, - msg: dataSingle.msg + `-init`, - one: `def-test`, - first: `init-test` + msg: dataSingle.msg + '-init', + one: 'def-test', + first: 'init-test' }); }); }); - describe(`method 'extend'`, () => { - it(`must extend columns`, () => { - const first = new helpers.ColumnSet([`one`, `two`], {table: `my-table`}); - const second = new helpers.ColumnSet([`three`, `four`]); - const result = new helpers.ColumnSet([`one`, `two`, `three`, `four`], {table: `my-table`}); + describe('method \'extend\'', () => { + it('must extend columns', () => { + const first = new helpers.ColumnSet(['one', 'two'], {table: 'my-table'}); + const second = new helpers.ColumnSet(['three', 'four']); + const result = new helpers.ColumnSet(['one', 'two', 'three', 'four'], {table: 'my-table'}); const dest1 = first.extend(second); - const dest2 = first.extend([`three`, `four`]); + const dest2 = first.extend(['three', 'four']); expect(dest1.table).toBe(first.table); expect(dest2.table).toBe(first.table); expect(dest1.toString()).toBe(result.toString()); expect(dest2.toString()).toBe(result.toString()); }); - it(`must throw on duplicate columns names`, () => { - const cs = new helpers.ColumnSet([`one`, `two`]); + it('must throw on duplicate columns names', () => { + const cs = new helpers.ColumnSet(['one', 'two']); expect(() => { - cs.extend([`two`]); - }).toThrow(`Duplicate column name "two".`); + cs.extend(['two']); + }).toThrow('Duplicate column name "two".'); }); }); - describe(`method 'merge'`, () => { - it(`must merge all columns`, () => { - const first = new helpers.ColumnSet([`one`, `two`], {table: `my-table`}); - const second = new helpers.ColumnSet([`two`, `three`]); - const result = new helpers.ColumnSet([`one`, `two`, `three`], {table: `my-table`}); + describe('method \'merge\'', () => { + it('must merge all columns', () => { + const first = new helpers.ColumnSet(['one', 'two'], {table: 'my-table'}); + const second = new helpers.ColumnSet(['two', 'three']); + const result = new helpers.ColumnSet(['one', 'two', 'three'], {table: 'my-table'}); const dest1 = first.merge(second); - const dest2 = first.merge([`two`, `three`]); + const dest2 = first.merge(['two', 'three']); expect(dest1.table).toBe(first.table); expect(dest2.table).toBe(first.table); expect(dest1.toString()).toBe(result.toString()); @@ -695,9 +695,9 @@ describe(`ColumnSet`, () => { }); }); - describe(`Negative`, () => { - it(`must throw on invalid columns`, () => { - const error = `Invalid parameter 'columns' specified.`; + describe('Negative', () => { + it('must throw on invalid columns', () => { + const error = 'Invalid parameter \'columns\' specified.'; expect(() => { new helpers.ColumnSet(); }).toThrow(error); @@ -705,72 +705,72 @@ describe(`ColumnSet`, () => { new helpers.ColumnSet(123); }).toThrow(error); }); - it(`must throw on duplicate columns`, () => { + it('must throw on duplicate columns', () => { expect(() => { - new helpers.ColumnSet([`one`, `one`]); - }).toThrow(`Duplicate column name "one".`); + new helpers.ColumnSet(['one', 'one']); + }).toThrow('Duplicate column name "one".'); }); - it(`must throw on invalid options`, () => { + it('must throw on invalid options', () => { expect(() => { new helpers.ColumnSet({}, 123); - }).toThrow(`Invalid "options" parameter: 123`); + }).toThrow('Invalid "options" parameter: 123'); }); }); - describe(`console coverage`, () => { - const cs1 = new helpers.ColumnSet([`name`]); - const cs2 = new helpers.ColumnSet([`name`], {table: `table`}); + describe('console coverage', () => { + const cs1 = new helpers.ColumnSet(['name']); + const cs2 = new helpers.ColumnSet(['name'], {table: 'table'}); const cs3 = new helpers.ColumnSet([]); const gap = utils.messageGap(1); - it(`must cover all lines`, () => { - expect(cs1.toString()).toContain(`columns: [`); - expect(cs2.toString()).toContain(`table: "table"`); - expect(cs3.toString()).toBe(`ColumnSet {` + os.EOL + gap + `columns: []` + os.EOL + `}`); + it('must cover all lines', () => { + expect(cs1.toString()).toContain('columns: ['); + expect(cs2.toString()).toContain('table: "table"'); + expect(cs3.toString()).toBe('ColumnSet {' + os.EOL + gap + 'columns: []' + os.EOL + '}'); expect(cs1.toString(1) !== tools.inspect(cs1)).toBe(true); }); }); }); -describe(`method 'sets'`, () => { +describe('method \'sets\'', () => { - describe(`with a ColumnSet`, () => { - it(`must reuse the ColumnSet`, () => { + describe('with a ColumnSet', () => { + it('must reuse the ColumnSet', () => { const cs = new helpers.ColumnSet(dataSingle); - expect(helpers.sets(dataSingle, cs)).toBe(`"val"=123,"msg"='test'`); + expect(helpers.sets(dataSingle, cs)).toBe('"val"=123,"msg"=\'test\''); }); - it(`must skip conditional columns`, () => { - const cs = new helpers.ColumnSet([`?val`, `msg`]); - expect(helpers.sets(dataSingle, cs)).toBe(`"msg"='test'`); + it('must skip conditional columns', () => { + const cs = new helpers.ColumnSet(['?val', 'msg']); + expect(helpers.sets(dataSingle, cs)).toBe('"msg"=\'test\''); }); - it(`must skip dynamic columns correctly`, () => { - const cs = new helpers.ColumnSet([`val`, {name: `msg`, skip: () => true}]); - expect(helpers.sets(dataSingle, cs)).toBe(`"val"=123`); + it('must skip dynamic columns correctly', () => { + const cs = new helpers.ColumnSet(['val', {name: 'msg', skip: () => true}]); + expect(helpers.sets(dataSingle, cs)).toBe('"val"=123'); }); - it(`must apply sql casting correctly`, () => { - const cs = new helpers.ColumnSet([{name: `msg`, cast: `text`}]); - expect(helpers.sets(dataSingle, cs)).toBe(`"msg"='test'::text`); + it('must apply sql casting correctly', () => { + const cs = new helpers.ColumnSet([{name: 'msg', cast: 'text'}]); + expect(helpers.sets(dataSingle, cs)).toBe('"msg"=\'test\'::text'); }); }); - describe(`without a ColumnSet`, () => { - it(`must create local ColumnSet`, () => { - expect(helpers.sets(dataSingle)).toBe(`"val"=123,"msg"='test'`); + describe('without a ColumnSet', () => { + it('must create local ColumnSet', () => { + expect(helpers.sets(dataSingle)).toBe('"val"=123,"msg"=\'test\''); }); }); - describe(`without columns`, () => { - it(`must return an empty string`, () => { - const cs = new helpers.ColumnSet([`?val`, `?msg`]); - expect(helpers.sets(dataSingle, cs)).toBe(``); - expect(helpers.sets(dataSingle, [])).toBe(``); + describe('without columns', () => { + it('must return an empty string', () => { + const cs = new helpers.ColumnSet(['?val', '?msg']); + expect(helpers.sets(dataSingle, cs)).toBe(''); + expect(helpers.sets(dataSingle, [])).toBe(''); }); }); - describe(`Negative`, () => { - const error = `Invalid parameter 'data' specified.`; - it(`must throw when 'data' is not an object`, () => { + describe('Negative', () => { + const error = 'Invalid parameter \'data\' specified.'; + it('must throw when \'data\' is not an object', () => { expect(() => { helpers.sets(); }).toThrow(error); @@ -787,50 +787,50 @@ describe(`method 'sets'`, () => { }); }); -describe(`method 'values'`, () => { +describe('method \'values\'', () => { - describe(`with a ColumnSet`, () => { - it(`must reuse the ColumnSet`, () => { + describe('with a ColumnSet', () => { + it('must reuse the ColumnSet', () => { const cs = new helpers.ColumnSet(dataSingle); - expect(helpers.values(dataSingle, cs)).toBe(`(123,'test')`); + expect(helpers.values(dataSingle, cs)).toBe('(123,\'test\')'); }); - it(`must apply sql casting`, () => { - const cs = new helpers.ColumnSet([`val`, {name: `msg`, cast: `text`}]); - expect(helpers.values(dataSingle, cs)).toBe(`(123,'test'::text)`); + it('must apply sql casting', () => { + const cs = new helpers.ColumnSet(['val', {name: 'msg', cast: 'text'}]); + expect(helpers.values(dataSingle, cs)).toBe('(123,\'test\'::text)'); }); }); - describe(`without a ColumnSet`, () => { - it(`must create local ColumnSet`, () => { - expect(helpers.values(dataSingle)).toBe(`(123,'test')`); + describe('without a ColumnSet', () => { + it('must create local ColumnSet', () => { + expect(helpers.values(dataSingle)).toBe('(123,\'test\')'); }); }); - describe(`with an array of data`, () => { - it(`must return query for a single object`, () => { - expect(helpers.values(dataSingle)).toBe(`(123,'test')`); + describe('with an array of data', () => { + it('must return query for a single object', () => { + expect(helpers.values(dataSingle)).toBe('(123,\'test\')'); }); - it(`must return query for multiple objects`, () => { - expect(helpers.values(dataMulti, [`val`, `msg`])).toBe(`(123,'hello'),(456,'world')`); + it('must return query for multiple objects', () => { + expect(helpers.values(dataMulti, ['val', 'msg'])).toBe('(123,\'hello\'),(456,\'world\')'); }); - it(`must apply casting correctly`, () => { - expect(helpers.values(dataMulti, [`val`, { - name: `msg`, - cast: `text` - }])).toBe(`(123,'hello'::text),(456,'world'::text)`); + it('must apply casting correctly', () => { + expect(helpers.values(dataMulti, ['val', { + name: 'msg', + cast: 'text' + }])).toBe('(123,\'hello\'::text),(456,\'world\'::text)'); }); }); - describe(`with an empty data array`, () => { - it(`must return an empty string`, () => { + describe('with an empty data array', () => { + it('must return an empty string', () => { const cs = new helpers.ColumnSet(dataSingle); - expect(helpers.values([], cs)).toBe(``); + expect(helpers.values([], cs)).toBe(''); }); }); - describe(`Negative`, () => { - it(`must throw when 'data' is not valid`, () => { - const error = `Invalid parameter 'data' specified.`; + describe('Negative', () => { + it('must throw when \'data\' is not valid', () => { + const error = 'Invalid parameter \'data\' specified.'; expect(() => { helpers.values(); }).toThrow(error); @@ -841,34 +841,34 @@ describe(`method 'values'`, () => { helpers.values(123); }).toThrow(error); }); - it(`must throw when there are no columns`, () => { - const error = `Cannot generate values without any columns.`; + it('must throw when there are no columns', () => { + const error = 'Cannot generate values without any columns.'; expect(() => { helpers.values(dataSingle, []); }).toThrow(error); }); - it(`must throw when no columns for an array`, () => { - const error = `Parameter 'columns' is required when generating multi-row values.`; + it('must throw when no columns for an array', () => { + const error = 'Parameter \'columns\' is required when generating multi-row values.'; expect(() => { helpers.values([{}]); }).toThrow(error); }); - it(`must throw on invalid data object`, () => { - const error = `Invalid object at index 0.`; + it('must throw on invalid data object', () => { + const error = 'Invalid object at index 0.'; expect(() => { - helpers.values([null], [`val`]); + helpers.values([null], ['val']); }).toThrow(error); expect(() => { - helpers.values([123], [`val`]); + helpers.values([123], ['val']); }).toThrow(error); }); }); }); -describe(`method 'concat'`, () => { - describe(`Negative`, () => { - it(`must throw on a non-array input`, () => { - const error = `Parameter 'queries' must be an array.`; +describe('method \'concat\'', () => { + describe('Negative', () => { + it('must throw on a non-array input', () => { + const error = 'Parameter \'queries\' must be an array.'; expect(() => { helpers.concat(); }).toThrow(error); @@ -876,8 +876,8 @@ describe(`method 'concat'`, () => { helpers.concat(123); }).toThrow(error); }); - it(`must throw on invalid elements inside array`, () => { - const error = new Error(`Invalid query element at index 0.`); + it('must throw on invalid elements inside array', () => { + const error = new Error('Invalid query element at index 0.'); expect(() => { helpers.concat([1]); }).toThrow(error); @@ -887,42 +887,42 @@ describe(`method 'concat'`, () => { }); }); - describe(`Positive`, () => { - describe(`with simple strings`, () => { - it(`must allow an empty array`, () => { - expect(helpers.concat([])).toBe(``); + describe('Positive', () => { + describe('with simple strings', () => { + it('must allow an empty array', () => { + expect(helpers.concat([])).toBe(''); }); - it(`must remove symbols correctly`, () => { - expect(helpers.concat([`one`, `two`])).toBe(`one;two`); // normal - expect(helpers.concat([`\t;;one;\t;`, ` two ;;\t\t`])).toBe(`one;two`); - expect(helpers.concat([`\t;;one;\t;here `, ` two ;;\t\t`])).toBe(`one;\t;here;two`); + it('must remove symbols correctly', () => { + expect(helpers.concat(['one', 'two'])).toBe('one;two'); // normal + expect(helpers.concat(['\t;;one;\t;', ' two ;;\t\t'])).toBe('one;two'); + expect(helpers.concat(['\t;;one;\t;here ', ' two ;;\t\t'])).toBe('one;\t;here;two'); }); }); - describe(`with QueryFile`, () => { - it(`must support mixed types correctly`, () => { - const qf = new QueryFile(path.join(__dirname, `./sql/allUsers.sql`), {minify: true, noWarnings: true}); - expect(helpers.concat([`one`, {query: `two`}, qf])).toBe(`one;two;select * from users`); + describe('with QueryFile', () => { + it('must support mixed types correctly', () => { + const qf = new QueryFile(path.join(__dirname, './sql/allUsers.sql'), {minify: true, noWarnings: true}); + expect(helpers.concat(['one', {query: 'two'}, qf])).toBe('one;two;select * from users'); }); }); - describe(`with formatting options`, () => { - it(`must format parameters correctly`, () => { + describe('with formatting options', () => { + it('must format parameters correctly', () => { expect(helpers.concat([{ - query: `$1^, $2^, $3^`, - values: [`a`, [1, 2]], + query: '$1^, $2^, $3^', + values: ['a', [1, 2]], options: { partial: true, capSQL: true } - }])).toBe(`a, ARRAY[1,2], $3^`); + }])).toBe('a, ARRAY[1,2], $3^'); }); }); - describe(`with empty queries`, () => { - it(`must skip them`, () => { - expect(helpers.concat([``, ``, ``])).toBe(``); + describe('with empty queries', () => { + it('must skip them', () => { + expect(helpers.concat(['', '', ''])).toBe(''); - expect(helpers.concat([`;\t\t;;;`, { - query: `; $1^ ; $2^ ;;;\t`, values: [` `, `\t\t\t`] - }])).toBe(``); + expect(helpers.concat([';\t\t;;;', { + query: '; $1^ ; $2^ ;;;\t', values: [' ', '\t\t\t'] + }])).toBe(''); }); }); }); diff --git a/test/parameterized.spec.js b/test/parameterized.spec.js index 1ac1d2971..fa1266a10 100644 --- a/test/parameterized.spec.js +++ b/test/parameterized.spec.js @@ -1,6 +1,6 @@ -const path = require(`path`); -const header = require(`./db/header`); -const tools = require(`./db/tools`); +const path = require('path'); +const header = require('./db/header'); +const tools = require('./db/tools'); const promise = header.defPromise; const options = { @@ -13,82 +13,82 @@ const db = dbHeader.db; const ParameterizedQueryError = pgp.errors.ParameterizedQueryError; -describe(`ParameterizedQuery`, () => { +describe('ParameterizedQuery', () => { - describe(`parameter-object initialization`, () => { - it(`must initialize correctly`, () => { - const pq1 = new pgp.ParameterizedQuery({text: `test-query`, values: [123]}); - const pq2 = new pgp.ParameterizedQuery({text: `test-query`, values: []}); - expect(pq1.parse()).toEqual({text: `test-query`, values: [123]}); - expect(pq2.parse()).toEqual({text: `test-query`}); + describe('parameter-object initialization', () => { + it('must initialize correctly', () => { + const pq1 = new pgp.ParameterizedQuery({text: 'test-query', values: [123]}); + const pq2 = new pgp.ParameterizedQuery({text: 'test-query', values: []}); + expect(pq1.parse()).toEqual({text: 'test-query', values: [123]}); + expect(pq2.parse()).toEqual({text: 'test-query'}); }); }); - describe(`property values`, () => { + describe('property values', () => { const values = [1, 2, 3]; - it(`must get correctly`, () => { + it('must get correctly', () => { const pq = new pgp.ParameterizedQuery({ - text: `original-sql`, + text: 'original-sql', values, binary: true, - rowMode: `array` + rowMode: 'array' }); - expect(pq.text).toBe(`original-sql`); + expect(pq.text).toBe('original-sql'); expect(pq.values).toBe(values); expect(pq.binary).toBe(true); - expect(pq.rowMode).toBe(`array`); + expect(pq.rowMode).toBe('array'); expect(tools.inspect(pq)).toBe(pq.toString()); }); - it(`must keep original object when set to the same value`, () => { + it('must keep original object when set to the same value', () => { const pq = new pgp.ParameterizedQuery({ - text: `original-sql`, + text: 'original-sql', values, binary: true, - rowMode: `array` + rowMode: 'array' }); const obj1 = pq.parse(); - pq.text = `original-sql`; + pq.text = 'original-sql'; pq.values = values; pq.binary = true; - pq.rowMode = `array`; + pq.rowMode = 'array'; const obj2 = pq.parse(); expect(obj1 === obj2).toBe(true); expect(tools.inspect(pq)).toBe(pq.toString()); }); - it(`must create a new object when changed`, () => { + it('must create a new object when changed', () => { const pq = new pgp.ParameterizedQuery({ - text: `original-sql`, + text: 'original-sql', values, binary: true, - rowMode: `array` + rowMode: 'array' }); const obj1 = pq.parse(); - pq.text = `new text`; + pq.text = 'new text'; const obj2 = pq.parse(); pq.values = [1, 2, 3]; const obj3 = pq.parse(); pq.binary = false; const obj4 = pq.parse(); - pq.rowMode = `new`; + pq.rowMode = 'new'; const obj5 = pq.parse(); expect(obj1 !== obj2 !== obj3 !== obj4 != obj5).toBe(true); expect(tools.inspect(pq)).toBe(pq.toString()); }); }); - describe(`parameters`, () => { - const pq = new pgp.ParameterizedQuery({text: `test-query`, values: [123], binary: true, rowMode: `array`}); - it(`must expose the values correctly`, () => { - expect(pq.text).toBe(`test-query`); + describe('parameters', () => { + const pq = new pgp.ParameterizedQuery({text: 'test-query', values: [123], binary: true, rowMode: 'array'}); + it('must expose the values correctly', () => { + expect(pq.text).toBe('test-query'); expect(pq.values).toEqual([123]); expect(pq.binary).toBe(true); - expect(pq.rowMode).toBe(`array`); + expect(pq.rowMode).toBe('array'); }); }); - describe(`valid, without parameters`, () => { + describe('valid, without parameters', () => { let result; - const pq = new pgp.ParameterizedQuery(`select 1 as value`); + const pq = new pgp.ParameterizedQuery('select 1 as value'); beforeEach(done => { db.one(pq) .then(data => { @@ -96,16 +96,16 @@ describe(`ParameterizedQuery`, () => { }) .finally(done); }); - it(`must return the right value`, () => { + it('must return the right value', () => { expect(result && result.value === 1).toBeTruthy(); }); }); - describe(`valid, with parameters`, () => { + describe('valid, with parameters', () => { let result; const pq = new pgp.ParameterizedQuery({ - text: `select count(*) from users where login = $1`, - values: [`non-existing`] + text: 'select count(*) from users where login = $1', + values: ['non-existing'] }); beforeEach(done => { db.one(pq) @@ -114,51 +114,51 @@ describe(`ParameterizedQuery`, () => { }) .finally(done); }); - it(`must return the right value`, () => { - expect(result && typeof result === `object`).toBeTruthy(); - expect(result.count).toBe(`0`); + it('must return the right value', () => { + expect(result && typeof result === 'object').toBeTruthy(); + expect(result.count).toBe('0'); }); }); - describe(`valid, with parameters override`, () => { + describe('valid, with parameters override', () => { let result; beforeEach(done => { db.one({ - text: `select * from users where id = $1` + text: 'select * from users where id = $1' }, 1) .then(data => { result = data; }) .finally(done); }); - it(`must return one user`, () => { - expect(result && typeof result === `object`).toBeTruthy(); + it('must return one user', () => { + expect(result && typeof result === 'object').toBeTruthy(); }); }); - describe(`object inspection`, () => { - const pq1 = new pgp.ParameterizedQuery(`test-query $1`); - const pq2 = new pgp.ParameterizedQuery(`test-query $1`, []); - it(`must stringify all values`, () => { + describe('object inspection', () => { + const pq1 = new pgp.ParameterizedQuery('test-query $1'); + const pq2 = new pgp.ParameterizedQuery('test-query $1', []); + it('must stringify all values', () => { expect(tools.inspect(pq1)).toBe(pq1.toString()); expect(tools.inspect(pq2)).toBe(pq2.toString()); }); }); - describe(`with QueryFile`, () => { + describe('with QueryFile', () => { - describe(`successful`, () => { - const f = path.join(__dirname, `./sql/simple.sql`); + describe('successful', () => { + const f = path.join(__dirname, './sql/simple.sql'); const qf = new pgp.QueryFile(f, {compress: true, noWarnings: true}); const pq = new pgp.ParameterizedQuery(qf); const result = pq.parse(); - expect(result && typeof result === `object`).toBeTruthy(); - expect(result.text).toBe(`select 1;`); + expect(result && typeof result === 'object').toBeTruthy(); + expect(result.text).toBe('select 1;'); expect(pq.toString()).toBe(tools.inspect(pq)); }); - describe(`with an error`, () => { - const qf = new pgp.QueryFile(`./invalid.sql`); + describe('with an error', () => { + const qf = new pgp.QueryFile('./invalid.sql'); const pq = new pgp.ParameterizedQuery(qf); const result = pq.parse(); expect(result instanceof ParameterizedQueryError).toBe(true); @@ -171,30 +171,30 @@ describe(`ParameterizedQuery`, () => { }); -describe(`Direct Parameterized Query`, () => { +describe('Direct Parameterized Query', () => { - describe(`valid, without parameters`, () => { + describe('valid, without parameters', () => { let result; beforeEach(done => { db.many({ - text: `select * from users` + text: 'select * from users' }) .then(data => { result = data; }) .finally(done); }); - it(`must return all users`, () => { + it('must return all users', () => { expect(Array.isArray(result)).toBe(true); expect(result.length > 0).toBe(true); }); }); - describe(`valid, with parameters`, () => { + describe('valid, with parameters', () => { let result; beforeEach(done => { db.one({ - text: `select * from users where id=$1`, + text: 'select * from users where id=$1', values: [1] }) .then(data => { @@ -202,29 +202,29 @@ describe(`Direct Parameterized Query`, () => { }) .finally(done); }); - it(`must return all users`, () => { - expect(result && typeof result === `object`).toBeTruthy(); + it('must return all users', () => { + expect(result && typeof result === 'object').toBeTruthy(); }); }); - describe(`with invalid query`, () => { + describe('with invalid query', () => { let result; beforeEach(done => { db.many({ - text: `select * from somewhere` + text: 'select * from somewhere' }) .catch(reason => { result = reason; }) .finally(done); }); - it(`must return an error`, () => { + it('must return an error', () => { expect(result instanceof Error).toBe(true); - expect(result.message).toContain(`relation "somewhere" does not exist`); + expect(result.message).toContain('relation "somewhere" does not exist'); }); }); - describe(`with an empty 'text'`, () => { + describe('with an empty \'text\'', () => { let result; beforeEach(done => { db.query({ @@ -235,7 +235,7 @@ describe(`Direct Parameterized Query`, () => { }) .finally(done); }); - it(`must return an error`, () => { + it('must return an error', () => { expect(result instanceof pgp.errors.ParameterizedQueryError).toBe(true); expect(result.toString()).toBe(tools.inspect(result)); }); diff --git a/test/prepared.spec.js b/test/prepared.spec.js index e68d206f3..5afc0d864 100644 --- a/test/prepared.spec.js +++ b/test/prepared.spec.js @@ -1,6 +1,6 @@ -const path = require(`path`); -const header = require(`./db/header`); -const tools = require(`./db/tools`); +const path = require('path'); +const header = require('./db/header'); +const tools = require('./db/tools'); const promise = header.defPromise; const options = { @@ -13,73 +13,73 @@ const db = dbHeader.db; const PreparedStatementError = pgp.errors.PreparedStatementError; -describe(`PreparedStatement`, () => { +describe('PreparedStatement', () => { - describe(`parameter-object initialization`, () => { - it(`must initialize correctly`, () => { - const ps = new pgp.PreparedStatement({name: `test-name`, text: `test-query`, values: [123]}); - expect(ps.parse()).toEqual({name: `test-name`, text: `test-query`, values: [123]}); + describe('parameter-object initialization', () => { + it('must initialize correctly', () => { + const ps = new pgp.PreparedStatement({name: 'test-name', text: 'test-query', values: [123]}); + expect(ps.parse()).toEqual({name: 'test-name', text: 'test-query', values: [123]}); }); }); - describe(`property values`, () => { + describe('property values', () => { const values = [1, 2, 3]; - it(`must get correctly`, () => { + it('must get correctly', () => { const ps = new pgp.PreparedStatement({ - name: `original-name`, - text: `original-sql`, + name: 'original-name', + text: 'original-sql', values, binary: true, - rowMode: `array`, + rowMode: 'array', rows: 1 }); - expect(ps.name).toBe(`original-name`); - expect(ps.text).toBe(`original-sql`); + expect(ps.name).toBe('original-name'); + expect(ps.text).toBe('original-sql'); expect(ps.values).toBe(values); expect(ps.binary).toBe(true); - expect(ps.rowMode).toBe(`array`); + expect(ps.rowMode).toBe('array'); expect(ps.rows).toBe(1); expect(tools.inspect(ps)).toBe(ps.toString()); }); - it(`must keep original object when set to the same value`, () => { + it('must keep original object when set to the same value', () => { const ps = new pgp.PreparedStatement({ - name: `original-name`, - text: `original-sql`, + name: 'original-name', + text: 'original-sql', values, binary: true, - rowMode: `array`, + rowMode: 'array', rows: 1 }); const obj1 = ps.parse(); - ps.name = `original-name`; - ps.text = `original-sql`; + ps.name = 'original-name'; + ps.text = 'original-sql'; ps.values = values; ps.binary = true; - ps.rowMode = `array`; + ps.rowMode = 'array'; ps.rows = 1; const obj2 = ps.parse(); expect(obj1 === obj2).toBe(true); expect(tools.inspect(ps)).toBe(ps.toString()); }); - it(`must create a new object when changed`, () => { + it('must create a new object when changed', () => { const ps = new pgp.PreparedStatement({ - name: `original-name`, - text: `original-sql`, + name: 'original-name', + text: 'original-sql', values, binary: true, - rowMode: `array`, + rowMode: 'array', rows: 1 }); const obj1 = ps.parse(); - ps.name = `new value`; + ps.name = 'new value'; const obj2 = ps.parse(); - ps.text = `new text`; + ps.text = 'new text'; const obj3 = ps.parse(); ps.values = [1, 2, 3]; const obj4 = ps.parse(); ps.binary = false; const obj5 = ps.parse(); - ps.rowMode = `new`; + ps.rowMode = 'new'; const obj6 = ps.parse(); ps.rows = 3; const obj7 = ps.parse(); @@ -88,29 +88,29 @@ describe(`PreparedStatement`, () => { }); }); - describe(`parameters`, () => { - const ps = new pgp.PreparedStatement({name: `test-name`, text: `test-query`, values: [123]}); - it(`must expose the values correctly`, () => { - expect(ps.name).toBe(`test-name`); - expect(ps.text).toBe(`test-query`); + describe('parameters', () => { + const ps = new pgp.PreparedStatement({name: 'test-name', text: 'test-query', values: [123]}); + it('must expose the values correctly', () => { + expect(ps.name).toBe('test-name'); + expect(ps.text).toBe('test-query'); expect(ps.values).toEqual([123]); // setting to the same values, for coverage: ps.name = ps.name; // eslint-disable-line ps.text = ps.text; // eslint-disable-line }); - it(`must set the values correctly`, () => { - ps.name = `new-name`; - ps.text = `new-query`; + it('must set the values correctly', () => { + ps.name = 'new-name'; + ps.text = 'new-query'; ps.values = [456]; - expect(ps.name).toBe(`new-name`); - expect(ps.text).toBe(`new-query`); + expect(ps.name).toBe('new-name'); + expect(ps.text).toBe('new-query'); expect(ps.values).toEqual([456]); }); }); - describe(`valid, without parameters`, () => { + describe('valid, without parameters', () => { let result; - const ps = new pgp.PreparedStatement({name: `test-1`, text: `select 1 as value`}); + const ps = new pgp.PreparedStatement({name: 'test-1', text: 'select 1 as value'}); beforeEach(done => { db.one(ps) .then(data => { @@ -118,17 +118,17 @@ describe(`PreparedStatement`, () => { }) .finally(done); }); - it(`must return the right value`, () => { + it('must return the right value', () => { expect(result && result.value === 1).toBeTruthy(); }); }); - describe(`valid, with parameters`, () => { + describe('valid, with parameters', () => { let result; const ps = new pgp.PreparedStatement({ - name: `test-2`, - text: `select count(*) from users where login = $1`, - values: [`non-existing`] + name: 'test-2', + text: 'select count(*) from users where login = $1', + values: ['non-existing'] }); beforeEach(done => { db.one(ps) @@ -137,37 +137,37 @@ describe(`PreparedStatement`, () => { }) .finally(done); }); - it(`must return the right value`, () => { - expect(result && typeof result === `object`).toBeTruthy(); - expect(result.count).toBe(`0`); + it('must return the right value', () => { + expect(result && typeof result === 'object').toBeTruthy(); + expect(result.count).toBe('0'); }); }); - describe(`object inspection`, () => { - const ps1 = new pgp.PreparedStatement({name: `test-name`, text: `test-query $1`}); - const ps2 = new pgp.PreparedStatement({name: `test-name`, text: `test-query $1`, values: [123]}); - it(`must stringify all values`, () => { + describe('object inspection', () => { + const ps1 = new pgp.PreparedStatement({name: 'test-name', text: 'test-query $1'}); + const ps2 = new pgp.PreparedStatement({name: 'test-name', text: 'test-query $1', values: [123]}); + it('must stringify all values', () => { expect(tools.inspect(ps1)).toBe(ps1.toString()); expect(tools.inspect(ps2)).toBe(ps2.toString()); }); }); - describe(`with QueryFile`, () => { + describe('with QueryFile', () => { - describe(`successful`, () => { - const f = path.join(__dirname, `./sql/simple.sql`); + describe('successful', () => { + const f = path.join(__dirname, './sql/simple.sql'); const qf = new pgp.QueryFile(f, {compress: true, noWarnings: true}); - const ps = new pgp.PreparedStatement({name: `test-name`, text: qf}); + const ps = new pgp.PreparedStatement({name: 'test-name', text: qf}); const result = ps.parse(); - expect(result && typeof result === `object`).toBeTruthy(); - expect(result.name).toBe(`test-name`); - expect(result.text).toBe(`select 1;`); + expect(result && typeof result === 'object').toBeTruthy(); + expect(result.name).toBe('test-name'); + expect(result.text).toBe('select 1;'); expect(ps.toString()).toBe(tools.inspect(ps)); }); - describe(`with error`, () => { - const qf = new pgp.QueryFile(`./invalid.sql`, {noWarnings: true}); - const ps = new pgp.PreparedStatement({name: `test-name`, text: qf}); + describe('with error', () => { + const qf = new pgp.QueryFile('./invalid.sql', {noWarnings: true}); + const ps = new pgp.PreparedStatement({name: 'test-name', text: qf}); const result = ps.parse(); expect(result instanceof pgp.errors.PreparedStatementError).toBe(true); expect(result.error instanceof pgp.errors.QueryFileError).toBe(true); @@ -177,14 +177,14 @@ describe(`PreparedStatement`, () => { }); -describe(`Direct Prepared Statements`, () => { +describe('Direct Prepared Statements', () => { - describe(`valid, without parameters`, () => { + describe('valid, without parameters', () => { let result; beforeEach(done => { db.many({ - name: `get all users`, - text: `select * from users`, + name: 'get all users', + text: 'select * from users', values: [] }) .then(data => { @@ -192,18 +192,18 @@ describe(`Direct Prepared Statements`, () => { }) .finally(done); }); - it(`must return all users`, () => { + it('must return all users', () => { expect(Array.isArray(result)).toBe(true); expect(result.length > 0).toBe(true); }); }); - describe(`valid, with parameters`, () => { + describe('valid, with parameters', () => { let result; beforeEach(done => { db.one({ - name: `find one user`, - text: `select * from users where id=$1`, + name: 'find one user', + text: 'select * from users where id=$1', values: [1] }) .then(data => { @@ -211,49 +211,49 @@ describe(`Direct Prepared Statements`, () => { }) .finally(done); }); - it(`must return one user`, () => { - expect(result && typeof result === `object`).toBeTruthy(); + it('must return one user', () => { + expect(result && typeof result === 'object').toBeTruthy(); }); }); - describe(`valid, with parameters override`, () => { + describe('valid, with parameters override', () => { let result; beforeEach(done => { db.one({ - name: `find one user`, - text: `select * from users where id=$1` + name: 'find one user', + text: 'select * from users where id=$1' }, 1) .then(data => { result = data; }) .finally(done); }); - it(`must return one user`, () => { - expect(result && typeof result === `object`).toBeTruthy(); + it('must return one user', () => { + expect(result && typeof result === 'object').toBeTruthy(); }); }); - describe(`with invalid query`, () => { + describe('with invalid query', () => { let result; beforeEach(done => { db.many({ - name: `break it`, - text: `select * from somewhere` + name: 'break it', + text: 'select * from somewhere' }) .catch(reason => { result = reason; }) .finally(done); }); - it(`must return an error`, () => { + it('must return an error', () => { expect(result instanceof Error).toBe(true); - expect(result.message).toContain(`relation "somewhere" does not exist`); + expect(result.message).toContain('relation "somewhere" does not exist'); }); }); - describe(`with an empty 'name'`, () => { + describe('with an empty \'name\'', () => { let result; - const ps = new pgp.PreparedStatement({name: ``, text: `non-empty`}); + const ps = new pgp.PreparedStatement({name: '', text: 'non-empty'}); beforeEach(done => { db.query(ps) .catch(reason => { @@ -261,18 +261,18 @@ describe(`Direct Prepared Statements`, () => { }) .finally(done); }); - it(`must return an error`, () => { + it('must return an error', () => { expect(result instanceof PreparedStatementError).toBe(true); expect(ps.toString(1) != tools.inspect(ps)).toBe(true); expect(result.toString()).toBe(tools.inspect(result)); }); }); - describe(`with an empty 'text'`, () => { + describe('with an empty \'text\'', () => { let result; beforeEach(done => { db.query({ - name: `non-empty`, + name: 'non-empty', text: null }) .catch(reason => { @@ -280,7 +280,7 @@ describe(`Direct Prepared Statements`, () => { }) .finally(done); }); - it(`must return an error`, () => { + it('must return an error', () => { expect(result instanceof PreparedStatementError).toBe(true); }); }); diff --git a/test/protocol.spec.js b/test/protocol.spec.js index 80f7b9ae6..eca5d4a62 100644 --- a/test/protocol.spec.js +++ b/test/protocol.spec.js @@ -1,13 +1,13 @@ -const PG = require(`pg`); -const header = require(`./db/header`); -const tools = require(`./db/tools`); +const PG = require('pg'); +const header = require('./db/header'); +const tools = require('./db/tools'); const promise = header.defPromise; const options = { promiseLib: promise, noWarnings: true }; -const testDC = `test_DC_123`; +const testDC = 'test_DC_123'; const dbHeader = header(options, testDC); const pgpLib = dbHeader.pgpLib; const pgp = dbHeader.pgp; @@ -17,18 +17,18 @@ function dummy() { } -describe(`Library instance`, () => { +describe('Library instance', () => { - it(`must NOT have property 'pg'`, () => { + it('must NOT have property \'pg\'', () => { expect(pgpLib.pg).toBeUndefined(); }); - it(`must NOT have function 'end'`, () => { + it('must NOT have function \'end\'', () => { expect(pgpLib.end).toBeUndefined(); }); - it(`must have valid property 'as'`, () => { - expect(pgpLib.as && typeof pgpLib.as === `object`).toBeTruthy(); + it('must have valid property \'as\'', () => { + expect(pgpLib.as && typeof pgpLib.as === 'object').toBeTruthy(); expect(pgpLib.as.text instanceof Function).toBe(true); expect(pgpLib.as.bool instanceof Function).toBe(true); expect(pgpLib.as.date instanceof Function).toBe(true); @@ -44,7 +44,7 @@ describe(`Library instance`, () => { expect(pgpLib.as.buffer instanceof Function).toBe(true); }); - it(`must have all error types`, () => { + it('must have all error types', () => { expect(pgp.errors && pgp.errors instanceof Object).toBeTruthy(); expect(pgpLib.errors.QueryResultError instanceof Function).toBe(true); expect(pgpLib.errors.queryResultErrorCode instanceof Object).toBe(true); @@ -52,24 +52,24 @@ describe(`Library instance`, () => { expect(pgpLib.errors.ParameterizedQueryError instanceof Function).toBe(true); }); - it(`must have function 'PromiseAdapter'`, () => { + it('must have function \'PromiseAdapter\'', () => { expect(pgpLib.PromiseAdapter instanceof Function).toBe(true); }); - it(`must have function 'PreparedStatement'`, () => { + it('must have function \'PreparedStatement\'', () => { expect(pgpLib.PreparedStatement instanceof Function).toBe(true); }); - it(`must have function 'ParameterizedQuery'`, () => { + it('must have function \'ParameterizedQuery\'', () => { expect(pgpLib.ParameterizedQuery instanceof Function).toBe(true); }); - it(`must have function 'minify'`, () => { + it('must have function \'minify\'', () => { expect(pgpLib.minify instanceof Function).toBe(true); }); - it(`must have valid property 'queryResult'`, () => { - expect(pgpLib.queryResult && typeof pgpLib.queryResult === `object`).toBeTruthy(); + it('must have valid property \'queryResult\'', () => { + expect(pgpLib.queryResult && typeof pgpLib.queryResult === 'object').toBeTruthy(); expect(pgpLib.queryResult.one).toBe(1); expect(pgpLib.queryResult.many).toBe(2); expect(pgpLib.queryResult.none).toBe(4); @@ -78,26 +78,26 @@ describe(`Library instance`, () => { }); -describe(`Initialized instance`, () => { +describe('Initialized instance', () => { - it(`must have valid property 'pg'`, () => { + it('must have valid property \'pg\'', () => { if (options.pgNative) { - expect(typeof pgp.pg).toBe(`object`); + expect(typeof pgp.pg).toBe('object'); } else { expect(pgp.pg).toBe(PG); } }); - it(`must have function 'end'`, () => { + it('must have function \'end\'', () => { expect(pgp.end instanceof Function).toBe(true); }); - it(`must have valid property 'as'`, () => { - expect(pgp.as && typeof pgp.as === `object`).toBeTruthy(); + it('must have valid property \'as\'', () => { + expect(pgp.as && typeof pgp.as === 'object').toBeTruthy(); expect(pgp.as).toBe(pgpLib.as); }); - it(`must have all error types`, () => { + it('must have all error types', () => { expect(pgp.errors && pgp.errors instanceof Object).toBeTruthy(); expect(pgp.errors.QueryResultError instanceof Function).toBe(true); expect(pgp.errors.queryResultErrorCode instanceof Object).toBe(true); @@ -105,52 +105,52 @@ describe(`Initialized instance`, () => { expect(pgp.errors.ParameterizedQueryError instanceof Function).toBe(true); }); - it(`must have function 'PromiseAdapter'`, () => { + it('must have function \'PromiseAdapter\'', () => { expect(pgp.PromiseAdapter instanceof Function).toBe(true); }); - it(`must have function 'PreparedStatement'`, () => { + it('must have function \'PreparedStatement\'', () => { expect(pgp.PreparedStatement instanceof Function).toBe(true); }); - it(`must have function 'ParameterizedQuery'`, () => { + it('must have function \'ParameterizedQuery\'', () => { expect(pgp.ParameterizedQuery instanceof Function).toBe(true); }); - it(`must have function 'minify'`, () => { + it('must have function \'minify\'', () => { expect(pgp.minify instanceof Function).toBe(true); }); - it(`must have valid property 'queryResult'`, () => { - expect(pgp.queryResult && typeof pgp.queryResult === `object`).toBeTruthy(); + it('must have valid property \'queryResult\'', () => { + expect(pgp.queryResult && typeof pgp.queryResult === 'object').toBeTruthy(); expect(pgp.queryResult).toBe(pgpLib.queryResult); }); }); -describe(`Database Protocol`, () => { - - it(`must have all the root-level methods`, () => { - expect(typeof db.connect).toBe(`function`); - expect(typeof db.task).toBe(`function`); - expect(typeof db.taskIf).toBe(`function`); - expect(typeof db.query).toBe(`function`); - expect(typeof db.result).toBe(`function`); - expect(typeof db.tx).toBe(`function`); - expect(typeof db.txIf).toBe(`function`); - expect(typeof db.one).toBe(`function`); - expect(typeof db.many).toBe(`function`); - expect(typeof db.any).toBe(`function`); - expect(typeof db.none).toBe(`function`); - expect(typeof db.oneOrNone).toBe(`function`); - expect(typeof db.manyOrNone).toBe(`function`); - expect(typeof db.stream).toBe(`function`); - expect(typeof db.func).toBe(`function`); - expect(typeof db.proc).toBe(`function`); - expect(typeof db.map).toBe(`function`); - expect(typeof db.each).toBe(`function`); - expect(typeof db.multi).toBe(`function`); - expect(typeof db.multiResult).toBe(`function`); +describe('Database Protocol', () => { + + it('must have all the root-level methods', () => { + expect(typeof db.connect).toBe('function'); + expect(typeof db.task).toBe('function'); + expect(typeof db.taskIf).toBe('function'); + expect(typeof db.query).toBe('function'); + expect(typeof db.result).toBe('function'); + expect(typeof db.tx).toBe('function'); + expect(typeof db.txIf).toBe('function'); + expect(typeof db.one).toBe('function'); + expect(typeof db.many).toBe('function'); + expect(typeof db.any).toBe('function'); + expect(typeof db.none).toBe('function'); + expect(typeof db.oneOrNone).toBe('function'); + expect(typeof db.manyOrNone).toBe('function'); + expect(typeof db.stream).toBe('function'); + expect(typeof db.func).toBe('function'); + expect(typeof db.proc).toBe('function'); + expect(typeof db.map).toBe('function'); + expect(typeof db.each).toBe('function'); + expect(typeof db.multi).toBe('function'); + expect(typeof db.multiResult).toBe('function'); // must not have task-level methods: expect(db.batch).toBeUndefined(); @@ -162,22 +162,22 @@ describe(`Database Protocol`, () => { expect(db.client).toBeUndefined(); // must have a hidden configurator; - expect(db.$config && typeof db.$config === `object`).toBeTruthy(); - expect(typeof db.$config.promise).toBe(`function`); - expect(typeof db.$config.promise.resolve).toBe(`function`); - expect(typeof db.$config.promise.reject).toBe(`function`); - expect(typeof db.$config.promise.all).toBe(`function`); + expect(db.$config && typeof db.$config === 'object').toBeTruthy(); + expect(typeof db.$config.promise).toBe('function'); + expect(typeof db.$config.promise.resolve).toBe('function'); + expect(typeof db.$config.promise.reject).toBe('function'); + expect(typeof db.$config.promise.all).toBe('function'); expect(db.$config.promiseLib).toBeTruthy(); - expect(typeof db.$config.options).toBe(`object`); - expect(typeof db.$config.pgp).toBe(`function`); - expect(typeof db.$config.version).toBe(`string`); - expect(typeof db.$config.$npm).toBe(`object`); + expect(typeof db.$config.options).toBe('object'); + expect(typeof db.$config.pgp).toBe('function'); + expect(typeof db.$config.version).toBe('string'); + expect(typeof db.$config.$npm).toBe('object'); expect(db.$cn).toBe(dbHeader.cn); - expect(`$dc` in db).toBe(true); - expect(db.$pool && db.$pool.constructor && db.$pool.constructor.name).toBe(`BoundPool`); + expect('$dc' in db).toBe(true); + expect(db.$pool && db.$pool.constructor && db.$pool.constructor.name).toBe('BoundPool'); }); - describe(`on connection level`, () => { + describe('on connection level', () => { let connection; beforeEach(done => { @@ -191,42 +191,42 @@ describe(`Database Protocol`, () => { }); }); - it(`must have all the required methods`, () => { - expect(connection && typeof connection === `object`).toBe(true); + it('must have all the required methods', () => { + expect(connection && typeof connection === 'object').toBe(true); expect(connection.connect).toBeUndefined(); - expect(typeof connection.query).toBe(`function`); - expect(typeof connection.result).toBe(`function`); - expect(typeof connection.task).toBe(`function`); - expect(typeof connection.taskIf).toBe(`function`); - expect(typeof connection.tx).toBe(`function`); - expect(typeof connection.txIf).toBe(`function`); - expect(typeof connection.one).toBe(`function`); - expect(typeof connection.many).toBe(`function`); - expect(typeof connection.any).toBe(`function`); - expect(typeof connection.none).toBe(`function`); - expect(typeof connection.oneOrNone).toBe(`function`); - expect(typeof connection.manyOrNone).toBe(`function`); - expect(typeof connection.stream).toBe(`function`); - expect(typeof connection.func).toBe(`function`); - expect(typeof connection.proc).toBe(`function`); - expect(typeof connection.map).toBe(`function`); - expect(typeof connection.each).toBe(`function`); - expect(typeof connection.done).toBe(`function`); - expect(typeof connection.batch).toBe(`function`); - expect(typeof connection.page).toBe(`function`); - expect(typeof connection.sequence).toBe(`function`); - expect(typeof connection.client).toBe(`object`); - expect(typeof connection.multi).toBe(`function`); - expect(typeof connection.multiResult).toBe(`function`); - - expect(`$config` in connection).toBe(false); - expect(`$cn` in connection).toBe(false); - expect(`$dc` in connection).toBe(false); - expect(`$pool` in connection).toBe(false); + expect(typeof connection.query).toBe('function'); + expect(typeof connection.result).toBe('function'); + expect(typeof connection.task).toBe('function'); + expect(typeof connection.taskIf).toBe('function'); + expect(typeof connection.tx).toBe('function'); + expect(typeof connection.txIf).toBe('function'); + expect(typeof connection.one).toBe('function'); + expect(typeof connection.many).toBe('function'); + expect(typeof connection.any).toBe('function'); + expect(typeof connection.none).toBe('function'); + expect(typeof connection.oneOrNone).toBe('function'); + expect(typeof connection.manyOrNone).toBe('function'); + expect(typeof connection.stream).toBe('function'); + expect(typeof connection.func).toBe('function'); + expect(typeof connection.proc).toBe('function'); + expect(typeof connection.map).toBe('function'); + expect(typeof connection.each).toBe('function'); + expect(typeof connection.done).toBe('function'); + expect(typeof connection.batch).toBe('function'); + expect(typeof connection.page).toBe('function'); + expect(typeof connection.sequence).toBe('function'); + expect(typeof connection.client).toBe('object'); + expect(typeof connection.multi).toBe('function'); + expect(typeof connection.multiResult).toBe('function'); + + expect('$config' in connection).toBe(false); + expect('$cn' in connection).toBe(false); + expect('$dc' in connection).toBe(false); + expect('$pool' in connection).toBe(false); }); }); - describe(`on transaction level`, () => { + describe('on transaction level', () => { let protocol; beforeEach(done => { @@ -237,37 +237,37 @@ describe(`Database Protocol`, () => { .finally(done); }); - it(`must have all the required methods`, () => { - expect(protocol && typeof protocol === `object`).toBe(true); + it('must have all the required methods', () => { + expect(protocol && typeof protocol === 'object').toBe(true); expect(protocol.connect).toBeUndefined(); expect(protocol.client).toBeUndefined(); expect(protocol.$config).toBeUndefined(); - expect(typeof protocol.query).toBe(`function`); - expect(typeof protocol.result).toBe(`function`); - expect(typeof protocol.task).toBe(`function`); - expect(typeof protocol.taskIf).toBe(`function`); - expect(typeof protocol.tx).toBe(`function`); - expect(typeof protocol.txIf).toBe(`function`); - expect(typeof protocol.one).toBe(`function`); - expect(typeof protocol.many).toBe(`function`); - expect(typeof protocol.any).toBe(`function`); - expect(typeof protocol.none).toBe(`function`); - expect(typeof protocol.oneOrNone).toBe(`function`); - expect(typeof protocol.manyOrNone).toBe(`function`); - expect(typeof protocol.stream).toBe(`function`); - expect(typeof protocol.func).toBe(`function`); - expect(typeof protocol.proc).toBe(`function`); - expect(typeof protocol.batch).toBe(`function`); - expect(typeof protocol.page).toBe(`function`); - expect(typeof protocol.sequence).toBe(`function`); - expect(typeof protocol.map).toBe(`function`); - expect(typeof protocol.each).toBe(`function`); - expect(typeof protocol.multi).toBe(`function`); - expect(typeof protocol.multiResult).toBe(`function`); + expect(typeof protocol.query).toBe('function'); + expect(typeof protocol.result).toBe('function'); + expect(typeof protocol.task).toBe('function'); + expect(typeof protocol.taskIf).toBe('function'); + expect(typeof protocol.tx).toBe('function'); + expect(typeof protocol.txIf).toBe('function'); + expect(typeof protocol.one).toBe('function'); + expect(typeof protocol.many).toBe('function'); + expect(typeof protocol.any).toBe('function'); + expect(typeof protocol.none).toBe('function'); + expect(typeof protocol.oneOrNone).toBe('function'); + expect(typeof protocol.manyOrNone).toBe('function'); + expect(typeof protocol.stream).toBe('function'); + expect(typeof protocol.func).toBe('function'); + expect(typeof protocol.proc).toBe('function'); + expect(typeof protocol.batch).toBe('function'); + expect(typeof protocol.page).toBe('function'); + expect(typeof protocol.sequence).toBe('function'); + expect(typeof protocol.map).toBe('function'); + expect(typeof protocol.each).toBe('function'); + expect(typeof protocol.multi).toBe('function'); + expect(typeof protocol.multiResult).toBe('function'); }); }); - describe(`on task level`, () => { + describe('on task level', () => { let protocol; beforeEach(done => { @@ -278,41 +278,41 @@ describe(`Database Protocol`, () => { .finally(done); }); - it(`must have all the required methods`, () => { - expect(protocol && typeof protocol === `object`).toBe(true); + it('must have all the required methods', () => { + expect(protocol && typeof protocol === 'object').toBe(true); expect(protocol.connect).toBeUndefined(); expect(protocol.client).toBeUndefined(); expect(protocol.$config).toBeUndefined(); - expect(typeof protocol.query).toBe(`function`); - expect(typeof protocol.result).toBe(`function`); - expect(typeof protocol.task).toBe(`function`); - expect(typeof protocol.taskIf).toBe(`function`); - expect(typeof protocol.tx).toBe(`function`); - expect(typeof protocol.txIf).toBe(`function`); - expect(typeof protocol.one).toBe(`function`); - expect(typeof protocol.many).toBe(`function`); - expect(typeof protocol.any).toBe(`function`); - expect(typeof protocol.none).toBe(`function`); - expect(typeof protocol.oneOrNone).toBe(`function`); - expect(typeof protocol.manyOrNone).toBe(`function`); - expect(typeof protocol.stream).toBe(`function`); - expect(typeof protocol.func).toBe(`function`); - expect(typeof protocol.proc).toBe(`function`); - expect(typeof protocol.batch).toBe(`function`); - expect(typeof protocol.page).toBe(`function`); - expect(typeof protocol.sequence).toBe(`function`); - expect(typeof protocol.map).toBe(`function`); - expect(typeof protocol.each).toBe(`function`); - expect(typeof protocol.multi).toBe(`function`); - expect(typeof protocol.multiResult).toBe(`function`); + expect(typeof protocol.query).toBe('function'); + expect(typeof protocol.result).toBe('function'); + expect(typeof protocol.task).toBe('function'); + expect(typeof protocol.taskIf).toBe('function'); + expect(typeof protocol.tx).toBe('function'); + expect(typeof protocol.txIf).toBe('function'); + expect(typeof protocol.one).toBe('function'); + expect(typeof protocol.many).toBe('function'); + expect(typeof protocol.any).toBe('function'); + expect(typeof protocol.none).toBe('function'); + expect(typeof protocol.oneOrNone).toBe('function'); + expect(typeof protocol.manyOrNone).toBe('function'); + expect(typeof protocol.stream).toBe('function'); + expect(typeof protocol.func).toBe('function'); + expect(typeof protocol.proc).toBe('function'); + expect(typeof protocol.batch).toBe('function'); + expect(typeof protocol.page).toBe('function'); + expect(typeof protocol.sequence).toBe('function'); + expect(typeof protocol.map).toBe('function'); + expect(typeof protocol.each).toBe('function'); + expect(typeof protocol.multi).toBe('function'); + expect(typeof protocol.multiResult).toBe('function'); }); }); }); -describe(`Protocol Extension`, () => { +describe('Protocol Extension', () => { - describe(`on database level`, () => { + describe('on database level', () => { let result, dcParam, THIS, ctx, counter = 0; const pgpTest = header({ promiseLib: header.defPromise, @@ -325,25 +325,25 @@ describe(`Protocol Extension`, () => { this.getOne = function (query, values) { return this.one(query, values); }; - throw new Error(`### Testing error output in 'extend'. Please ignore. ###`); + throw new Error('### Testing error output in \'extend\'. Please ignore. ###'); } }, testDC); beforeEach(done => { - pgpTest.db.getOne(`select 'hello' as msg`) + pgpTest.db.getOne('select \'hello\' as msg') .then(data => { result = data; }) .finally(done); }); - it(`must allow custom properties`, () => { + it('must allow custom properties', () => { expect(THIS && ctx && THIS === ctx).toBeTruthy(); expect(counter).toBe(1); - expect(result.msg).toBe(`hello`); + expect(result.msg).toBe('hello'); expect(dcParam).toBe(testDC); }); }); - describe(`on transaction level`, () => { + describe('on transaction level', () => { let result, THIS, ctx, counter = 0; const pgpTest = header({ promiseLib: header.defPromise, @@ -364,7 +364,7 @@ describe(`Protocol Extension`, () => { beforeEach(done => { pgpTest.db.tx(t => { - return t.getOne(`select 'hello' as msg`); + return t.getOne('select \'hello\' as msg'); }) .then(data => { result = data; @@ -372,11 +372,11 @@ describe(`Protocol Extension`, () => { .finally(done); }); - it(`must allow custom properties`, () => { + it('must allow custom properties', () => { expect(THIS && ctx && THIS === ctx).toBeTruthy(); expect(counter).toBe(2); - expect(result && typeof result === `object`).toBe(true); - expect(result.msg).toBe(`hello`); + expect(result && typeof result === 'object').toBe(true); + expect(result.msg).toBe('hello'); }); }); @@ -384,10 +384,10 @@ describe(`Protocol Extension`, () => { // SPEX tests are just for coverage, because the actual methods // are properly tested within the spex library itself. -describe(`spex`, () => { +describe('spex', () => { - describe(`batch`, () => { - describe(`in tasks`, () => { + describe('batch', () => { + describe('in tasks', () => { let result; beforeEach(done => { db.task(t => { @@ -398,11 +398,11 @@ describe(`spex`, () => { }) .finally(done); }); - it(`must work in general`, () => { + it('must work in general', () => { expect(result).toEqual([1, 2]); }); }); - describe(`after connection`, () => { + describe('after connection', () => { let result, sco; beforeEach(done => { db.connect() @@ -416,14 +416,14 @@ describe(`spex`, () => { }) .finally(done); }); - it(`must work in general`, () => { + it('must work in general', () => { expect(result).toEqual([1, 2]); }); }); }); - describe(`page`, () => { - describe(`in tasks`, () => { + describe('page', () => { + describe('in tasks', () => { let result; beforeEach(done => { db.task(t => { @@ -434,13 +434,13 @@ describe(`spex`, () => { }) .finally(done); }); - it(`must work in general`, () => { - expect(result && typeof result === `object`).toBe(true); + it('must work in general', () => { + expect(result && typeof result === 'object').toBe(true); expect(result.pages).toBe(0); expect(result.total).toBe(0); }); }); - describe(`after connection`, () => { + describe('after connection', () => { let result, sco; beforeEach(done => { db.connect() @@ -454,16 +454,16 @@ describe(`spex`, () => { }) .finally(done); }); - it(`must work in general`, () => { - expect(result && typeof result === `object`).toBe(true); + it('must work in general', () => { + expect(result && typeof result === 'object').toBe(true); expect(result.pages).toBe(0); expect(result.total).toBe(0); }); }); }); - describe(`sequence`, () => { - describe(`in tasks`, () => { + describe('sequence', () => { + describe('in tasks', () => { let result; beforeEach(done => { db.task(t => { @@ -474,12 +474,12 @@ describe(`spex`, () => { }) .finally(done); }); - it(`must work in general`, () => { - expect(result && typeof result === `object`).toBe(true); + it('must work in general', () => { + expect(result && typeof result === 'object').toBe(true); expect(result.total).toBe(0); }); }); - describe(`after connection`, () => { + describe('after connection', () => { let result, sco; beforeEach(done => { db.connect() @@ -493,8 +493,8 @@ describe(`spex`, () => { }) .finally(done); }); - it(`must work in general`, () => { - expect(result && typeof result === `object`).toBe(true); + it('must work in general', () => { + expect(result && typeof result === 'object').toBe(true); expect(result.total).toBe(0); }); }); @@ -502,14 +502,14 @@ describe(`spex`, () => { }); // This one is just for coverage; -describe(`Error protocol`, () => { +describe('Error protocol', () => { const result = { rows: [] }; - it(`must return correctly formatted error body`, () => { - const error1 = new pgp.errors.QueryResultError(0, result, ``); - const error2 = new pgp.errors.QueryResultError(0, result, {name: `name`, text: `text`}, []); + it('must return correctly formatted error body', () => { + const error1 = new pgp.errors.QueryResultError(0, result, ''); + const error2 = new pgp.errors.QueryResultError(0, result, {name: 'name', text: 'text'}, []); expect(tools.inspect(error1)).toBe(error1.toString()); expect(tools.inspect(error2)).toBe(error2.toString()); }); diff --git a/test/stream.spec.js b/test/stream.spec.js index 2eb9c5548..bb459009f 100644 --- a/test/stream.spec.js +++ b/test/stream.spec.js @@ -1,6 +1,6 @@ -const QueryStream = require(`pg-query-stream`); -const JSONStream = require(`JSONStream`); -const header = require(`./db/header`); +const QueryStream = require('pg-query-stream'); +const JSONStream = require('JSONStream'); +const header = require('./db/header'); const promise = header.defPromise; const options = { @@ -16,20 +16,20 @@ if (options.pgNative) { return; } -const $text = require(`../lib/text`); +const $text = require('../lib/text'); const dummy = () => { // dummy/empty function; }; -describe(`Method stream`, () => { - describe(`with invalid stream object`, () => { +describe('Method stream', () => { + describe('with invalid stream object', () => { let result; beforeEach(done => { promise.any([ db.stream(), db.stream(null), - db.stream(`test`), + db.stream('test'), db.stream({}) ]) .catch(reason => { @@ -37,7 +37,7 @@ describe(`Method stream`, () => { }) .finally(done); }); - it(`must throw an error`, () => { + it('must throw an error', () => { expect(result.length).toBe(4); for (let i = 0; i < result.length; i++) { expect(result[i] instanceof TypeError).toBe(true); @@ -45,12 +45,12 @@ describe(`Method stream`, () => { } }); }); - describe(`with invalid stream state`, () => { + describe('with invalid stream state', () => { let result; beforeEach(done => { - const stream1 = new QueryStream(`select 1`); + const stream1 = new QueryStream('select 1'); stream1._reading = true; - const stream2 = new QueryStream(`select 2`); + const stream2 = new QueryStream('select 2'); stream2._closed = true; promise.any([ db.stream(stream1), @@ -61,17 +61,17 @@ describe(`Method stream`, () => { }) .finally(done); }); - it(`must throw an error`, () => { + it('must throw an error', () => { expect(result.length).toBe(2); for (let i = 0; i < result.length; i++) { expect(result[i] instanceof Error).toBe(true); expect(result[i].message).toBe($text.invalidStreamState); } }); - describe(`with invalid initialization callback`, () => { + describe('with invalid initialization callback', () => { let res; beforeEach(done => { - const stream = new QueryStream(`select 1`); + const stream = new QueryStream('select 1'); promise.any([ db.stream(stream), db.stream(stream, null), @@ -83,7 +83,7 @@ describe(`Method stream`, () => { }) .finally(done); }); - it(`must throw an error`, () => { + it('must throw an error', () => { expect(res.length).toBe(4); for (let i = 0; i < res.length; i++) { expect(res[i] instanceof TypeError).toBe(true); @@ -91,28 +91,28 @@ describe(`Method stream`, () => { } }); }); - describe(`with initialization callback throwing error`, () => { + describe('with initialization callback throwing error', () => { let res; beforeEach(done => { - db.stream(new QueryStream(`select 1`), () => { - throw new Error(`initialization error`); + db.stream(new QueryStream('select 1'), () => { + throw new Error('initialization error'); }) .catch(reason => { res = reason; }) .finally(done); }); - it(`must throw an error`, () => { + it('must throw an error', () => { expect(res instanceof Error); - expect(res.message).toBe(`initialization error`); + expect(res.message).toBe('initialization error'); }); }); - describe(`throwing error during query notification`, () => { + describe('throwing error during query notification', () => { let res; beforeEach(done => { options.query = () => { - throw `query notification error`; + throw 'query notification error'; }; db.stream(new QueryStream(), dummy) .catch(error => { @@ -120,18 +120,18 @@ describe(`Method stream`, () => { }) .finally(done); }); - it(`must reject with the same error`, () => { + it('must reject with the same error', () => { expect(res instanceof Error).toBe(false); - expect(res).toBe(`query notification error`); + expect(res).toBe('query notification error'); }); afterEach(() => { options.query = null; }); }); - describe(`with a valid request`, () => { + describe('with a valid request', () => { let res, count = 0, context, initCtx; - const qs = new QueryStream(`select * from users where id = $1`, [1]); + const qs = new QueryStream('select * from users where id = $1', [1]); beforeEach(async done => { options.query = e => { context = e; @@ -142,13 +142,13 @@ describe(`Method stream`, () => { stream.pipe(JSONStream.stringify()); }).finally(done); }); - it(`must return the correct data and provide notification`, () => { - expect(typeof res).toBe(`object`); + it('must return the correct data and provide notification', () => { + expect(typeof res).toBe('object'); expect(res.processed).toBe(1); expect(res.duration >= 0).toBe(true); expect(count).toBe(1); - expect(context.query).toBe(`select * from users where id = $1`); - expect(JSON.stringify(context.params)).toBe(`["1"]`); + expect(context.query).toBe('select * from users where id = $1'); + expect(JSON.stringify(context.params)).toBe('["1"]'); expect(initCtx).toBe(qs); }); afterEach(() => { @@ -156,7 +156,7 @@ describe(`Method stream`, () => { }); }); - describe(`with invalid request`, () => { + describe('with invalid request', () => { let res, err, context, count = 0; beforeEach(async done => { options.error = (error, e) => { @@ -165,7 +165,7 @@ describe(`Method stream`, () => { count++; }; try { - const qs = new QueryStream(`select * from unknown where id = $1`, [1]); + const qs = new QueryStream('select * from unknown where id = $1', [1]); await db.stream(qs, stream => { stream.pipe(JSONStream.stringify()); }); @@ -175,14 +175,14 @@ describe(`Method stream`, () => { done(); } }); - it(`must return the correct data and provide notification`, () => { + it('must return the correct data and provide notification', () => { expect(res instanceof Error).toBe(true); - expect(res.message).toBe(`relation "unknown" does not exist`); + expect(res.message).toBe('relation "unknown" does not exist'); expect(count).toBe(1); - expect(context.query).toBe(`select * from unknown where id = $1`); - expect(JSON.stringify(context.params)).toBe(`["1"]`); + expect(context.query).toBe('select * from unknown where id = $1'); + expect(JSON.stringify(context.params)).toBe('["1"]'); expect(err instanceof Error).toBe(true); - expect(err.message).toBe(`relation "unknown" does not exist`); + expect(err.message).toBe('relation "unknown" does not exist'); }); afterEach(() => { options.error = null; diff --git a/test/tx-mode.spec.js b/test/tx-mode.spec.js index b0fc93a11..749686d38 100644 --- a/test/tx-mode.spec.js +++ b/test/tx-mode.spec.js @@ -1,5 +1,5 @@ -const header = require(`./db/header`); -const tools = require(`./db/tools`); +const header = require('./db/header'); +const tools = require('./db/tools'); const promise = header.defPromise; const options = { @@ -12,20 +12,20 @@ const db = dbHeader.db; const {TransactionMode, isolationLevel} = pgp.txMode; -describe(`TransactionMode`, () => { +describe('TransactionMode', () => { - describe(`Negative`, () => { - it(`must throw throw on invalid options`, () => { + describe('Negative', () => { + it('must throw throw on invalid options', () => { expect(() => { new TransactionMode(0); - }).toThrow(`Invalid "options" parameter: 0`); + }).toThrow('Invalid "options" parameter: 0'); expect(() => { new TransactionMode({value: 123}); - }).toThrow(`Option "value" is not recognized.`); + }).toThrow('Option "value" is not recognized.'); }); }); - describe(`without parameters, capitalized`, () => { + describe('without parameters, capitalized', () => { const queries = []; let result, ctx; const context = {}; @@ -38,7 +38,7 @@ describe(`TransactionMode`, () => { async function txNoParams() { ctx = this.ctx.context; - return `success`; + return 'success'; } txNoParams.txMode = new TransactionMode(); @@ -49,10 +49,10 @@ describe(`TransactionMode`, () => { done(); }); }); - it(`must execute default transaction opening`, () => { - expect(result).toBe(`success`); + it('must execute default transaction opening', () => { + expect(result).toBe('success'); expect(queries.length).toBe(2); - expect(queries[0]).toBe(`BEGIN`); + expect(queries[0]).toBe('BEGIN'); expect(ctx).toBe(context); }); afterEach(() => { @@ -61,7 +61,7 @@ describe(`TransactionMode`, () => { }); }); - describe(`with isolation level`, () => { + describe('with isolation level', () => { const queries = []; let result; beforeEach(done => { @@ -72,23 +72,23 @@ describe(`TransactionMode`, () => { const mode = new TransactionMode({tiLevel: isolationLevel.serializable}); - db.tx({mode}, async () => `success`) + db.tx({mode}, async () => 'success') .then(data => { result = data; done(); }); }); - it(`must execute correct command`, () => { - expect(result).toBe(`success`); + it('must execute correct command', () => { + expect(result).toBe('success'); expect(queries.length).toBe(2); - expect(queries[0]).toBe(`begin isolation level serializable`); + expect(queries[0]).toBe('begin isolation level serializable'); }); afterEach(() => { delete options.query; }); }); - describe(`with access mode = read only`, () => { + describe('with access mode = read only', () => { const queries = []; let result; beforeEach(done => { @@ -99,23 +99,23 @@ describe(`TransactionMode`, () => { const mode = new TransactionMode({readOnly: true}); - db.tx({mode}, async () => `success`) + db.tx({mode}, async () => 'success') .then(data => { result = data; done(); }); }); - it(`must execute correct command`, () => { - expect(result).toBe(`success`); + it('must execute correct command', () => { + expect(result).toBe('success'); expect(queries.length).toBe(2); - expect(queries[0]).toBe(`begin read only`); + expect(queries[0]).toBe('begin read only'); }); afterEach(() => { delete options.query; }); }); - describe(`with access mode = read/write`, () => { + describe('with access mode = read/write', () => { const queries = []; let result; beforeEach(done => { @@ -126,23 +126,23 @@ describe(`TransactionMode`, () => { const mode = new TransactionMode({readOnly: false}); - db.tx({mode}, async () => `success`) + db.tx({mode}, async () => 'success') .then(data => { result = data; done(); }); }); - it(`must execute correct command`, () => { - expect(result).toBe(`success`); + it('must execute correct command', () => { + expect(result).toBe('success'); expect(queries.length).toBe(2); - expect(queries[0]).toBe(`begin read write`); + expect(queries[0]).toBe('begin read write'); }); afterEach(() => { delete options.query; }); }); - describe(`with serializable and read-only`, () => { + describe('with serializable and read-only', () => { const queries = []; let result; beforeEach(done => { @@ -156,23 +156,23 @@ describe(`TransactionMode`, () => { readOnly: true }); - db.tx({mode}, async () => `success`) + db.tx({mode}, async () => 'success') .then(data => { result = data; done(); }); }); - it(`must execute correct command`, () => { - expect(result).toBe(`success`); + it('must execute correct command', () => { + expect(result).toBe('success'); expect(queries.length).toBe(2); - expect(queries[0]).toBe(`begin isolation level serializable read only`); + expect(queries[0]).toBe('begin isolation level serializable read only'); }); afterEach(() => { delete options.query; }); }); - describe(`with deferrable`, () => { + describe('with deferrable', () => { const queries = []; let result; beforeEach(done => { @@ -187,23 +187,23 @@ describe(`TransactionMode`, () => { deferrable: true }); - db.tx({mode}, async () => `success`) + db.tx({mode}, async () => 'success') .then(data => { result = data; done(); }); }); - it(`must execute correct command`, () => { - expect(result).toBe(`success`); + it('must execute correct command', () => { + expect(result).toBe('success'); expect(queries.length).toBe(2); - expect(queries[0]).toBe(`begin isolation level serializable read only deferrable`); + expect(queries[0]).toBe('begin isolation level serializable read only deferrable'); }); afterEach(() => { delete options.query; }); }); - describe(`with not deferrable`, () => { + describe('with not deferrable', () => { const queries = []; let result; beforeEach(done => { @@ -218,23 +218,23 @@ describe(`TransactionMode`, () => { deferrable: false }); - db.tx({mode}, async () => `success`) + db.tx({mode}, async () => 'success') .then(data => { result = data; done(); }); }); - it(`must execute correct command`, () => { - expect(result).toBe(`success`); + it('must execute correct command', () => { + expect(result).toBe('success'); expect(queries.length).toBe(2); - expect(queries[0]).toBe(`begin isolation level serializable read only not deferrable`); + expect(queries[0]).toBe('begin isolation level serializable read only not deferrable'); }); afterEach(() => { delete options.query; }); }); - describe(`when deferrable is irrelevant`, () => { + describe('when deferrable is irrelevant', () => { const queries = []; let result; beforeEach(done => { @@ -249,25 +249,25 @@ describe(`TransactionMode`, () => { deferrable: false }); - db.tx({mode}, async () => `success`) + db.tx({mode}, async () => 'success') .then(data => { result = data; done(); }); }); - it(`must execute correct command`, () => { - expect(result).toBe(`success`); + it('must execute correct command', () => { + expect(result).toBe('success'); expect(queries.length).toBe(2); - expect(queries[0]).toBe(`begin isolation level repeatable read read only`); + expect(queries[0]).toBe('begin isolation level repeatable read read only'); }); afterEach(() => { delete options.query; }); }); - describe(`inspection`, () => { + describe('inspection', () => { const mode = new TransactionMode(); - it(`must return the same as method begin()`, () => { + it('must return the same as method begin()', () => { expect(mode.begin(true)).toBe(tools.inspect(mode)); }); }); diff --git a/test/typescript.spec.js b/test/typescript.spec.js index 93ffad4c0..45d9bf723 100644 --- a/test/typescript.spec.js +++ b/test/typescript.spec.js @@ -1,11 +1,11 @@ -const exec = require(`child_process`).exec; -const path = require(`path`); +const exec = require('child_process').exec; +const path = require('path'); const TIMEOUT = 20000; // 20 SECONDS -describe(`Typescript`, () => { - describe(`build`, () => { - it(`must build without error`, done => { - exec(`tsc`, {cwd: path.join(`test`, `typescript`)}, error => { +describe('Typescript', () => { + describe('build', () => { + it('must build without error', done => { + exec('tsc', {cwd: path.join('test', 'typescript')}, error => { expect(error).toBe(null); done(); }); diff --git a/test/utils.spec.js b/test/utils.spec.js index ff95a663c..f2e421d9e 100644 --- a/test/utils.spec.js +++ b/test/utils.spec.js @@ -1,14 +1,14 @@ -const $u = require(`../lib/utils`); -const utils = require(`../lib/utils/public`); -const internal = require(`../lib/utils`); +const $u = require('../lib/utils'); +const utils = require('../lib/utils/public'); +const internal = require('../lib/utils'); function dummy() { } -describe(`taskArgs`, () => { - describe(`with invalid arguments`, () => { - const error = `Parameter 'args' must be an array-like object of arguments.`; - it(`must throw error`, () => { +describe('taskArgs', () => { + describe('with invalid arguments', () => { + const error = 'Parameter \'args\' must be an array-like object of arguments.'; + it('must throw error', () => { expect(() => { utils.taskArgs(); }).toThrow(error); @@ -17,17 +17,17 @@ describe(`taskArgs`, () => { }).toThrow(error); }); }); - describe(`without options`, () => { - describe(`with empty arguments`, () => { + describe('without options', () => { + describe('with empty arguments', () => { const emptyResult = [{}, undefined]; emptyResult.options = emptyResult[0]; emptyResult.cb = emptyResult[1]; - it(`must return empty result`, () => { + it('must return empty result', () => { expect(utils.taskArgs([])).toEqual(emptyResult); }); }); - describe(`with a function`, () => { - it(`must detect as the first argument`, () => { + describe('with a function', () => { + it('must detect as the first argument', () => { const args = [() => { }]; const result = [{}, args[0]]; @@ -35,7 +35,7 @@ describe(`taskArgs`, () => { result.cb = result[1]; expect(utils.taskArgs(args)).toEqual(result); }); - it(`must detect as the second argument`, () => { + it('must detect as the second argument', () => { const args = [undefined, () => { }]; const result = [{}, args[1]]; @@ -43,7 +43,7 @@ describe(`taskArgs`, () => { result.cb = result[1]; expect(utils.taskArgs(args)).toEqual(result); }); - it(`must ignore as the third argument`, () => { + it('must ignore as the third argument', () => { const args = [undefined, undefined, () => { }]; const result = [{}, undefined]; @@ -51,7 +51,7 @@ describe(`taskArgs`, () => { result.cb = result[1]; expect(utils.taskArgs(args)).toEqual(result); }); - it(`must allow overrides`, () => { + it('must allow overrides', () => { const args = utils.taskArgs([]); args.cb = 123; const result = [{}, 123]; @@ -62,13 +62,13 @@ describe(`taskArgs`, () => { }); }); }); - describe(`with options`, () => { - it(`must support random options`, () => { - const result = [{first: 1, second: `hello`}, undefined]; + describe('with options', () => { + it('must support random options', () => { + const result = [{first: 1, second: 'hello'}, undefined]; result.options = result[0]; - expect(utils.taskArgs([{first: 1, second: `hello`}])).toEqual(result); + expect(utils.taskArgs([{first: 1, second: 'hello'}])).toEqual(result); }); - it(`must allow overrides`, () => { + it('must allow overrides', () => { const args = utils.taskArgs([]); args.options = 123; const result = [123, undefined]; @@ -77,141 +77,141 @@ describe(`taskArgs`, () => { expect(args).toEqual(result); }); }); - describe(`direct tag`, () => { - it(`must support strings`, () => { - const result = [{tag: `hello`}, undefined]; + describe('direct tag', () => { + it('must support strings', () => { + const result = [{tag: 'hello'}, undefined]; result.options = result[0]; - expect(utils.taskArgs([`hello`])).toEqual(result); + expect(utils.taskArgs(['hello'])).toEqual(result); }); - it(`must support empty strings`, () => { - const result = [{tag: ``}, undefined]; + it('must support empty strings', () => { + const result = [{tag: ''}, undefined]; result.options = result[0]; - expect(utils.taskArgs([``])).toEqual(result); + expect(utils.taskArgs([''])).toEqual(result); }); - it(`must support numbers`, () => { + it('must support numbers', () => { const result = [{tag: 123}, undefined]; result.options = result[0]; expect(utils.taskArgs([123])).toEqual(result); }); }); - describe(`indirect tag`, () => { - it(`must support numbers`, () => { + describe('indirect tag', () => { + it('must support numbers', () => { const result = [{tag: 123}, undefined]; result.options = result[0]; expect(utils.taskArgs([{tag: 123}])).toEqual(result); }); - it(`must support strings`, () => { - const result = [{tag: `hello`}, undefined]; + it('must support strings', () => { + const result = [{tag: 'hello'}, undefined]; result.options = result[0]; - expect(utils.taskArgs([{tag: `hello`}])).toEqual(result); + expect(utils.taskArgs([{tag: 'hello'}])).toEqual(result); }); - it(`must use callback name when without tag`, () => { + it('must use callback name when without tag', () => { function tst() { } - const result = [{tag: `tst`}, tst]; + const result = [{tag: 'tst'}, tst]; result.options = result[0]; result.cb = result[1]; expect(utils.taskArgs([tst])).toEqual(result); expect(utils.taskArgs([{}, tst])).toEqual(result); }); - it(`must skip callback name when with tag`, () => { + it('must skip callback name when with tag', () => { function tst() { } - const result = [{tag: `hello`}, tst]; + const result = [{tag: 'hello'}, tst]; result.options = result[0]; result.cb = result[1]; - expect(utils.taskArgs([{tag: `hello`}, tst])).toEqual(result); - expect(utils.taskArgs([`hello`, tst])).toEqual(result); + expect(utils.taskArgs([{tag: 'hello'}, tst])).toEqual(result); + expect(utils.taskArgs(['hello', tst])).toEqual(result); }); }); }); -describe(`camelize`, () => { +describe('camelize', () => { - it(`must keep leading digits`, () => { - expect(utils.camelize(` 123 name 456`)).toBe(`123Name456`); + it('must keep leading digits', () => { + expect(utils.camelize(' 123 name 456')).toBe('123Name456'); }); - it(`must replace all gaps correctly`, () => { - expect(utils.camelize(` one two - three _ four `)).toBe(`oneTwoThreeFour`); - expect(utils.camelize(`one.two-three_four`)).toBe(`oneTwoThreeFour`); + it('must replace all gaps correctly', () => { + expect(utils.camelize(' one two - three _ four ')).toBe('oneTwoThreeFour'); + expect(utils.camelize('one.two-three_four')).toBe('oneTwoThreeFour'); }); }); -describe(`camelizeVar`, () => { - it(`must remove leading digits and white spaces`, () => { - expect(utils.camelizeVar(` 123 name 456`)).toBe(`name456`); +describe('camelizeVar', () => { + it('must remove leading digits and white spaces', () => { + expect(utils.camelizeVar(' 123 name 456')).toBe('name456'); }); - it(`must handle all special symbols`, () => { - expect(utils.camelizeVar(`-123_ 456.78.one.two . three.8`)).toBe(`oneTwoThree8`); + it('must handle all special symbols', () => { + expect(utils.camelizeVar('-123_ 456.78.one.two . three.8')).toBe('oneTwoThree8'); }); }); -describe(`enumSql`, () => { +describe('enumSql', () => { - it(`must list all sql files in a folder`, () => { - const sql = utils.enumSql(`./test/sql`); - expect(sql.allUsers).toContain(`allUsers.sql`); - expect(sql.invalid).toContain(`invalid.sql`); - expect(sql.params).toContain(`params.sql`); - expect(sql.simple).toContain(`simple.sql`); - expect(`sub` in sql).toBe(false); + it('must list all sql files in a folder', () => { + const sql = utils.enumSql('./test/sql'); + expect(sql.allUsers).toContain('allUsers.sql'); + expect(sql.invalid).toContain('invalid.sql'); + expect(sql.params).toContain('params.sql'); + expect(sql.simple).toContain('simple.sql'); + expect('sub' in sql).toBe(false); }); - it(`must list sql files in sub-folders`, () => { - const sql = utils.enumSql(`./test/sql`, {recursive: true}, dummy); - expect(sql.allUsers).toContain(`allUsers.sql`); - expect(sql.invalid).toContain(`invalid.sql`); - expect(sql.params).toContain(`params.sql`); - expect(sql.simple).toContain(`simple.sql`); - expect(sql.sub.one).toContain(`one.sql`); - expect(sql.sub.two).toContain(`two.sql`); - expect(`third` in sql.sub).toBe(false); + it('must list sql files in sub-folders', () => { + const sql = utils.enumSql('./test/sql', {recursive: true}, dummy); + expect(sql.allUsers).toContain('allUsers.sql'); + expect(sql.invalid).toContain('invalid.sql'); + expect(sql.params).toContain('params.sql'); + expect(sql.simple).toContain('simple.sql'); + expect(sql.sub.one).toContain('one.sql'); + expect(sql.sub.two).toContain('two.sql'); + expect('third' in sql.sub).toBe(false); }); - it(`must set values correctly`, () => { - const sql = utils.enumSql(`./test/sql`, {recursive: true}, (file, name, p) => { + it('must set values correctly', () => { + const sql = utils.enumSql('./test/sql', {recursive: true}, (file, name, p) => { return p; }); - expect(sql.allUsers).toBe(`allUsers`); - expect(sql.invalid).toBe(`invalid`); - expect(sql.params).toBe(`params`); - expect(sql.simple).toBe(`simple`); - expect(sql.sub.one).toContain(`sub.one`); - expect(sql.sub.two).toContain(`sub.two`); - expect(sql.sub.oneTwoThree).toContain(`sub.oneTwoThree`); + expect(sql.allUsers).toBe('allUsers'); + expect(sql.invalid).toBe('invalid'); + expect(sql.params).toBe('params'); + expect(sql.simple).toBe('simple'); + expect(sql.sub.one).toContain('sub.one'); + expect(sql.sub.two).toContain('sub.two'); + expect(sql.sub.oneTwoThree).toContain('sub.oneTwoThree'); }); - it(`must be able to ignore duplicate folders`, () => { - const tree = utils.enumSql(`./test/sql-special/dup-folders`, { + it('must be able to ignore duplicate folders', () => { + const tree = utils.enumSql('./test/sql-special/dup-folders', { recursive: true, ignoreErrors: true }, (file, name, p) => { return p; }); - expect(tree && typeof tree === `object`).toBeTruthy(); - expect(tree.sub.first).toBe(`sub.first`); + expect(tree && typeof tree === 'object').toBeTruthy(); + expect(tree.sub.first).toBe('sub.first'); }); - it(`must be able to ignore duplicate files`, () => { - const tree = utils.enumSql(`./test/sql-special/dup-files`, { + it('must be able to ignore duplicate files', () => { + const tree = utils.enumSql('./test/sql-special/dup-files', { recursive: true, ignoreErrors: true }, (file, name, p) => { return p; }); - expect(tree && typeof tree === `object`).toBeTruthy(); - expect(tree.one).toBe(`one`); + expect(tree && typeof tree === 'object').toBeTruthy(); + expect(tree.one).toBe('one'); }); - describe(`negative`, () => { - it(`must throw on invalid or empty directory`, () => { - const errMsg = `Parameter 'dir' must be a non-empty text string.`; + describe('negative', () => { + it('must throw on invalid or empty directory', () => { + const errMsg = 'Parameter \'dir\' must be a non-empty text string.'; expect(() => { utils.enumSql(); }).toThrow(errMsg); @@ -219,56 +219,56 @@ describe(`enumSql`, () => { utils.enumSql(null); }).toThrow(errMsg); expect(() => { - utils.enumSql(``); + utils.enumSql(''); }).toThrow(errMsg); }); - it(`must throw on duplicate folder`, () => { + it('must throw on duplicate folder', () => { let err; try { - utils.enumSql(`./test/sql-special/dup-folders`, {recursive: true}); + utils.enumSql('./test/sql-special/dup-folders', {recursive: true}); } catch (e) { err = e; } expect(err instanceof Error).toBe(true); - expect(err.message).toContain(`Empty or duplicate camelized folder name:`); + expect(err.message).toContain('Empty or duplicate camelized folder name:'); }); - it(`must throw on a duplicate file`, () => { + it('must throw on a duplicate file', () => { let err; try { - utils.enumSql(`./test/sql-special/dup-files`, {recursive: true}); + utils.enumSql('./test/sql-special/dup-files', {recursive: true}); } catch (e) { err = e; } expect(err instanceof Error).toBe(true); - expect(err.message).toContain(`Empty or duplicate camelized file name:`); + expect(err.message).toContain('Empty or duplicate camelized file name:'); }); }); }); -describe(`isDev`, () => { +describe('isDev', () => { const env = process.env.NODE_ENV; - it(`must detect the default environment`, () => { + it('must detect the default environment', () => { delete process.env.NODE_ENV; expect(internal.isDev()).toBe(false); }); - it(`must detect a dev environment`, () => { - process.env.NODE_ENV = `development`; + it('must detect a dev environment', () => { + process.env.NODE_ENV = 'development'; expect(internal.isDev()).toBe(true); - process.env.NODE_ENV = `dev`; + process.env.NODE_ENV = 'dev'; expect(internal.isDev()).toBe(true); - process.env.NODE_ENV = `something-dev`; + process.env.NODE_ENV = 'something-dev'; expect(internal.isDev()).toBe(true); }); - it(`must detect a non-dev environment`, () => { - process.env.NODE_ENV = `production`; + it('must detect a non-dev environment', () => { + process.env.NODE_ENV = 'production'; expect(internal.isDev()).toBe(false); }); @@ -277,33 +277,33 @@ describe(`isDev`, () => { }); }); -describe(`getSafeConnection`, () => { - const cn1 = `postgres://postgres:password@localhost:5432/invalidDB`; - const cn2 = {connectionString: `postgres://postgres:password@localhost:5432/invalidDB`}; - const cn3 = {password: `hello`, connectionString: `postgres://postgres:password@localhost:5432/invalidDB`}; - it(`must obscure direct passwords`, () => { - expect(internal.getSafeConnection(cn1)).toBe(`postgres://postgres:########@localhost:5432/invalidDB`); +describe('getSafeConnection', () => { + const cn1 = 'postgres://postgres:password@localhost:5432/invalidDB'; + const cn2 = {connectionString: 'postgres://postgres:password@localhost:5432/invalidDB'}; + const cn3 = {password: 'hello', connectionString: 'postgres://postgres:password@localhost:5432/invalidDB'}; + it('must obscure direct passwords', () => { + expect(internal.getSafeConnection(cn1)).toBe('postgres://postgres:########@localhost:5432/invalidDB'); }); - it(`must obscure indirect passwords`, () => { - expect(internal.getSafeConnection(cn2)).toEqual({connectionString: `postgres://postgres:########@localhost:5432/invalidDB`}); + it('must obscure indirect passwords', () => { + expect(internal.getSafeConnection(cn2)).toEqual({connectionString: 'postgres://postgres:########@localhost:5432/invalidDB'}); }); - it(`must obscure all passwords`, () => { + it('must obscure all passwords', () => { expect(internal.getSafeConnection(cn3)).toEqual({ - password: `#####`, - connectionString: `postgres://postgres:########@localhost:5432/invalidDB` + password: '#####', + connectionString: 'postgres://postgres:########@localhost:5432/invalidDB' }); }); }); -describe(`Nested Named Parameters`, () => { +describe('Nested Named Parameters', () => { let tmp, result, duration; beforeEach(() => { const obj = {}, depth = 10000; - let varPath = ``; + let varPath = ''; tmp = obj; for (let i = 1; i < depth; i++) { if (varPath) { - varPath += `.` + i; + varPath += '.' + i; } else { varPath = i; } @@ -313,13 +313,13 @@ describe(`Nested Named Parameters`, () => { } tmp.value = 123; const start = Date.now(); - result = $u.getIfHas(obj, varPath + `.value`); + result = $u.getIfHas(obj, varPath + '.value'); duration = Date.now() - start; }); - it(`must support any depth level`, () => { + it('must support any depth level', () => { expect(result).toEqual({valid: true, has: true, target: tmp, value: 123}); }); - it(`must be fast`, () => { + it('must be fast', () => { // In reality, it is very fast, i.e. way under 10ms for 10,000 levels; // However, Travis CI test environment is too slow to test it properly, // so the expectation here is significantly lowered for that reason: @@ -327,28 +327,28 @@ describe(`Nested Named Parameters`, () => { }); }); -describe(`toJson`, () => { - const v = process.versions.node.split(`.`), +describe('toJson', () => { + const v = process.versions.node.split('.'), highVer = +v[0], lowVer = +v[1]; if (highVer > 10 || (highVer === 10 && lowVer >= 4)) { // Node.js v10.4.0 is required to support BigInt natively. - describe(`for a direct value`, () => { - expect(internal.toJson(BigInt(`0`))).toBe(`0`); - expect(internal.toJson(BigInt(`123`))).toBe(`123`); - expect(internal.toJson(BigInt(`-12345678901234567890`))).toBe(`-12345678901234567890`); + describe('for a direct value', () => { + expect(internal.toJson(BigInt('0'))).toBe('0'); + expect(internal.toJson(BigInt('123'))).toBe('123'); + expect(internal.toJson(BigInt('-12345678901234567890'))).toBe('-12345678901234567890'); }); - describe(`for an object`, () => { - expect(internal.toJson({value: BigInt(`0`)})).toEqual(`{"value":0}`); - expect(internal.toJson({value: BigInt(`123`)})).toEqual(`{"value":123}`); - expect(internal.toJson({value: BigInt(`-456`)})).toEqual(`{"value":-456}`); + describe('for an object', () => { + expect(internal.toJson({value: BigInt('0')})).toEqual('{"value":0}'); + expect(internal.toJson({value: BigInt('123')})).toEqual('{"value":123}'); + expect(internal.toJson({value: BigInt('-456')})).toEqual('{"value":-456}'); const mix1 = { // eslint-disable-next-line no-loss-of-precision val1: 12345678901234567890, - val2: BigInt(`12345678901234567890`) + val2: BigInt('12345678901234567890') }; - expect(internal.toJson(mix1)).toEqual(`{"val1":12345678901234567000,"val2":12345678901234567890}`); + expect(internal.toJson(mix1)).toEqual('{"val1":12345678901234567000,"val2":12345678901234567890}'); }); - describe(`for an undefined`, () => { + describe('for an undefined', () => { expect(internal.toJson()).toBeUndefined(); expect(internal.toJson(undefined)).toBeUndefined(); });