remove dependency on bluebird methods from sources (#3683)

Co-authored-by: Brian Lauber <constructible.truth@gmail.com>
This commit is contained in:
maximelkin 2020-02-26 00:50:24 +03:00 committed by GitHub
parent 8c07192ade
commit b025aea318
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 215 additions and 272 deletions

View File

@ -1,5 +1,3 @@
const Bluebird = require('bluebird');
const Raw = require('./raw');
const Ref = require('./ref');
const Runner = require('./runner');
@ -335,28 +333,23 @@ Object.assign(Client.prototype, {
},
// Acquire a connection from the pool.
acquireConnection() {
async acquireConnection() {
if (!this.pool) {
return Bluebird.reject(new Error('Unable to acquire a connection'));
throw new Error('Unable to acquire a connection');
}
try {
return Bluebird.try(() => this.pool.acquire().promise)
.then((connection) => {
debug('acquired connection from pool: %s', connection.__knexUid);
return connection;
})
.catch((error) => {
let convertedError = error;
if (error instanceof TimeoutError) {
convertedError = new KnexTimeoutError(
'Knex: Timeout acquiring a connection. The pool is probably full. ' +
'Are you missing a .transacting(trx) call?'
);
}
throw convertedError;
});
} catch (e) {
return Bluebird.reject(e);
const connection = await this.pool.acquire().promise;
debug('acquired connection from pool: %s', connection.__knexUid);
return connection;
} catch (error) {
let convertedError = error;
if (error instanceof TimeoutError) {
convertedError = new KnexTimeoutError(
'Knex: Timeout acquiring a connection. The pool is probably full. ' +
'Are you missing a .transacting(trx) call?'
);
}
throw convertedError;
}
},
@ -370,14 +363,14 @@ Object.assign(Client.prototype, {
debug('pool refused connection: %s', connection.__knexUid);
}
return Bluebird.resolve();
return Promise.resolve();
},
// Destroy the current connection pool for the client.
destroy(callback) {
const maybeDestroy = this.pool && this.pool.destroy();
return Bluebird.resolve(maybeDestroy)
return Promise.resolve(maybeDestroy)
.then(() => {
this.pool = void 0;
@ -390,7 +383,7 @@ Object.assign(Client.prototype, {
callback(err);
}
return Bluebird.reject(err);
return Promise.reject(err);
});
},

View File

@ -4,7 +4,6 @@ const { map, flatten, values } = require('lodash');
const inherits = require('inherits');
const Client = require('../../client');
const Bluebird = require('bluebird');
const Formatter = require('../../formatter');
const Transaction = require('./transaction');
@ -217,7 +216,7 @@ Object.assign(Client_MSSQL.prototype, {
// Get a raw connection, called by the `pool` whenever a new
// connection needs to be added to the pool.
acquireRawConnection() {
return new Bluebird((resolver, rejecter) => {
return new Promise((resolver, rejecter) => {
const settings = Object.assign({}, this.connectionSettings);
settings.pool = this.mssqlPoolSettings;
@ -264,7 +263,7 @@ Object.assign(Client_MSSQL.prototype, {
// and pass that through to the stream we've sent back to the client.
_stream(connection, obj, stream) {
if (!obj || typeof obj === 'string') obj = { sql: obj };
return new Bluebird((resolver, rejecter) => {
return new Promise((resolver, rejecter) => {
stream.on('error', (err) => {
rejecter(err);
});
@ -290,7 +289,7 @@ Object.assign(Client_MSSQL.prototype, {
_query(connection, obj) {
const client = this;
if (!obj || typeof obj === 'string') obj = { sql: obj };
return new Bluebird((resolver, rejecter) => {
return new Promise((resolver, rejecter) => {
const { sql } = obj;
if (!sql) return resolver();
const req = (connection.tx_ || connection).request();

View File

@ -1,4 +1,3 @@
const Bluebird = require('bluebird');
const Transaction = require('../../transaction');
const { isUndefined } = require('lodash');
const debug = require('debug')('knex:tx');
@ -9,11 +8,9 @@ module.exports = class Transaction_MSSQL extends Transaction {
return conn.tx_.begin().then(this._resolver, this._rejecter);
}
savepoint(conn) {
async savepoint(conn) {
debug('%s: savepoint at', this.txid);
return Bluebird.resolve().then(() =>
this.query(conn, `SAVE TRANSACTION ${this.txid}`)
);
return this.query(conn, `SAVE TRANSACTION ${this.txid}`);
}
commit(conn, value) {
@ -48,13 +45,11 @@ module.exports = class Transaction_MSSQL extends Transaction {
);
}
rollbackTo(conn, error) {
async rollbackTo(conn, error) {
debug('%s: rolling backTo', this.txid);
return Bluebird.resolve()
.then(() =>
this.query(conn, `ROLLBACK TRANSACTION ${this.txid}`, 2, error)
)
.then(() => this._rejecter(error));
await this.query(conn, `ROLLBACK TRANSACTION ${this.txid}`, 2, error);
this._rejecter(error);
}
// Acquire a connection and create a disposer - either using the one passed
@ -62,7 +57,7 @@ module.exports = class Transaction_MSSQL extends Transaction {
// the original promise is marked completed.
acquireConnection(config, cb) {
const configConnection = config && config.connection;
return new Bluebird((resolve, reject) => {
return new Promise((resolve, reject) => {
try {
resolve(
(this.outerTx ? this.outerTx.conn : null) ||

View File

@ -4,7 +4,6 @@ const inherits = require('inherits');
const { map, defer } = require('lodash');
const { promisify } = require('util');
const Client = require('../../client');
const Bluebird = require('bluebird');
const Transaction = require('./transaction');
const QueryCompiler = require('./query/compiler');
@ -61,7 +60,7 @@ Object.assign(Client_MySQL.prototype, {
// Get a raw connection, called by the `pool` whenever a new
// connection needs to be added to the pool.
acquireRawConnection() {
return new Bluebird((resolver, rejecter) => {
return new Promise((resolver, rejecter) => {
const connection = this.driver.createConnection(this.connectionSettings);
connection.on('error', (err) => {
connection.__knex__disposed = err;
@ -106,7 +105,7 @@ Object.assign(Client_MySQL.prototype, {
_stream(connection, obj, stream, options) {
options = options || {};
const queryOptions = Object.assign({ sql: obj.sql }, obj.options);
return new Bluebird((resolver, rejecter) => {
return new Promise((resolver, rejecter) => {
stream.on('error', rejecter);
stream.on('end', resolver);
const queryStream = connection
@ -126,7 +125,7 @@ Object.assign(Client_MySQL.prototype, {
// and any other necessary prep work.
_query(connection, obj) {
if (!obj || typeof obj === 'string') obj = { sql: obj };
return new Bluebird(function(resolver, rejecter) {
return new Promise(function(resolver, rejecter) {
if (!obj.sql) {
resolver();
return;

View File

@ -5,7 +5,6 @@ const { promisify } = require('util');
const inherits = require('inherits');
const Client = require('../../client');
const Bluebird = require('bluebird');
const { bufferToString } = require('../../query/string');
const Formatter = require('./formatter');
@ -80,10 +79,10 @@ Object.assign(Client_Oracle.prototype, {
// Get a raw connection, called by the `pool` whenever a new
// connection needs to be added to the pool.
acquireRawConnection() {
return new Bluebird((resolver, rejecter) => {
return new Promise((resolver, rejecter) => {
this.driver.connect(this.connectionSettings, (err, connection) => {
if (err) return rejecter(err);
Bluebird.promisifyAll(connection);
connection.executeAsync = promisify(connection.execute);
if (this.connectionSettings.prefetchRowCount) {
connection.setPrefetchRowCount(
this.connectionSettings.prefetchRowCount
@ -116,7 +115,7 @@ Object.assign(Client_Oracle.prototype, {
},
_stream(connection, obj, stream, options) {
return new Bluebird(function(resolver, rejecter) {
return new Promise(function(resolver, rejecter) {
stream.on('error', (err) => {
if (isConnectionError(err)) {
connection.__knex__disposed = err;

View File

@ -1,4 +1,3 @@
const Bluebird = require('bluebird');
const Transaction = require('../../transaction');
const { isUndefined } = require('lodash');
const debugTx = require('debug')('knex:tx');
@ -6,7 +5,7 @@ const debugTx = require('debug')('knex:tx');
module.exports = class Oracle_Transaction extends Transaction {
// disable autocommit to allow correct behavior (default is true)
begin() {
return Bluebird.resolve();
return Promise.resolve();
}
commit(conn, value) {
@ -42,7 +41,7 @@ module.exports = class Oracle_Transaction extends Transaction {
acquireConnection(config, cb) {
const configConnection = config && config.connection;
return new Bluebird((resolve, reject) => {
return new Promise((resolve, reject) => {
try {
resolve(configConnection || this.client.acquireConnection());
} catch (e) {

View File

@ -5,7 +5,6 @@ const inherits = require('inherits');
const QueryCompiler = require('./query/compiler');
const ColumnCompiler = require('./schema/columncompiler');
const { BlobHelper, ReturningHelper, isConnectionError } = require('./utils');
const Bluebird = require('bluebird');
const stream = require('stream');
const { promisify } = require('util');
const Transaction = require('./transaction');
@ -82,7 +81,7 @@ Client_Oracledb.prototype.prepBindings = function(bindings) {
// connection needs to be added to the pool.
Client_Oracledb.prototype.acquireRawConnection = function() {
const client = this;
const asyncConnection = new Bluebird(function(resolver, rejecter) {
const asyncConnection = new Promise(function(resolver, rejecter) {
// If external authentication don't have to worry about username/password and
// if not need to set the username and password
const oracleDbConfig = client.connectionSettings.externalAuth
@ -112,7 +111,7 @@ Client_Oracledb.prototype.acquireRawConnection = function() {
return rejecter(err);
}
connection.commitAsync = function() {
return new Bluebird((commitResolve, commitReject) => {
return new Promise((commitResolve, commitReject) => {
this.commit(function(err) {
if (err) {
return commitReject(err);
@ -122,7 +121,7 @@ Client_Oracledb.prototype.acquireRawConnection = function() {
});
};
connection.rollbackAsync = function() {
return new Bluebird((rollbackResolve, rollbackReject) => {
return new Promise((rollbackResolve, rollbackReject) => {
this.rollback(function(err) {
if (err) {
return rollbackReject(err);
@ -259,100 +258,100 @@ Client_Oracledb.prototype._query = function(connection, obj) {
if (obj.method === 'select') {
options.resultSet = true;
}
return Bluebird.resolve(
connection.executeAsync(obj.sql, obj.bindings, options)
).then(async function(response) {
// Flatten outBinds
let outBinds = _.flatten(response.outBinds);
obj.response = response.rows || [];
obj.rowsAffected = response.rows
? response.rows.rowsAffected
: response.rowsAffected;
return connection
.executeAsync(obj.sql, obj.bindings, options)
.then(async function(response) {
// Flatten outBinds
let outBinds = _.flatten(response.outBinds);
obj.response = response.rows || [];
obj.rowsAffected = response.rows
? response.rows.rowsAffected
: response.rowsAffected;
//added for outBind parameter
if (obj.method === 'raw' && outBinds.length > 0) {
return {
response: outBinds,
};
}
if (obj.method === 'update') {
const modifiedRowsCount = obj.rowsAffected.length || obj.rowsAffected;
const updatedObjOutBinding = [];
const updatedOutBinds = [];
const updateOutBinds = (i) =>
function(value, index) {
const OutBindsOffset = index * modifiedRowsCount;
updatedOutBinds.push(outBinds[i + OutBindsOffset]);
//added for outBind parameter
if (obj.method === 'raw' && outBinds.length > 0) {
return {
response: outBinds,
};
for (let i = 0; i < modifiedRowsCount; i++) {
updatedObjOutBinding.push(obj.outBinding[0]);
_.each(obj.outBinding[0], updateOutBinds(i));
}
outBinds = updatedOutBinds;
obj.outBinding = updatedObjOutBinding;
}
if (!obj.returning && outBinds.length === 0) {
if (!connection.isTransaction) {
await connection.commitAsync();
if (obj.method === 'update') {
const modifiedRowsCount = obj.rowsAffected.length || obj.rowsAffected;
const updatedObjOutBinding = [];
const updatedOutBinds = [];
const updateOutBinds = (i) =>
function(value, index) {
const OutBindsOffset = index * modifiedRowsCount;
updatedOutBinds.push(outBinds[i + OutBindsOffset]);
};
for (let i = 0; i < modifiedRowsCount; i++) {
updatedObjOutBinding.push(obj.outBinding[0]);
_.each(obj.outBinding[0], updateOutBinds(i));
}
outBinds = updatedOutBinds;
obj.outBinding = updatedObjOutBinding;
}
return obj;
}
const rowIds = [];
let offset = 0;
for (let line = 0; line < obj.outBinding.length; line++) {
const ret = obj.outBinding[line];
if (!obj.returning && outBinds.length === 0) {
if (!connection.isTransaction) {
await connection.commitAsync();
}
return obj;
}
const rowIds = [];
let offset = 0;
offset =
offset +
(obj.outBinding[line - 1] ? obj.outBinding[line - 1].length : 0);
for (let line = 0; line < obj.outBinding.length; line++) {
const ret = obj.outBinding[line];
for (let index = 0; index < ret.length; index++) {
const out = ret[index];
offset =
offset +
(obj.outBinding[line - 1] ? obj.outBinding[line - 1].length : 0);
await new Promise(function(bindResolver, bindRejecter) {
if (out instanceof BlobHelper) {
const blob = outBinds[index + offset];
if (out.returning) {
obj.response[line] = obj.response[line] || {};
obj.response[line][out.columnName] = out.value;
}
blob.on('error', function(err) {
bindRejecter(err);
});
blob.on('finish', function() {
for (let index = 0; index < ret.length; index++) {
const out = ret[index];
await new Promise(function(bindResolver, bindRejecter) {
if (out instanceof BlobHelper) {
const blob = outBinds[index + offset];
if (out.returning) {
obj.response[line] = obj.response[line] || {};
obj.response[line][out.columnName] = out.value;
}
blob.on('error', function(err) {
bindRejecter(err);
});
blob.on('finish', function() {
bindResolver();
});
blob.write(out.value);
blob.end();
} else if (obj.outBinding[line][index] === 'ROWID') {
rowIds.push(outBinds[index + offset]);
bindResolver();
});
blob.write(out.value);
blob.end();
} else if (obj.outBinding[line][index] === 'ROWID') {
rowIds.push(outBinds[index + offset]);
bindResolver();
} else {
obj.response[line] = obj.response[line] || {};
obj.response[line][out] = outBinds[index + offset];
bindResolver();
}
});
} else {
obj.response[line] = obj.response[line] || {};
obj.response[line][out] = outBinds[index + offset];
bindResolver();
}
});
}
}
if (connection.isTransaction) {
return obj;
}
await connection.commitAsync();
if (obj.returningSql) {
const response = await connection.executeAsync(
obj.returningSql(),
rowIds,
{ resultSet: true }
);
obj.response = response.rows;
}
}
if (connection.isTransaction) {
return obj;
}
await connection.commitAsync();
if (obj.returningSql) {
const response = await connection.executeAsync(
obj.returningSql(),
rowIds,
{ resultSet: true }
);
obj.response = response.rows;
}
return obj;
});
});
};
/**

View File

@ -1,6 +1,5 @@
const { isUndefined } = require('lodash');
const Bluebird = require('bluebird');
const Transaction = require('../../transaction');
const { timeout, KnexTimeoutError } = require('../../util/timeout');
const debugTx = require('debug')('knex:tx');
@ -8,7 +7,7 @@ const debugTx = require('debug')('knex:tx');
module.exports = class Oracle_Transaction extends Transaction {
// disable autocommit to allow correct behavior (default is true)
begin() {
return Bluebird.resolve();
return Promise.resolve();
}
async commit(conn, value) {
@ -54,7 +53,7 @@ module.exports = class Oracle_Transaction extends Transaction {
acquireConnection(config, cb) {
const configConnection = config && config.connection;
const t = this;
return new Bluebird((resolve, reject) => {
return new Promise((resolve, reject) => {
try {
this.client
.acquireConnection()

View File

@ -4,7 +4,6 @@ const { map, extend, isString } = require('lodash');
const { promisify } = require('util');
const inherits = require('inherits');
const Client = require('../../client');
const Bluebird = require('bluebird');
const QueryCompiler = require('./query/compiler');
const ColumnCompiler = require('./schema/columncompiler');
@ -106,7 +105,7 @@ Object.assign(Client_PG.prototype, {
// connection needs to be added to the pool.
acquireRawConnection() {
const client = this;
return new Bluebird(function(resolver, rejecter) {
return new Promise(function(resolver, rejecter) {
const connection = new client.driver.Client(client.connectionSettings);
connection.connect(function(err, connection) {
if (err) {
@ -142,7 +141,7 @@ Object.assign(Client_PG.prototype, {
// In PostgreSQL, we need to do a version check to do some feature
// checking on the database.
checkVersion(connection) {
return new Bluebird(function(resolver, rejecter) {
return new Promise(function(resolver, rejecter) {
connection.query('select version();', function(err, resp) {
if (err) return rejecter(err);
resolver(/^PostgreSQL (.*?)( |$)/.exec(resp.rows[0].version)[1]);
@ -167,7 +166,7 @@ Object.assign(Client_PG.prototype, {
setSchemaSearchPath(connection, searchPath) {
let path = searchPath || this.searchPath;
if (!path) return Bluebird.resolve(true);
if (!path) return Promise.resolve(true);
if (!Array.isArray(path) && !isString(path)) {
throw new TypeError(
@ -191,7 +190,7 @@ Object.assign(Client_PG.prototype, {
path = path.map((schemaName) => `"${schemaName}"`).join(',');
return new Bluebird(function(resolver, rejecter) {
return new Promise(function(resolver, rejecter) {
connection.query(`set search_path to ${path}`, function(err) {
if (err) return rejecter(err);
resolver(true);
@ -205,7 +204,7 @@ Object.assign(Client_PG.prototype, {
: require('pg-query-stream');
const sql = obj.sql;
return new Bluebird(function(resolver, rejecter) {
return new Promise(function(resolver, rejecter) {
const queryStream = connection.query(
new PGQueryStream(sql, obj.bindings, options)
);
@ -233,7 +232,7 @@ Object.assign(Client_PG.prototype, {
queryConfig = extend(queryConfig, obj.options);
}
return new Bluebird(function(resolver, rejecter) {
return new Promise(function(resolver, rejecter) {
connection.query(queryConfig, function(err, response) {
if (err) return rejecter(err);
obj.response = response;
@ -273,22 +272,20 @@ Object.assign(Client_PG.prototype, {
},
canCancelQuery: true,
cancelQuery(connectionToKill) {
const acquiringConn = this.acquireConnection();
async cancelQuery(connectionToKill) {
// Error out if we can't acquire connection in time.
// Purposely not putting timeout on `pg_cancel_backend` execution because erroring
// early there would release the `connectionToKill` back to the pool with
// a `KILL QUERY` command yet to finish.
return acquiringConn.then((conn) => {
return this._wrappedCancelQueryCall(conn, connectionToKill).finally(
() => {
// NOT returning this promise because we want to release the connection
// in a non-blocking fashion
this.releaseConnection(conn);
}
);
});
const conn = await this.acquireConnection();
try {
return await this._wrappedCancelQueryCall(conn, connectionToKill);
} finally {
// NOT returning this promise because we want to release the connection
// in a non-blocking fashion
this.releaseConnection(conn);
}
},
_wrappedCancelQueryCall(conn, connectionToKill) {
return this.query(conn, {

View File

@ -1,7 +1,5 @@
// SQLite3
// -------
const Bluebird = require('bluebird');
const inherits = require('inherits');
const { isUndefined, map, defaults } = require('lodash');
const { promisify } = require('util');
@ -63,7 +61,7 @@ Object.assign(Client_SQLite3.prototype, {
// Get a raw connection from the database, returning a promise with the connection object.
acquireRawConnection() {
return new Bluebird((resolve, reject) => {
return new Promise((resolve, reject) => {
const db = new this.driver.Database(
this.connectionSettings.filename,
(err) => {
@ -98,7 +96,7 @@ Object.assign(Client_SQLite3.prototype, {
default:
callMethod = 'all';
}
return new Bluebird(function(resolver, rejecter) {
return new Promise(function(resolver, rejecter) {
if (!connection || !connection[callMethod]) {
return rejecter(
new Error(`Error calling ${callMethod} on connection.`)
@ -118,7 +116,7 @@ Object.assign(Client_SQLite3.prototype, {
_stream(connection, sql, stream) {
const client = this;
return new Bluebird(function(resolver, rejecter) {
return new Promise(function(resolver, rejecter) {
stream.on('error', rejecter);
stream.on('end', resolver);
return client

View File

@ -1,5 +1,6 @@
const { isEmpty, map, clone, each } = require('lodash');
const Bluebird = require('bluebird');
const { isEmpty, map, clone } = require('lodash');
const { callbackify } = require('util');
const finallyMixin = require('./util/finally-mixin');
module.exports = function(Target) {
Target.prototype.toQuery = function(tz) {
@ -25,7 +26,7 @@ module.exports = function(Target) {
});
}
return Bluebird.resolve(result.then.apply(result, arguments));
return result.then.apply(result, arguments);
};
// Add additional "options" to the builder. Typically used for client specific
@ -81,31 +82,15 @@ module.exports = function(Target) {
);
};
// Creates a method which "coerces" to a promise, by calling a
// "then" method on the current `Target`
each(
[
'bind',
'catch',
'finally',
'asCallback',
'spread',
'map',
'reduce',
'thenReturn',
'return',
'yield',
'ensure',
'reflect',
'get',
'mapSeries',
'delay',
],
function(method) {
Target.prototype[method] = function() {
const promise = this.then();
return promise[method].apply(promise, arguments);
};
}
);
Target.prototype.asCallback = function(cb) {
const promise = this.then();
callbackify(() => promise)(cb);
return promise;
};
Target.prototype.catch = function(onReject) {
return this.then().catch(onReject);
};
finallyMixin(Target.prototype);
};

View File

@ -1,4 +1,3 @@
const Bluebird = require('bluebird');
const { getTableName } = require('./table-resolver');
const { ensureTable } = require('./table-creator');
@ -27,7 +26,7 @@ function listCompleted(tableName, schemaName, trxOrKnex) {
// Gets the migration list from the migration directory specified in config, as well as
// the list of completed migrations to check what should be run.
function listAllAndCompleted(config, trxOrKnex) {
return Bluebird.all([
return Promise.all([
listAll(config.migrationSource, config.loadExtensions),
listCompleted(config.tableName, config.schemaName, trxOrKnex),
]);

View File

@ -1,4 +1,3 @@
const Bluebird = require('bluebird');
const { KnexTimeoutError } = require('./util/timeout');
const { timeout } = require('./util/timeout');
@ -105,7 +104,7 @@ Object.assign(Runner.prototype, {
// and the promise will take care of itself.
if (hasHandler) {
handler(stream);
return Bluebird.resolve(promise);
return promise;
}
// Emit errors on the stream if the error occurred before a connection
@ -181,7 +180,7 @@ Object.assign(Runner.prototype, {
// return the connection to the pool, it will be useless until the current operation
// that timed out, finally finishes.
this.connection.__knex__disposed = error;
cancelQuery = Bluebird.resolve();
cancelQuery = Promise.resolve();
}
return cancelQuery

View File

@ -1,11 +1,12 @@
// Transaction
// -------
const Bluebird = require('bluebird');
const { EventEmitter } = require('events');
const Debug = require('debug');
const makeKnex = require('./util/make-knex');
const { callbackify } = require('util');
const { timeout, KnexTimeoutError } = require('./util/timeout');
const finallyMixin = require('./util/finally-mixin');
const debug = Debug('knex:tx');
@ -57,7 +58,7 @@ class Transaction extends EventEmitter {
const init = client.transacting
? this.savepoint(connection)
: this.begin(connection);
const executionPromise = new Bluebird((resolver, rejecter) => {
const executionPromise = new Promise((resolver, rejecter) => {
this._resolver = resolver;
this._rejecter = rejecter;
});
@ -76,7 +77,7 @@ class Transaction extends EventEmitter {
try {
result = container(transactor);
} catch (err) {
result = Bluebird.reject(err);
result = Promise.reject(err);
}
if (result && result.then && typeof result.then === 'function') {
result
@ -96,10 +97,9 @@ class Transaction extends EventEmitter {
return executionPromise;
});
// FYI: This is the Promise Chain for EXTERNAL use. It ensures that the
// caller must handle any exceptions that result from `basePromise`.
this._promise = basePromise.then((x)=> x);
this._promise = basePromise.then((x) => x);
this._completed = false;
@ -107,14 +107,14 @@ class Transaction extends EventEmitter {
// transactions to settle (commit or rollback) before we can start, and we
// need to register ourselves with the parent transaction so any younger
// siblings can wait for us to complete before they can start.
this._previousSibling = Bluebird.resolve(true);
this._previousSibling = Promise.resolve(true);
if (outerTx) {
if (outerTx._lastChild) this._previousSibling = outerTx._lastChild;
// FYI: This is the Promise Chain for INTERNAL use. It serves as a signal
// for when the next sibling should begin its execution. Therefore,
// exceptions are caught and ignored.
outerTx._lastChild = basePromise.catch(()=> {});
outerTx._lastChild = basePromise.catch(() => {});
}
}
@ -205,7 +205,7 @@ class Transaction extends EventEmitter {
// the original promise is marked completed.
acquireConnection(config, cb) {
const configConnection = config && config.connection;
return new Bluebird((resolve, reject) => {
return new Promise((resolve, reject) => {
try {
resolve(configConnection || this.client.acquireConnection());
} catch (e) {
@ -215,11 +215,13 @@ class Transaction extends EventEmitter {
.then((connection) => {
connection.__knexTxId = this.txid;
return this._previousSibling
// .catch(() => {}) // TODO: Investigate this line
.then(function() {
return connection;
});
return (
this._previousSibling
// .catch(() => {}) // TODO: Investigate this line
.then(function() {
return connection;
})
);
})
.then(async (connection) => {
try {
@ -234,7 +236,21 @@ class Transaction extends EventEmitter {
}
});
}
then(onResolve, onReject) {
return this._promise.then(onResolve, onReject);
}
catch(onReject) {
return this._promise.catch(onReject);
}
asCallback(cb) {
callbackify(() => this._promise)(cb);
return this._promise;
}
}
finallyMixin(Transaction.prototype);
// The transactor is a full featured knex object, with a "commit", a "rollback"
// and a "savepoint" function. The "savepoint" is just sugar for creating a new
@ -320,7 +336,7 @@ function makeTxClient(trx, client, connection) {
const _query = trxClient.query;
trxClient.query = function(conn, obj) {
const completed = trx.isCompleted();
return new Bluebird(function(resolve, reject) {
return new Promise(function(resolve, reject) {
try {
if (conn !== connection)
throw new Error('Invalid connection for transaction query.');
@ -334,7 +350,7 @@ function makeTxClient(trx, client, connection) {
const _stream = trxClient.stream;
trxClient.stream = function(conn, obj, stream, options) {
const completed = trx.isCompleted();
return new Bluebird(function(resolve, reject) {
return new Promise(function(resolve, reject) {
try {
if (conn !== connection)
throw new Error('Invalid connection for transaction query.');
@ -346,10 +362,10 @@ function makeTxClient(trx, client, connection) {
});
};
trxClient.acquireConnection = function() {
return Bluebird.resolve(connection);
return Promise.resolve(connection);
};
trxClient.releaseConnection = function() {
return Bluebird.resolve();
return Promise.resolve();
};
return trxClient;
@ -363,32 +379,4 @@ function completedError(trx, obj) {
);
}
const promiseInterface = [
'then',
'bind',
'catch',
'finally',
'asCallback',
'spread',
'map',
'reduce',
'thenReturn',
'return',
'yield',
'ensure',
'exec',
'reflect',
'get',
'mapSeries',
'delay',
];
// Creates methods which proxy promise interface methods to
// internal transaction resolution promise
promiseInterface.forEach(function(method) {
Transaction.prototype[method] = function() {
return this._promise[method].apply(this._promise, arguments);
};
});
module.exports = Transaction;

13
lib/util/finally-mixin.js Normal file
View File

@ -0,0 +1,13 @@
const noop = require('./noop');
const finallyMixin = (prototype) =>
Object.assign(prototype, {
finally(onFinally) {
return this.then().finally(onFinally);
},
});
// FYI: Support for `Promise.prototype.finally` was not introduced until Node 9.
// Therefore, Knex will need to conditionally inject support for `.finally(..)`
// until support for Node 8 is officially dropped.
module.exports = Promise.prototype.finally ? noop : finallyMixin;

View File

@ -1,4 +1,3 @@
const Bluebird = require('bluebird');
const delay = require('./delay');
class KnexTimeoutError extends Error {
@ -10,11 +9,9 @@ class KnexTimeoutError extends Error {
module.exports.KnexTimeoutError = KnexTimeoutError;
module.exports.timeout = (promise, ms) =>
Bluebird.resolve(
Promise.race([
promise,
delay(ms).then(() =>
Promise.reject(new KnexTimeoutError('operation timed out'))
),
])
);
Promise.race([
promise,
delay(ms).then(() =>
Promise.reject(new KnexTimeoutError('operation timed out'))
),
]);

View File

@ -28,7 +28,6 @@
"stress:destroy": "docker-compose -f scripts/stress-test/docker-compose.yml stop"
},
"dependencies": {
"bluebird": "^3.7.2",
"colorette": "1.1.0",
"commander": "^4.1.1",
"debug": "4.1.1",

View File

@ -2,7 +2,6 @@
const fs = require('fs');
const path = require('path');
const child_process = require('child_process');
const Promise = require('bluebird');
const _ = require('lodash');
const exec = function(cmd, args) {
@ -91,7 +90,7 @@ if (POSTINSTALL_BUILD_CWD !== CWD) {
? exec('npm install ' + installArgs, opts)
: Promise.resolve();
dependenciesInstalledQ
.then(function(stdout, stderr) {
.then(function() {
console.log('✓');
// Don't need the flag anymore as `postinstall` was already run.
// Change it back so the environment is minimally changed for the
@ -104,7 +103,7 @@ if (POSTINSTALL_BUILD_CWD !== CWD) {
console.error(err);
process.exit(1);
})
.then(function(stdout, stderr) {
.then(function() {
if (process.env.NODE_ENV === 'production') {
console.log('✓');
console.log('Pruning dev dependencies for production build');

17
types/index.d.ts vendored
View File

@ -1421,21 +1421,8 @@ declare namespace Knex {
type ExposedPromiseKeys =
| "then"
| "bind"
| "catch"
| "finally"
| "asCallback"
| "spread"
| "map"
| "reduce"
| "thenReturn"
| "return"
| "yield"
| "ensure"
| "reflect"
| "get"
| "mapSeries"
| "delay";
| "finally";
interface ChainableInterface<T = any> extends Pick<Promise<T>, keyof Promise<T> & ExposedPromiseKeys> {
toQuery(): string;
@ -1453,7 +1440,7 @@ declare namespace Knex {
writable: T,
options?: Readonly<{ [key: string]: any }>
): stream.PassThrough;
asCallback(callback: Function): this;
asCallback(callback: Function): Promise<T>;
}
interface Transaction<TRecord extends {} = any, TResult = any>