function Client() { var config = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.config = config; //Client is a required field, so throw error if it's not supplied. //If 'this.dialect' is set, then this is a 'super()' call, in which case //'client' does not have to be set as it's already assigned on the client prototype. if (!this.config.client && !this.dialect) { throw new Error('knex: Required configuration option \'client\' is missing.'); } this.connectionSettings = (0, _cloneDeep3.default)(config.connection || {}); if (this.driverName && config.connection) { this.initializeDriver(); if (!config.pool || config.pool && config.pool.max !== 0) { this.__cid = clientId(); this.initializePool(config); } } this.valueForUndefined = this.raw('DEFAULT'); if (config.useNullAsDefault) { this.valueForUndefined = null; } }
n/a
function Formatter(client) { (0, _classCallCheck3.default)(this, Formatter); this.client = client; this.bindings = []; }
...
return this.toQuery();
},
// Returns the raw sql for the query.
toSQL: function toSQL(method, tz) {
var obj = void 0;
var formatter = this.client.formatter();
if (Array.isArray(this.bindings)) {
obj = replaceRawArrBindings(this, formatter);
} else if (this.bindings && (0, _isPlainObject3.default)(this.bindings)) {
obj = replaceKeyBindings(this, formatter);
} else {
obj = {
...
function FunctionHelper(client) { this.client = client; }
n/a
function Migrator(knex) { (0, _classCallCheck3.default)(this, Migrator); this.knex = knex; this.config = this.setConfig(knex.client.config.migrations); }
n/a
raw = function (sql, bindings) { (0, _helpers.warn)('global Knex.raw is deprecated, use knex.raw (chain off an initialized knex object)'); return new _raw2.default().set(sql, bindings); }
...
// FunctionHelper
// -------
function FunctionHelper(client) {
this.client = client;
}
FunctionHelper.prototype.now = function () {
return this.client.raw('CURRENT_TIMESTAMP');
};
exports.default = FunctionHelper;
module.exports = exports['default'];
...
function Runner(client, builder) { this.client = client; this.builder = builder; this.queries = []; // The "connection" object is set on the runner when // "run" is called. this.connection = void 0; }
...
return (0, _map3.default)(data, function (statement) {
return _this.client._formatQuery(statement.sql, statement.bindings, tz);
}).join(';\n');
};
// Create a new instance of the `Runner`, passing in the current object.
Target.prototype.then = function () /* onFulfilled, onRejected */{
var result = this.client.runner(this).run();
return result.then.apply(result, arguments);
};
// Add additional "options" to the builder. Typically used for client specific
// items, like the `mysql` and `sqlite3` drivers.
Target.prototype.options = function (opts) {
this._options = this._options || [];
...
function Seeder(knex) { this.knex = knex; this.config = this.setConfig(knex.client.config.seeds); }
n/a
function Transaction(client, container, config, outerTx) { (0, _classCallCheck3.default)(this, Transaction); var _this = (0, _possibleConstructorReturn3.default)(this, _EventEmitter.call(this)); var txid = _this.txid = (0, _uniqueId3.default)('trx'); _this.client = client; _this.outerTx = outerTx; _this.trxClient = undefined; _this._debug = client.config && client.config.debug; debug('%s: Starting %s transaction', txid, outerTx ? 'nested' : 'top level'); _this._promise = _bluebird2.default.using(_this.acquireConnection(client, config, txid), function (connection) { var trxClient = _this.trxClient = makeTxClient(_this, client, connection); var init = client.transacting ? _this.savepoint(connection) : _this.begin(connection); init.then(function () { return makeTransactor(_this, connection, trxClient); }).then(function (transactor) { // If we've returned a "thenable" from the transaction container, assume // the rollback and commit are chained to this object's success / failure. // Directly thrown errors are treated as automatic rollbacks. var result = void 0; try { result = container(transactor); } catch (err) { result = _bluebird2.default.reject(err); } if (result && result.then && typeof result.then === 'function') { result.then(function (val) { return transactor.commit(val); }).catch(function (err) { return transactor.rollback(err); }); } return null; }).catch(function (e) { return _this._rejecter(e); }); return new _bluebird2.default(function (resolver, rejecter) { _this._resolver = resolver; _this._rejecter = rejecter; }); }); _this._completed = false; // If there's a wrapping transaction, we need to wait for any older sibling // 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 = _bluebird2.default.resolve(true); if (outerTx) { if (outerTx._lastChild) _this._previousSibling = outerTx._lastChild; outerTx._lastChild = _this._promise; } return _this; }
...
exports.default = Transaction;
function makeTransactor(trx, connection, trxClient) {
var transactor = (0, _makeKnex2.default)(trxClient);
transactor.transaction = function (container, options) {
return trxClient.transaction(container, options, trx);
};
transactor.savepoint = function (container, options) {
return transactor.transaction(container, options);
};
if (trx.client.transacting) {
transactor.commit = function (value) {
...
function Client() { var config = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.config = config; //Client is a required field, so throw error if it's not supplied. //If 'this.dialect' is set, then this is a 'super()' call, in which case //'client' does not have to be set as it's already assigned on the client prototype. if (!this.config.client && !this.dialect) { throw new Error('knex: Required configuration option \'client\' is missing.'); } this.connectionSettings = (0, _cloneDeep3.default)(config.connection || {}); if (this.driverName && config.connection) { this.initializeDriver(); if (!config.pool || config.pool && config.pool.max !== 0) { this.__cid = clientId(); this.initializePool(config); } } this.valueForUndefined = this.raw('DEFAULT'); if (config.useNullAsDefault) { this.valueForUndefined = null; } }
n/a
function EventEmitter() { EventEmitter.init.call(this); }
n/a
function finalEscape(val) { var ctx = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; return escapeFn(val, finalEscape, ctx); }
n/a
function _formatQuery(sql, bindings, timeZone) { var _this = this; bindings = bindings == null ? [] : [].concat(bindings); var index = 0; return sql.replace(/\\?\?/g, function (match) { if (match === '\\?') { return '?'; } if (index === bindings.length) { return match; } var value = bindings[index++]; return _this._escapeBinding(value, { timeZone: timeZone }); }); }
...
Target.prototype.toQuery = function (tz) {
var _this = this;
var data = this.toSQL(this._method, tz);
if (!(0, _isArray3.default)(data)) data = [data];
return (0, _map3.default)(data, function (statement) {
return _this.client._formatQuery(statement.sql, statement.bindings, tz);
}).join(';\n');
};
// Create a new instance of the `Runner`, passing in the current object.
Target.prototype.then = function () /* onFulfilled, onRejected */{
var result = this.client.runner(this).run();
return result.then.apply(result, arguments);
...
function acquireConnection() { var _this4 = this; return new _bluebird2.default(function (resolver, rejecter) { if (!_this4.pool) { return rejecter(new Error('Unable to acquire a connection')); } var wasRejected = false; var t = setTimeout(function () { wasRejected = true; rejecter(new _bluebird2.default.TimeoutError('Knex: Timeout acquiring a connection. The pool is probably full. ' + 'Are you missing a .transacting(trx) call?')); }, _this4.config.acquireConnectionTimeout || 60000); _this4.pool.acquire(function (err, connection) { clearTimeout(t); if (err) { return rejecter(err); } if (wasRejected) { _this4.pool.release(connection); } else { debug('acquired connection from pool: %s', connection.__knexUid); resolver(connection); } }); }); }
...
// Check whether there's a transaction flag, and that it has a connection.
ensureConnection: function ensureConnection() {
var _this2 = this;
return _bluebird2.default.try(function () {
return _this2.connection || new _bluebird2.default(function (resolver, rejecter) {
// need to return promise or null from handler to prevent warning from bluebird
return _this2.client.acquireConnection().then(resolver).catch(_bluebird2.default.
TimeoutError, function (error) {
if (_this2.builder) {
error.sql = _this2.builder.sql;
error.bindings = _this2.builder.bindings;
}
throw error;
}).catch(rejecter);
});
...
function assertCanCancelQuery() { if (!this.canCancelQuery) { throw new Error("Query cancelling not supported for this dialect"); } }
...
var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var cancel = _ref.cancel;
if ((0, _isNumber3.default)(ms) && ms > 0) {
this._timeout = ms;
if (cancel) {
this.client.assertCanCancelQuery();
this._cancelOnTimeout = true;
}
}
return this;
},
...
function cancelQuery() { throw new Error("Query cancelling not supported for this dialect"); }
...
var timeout = obj.timeout;
var sql = obj.sql;
var bindings = obj.bindings;
var cancelQuery = void 0;
if (obj.cancelOnTimeout) {
cancelQuery = _this.client.cancelQuery(_this.connection);
} else {
cancelQuery = _bluebird2.default.resolve();
}
return cancelQuery.catch(function (cancelError) {
// cancellation failed
throw (0, _assign3.default)(cancelError, {
...
function columnBuilder(tableBuilder, type, args) { return new _columnbuilder2.default(this, tableBuilder, type, args); }
n/a
function columnCompiler(tableBuilder, columnBuilder) { return new _columncompiler2.default(this, tableBuilder, columnBuilder); }
n/a
function database() { return this.connectionSettings.database; }
n/a
function destroy(callback) { var _this6 = this; var promise = new _bluebird2.default(function (resolver) { if (!_this6.pool) { return resolver(); } _this6.pool.drain(function () { _this6.pool.destroyAllNow(function () { _this6.pool = undefined; resolver(); }); }); }); // Allow either a callback or promise interface for destruction. if (typeof callback === 'function') { promise.asCallback(callback); } else { return promise; } }
n/a
function formatter() { return new _formatter2.default(this); }
...
return this.toQuery();
},
// Returns the raw sql for the query.
toSQL: function toSQL(method, tz) {
var obj = void 0;
var formatter = this.client.formatter();
if (Array.isArray(this.bindings)) {
obj = replaceRawArrBindings(this, formatter);
} else if (this.bindings && (0, _isPlainObject3.default)(this.bindings)) {
obj = replaceKeyBindings(this, formatter);
} else {
obj = {
...
function initializeDriver() { try { this.driver = this._driver(); } catch (e) { helpers.exit('Knex: run\n$ npm install ' + this.driverName + ' --save\n' + e.stack); } }
n/a
function initializePool(config) { if (this.pool) { helpers.warn('The pool has already been initialized'); return; } this.pool = new _genericPool.Pool((0, _assign3.default)(this.poolDefaults(config.pool || {}), config.pool)); }
n/a
function poolDefaults(poolConfig) { var _this3 = this; var name = this.dialect + ':' + this.driverName + ':' + this.__cid; return { min: 2, max: 10, name: name, log: function log(str, level) { if (level === 'info') { debugPool(level.toUpperCase() + ' pool ' + name + ' - ' + str); } }, create: function create(callback) { _this3.acquireRawConnection().tap(function (connection) { connection.__knexUid = (0, _uniqueId3.default)('__knexUid'); if (poolConfig.afterCreate) { return _bluebird2.default.promisify(poolConfig.afterCreate)(connection); } }).asCallback(callback); }, destroy: function destroy(connection) { if (poolConfig.beforeDestroy) { helpers.warn('\n beforeDestroy is deprecated, please open an issue if you use this\n to discuss alternative apis\n '); poolConfig.beforeDestroy(connection, function () {}); } if (connection !== void 0) { _this3.destroyRawConnection(connection); } }, validate: function validate(connection) { if (connection.__knex__disposed) { helpers.warn('Connection Error: ' + connection.__knex__disposed); return false; } return _this3.validateConnection(connection); } }; }
n/a
function prepBindings(bindings) { return bindings; }
n/a
function query(connection, obj) { var _this2 = this; if (typeof obj === 'string') obj = { sql: obj }; obj.bindings = this.prepBindings(obj.bindings); debugQuery(obj.sql); this.emit('query', (0, _assign3.default)({ __knexUid: connection.__knexUid }, obj)); debugBindings(obj.bindings); return this._query(connection, obj).catch(function (err) { err.message = _this2._formatQuery(obj.sql, obj.bindings) + ' - ' + err.message; _this2.emit('query-error', err, (0, _assign3.default)({ __knexUid: connection.__knexUid }, obj)); throw err; }); }
...
if (runner.builder._debug) {
helpers.debugLog(sql);
}
if ((0, _isArray3.default)(sql)) {
return runner.queryArray(sql);
}
return runner.query(sql);
})
// If there are any "error" listeners, we fire an error event
// and then re-throw the error to be eventually handled by
// the promise chain. Useful if you're wrapping in a custom `Promise`.
.catch(function (err) {
if (runner.builder._events && runner.builder._events.error) {
...
function queryBuilder() { return new _builder2.default(this); }
...
Formatter.prototype.compileCallback = function compileCallback(callback, method) {
var client = this.client;
// Build the callback
var builder = client.queryBuilder();
callback.call(builder, builder);
// Compile the callback, using the current formatter (to track all bindings).
var compiler = client.queryCompiler(builder);
compiler.formatter = this;
// Return the compiled & parameterized sql.
...
function queryCompiler(builder) { return new _compiler2.default(this, builder); }
...
}
return this.unwrapRaw(value, true) || '?';
};
Formatter.prototype.unwrapRaw = function unwrapRaw(value, isParameter) {
var query = void 0;
if (value instanceof _builder2.default) {
query = this.client.queryCompiler(value).toSQL();
if (query.bindings) {
this.bindings = this.bindings.concat(query.bindings);
}
return this.outputQuery(query, isParameter);
}
if (value instanceof _raw2.default) {
value.client = this.client;
...
function raw() { var _ref; return (_ref = new _raw2.default(this)).set.apply(_ref, arguments); }
...
// FunctionHelper
// -------
function FunctionHelper(client) {
this.client = client;
}
FunctionHelper.prototype.now = function () {
return this.client.raw('CURRENT_TIMESTAMP');
};
exports.default = FunctionHelper;
module.exports = exports['default'];
...
function releaseConnection(connection) { var _this5 = this; return new _bluebird2.default(function (resolver) { debug('releasing connection to pool: %s', connection.__knexUid); _this5.pool.release(connection); resolver(); }); }
...
error.bindings = _this2.builder.bindings;
}
throw error;
}).catch(rejecter);
});
}).disposer(function () {
// need to return promise or null from handler to prevent warning from bluebird
return _this2.client.releaseConnection(_this2.connection);
});
}
});
exports.default = Runner;
module.exports = exports['default'];
...
function runner(connection) { return new _runner2.default(this, connection); }
...
return (0, _map3.default)(data, function (statement) {
return _this.client._formatQuery(statement.sql, statement.bindings, tz);
}).join(';\n');
};
// Create a new instance of the `Runner`, passing in the current object.
Target.prototype.then = function () /* onFulfilled, onRejected */{
var result = this.client.runner(this).run();
return result.then.apply(result, arguments);
};
// Add additional "options" to the builder. Typically used for client specific
// items, like the `mysql` and `sqlite3` drivers.
Target.prototype.options = function (opts) {
this._options = this._options || [];
...
function schemaBuilder() { return new _builder4.default(this); }
n/a
function schemaCompiler(builder) { return new _compiler4.default(this, builder); }
n/a
function stream(connection, obj, _stream, options) { if (typeof obj === 'string') obj = { sql: obj }; this.emit('query', (0, _assign3.default)({ __knexUid: connection.__knexUid }, obj)); debugQuery(obj.sql); obj.bindings = this.prepBindings(obj.bindings); debugBindings(obj.bindings); return this._stream(connection, obj, _stream, options); }
...
}
}
return this;
};
// Initializes a stream.
Target.prototype.stream = function (options) {
return this.client.runner(this).stream(options);
};
// Initialize a stream & pipe automatically.
Target.prototype.pipe = function (writable, options) {
return this.client.runner(this).pipe(writable, options);
};
...
function tableBuilder(type, tableName, fn) { return new _tablebuilder2.default(this, type, tableName, fn); }
n/a
function tableCompiler(tableBuilder) { return new _tablecompiler2.default(this, tableBuilder); }
n/a
function toString() { return '[object KnexClient]'; }
n/a
function transaction(container, config, outerTx) { return new _transaction2.default(this, container, config, outerTx); }
...
exports.default = Transaction;
function makeTransactor(trx, connection, trxClient) {
var transactor = (0, _makeKnex2.default)(trxClient);
transactor.transaction = function (container, options) {
return trxClient.transaction(container, options, trx);
};
transactor.savepoint = function (container, options) {
return transactor.transaction(container, options);
};
if (trx.client.transacting) {
transactor.commit = function (value) {
...
function validateConnection(connection) { return true; }
n/a
function wrapIdentifier(value) { return value !== '*' ? '"' + value.replace(/"/g, '""') + '"' : '*'; }
...
var raw = this.unwrapRaw(value);
if (raw) return raw;
if (typeof value === 'number') return value;
return this._wrapString(value + '');
};
Formatter.prototype.wrapAsIdentifier = function wrapAsIdentifier(value) {
return this.client.wrapIdentifier((value || '').trim());
};
Formatter.prototype.alias = function alias(first, second) {
return first + ' as ' + second;
};
// The operator method takes a value and returns something or other.
...
function Formatter(client) { (0, _classCallCheck3.default)(this, Formatter); this.client = client; this.bindings = []; }
...
return this.toQuery();
},
// Returns the raw sql for the query.
toSQL: function toSQL(method, tz) {
var obj = void 0;
var formatter = this.client.formatter();
if (Array.isArray(this.bindings)) {
obj = replaceRawArrBindings(this, formatter);
} else if (this.bindings && (0, _isPlainObject3.default)(this.bindings)) {
obj = replaceKeyBindings(this, formatter);
} else {
obj = {
...
function _wrapString(value) { var asIndex = value.toLowerCase().indexOf(' as '); if (asIndex !== -1) { var first = value.slice(0, asIndex); var second = value.slice(asIndex + 4); return this.alias(this.wrap(first), this.wrapAsIdentifier(second)); } var wrapped = []; var i = -1; var segments = value.split('.'); while (++i < segments.length) { value = segments[i]; if (i === 0 && segments.length > 1) { wrapped.push(this.wrap((value || '').trim())); } else { wrapped.push(this.client.wrapIdentifier((value || '').trim())); } } return wrapped.join('.'); }
...
Formatter.prototype.wrap = function wrap(value) {
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
var raw = this.unwrapRaw(value);
if (raw) return raw;
if (typeof value === 'number') return value;
return this._wrapString(value + '');
};
Formatter.prototype.wrapAsIdentifier = function wrapAsIdentifier(value) {
return this.client.wrapIdentifier((value || '').trim());
};
Formatter.prototype.alias = function alias(first, second) {
...
function alias(first, second) { return first + ' as ' + second; }
...
Formatter.prototype.outputQuery = function outputQuery(compiled, isParameter) {
var sql = compiled.sql || '';
if (sql) {
if ((compiled.method === 'select' || compiled.method === 'first') && (isParameter || compiled.
as)) {
sql = '(' + sql + ')';
if (compiled.as) return this.alias(sql, this.wrap(compiled.as));
}
}
return sql;
};
// Coerce to string to prevent strange errors when it's not a string.
...
function columnize(target) { var columns = typeof target === 'string' ? [target] : target; var str = '', i = -1; while (++i < columns.length) { if (i > 0) str += ', '; str += this.wrap(columns[i]); } return str; }
...
if (match === '\\?') {
return match;
}
var value = values[index++];
if (match === '??') {
return formatter.columnize(value);
}
return formatter.parameter(value);
});
if (expectedBindings !== index) {
throw new Error('Expected ' + expectedBindings + ' bindings, saw ' + index);
}
...
function compileCallback(callback, method) { var client = this.client; // Build the callback var builder = client.queryBuilder(); callback.call(builder, builder); // Compile the callback, using the current formatter (to track all bindings). var compiler = client.queryCompiler(builder); compiler.formatter = this; // Return the compiled & parameterized sql. return compiler.toSQL(method || 'select'); }
...
// Checks whether a value is a function... if it is, we compile it
// otherwise we check whether it's a raw
Formatter.prototype.parameter = function parameter(value) {
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
return this.unwrapRaw(value, true) || '?';
};
Formatter.prototype.unwrapRaw = function unwrapRaw(value, isParameter) {
var query = void 0;
if (value instanceof _builder2.default) {
...
function direction(value) { var raw = this.unwrapRaw(value); if (raw) return raw; return orderBys.indexOf((value || '').toLowerCase()) !== -1 ? value : 'asc'; }
n/a
function operator(value) { var raw = this.unwrapRaw(value); if (raw) return raw; if (operators[(value || '').toLowerCase()] !== true) { throw new TypeError('The operator "' + value + '" is not permitted'); } return value; }
n/a
function outputQuery(compiled, isParameter) { var sql = compiled.sql || ''; if (sql) { if ((compiled.method === 'select' || compiled.method === 'first') && (isParameter || compiled.as)) { sql = '(' + sql + ')'; if (compiled.as) return this.alias(sql, this.wrap(compiled.as)); } } return sql; }
...
// Checks whether a value is a function... if it is, we compile it
// otherwise we check whether it's a raw
Formatter.prototype.parameter = function parameter(value) {
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
return this.unwrapRaw(value, true) || '?';
};
Formatter.prototype.unwrapRaw = function unwrapRaw(value, isParameter) {
var query = void 0;
if (value instanceof _builder2.default) {
...
function parameter(value) { if (typeof value === 'function') { return this.outputQuery(this.compileCallback(value), true); } return this.unwrapRaw(value, true) || '?'; }
...
};
// Turns a list of values into a list of ?'s, joining them with commas unless
// a "joining" value is specified (e.g. ' and ')
Formatter.prototype.parameterize = function parameterize(values, notSetValue) {
if (typeof values === 'function') return this.parameter(values);
values = Array.isArray(values) ? values : [values];
var str = '',
i = -1;
while (++i < values.length) {
if (i > 0) str += ', ';
str += this.parameter(values[i] === undefined ? notSetValue : values[i]);
}
...
function parameterize(values, notSetValue) { if (typeof values === 'function') return this.parameter(values); values = Array.isArray(values) ? values : [values]; var str = '', i = -1; while (++i < values.length) { if (i > 0) str += ', '; str += this.parameter(values[i] === undefined ? notSetValue : values[i]); } return str; }
n/a
function rawOrFn(value, method) { if (typeof value === 'function') { return this.outputQuery(this.compileCallback(value, method)); } return this.unwrapRaw(value) || ''; }
n/a
function unwrapRaw(value, isParameter) { var query = void 0; if (value instanceof _builder2.default) { query = this.client.queryCompiler(value).toSQL(); if (query.bindings) { this.bindings = this.bindings.concat(query.bindings); } return this.outputQuery(query, isParameter); } if (value instanceof _raw2.default) { value.client = this.client; query = value.toSQL(); if (query.bindings) { this.bindings = this.bindings.concat(query.bindings); } return query.sql; } if (isParameter) { this.bindings.push(value); } }
...
// otherwise we check whether it's a raw
Formatter.prototype.parameter = function parameter(value) {
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
return this.unwrapRaw(value, true) || '?';
};
Formatter.prototype.unwrapRaw = function unwrapRaw(value, isParameter) {
var query = void 0;
if (value instanceof _builder2.default) {
query = this.client.queryCompiler(value).toSQL();
if (query.bindings) {
...
function wrap(value) { if (typeof value === 'function') { return this.outputQuery(this.compileCallback(value), true); } var raw = this.unwrapRaw(value); if (raw) return raw; if (typeof value === 'number') return value; return this._wrapString(value + ''); }
...
Formatter.prototype.columnize = function columnize(target) {
var columns = typeof target === 'string' ? [target] : target;
var str = '',
i = -1;
while (++i < columns.length) {
if (i > 0) str += ', ';
str += this.wrap(columns[i]);
}
return str;
};
// Turns a list of values into a list of ?'s, joining them with commas unless
// a "joining" value is specified (e.g. ' and ')
...
function wrapAsIdentifier(value) { return this.client.wrapIdentifier((value || '').trim()); }
...
Formatter.prototype._wrapString = function _wrapString(value) {
var asIndex = value.toLowerCase().indexOf(' as ');
if (asIndex !== -1) {
var first = value.slice(0, asIndex);
var second = value.slice(asIndex + 4);
return this.alias(this.wrap(first), this.wrapAsIdentifier(second));
}
var wrapped = [];
var i = -1;
var segments = value.split('.');
while (++i < segments.length) {
value = segments[i];
if (i === 0 && segments.length > 1) {
...
function FunctionHelper(client) { this.client = client; }
n/a
now = function () { return this.client.raw('CURRENT_TIMESTAMP'); }
n/a
function containsUndefined(mixed) { var argContainsUndefined = false; if ((0, _isTypedArray3.default)(mixed)) return false; if (mixed && (0, _isFunction3.default)(mixed.toSQL)) { //Any QueryBuilder or Raw will automatically be validated during compile. return argContainsUndefined; } if ((0, _isArray3.default)(mixed)) { for (var i = 0; i < mixed.length; i++) { if (argContainsUndefined) break; argContainsUndefined = this.containsUndefined(mixed[i]); } } else if ((0, _isObject3.default)(mixed)) { for (var key in mixed) { if (argContainsUndefined) break; argContainsUndefined = this.containsUndefined(mixed[key]); } } else { argContainsUndefined = (0, _isUndefined3.default)(mixed); } return argContainsUndefined; }
...
//Any QueryBuilder or Raw will automatically be validated during compile.
return argContainsUndefined;
}
if ((0, _isArray3.default)(mixed)) {
for (var i = 0; i < mixed.length; i++) {
if (argContainsUndefined) break;
argContainsUndefined = this.containsUndefined(mixed[i]);
}
} else if ((0, _isObject3.default)(mixed)) {
for (var key in mixed) {
if (argContainsUndefined) break;
argContainsUndefined = this.containsUndefined(mixed[key]);
}
} else {
...
function debugLog(msg) { console.log(msg); }
...
runner.connection = connection;
runner.client.emit('start', runner.builder);
runner.builder.emit('start', runner.builder);
var sql = runner.builder.toSQL();
if (runner.builder._debug) {
helpers.debugLog(sql);
}
if ((0, _isArray3.default)(sql)) {
return runner.queryArray(sql);
}
return runner.query(sql);
})
...
function deprecate(method, alternate) { warn(method + ' is deprecated, please use ' + alternate); }
n/a
function error(msg) { console.log(_chalk2.default.red('Knex:Error ' + msg)); }
...
// .map over the results
.map(function(row) {
console.log(row);
})
// Finally, add a .catch handler for the promise chain
.catch(function(e) {
console.error(e);
});
```
...
function exit(msg) { console.log(_chalk2.default.red(msg)); process.exit(1); }
...
// Used to warn about incorrect use, without error'ing
function warn(msg) {
console.log(_chalk2.default.yellow('Knex:warning - ' + msg));
}
function exit(msg) {
console.log(_chalk2.default.red(msg));
process.exit(1);
}
function containsUndefined(mixed) {
var argContainsUndefined = false;
if ((0, _isTypedArray3.default)(mixed)) return false;
...
function normalizeArr() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { return args[0]; } return args; }
n/a
function skim(data) { return (0, _map3.default)(data, function (obj) { return (0, _pick3.default)(obj, (0, _keys3.default)(obj)); }); }
n/a
function warn(msg) { console.log(_chalk2.default.yellow('Knex:warning - ' + msg)); }
...
return this;
};
// Set the transaction object for this query.
Target.prototype.transacting = function (t) {
if (t && t.client) {
if (!t.client.transacting) {
helpers.warn('Invalid transaction value: ' + t.client);
} else {
this.client = t.client;
}
}
return this;
};
...
function Migrator(knex) { (0, _classCallCheck3.default)(this, Migrator); this.knex = knex; this.config = this.setConfig(knex.client.config.migrations); }
n/a
function _absoluteConfigDir() { return _path2.default.resolve(process.cwd(), this.config.directory); }
n/a
function _createMigrationLockTable(tableName) { return this.knex.schema.createTableIfNotExists(tableName, function (t) { t.integer('is_locked'); }); }
n/a
function _createMigrationTable(tableName) { return this.knex.schema.createTableIfNotExists(tableName, function (t) { t.increments(); t.string('name'); t.integer('batch'); t.timestamp('migration_time'); }); }
n/a
function _ensureFolder() { var dir = this._absoluteConfigDir(); return _bluebird2.default.promisify(_fs2.default.stat, { context: _fs2.default })(dir).catch(function () { return _bluebird2.default.promisify(_mkdirp2.default)(dir); }); }
n/a
function _ensureTable() { var _this5 = this; var table = this.config.tableName; var lockTable = this._getLockTableName(); return this.knex.schema.hasTable(table).then(function (exists) { return !exists && _this5._createMigrationTable(table); }).then(function () { return _this5.knex.schema.hasTable(lockTable); }).then(function (exists) { return !exists && _this5._createMigrationLockTable(lockTable); }).then(function () { return _this5.knex(lockTable).select('*'); }).then(function (data) { return !data.length && _this5.knex(lockTable).insert({ is_locked: 0 }); }); }
n/a
function _freeLock() { var tableName = this._getLockTableName(); return this.knex(tableName).update({ is_locked: 0 }); }
n/a
function _generateStubTemplate() { var stubPath = this.config.stub || _path2.default.join(__dirname, 'stub', this.config.extension + '.stub'); return _bluebird2.default.promisify(_fs2.default.readFile, { context: _fs2.default })(stubPath).then(function (stub) { return (0, _template3.default)(stub.toString(), { variable: 'd' }); }); }
n/a
function _getLastBatch() { var tableName = this.config.tableName; return this.knex(tableName).where('batch', function (qb) { qb.max('batch').from(tableName); }).orderBy('id', 'desc'); }
n/a
function _getLock() { var _this6 = this; return this.knex.transaction(function (trx) { return _this6._isLocked(trx).then(function (isLocked) { if (isLocked) { throw new Error("Migration table is already locked"); } }).then(function () { return _this6._lockMigrations(trx); }); }).catch(function (err) { throw new LockError(err.message); }); }
n/a
function _getLockTableName() { return this.config.tableName + '_lock'; }
n/a
function _isLocked(trx) { var tableName = this._getLockTableName(); return this.knex(tableName).transacting(trx).forUpdate().select('*').then(function (data) { return data[0].is_locked; }); }
n/a
function _latestBatchNumber() { return this.knex(this.config.tableName).max('batch as max_batch').then(function (obj) { return obj[0].max_batch || 0; }); }
n/a
function _listAll(config) { this.config = this.setConfig(config); return _bluebird2.default.promisify(_fs2.default.readdir, { context: _fs2.default })(this._absoluteConfigDir()).then(function ( migrations) { return (0, _filter3.default)(migrations, function (value) { var extension = _path2.default.extname(value); return (0, _includes3.default)(SUPPORTED_EXTENSIONS, extension); }).sort(); }); }
n/a
function _listCompleted() { var _this8 = this; var tableName = this.config.tableName; return this._ensureTable(tableName).then(function () { return _this8.knex(tableName).orderBy('id').select('name'); }).then(function (migrations) { return (0, _map3.default)(migrations, 'name'); }); }
n/a
function _lockMigrations(trx) { var tableName = this._getLockTableName(); return this.knex(tableName).transacting(trx).update({ is_locked: 1 }); }
n/a
function _migrationData() { return _bluebird2.default.all([this._listAll(), this._listCompleted()]); }
n/a
function _runBatch(migrations, direction) { var _this7 = this; return this._getLock().then(function () { return _bluebird2.default.all((0, _map3.default)(migrations, (0, _bind3.default)(_this7._validateMigrationStructure, _this7))); }).then(function () { return _this7._latestBatchNumber(); }).then(function (batchNo) { if (direction === 'up') batchNo++; return batchNo; }).then(function (batchNo) { return _this7._waterfallBatch(batchNo, migrations, direction); }).tap(function () { return _this7._freeLock(); }).catch(function (error) { var cleanupReady = _bluebird2.default.resolve(); if (error instanceof LockError) { // If locking error do not free the lock. helpers.warn('Can\'t take lock to run migrations: ' + error.message); helpers.warn('If you are sure migrations are not running you can release the ' + 'lock manually by deleting all the rows from migrations lock ' + 'table: ' + _this7._getLockTableName()); } else { helpers.warn('migrations failed with error: ' + error.message); // If the error was not due to a locking issue, then remove the lock. cleanupReady = _this7._freeLock(); } return cleanupReady.finally(function () { throw error; }); }); }
n/a
function _transaction(migration, direction, name) { return this.knex.transaction(function (trx) { return warnPromise(migration[direction](trx, _bluebird2.default), name, function () { trx.commit(); }); }); }
n/a
function _useTransaction(migration, allTransactionsDisabled) { var singleTransactionValue = (0, _get3.default)(migration, 'config.transaction'); return (0, _isBoolean3.default)(singleTransactionValue) ? singleTransactionValue : !allTransactionsDisabled; }
n/a
function _validateMigrationStructure(name) { var migration = require(_path2.default.join(this._absoluteConfigDir(), name)); if (typeof migration.up !== 'function' || typeof migration.down !== 'function') { throw new Error('Invalid migration: ' + name + ' must have both an up and down function'); } return name; }
n/a
function _waterfallBatch(batchNo, migrations, direction) { var _this9 = this; var knex = this.knex; var _config = this.config; var tableName = _config.tableName; var disableTransactions = _config.disableTransactions; var directory = this._absoluteConfigDir(); var current = _bluebird2.default.bind({ failed: false, failedOn: 0 }); var log = []; (0, _each3.default)(migrations, function (migration) { var name = migration; migration = require(directory + '/' + name); // We're going to run each of the migrations in the current "up". current = current.then(function () { if (_this9._useTransaction(migration, disableTransactions)) { return _this9._transaction(migration, direction, name); } return warnPromise(migration[direction](knex, _bluebird2.default), name); }).then(function () { log.push(_path2.default.join(directory, name)); if (direction === 'up') { return knex(tableName).insert({ name: name, batch: batchNo, migration_time: new Date() }); } if (direction === 'down') { return knex(tableName).where({ name: name }).del(); } }); }); return current.thenReturn([batchNo, log]); }
n/a
function _writeNewMigration(name, tmpl) { var config = this.config; var dir = this._absoluteConfigDir(); if (name[0] === '-') name = name.slice(1); var filename = yyyymmddhhmmss() + '_' + name + '.' + config.extension; return _bluebird2.default.promisify(_fs2.default.writeFile, { context: _fs2.default })(_path2.default.join(dir, filename), tmpl (config.variables || {})).return(_path2.default.join(dir, filename)); }
n/a
function currentVersion(config) { this.config = this.setConfig(config); return this._listCompleted(config).then(function (completed) { var val = (0, _max3.default)((0, _map3.default)(completed, function (value) { return value.split('_')[0]; })); return (0, _isUndefined3.default)(val) ? 'none' : val; }); }
n/a
function forceFreeMigrationsLock(config) { var _this3 = this; this.config = this.setConfig(config); var lockTable = this._getLockTableName(); return this.knex.schema.hasTable(lockTable).then(function (exist) { return exist && _this3._freeLock(); }); }
n/a
function latest(config) { var _this = this; this.config = this.setConfig(config); return this._migrationData().tap(validateMigrationList).spread(function (all, completed) { return _this._runBatch((0, _difference3.default)(all, completed), 'up'); }); }
n/a
function make(name, config) { var _this4 = this; this.config = this.setConfig(config); if (!name) { return _bluebird2.default.reject(new Error('A name must be specified for the generated migration')); } return this._ensureFolder(config).then(function (val) { return _this4._generateStubTemplate(val); }).then(function (val) { return _this4._writeNewMigration(name, val); }); }
n/a
function rollback(config) { var _this2 = this; return _bluebird2.default.try(function () { _this2.config = _this2.setConfig(config); return _this2._migrationData().tap(validateMigrationList).then(function (val) { return _this2._getLastBatch(val); }).then(function (migrations) { return _this2._runBatch((0, _map3.default)(migrations, 'name'), 'down'); }); }); }
...
} catch (err) {
result = _bluebird2.default.reject(err);
}
if (result && result.then && typeof result.then === 'function') {
result.then(function (val) {
return transactor.commit(val);
}).catch(function (err) {
return transactor.rollback(err);
});
}
return null;
}).catch(function (e) {
return _this._rejecter(e);
});
...
function setConfig(config) { return (0, _assign3.default)({}, CONFIG_DEFAULT, this.config || {}, config); }
n/a
function status(config) { this.config = this.setConfig(config); return _bluebird2.default.all([this.knex(this.config.tableName).select('*'), this._listAll()]).spread(function (db, code) { return db.length - code.length; }); }
n/a
function Raw() { var client = arguments.length <= 0 || arguments[0] === undefined ? fakeClient : arguments[0]; this.client = client; this.sql = ''; this.bindings = []; // Todo: Deprecate this._wrappedBefore = undefined; this._wrappedAfter = undefined; this._debug = client && client.config && client.config.debug; }
...
// FunctionHelper
// -------
function FunctionHelper(client) {
this.client = client;
}
FunctionHelper.prototype.now = function () {
return this.client.raw('CURRENT_TIMESTAMP');
};
exports.default = FunctionHelper;
module.exports = exports['default'];
...
function EventEmitter() { EventEmitter.init.call(this); }
n/a
asCallback = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
n/a
bind = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
...
throw error;
});
}),
// In the case of the "schema builder" we call `queryArray`, which runs each
// of the queries in sequence.
queryArray: function queryArray(queries) {
return queries.length === 1 ? this.query(queries[0]) : _bluebird2.default.bind(this
).return(queries).reduce(function (memo, query) {
return this.query(query).then(function (resp) {
memo.push(resp);
return memo;
});
}, []);
},
...
catch = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
...
// .map over the results
.map(function(row) {
console.log(row);
})
// Finally, add a .catch handler for the promise chain
.catch(function(e) {
console.error(e);
});
```
...
connection = function (connection) { this._connection = connection; return this; }
n/a
debug = function (enabled) { this._debug = arguments.length ? enabled : true; return this; }
n/a
delay = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
n/a
ensure = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
n/a
finally = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
n/a
get = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
n/a
map = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
...
.then(function() {
return knex('users')
.join('accounts', 'users.id', 'accounts.user_id')
.select('users.user_name as user', 'accounts.account_name as account');
})
// .map over the results
.map(function(row) {
console.log(row);
})
// Finally, add a .catch handler for the promise chain
.catch(function(e) {
console.error(e);
});
...
mapSeries = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
n/a
options = function (opts) { this._options = this._options || []; this._options.push((0, _clone3.default)(opts) || {}); return this; }
n/a
pipe = function (writable, options) { return this.client.runner(this).pipe(writable, options); }
...
// Initializes a stream.
Target.prototype.stream = function (options) {
return this.client.runner(this).stream(options);
};
// Initialize a stream & pipe automatically.
Target.prototype.pipe = function (writable, options) {
return this.client.runner(this).pipe(writable, options);
};
// Creates a method which "coerces" to a promise, by calling a
// "then" method on the current `Target`
(0, _each3.default)(['bind', 'catch', 'finally', 'asCallback', 'spread', '
;map', 'reduce', 'tap', 'thenReturn', 'return', 'yield', 'ensure'
;, 'reflect', 'get', 'mapSeries', 'delay'], function (method) {
Target.prototype[method] = function () {
var promise = this.then();
...
reduce = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
...
throw error;
});
}),
// In the case of the "schema builder" we call `queryArray`, which runs each
// of the queries in sequence.
queryArray: function queryArray(queries) {
return queries.length === 1 ? this.query(queries[0]) : _bluebird2.default.bind(this).return(queries).reduce(function (memo, query) {
return this.query(query).then(function (resp) {
memo.push(resp);
return memo;
});
}, []);
},
...
reflect = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
n/a
return = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
...
throw error;
});
}),
// In the case of the "schema builder" we call `queryArray`, which runs each
// of the queries in sequence.
queryArray: function queryArray(queries) {
return queries.length === 1 ? this.query(queries[0]) : _bluebird2.default.bind(this).return
(queries).reduce(function (memo, query) {
return this.query(query).then(function (resp) {
memo.push(resp);
return memo;
});
}, []);
},
...
function set(sql, bindings) { this.sql = sql; this.bindings = (0, _isObject3.default)(bindings) && !bindings.toSQL || (0, _isUndefined3.default)(bindings) ? bindings : [bindings ]; return this; }
n/a
spread = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
n/a
stream = function (options) { return this.client.runner(this).stream(options); }
...
}
}
return this;
};
// Initializes a stream.
Target.prototype.stream = function (options) {
return this.client.runner(this).stream(options);
};
// Initialize a stream & pipe automatically.
Target.prototype.pipe = function (writable, options) {
return this.client.runner(this).pipe(writable, options);
};
...
tap = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
...
runner.builder.emit('error', err);
}
throw err;
})
// Fire a single "end" event on the builder when
// all queries have successfully completed.
.tap(function () {
runner.builder.emit('end');
});
},
// Stream the result set, by passing through to the dialect's streaming
// capabilities. If the options are
...
then = function () /* onFulfilled, onRejected */{ var result = this.client.runner(this).run(); return result.then.apply(result, arguments); }
...
.createTable('accounts', function(table) {
table.increments('id');
table.string('account_name');
table.integer('user_id').unsigned().references('users.id');
})
// Then query the table...
.then(function() {
return knex.insert({user_name: 'Tim'}).into('users');
})
// ...and using the insert id, insert into the other table.
.then(function(rows) {
return knex.table('accounts').insert({account_name: 'knex', user_id: rows[0]});
})
...
thenReturn = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
n/a
function timeout(ms) { var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var cancel = _ref.cancel; if ((0, _isNumber3.default)(ms) && ms > 0) { this._timeout = ms; if (cancel) { this.client.assertCanCancelQuery(); this._cancelOnTimeout = true; } } return this; }
...
var _this = this;
this.builder.emit('query', (0, _assign3.default)({ __knexUid: this.connection.__knexUid }, obj));
var runner = this;
var queryPromise = this.client.query(this.connection, obj);
if (obj.timeout) {
queryPromise = queryPromise.timeout(obj.timeout);
}
return queryPromise.then(function (resp) {
var processedResponse = _this.client.processResponse(resp, runner);
_this.builder.emit('query-response', processedResponse, (0, _assign3.default)({ __knexUid: _this.connection.__knexUid
}, obj), _this.builder);
_this.client.emit('query-response', processedResponse, (0, _assign3.default)({ __knexUid: _this.connection.__knexUid
}, obj), _this.builder);
return processedResponse;
...
toQuery = function (tz) { var _this = this; var data = this.toSQL(this._method, tz); if (!(0, _isArray3.default)(data)) data = [data]; return (0, _map3.default)(data, function (statement) { return _this.client._formatQuery(statement.sql, statement.bindings, tz); }).join(';\n'); }
...
this._wrappedAfter = after;
return this;
},
// Calls `toString` on the Knex object.
toString: function toString() {
return this.toQuery();
},
// Returns the raw sql for the query.
toSQL: function toSQL(method, tz) {
var obj = void 0;
var formatter = this.client.formatter();
...
function toSQL(method, tz) { var obj = void 0; var formatter = this.client.formatter(); if (Array.isArray(this.bindings)) { obj = replaceRawArrBindings(this, formatter); } else if (this.bindings && (0, _isPlainObject3.default)(this.bindings)) { obj = replaceKeyBindings(this, formatter); } else { obj = { method: 'raw', sql: this.sql, bindings: (0, _isUndefined3.default)(this.bindings) ? [] : [this.bindings] }; } if (this._wrappedBefore) { obj.sql = this._wrappedBefore + obj.sql; } if (this._wrappedAfter) { obj.sql = obj.sql + this._wrappedAfter; } obj.options = (0, _reduce3.default)(this._options, _assign3.default, {}); if (this._timeout) { obj.timeout = this._timeout; if (this._cancelOnTimeout) { obj.cancelOnTimeout = this._cancelOnTimeout; } } obj.bindings = obj.bindings || []; if (helpers.containsUndefined(obj.bindings)) { debugBindings(obj.bindings); throw new Error('Undefined binding(s) detected when compiling RAW query: ' + obj.sql); } obj.__knexQueryUid = _uuid2.default.v4(); return obj; }
...
}
return this.unwrapRaw(value, true) || '?';
};
Formatter.prototype.unwrapRaw = function unwrapRaw(value, isParameter) {
var query = void 0;
if (value instanceof _builder2.default) {
query = this.client.queryCompiler(value).toSQL();
if (query.bindings) {
this.bindings = this.bindings.concat(query.bindings);
}
return this.outputQuery(query, isParameter);
}
if (value instanceof _raw2.default) {
value.client = this.client;
...
function toString() { return this.toQuery(); }
n/a
transacting = function (t) { if (t && t.client) { if (!t.client.transacting) { helpers.warn('Invalid transaction value: ' + t.client); } else { this.client = t.client; } } return this; }
n/a
function wrap(before, after) { this._wrappedBefore = before; this._wrappedAfter = after; return this; }
...
Formatter.prototype.columnize = function columnize(target) {
var columns = typeof target === 'string' ? [target] : target;
var str = '',
i = -1;
while (++i < columns.length) {
if (i > 0) str += ', ';
str += this.wrap(columns[i]);
}
return str;
};
// Turns a list of values into a list of ?'s, joining them with commas unless
// a "joining" value is specified (e.g. ' and ')
...
yield = function () { var promise = this.then(); return promise[method].apply(promise, arguments); }
n/a
function Runner(client, builder) { this.client = client; this.builder = builder; this.queries = []; // The "connection" object is set on the runner when // "run" is called. this.connection = void 0; }
...
return (0, _map3.default)(data, function (statement) {
return _this.client._formatQuery(statement.sql, statement.bindings, tz);
}).join(';\n');
};
// Create a new instance of the `Runner`, passing in the current object.
Target.prototype.then = function () /* onFulfilled, onRejected */{
var result = this.client.runner(this).run();
return result.then.apply(result, arguments);
};
// Add additional "options" to the builder. Typically used for client specific
// items, like the `mysql` and `sqlite3` drivers.
Target.prototype.options = function (opts) {
this._options = this._options || [];
...
function ensureConnection() { var _this2 = this; return _bluebird2.default.try(function () { return _this2.connection || new _bluebird2.default(function (resolver, rejecter) { // need to return promise or null from handler to prevent warning from bluebird return _this2.client.acquireConnection().then(resolver).catch(_bluebird2.default.TimeoutError, function (error) { if (_this2.builder) { error.sql = _this2.builder.sql; error.bindings = _this2.builder.bindings; } throw error; }).catch(rejecter); }); }).disposer(function () { // need to return promise or null from handler to prevent warning from bluebird return _this2.client.releaseConnection(_this2.connection); }); }
...
(0, _assign3.default)(Runner.prototype, {
// "Run" the target, calling "toSQL" on the builder, returning
// an object or array of queries to run, each of which are run on
// a single connection.
run: function run() {
var runner = this;
return _bluebird2.default.using(this.ensureConnection(), function (connection) {
runner.connection = connection;
runner.client.emit('start', runner.builder);
runner.builder.emit('start', runner.builder);
var sql = runner.builder.toSQL();
if (runner.builder._debug) {
...
function pipe(writable, options) { return this.stream(options).pipe(writable); }
...
// Initializes a stream.
Target.prototype.stream = function (options) {
return this.client.runner(this).stream(options);
};
// Initialize a stream & pipe automatically.
Target.prototype.pipe = function (writable, options) {
return this.client.runner(this).pipe(writable, options);
};
// Creates a method which "coerces" to a promise, by calling a
// "then" method on the current `Target`
(0, _each3.default)(['bind', 'catch', 'finally', 'asCallback', 'spread', '
;map', 'reduce', 'tap', 'thenReturn', 'return', 'yield', 'ensure'
;, 'reflect', 'get', 'mapSeries', 'delay'], function (method) {
Target.prototype[method] = function () {
var promise = this.then();
...
query = function () { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value = tryCatch(fn).apply(this, arguments); var promiseCreated = ret._popContext(); debug.checkForgottenReturns( value, promiseCreated, "Promise.method", ret); ret._resolveFromSyncValue(value); return ret; }
...
if (runner.builder._debug) {
helpers.debugLog(sql);
}
if ((0, _isArray3.default)(sql)) {
return runner.queryArray(sql);
}
return runner.query(sql);
})
// If there are any "error" listeners, we fire an error event
// and then re-throw the error to be eventually handled by
// the promise chain. Useful if you're wrapping in a custom `Promise`.
.catch(function (err) {
if (runner.builder._events && runner.builder._events.error) {
...
function queryArray(queries) { return queries.length === 1 ? this.query(queries[0]) : _bluebird2.default.bind(this).return(queries).reduce(function (memo, query ) { return this.query(query).then(function (resp) { memo.push(resp); return memo; }); }, []); }
...
var sql = runner.builder.toSQL();
if (runner.builder._debug) {
helpers.debugLog(sql);
}
if ((0, _isArray3.default)(sql)) {
return runner.queryArray(sql);
}
return runner.query(sql);
})
// If there are any "error" listeners, we fire an error event
// and then re-throw the error to be eventually handled by
// the promise chain. Useful if you're wrapping in a custom `Promise`.
...
function run() { var runner = this; return _bluebird2.default.using(this.ensureConnection(), function (connection) { runner.connection = connection; runner.client.emit('start', runner.builder); runner.builder.emit('start', runner.builder); var sql = runner.builder.toSQL(); if (runner.builder._debug) { helpers.debugLog(sql); } if ((0, _isArray3.default)(sql)) { return runner.queryArray(sql); } return runner.query(sql); }) // If there are any "error" listeners, we fire an error event // and then re-throw the error to be eventually handled by // the promise chain. Useful if you're wrapping in a custom `Promise`. .catch(function (err) { if (runner.builder._events && runner.builder._events.error) { runner.builder.emit('error', err); } throw err; }) // Fire a single "end" event on the builder when // all queries have successfully completed. .tap(function () { runner.builder.emit('end'); }); }
...
return (0, _map3.default)(data, function (statement) {
return _this.client._formatQuery(statement.sql, statement.bindings, tz);
}).join(';\n');
};
// Create a new instance of the `Runner`, passing in the current object.
Target.prototype.then = function () /* onFulfilled, onRejected */{
var result = this.client.runner(this).run();
return result.then.apply(result, arguments);
};
// Add additional "options" to the builder. Typically used for client specific
// items, like the `mysql` and `sqlite3` drivers.
Target.prototype.options = function (opts) {
this._options = this._options || [];
...
function stream(options, handler) { // If we specify stream(handler).then(... if (arguments.length === 1) { if (typeof options === 'function') { handler = options; options = {}; } } // Determines whether we emit an error or throw here. var hasHandler = typeof handler === 'function'; // Lazy-load the "PassThrough" dependency. PassThrough = PassThrough || require('readable-stream').PassThrough; var runner = this; var stream = new PassThrough({ objectMode: true }); var promise = _bluebird2.default.using(this.ensureConnection(), function (connection) { runner.connection = connection; var sql = runner.builder.toSQL(); var err = new Error('The stream may only be used with a single query statement.'); if ((0, _isArray3.default)(sql)) { if (hasHandler) throw err; stream.emit('error', err); } return runner.client.stream(runner.connection, sql, stream, options); }); // If a function is passed to handle the stream, send the stream // there and return the promise, otherwise just return the stream // and the promise will take care of itsself. if (hasHandler) { handler(stream); return promise; } // This promise is unreachable since no handler was given, so noop any // exceptions. Errors should be handled in the stream's 'error' event. promise.catch(_noop3.default); return stream; }
...
}
}
return this;
};
// Initializes a stream.
Target.prototype.stream = function (options) {
return this.client.runner(this).stream(options);
};
// Initialize a stream & pipe automatically.
Target.prototype.pipe = function (writable, options) {
return this.client.runner(this).pipe(writable, options);
};
...
function Seeder(knex) { this.knex = knex; this.config = this.setConfig(knex.client.config.seeds); }
n/a
_absoluteConfigDir = function () { return _path2.default.resolve(process.cwd(), this.config.directory); }
n/a
_ensureFolder = function () { var dir = this._absoluteConfigDir(); return _bluebird2.default.promisify(_fs2.default.stat, { context: _fs2.default })(dir).catch(function () { return _bluebird2.default.promisify(_mkdirp2.default)(dir); }); }
n/a
_generateStubTemplate = function () { var stubPath = this.config.stub || _path2.default.join(__dirname, 'stub', this.config.extension + '.stub'); return _bluebird2.default.promisify(_fs2.default.readFile, { context: _fs2.default })(stubPath).then(function (stub) { return (0, _template3.default)(stub.toString(), { variable: 'd' }); }); }
n/a
_listAll = function () { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value = tryCatch(fn).apply(this, arguments); var promiseCreated = ret._popContext(); debug.checkForgottenReturns( value, promiseCreated, "Promise.method", ret); ret._resolveFromSyncValue(value); return ret; }
n/a
_runSeeds = function (seeds) { return _bluebird2.default.all((0, _map3.default)(seeds, (0, _bind3.default)(this._validateSeedStructure, this))).bind(this).then (function (seeds) { return _bluebird2.default.bind(this).then(function () { return this._waterfallBatch(seeds); }); }); }
n/a
_seedData = function () { return _bluebird2.default.join(this._listAll()); }
n/a
_validateSeedStructure = function (name) { var seed = require(_path2.default.join(this._absoluteConfigDir(), name)); if (typeof seed.seed !== 'function') { throw new Error('Invalid seed file: ' + name + ' must have a seed function'); } return name; }
n/a
_waterfallBatch = function (seeds) { var knex = this.knex; var seedDirectory = this._absoluteConfigDir(); var current = _bluebird2.default.bind({ failed: false, failedOn: 0 }); var log = []; (0, _each3.default)(seeds, function (seed) { var name = _path2.default.join(seedDirectory, seed); seed = require(name); // Run each seed file. current = current.then(function () { return seed.seed(knex, _bluebird2.default); }).then(function () { log.push(name); }); }); return current.thenReturn([log]); }
n/a
_writeNewSeed = function (name) { var config = this.config; var dir = this._absoluteConfigDir(); return function (tmpl) { if (name[0] === '-') name = name.slice(1); var filename = name + '.' + config.extension; return _bluebird2.default.promisify(_fs2.default.writeFile, { context: _fs2.default })(_path2.default.join(dir, filename), tmpl (config.variables || {})).return(_path2.default.join(dir, filename)); }; }
n/a
make = function (name, config) { this.config = this.setConfig(config); if (!name) _bluebird2.default.rejected(new Error('A name must be specified for the generated seed')); return this._ensureFolder(config).bind(this).then(this._generateStubTemplate).then(this._writeNewSeed(name)); }
n/a
run = function () { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value = tryCatch(fn).apply(this, arguments); var promiseCreated = ret._popContext(); debug.checkForgottenReturns( value, promiseCreated, "Promise.method", ret); ret._resolveFromSyncValue(value); return ret; }
...
return (0, _map3.default)(data, function (statement) {
return _this.client._formatQuery(statement.sql, statement.bindings, tz);
}).join(';\n');
};
// Create a new instance of the `Runner`, passing in the current object.
Target.prototype.then = function () /* onFulfilled, onRejected */{
var result = this.client.runner(this).run();
return result.then.apply(result, arguments);
};
// Add additional "options" to the builder. Typically used for client specific
// items, like the `mysql` and `sqlite3` drivers.
Target.prototype.options = function (opts) {
this._options = this._options || [];
...
setConfig = function (config) { return (0, _extend3.default)({ extension: 'js', directory: './seeds' }, this.config || {}, config); }
n/a
function Transaction(client, container, config, outerTx) { (0, _classCallCheck3.default)(this, Transaction); var _this = (0, _possibleConstructorReturn3.default)(this, _EventEmitter.call(this)); var txid = _this.txid = (0, _uniqueId3.default)('trx'); _this.client = client; _this.outerTx = outerTx; _this.trxClient = undefined; _this._debug = client.config && client.config.debug; debug('%s: Starting %s transaction', txid, outerTx ? 'nested' : 'top level'); _this._promise = _bluebird2.default.using(_this.acquireConnection(client, config, txid), function (connection) { var trxClient = _this.trxClient = makeTxClient(_this, client, connection); var init = client.transacting ? _this.savepoint(connection) : _this.begin(connection); init.then(function () { return makeTransactor(_this, connection, trxClient); }).then(function (transactor) { // If we've returned a "thenable" from the transaction container, assume // the rollback and commit are chained to this object's success / failure. // Directly thrown errors are treated as automatic rollbacks. var result = void 0; try { result = container(transactor); } catch (err) { result = _bluebird2.default.reject(err); } if (result && result.then && typeof result.then === 'function') { result.then(function (val) { return transactor.commit(val); }).catch(function (err) { return transactor.rollback(err); }); } return null; }).catch(function (e) { return _this._rejecter(e); }); return new _bluebird2.default(function (resolver, rejecter) { _this._resolver = resolver; _this._rejecter = rejecter; }); }); _this._completed = false; // If there's a wrapping transaction, we need to wait for any older sibling // 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 = _bluebird2.default.resolve(true); if (outerTx) { if (outerTx._lastChild) _this._previousSibling = outerTx._lastChild; outerTx._lastChild = _this._promise; } return _this; }
...
exports.default = Transaction;
function makeTransactor(trx, connection, trxClient) {
var transactor = (0, _makeKnex2.default)(trxClient);
transactor.transaction = function (container, options) {
return trxClient.transaction(container, options, trx);
};
transactor.savepoint = function (container, options) {
return transactor.transaction(container, options);
};
if (trx.client.transacting) {
transactor.commit = function (value) {
...
function acquireConnection(client, config, txid) { var configConnection = config && config.connection; return _bluebird2.default.try(function () { return configConnection || client.acquireConnection(); }).disposer(function (connection) { if (!configConnection) { debug('%s: releasing connection', txid); client.releaseConnection(connection); } else { debug('%s: not releasing external connection', txid); } }); }
...
// Check whether there's a transaction flag, and that it has a connection.
ensureConnection: function ensureConnection() {
var _this2 = this;
return _bluebird2.default.try(function () {
return _this2.connection || new _bluebird2.default(function (resolver, rejecter) {
// need to return promise or null from handler to prevent warning from bluebird
return _this2.client.acquireConnection().then(resolver).catch(_bluebird2.default.
TimeoutError, function (error) {
if (_this2.builder) {
error.sql = _this2.builder.sql;
error.bindings = _this2.builder.bindings;
}
throw error;
}).catch(rejecter);
});
...
asCallback = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
n/a
function begin(conn) { return this.query(conn, 'BEGIN;'); }
...
_this._debug = client.config && client.config.debug;
debug('%s: Starting %s transaction', txid, outerTx ? 'nested' : 'top level');
_this._promise = _bluebird2.default.using(_this.acquireConnection(client, config, txid), function (connection) {
var trxClient = _this.trxClient = makeTxClient(_this, client, connection);
var init = client.transacting ? _this.savepoint(connection) : _this.begin(connection);
init.then(function () {
return makeTransactor(_this, connection, trxClient);
}).then(function (transactor) {
// If we've returned a "thenable" from the transaction container, assume
// the rollback and commit are chained to this object's success / failure.
// Directly thrown errors are treated as automatic rollbacks.
...
bind = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
...
throw error;
});
}),
// In the case of the "schema builder" we call `queryArray`, which runs each
// of the queries in sequence.
queryArray: function queryArray(queries) {
return queries.length === 1 ? this.query(queries[0]) : _bluebird2.default.bind(this
).return(queries).reduce(function (memo, query) {
return this.query(query).then(function (resp) {
memo.push(resp);
return memo;
});
}, []);
},
...
catch = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
...
// .map over the results
.map(function(row) {
console.log(row);
})
// Finally, add a .catch handler for the promise chain
.catch(function(e) {
console.error(e);
});
```
...
function commit(conn, value) { return this.query(conn, 'COMMIT;', 1, value); }
...
try {
result = container(transactor);
} catch (err) {
result = _bluebird2.default.reject(err);
}
if (result && result.then && typeof result.then === 'function') {
result.then(function (val) {
return transactor.commit(val);
}).catch(function (err) {
return transactor.rollback(err);
});
}
return null;
}).catch(function (e) {
return _this._rejecter(e);
...
function debug(enabled) { this._debug = arguments.length ? enabled : true; return this; }
n/a
delay = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
n/a
ensure = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
n/a
exec = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
n/a
finally = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
n/a
get = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
n/a
function isCompleted() { return this._completed || this.outerTx && this.outerTx.isCompleted() || false; }
...
if (outerTx._lastChild) _this._previousSibling = outerTx._lastChild;
outerTx._lastChild = _this._promise;
}
return _this;
}
Transaction.prototype.isCompleted = function isCompleted() {
return this._completed || this.outerTx && this.outerTx.isCompleted() || false
;
};
Transaction.prototype.begin = function begin(conn) {
return this.query(conn, 'BEGIN;');
};
Transaction.prototype.savepoint = function savepoint(conn) {
...
map = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
...
.then(function() {
return knex('users')
.join('accounts', 'users.id', 'accounts.user_id')
.select('users.user_name as user', 'accounts.account_name as account');
})
// .map over the results
.map(function(row) {
console.log(row);
})
// Finally, add a .catch handler for the promise chain
.catch(function(e) {
console.error(e);
});
...
mapSeries = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
n/a
function query(conn, sql, status, value) { var _this4 = this; var q = this.trxClient.query(conn, sql).catch(function (err) { status = 2; value = err; _this4._completed = true; debug('%s error running transaction query', _this4.txid); }).tap(function () { if (status === 1) { _this4._resolver(value); } if (status === 2) { if ((0, _isUndefined3.default)(value)) { value = new Error('Transaction rejected with non-error: ' + value); } _this4._rejecter(value); } }); if (status === 1 || status === 2) { this._completed = true; } return q; }
...
if (runner.builder._debug) {
helpers.debugLog(sql);
}
if ((0, _isArray3.default)(sql)) {
return runner.queryArray(sql);
}
return runner.query(sql);
})
// If there are any "error" listeners, we fire an error event
// and then re-throw the error to be eventually handled by
// the promise chain. Useful if you're wrapping in a custom `Promise`.
.catch(function (err) {
if (runner.builder._events && runner.builder._events.error) {
...
reduce = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
...
throw error;
});
}),
// In the case of the "schema builder" we call `queryArray`, which runs each
// of the queries in sequence.
queryArray: function queryArray(queries) {
return queries.length === 1 ? this.query(queries[0]) : _bluebird2.default.bind(this).return(queries).reduce(function (memo, query) {
return this.query(query).then(function (resp) {
memo.push(resp);
return memo;
});
}, []);
},
...
reflect = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
n/a
function release(conn, value) { return this.query(conn, 'RELEASE SAVEPOINT ' + this.txid + ';', 1, value); }
...
};
transactor.savepoint = function (container, options) {
return transactor.transaction(container, options);
};
if (trx.client.transacting) {
transactor.commit = function (value) {
return trx.release(connection, value);
};
transactor.rollback = function (error) {
return trx.rollbackTo(connection, error);
};
} else {
transactor.commit = function (value) {
return trx.commit(connection, value);
...
return = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
...
throw error;
});
}),
// In the case of the "schema builder" we call `queryArray`, which runs each
// of the queries in sequence.
queryArray: function queryArray(queries) {
return queries.length === 1 ? this.query(queries[0]) : _bluebird2.default.bind(this).return
(queries).reduce(function (memo, query) {
return this.query(query).then(function (resp) {
memo.push(resp);
return memo;
});
}, []);
},
...
function rollback(conn, error) { var _this2 = this; return this.query(conn, 'ROLLBACK;', 2, error).timeout(5000).catch(_bluebird2.default.TimeoutError, function () { _this2._resolver(); }); }
...
} catch (err) {
result = _bluebird2.default.reject(err);
}
if (result && result.then && typeof result.then === 'function') {
result.then(function (val) {
return transactor.commit(val);
}).catch(function (err) {
return transactor.rollback(err);
});
}
return null;
}).catch(function (e) {
return _this._rejecter(e);
});
...
function rollbackTo(conn, error) { var _this3 = this; return this.query(conn, 'ROLLBACK TO SAVEPOINT ' + this.txid, 2, error).timeout(5000).catch(_bluebird2.default.TimeoutError, function () { _this3._resolver(); }); }
...
};
if (trx.client.transacting) {
transactor.commit = function (value) {
return trx.release(connection, value);
};
transactor.rollback = function (error) {
return trx.rollbackTo(connection, error);
};
} else {
transactor.commit = function (value) {
return trx.commit(connection, value);
};
transactor.rollback = function (error) {
return trx.rollback(connection, error);
...
function savepoint(conn) { return this.query(conn, 'SAVEPOINT ' + this.txid + ';'); }
...
_this._debug = client.config && client.config.debug;
debug('%s: Starting %s transaction', txid, outerTx ? 'nested' : 'top level');
_this._promise = _bluebird2.default.using(_this.acquireConnection(client, config, txid), function (connection) {
var trxClient = _this.trxClient = makeTxClient(_this, client, connection);
var init = client.transacting ? _this.savepoint(connection) : _this.begin(connection);
init.then(function () {
return makeTransactor(_this, connection, trxClient);
}).then(function (transactor) {
// If we've returned a "thenable" from the transaction container, assume
// the rollback and commit are chained to this object's success / failure.
// Directly thrown errors are treated as automatic rollbacks.
...
spread = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
n/a
tap = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
...
runner.builder.emit('error', err);
}
throw err;
})
// Fire a single "end" event on the builder when
// all queries have successfully completed.
.tap(function () {
runner.builder.emit('end');
});
},
// Stream the result set, by passing through to the dialect's streaming
// capabilities. If the options are
...
then = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
...
.createTable('accounts', function(table) {
table.increments('id');
table.string('account_name');
table.integer('user_id').unsigned().references('users.id');
})
// Then query the table...
.then(function() {
return knex.insert({user_name: 'Tim'}).into('users');
})
// ...and using the insert id, insert into the other table.
.then(function(rows) {
return knex.table('accounts').insert({account_name: 'knex', user_id: rows[0]});
})
...
thenReturn = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
n/a
yield = function () { return this._promise = this._promise[method].apply(this._promise, arguments); }
n/a