Add initial version of dijkstra backend cloudron image

This commit is contained in:
2020-10-12 11:27:15 +02:00
commit 4f5db9ab26
4209 changed files with 448228 additions and 0 deletions

384
node_modules/knex/lib/dialects/mssql/index.js generated vendored Normal file
View File

@@ -0,0 +1,384 @@
// MSSQL Client
// -------
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');
const QueryCompiler = require('./query/compiler');
const SchemaCompiler = require('./schema/compiler');
const TableCompiler = require('./schema/tablecompiler');
const ColumnCompiler = require('./schema/columncompiler');
const SQL_INT4 = { MIN: -2147483648, MAX: 2147483647 };
const SQL_BIGINT_SAFE = { MIN: -9007199254740991, MAX: 9007199254740991 };
// Always initialize with the "QueryBuilder" and "QueryCompiler" objects, which
// extend the base 'lib/query/builder' and 'lib/query/compiler', respectively.
function Client_MSSQL(config = {}) {
// #1235 mssql module wants 'server', not 'host'. This is to enforce the same
// options object across all dialects.
if (config && config.connection && config.connection.host) {
config.connection.server = config.connection.host;
}
// mssql always creates pool :( lets try to unpool it as much as possible
this.mssqlPoolSettings = {
min: 1,
max: 1,
idleTimeoutMillis: Number.MAX_SAFE_INTEGER,
evictionRunIntervalMillis: 0,
};
Client.call(this, config);
}
inherits(Client_MSSQL, Client);
Object.assign(Client_MSSQL.prototype, {
dialect: 'mssql',
driverName: 'mssql',
_driver() {
const tds = require('tedious');
const mssqlTedious = require('mssql');
const base = require('mssql/lib/base');
// Monkey patch mssql's tedious driver _poolCreate method to fix problem with hanging acquire
// connection, this should be removed when https://github.com/tediousjs/node-mssql/pull/614 is
// merged and released.
// Also since this dialect actually always uses tedious driver (msnodesqlv8 driver should be
// required in different way), it might be better to use tedious directly, because mssql
// driver uses always internally extra generic-pool and just adds one unnecessary layer of
// indirection between database and knex and mssql driver has been lately without maintainer
// (changing implementation to use tedious will be breaking change though).
// TODO: remove mssql implementation all together and use tedious directly
/* istanbul ignore next */
const mssqlVersion = require('mssql/package.json').version;
/* istanbul ignore next */
if (mssqlVersion === '4.1.0') {
mssqlTedious.ConnectionPool.prototype.release = release;
mssqlTedious.ConnectionPool.prototype._poolCreate = _poolCreate;
} else {
const [major] = mssqlVersion.split('.');
// if version is not ^5.0.0
if (major < 5) {
throw new Error(
'This knex version only supports mssql driver versions 4.1.0 and 5.0.0+'
);
}
}
/* istanbul ignore next */
// in some rare situations release is called when stream is interrupted, but
// after pool is already destroyed
function release(connection) {
if (this.pool) {
this.pool.release(connection);
}
}
/* istanbul ignore next */
function _poolCreate() {
// implementation is copy-pasted from https://github.com/tediousjs/node-mssql/pull/614
return new base.Promise((resolve, reject) => {
const cfg = {
userName: this.config.user,
password: this.config.password,
server: this.config.server,
options: Object.assign({}, this.config.options),
domain: this.config.domain,
};
cfg.options.database = this.config.database;
cfg.options.port = this.config.port;
cfg.options.connectTimeout =
this.config.connectionTimeout || this.config.timeout || 15000;
cfg.options.requestTimeout =
this.config.requestTimeout != null
? this.config.requestTimeout
: 15000;
cfg.options.tdsVersion = cfg.options.tdsVersion || '7_4';
cfg.options.rowCollectionOnDone = false;
cfg.options.rowCollectionOnRequestCompletion = false;
cfg.options.useColumnNames = false;
cfg.options.appName = cfg.options.appName || 'node-mssql';
// tedious always connect via tcp when port is specified
if (cfg.options.instanceName) delete cfg.options.port;
if (isNaN(cfg.options.requestTimeout))
cfg.options.requestTimeout = 15000;
if (cfg.options.requestTimeout === Infinity)
cfg.options.requestTimeout = 0;
if (cfg.options.requestTimeout < 0) cfg.options.requestTimeout = 0;
if (this.config.debug) {
cfg.options.debug = {
packet: true,
token: true,
data: true,
payload: true,
};
}
const tedious = new tds.Connection(cfg);
// prevent calling resolve again on end event
let alreadyResolved = false;
function safeResolve(err) {
if (!alreadyResolved) {
alreadyResolved = true;
resolve(err);
}
}
function safeReject(err) {
if (!alreadyResolved) {
alreadyResolved = true;
reject(err);
}
}
tedious.once('end', (evt) => {
safeReject(
new base.ConnectionError(
'Connection ended unexpectedly during connecting'
)
);
});
tedious.once('connect', (err) => {
if (err) {
err = new base.ConnectionError(err);
return safeReject(err);
}
safeResolve(tedious);
});
tedious.on('error', (err) => {
if (err.code === 'ESOCKET') {
tedious.hasError = true;
return;
}
this.emit('error', err);
});
if (this.config.debug) {
tedious.on('debug', this.emit.bind(this, 'debug', tedious));
}
});
}
return mssqlTedious;
},
formatter() {
return new MSSQL_Formatter(this, ...arguments);
},
transaction() {
return new Transaction(this, ...arguments);
},
queryCompiler() {
return new QueryCompiler(this, ...arguments);
},
schemaCompiler() {
return new SchemaCompiler(this, ...arguments);
},
tableCompiler() {
return new TableCompiler(this, ...arguments);
},
columnCompiler() {
return new ColumnCompiler(this, ...arguments);
},
wrapIdentifierImpl(value) {
if (value === '*') {
return '*';
}
return `[${value.replace(/[[\]']+/g, '')}]`;
},
// 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) => {
const settings = Object.assign({}, this.connectionSettings);
settings.pool = this.mssqlPoolSettings;
const connection = new this.driver.ConnectionPool(settings);
connection.connect((err) => {
if (err) {
return rejecter(err);
}
connection.on('error', (err) => {
connection.__knex__disposed = err;
});
resolver(connection);
});
});
},
validateConnection(connection) {
if (connection.connected === true) {
return true;
}
return false;
},
// Used to explicitly close a connection, called internally by the pool
// when a connection times out or the pool is shutdown.
destroyRawConnection(connection) {
return connection.close().catch((err) => {
// some times close will reject just because pool has already been destoyed
// internally by the driver there is nothing we can do in this case
});
},
// Position the bindings for the query.
positionBindings(sql) {
let questionCount = -1;
return sql.replace(/\?/g, function() {
questionCount += 1;
return `@p${questionCount}`;
});
},
// Grab a connection, run the query via the MSSQL streaming interface,
// 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) => {
stream.on('error', (err) => {
rejecter(err);
});
stream.on('end', resolver);
const { sql } = obj;
if (!sql) return resolver();
const req = (connection.tx_ || connection).request();
//req.verbose = true;
req.multiple = true;
req.stream = true;
if (obj.bindings) {
for (let i = 0; i < obj.bindings.length; i++) {
this._setReqInput(req, i, obj.bindings[i]);
}
}
req.pipe(stream);
req.query(sql);
});
},
// Runs the query on the specified connection, providing the bindings
// and any other necessary prep work.
_query(connection, obj) {
const client = this;
if (!obj || typeof obj === 'string') obj = { sql: obj };
return new Bluebird((resolver, rejecter) => {
const { sql } = obj;
if (!sql) return resolver();
const req = (connection.tx_ || connection).request();
// req.verbose = true;
req.multiple = true;
if (obj.bindings) {
for (let i = 0; i < obj.bindings.length; i++) {
client._setReqInput(req, i, obj.bindings[i]);
}
}
req.query(sql, (err, recordset) => {
if (err) {
return rejecter(err);
}
obj.response = recordset.recordsets[0];
resolver(obj);
});
});
},
// sets a request input parameter. Detects bigints and decimals and sets type appropriately.
_setReqInput(req, i, binding) {
if (typeof binding == 'number') {
if (binding % 1 !== 0) {
req.input(`p${i}`, this.driver.Decimal(38, 10), binding);
} else if (binding < SQL_INT4.MIN || binding > SQL_INT4.MAX) {
if (binding < SQL_BIGINT_SAFE.MIN || binding > SQL_BIGINT_SAFE.MAX) {
throw new Error(
`Bigint must be safe integer or must be passed as string, saw ${binding}`
);
}
req.input(`p${i}`, this.driver.BigInt, binding);
} else {
req.input(`p${i}`, this.driver.Int, binding);
}
} else {
req.input(`p${i}`, binding);
}
},
// Process the response as returned from the query.
processResponse(obj, runner) {
if (obj == null) return;
const { response, method } = obj;
if (obj.output) return obj.output.call(runner, response);
switch (method) {
case 'select':
case 'pluck':
case 'first':
if (method === 'pluck') return map(response, obj.pluck);
return method === 'first' ? response[0] : response;
case 'insert':
case 'del':
case 'update':
case 'counter':
if (obj.returning) {
if (obj.returning === '@@rowcount') {
return response[0][''];
}
if (
(Array.isArray(obj.returning) && obj.returning.length > 1) ||
obj.returning[0] === '*'
) {
return response;
}
// return an array with values if only one returning value was specified
return flatten(map(response, values));
}
return response;
default:
return response;
}
},
});
class MSSQL_Formatter extends Formatter {
// Accepts a string or array of columns to wrap as appropriate.
columnizeWithPrefix(prefix, target) {
const columns = typeof target === 'string' ? [target] : target;
let str = '',
i = -1;
while (++i < columns.length) {
if (i > 0) str += ', ';
str += prefix + this.wrap(columns[i]);
}
return str;
}
}
module.exports = Client_MSSQL;

264
node_modules/knex/lib/dialects/mssql/query/compiler.js generated vendored Normal file
View File

@@ -0,0 +1,264 @@
// MSSQL Query Compiler
// ------
const inherits = require('inherits');
const QueryCompiler = require('../../../query/compiler');
const { isEmpty, compact, identity } = require('lodash');
function QueryCompiler_MSSQL(client, builder) {
QueryCompiler.call(this, client, builder);
}
inherits(QueryCompiler_MSSQL, QueryCompiler);
const components = [
'columns',
'join',
'lock',
'where',
'union',
'group',
'having',
'order',
'limit',
'offset',
];
Object.assign(QueryCompiler_MSSQL.prototype, {
_emptyInsertValue: 'default values',
select() {
const sql = this.with();
const statements = components.map((component) => this[component](this));
return sql + compact(statements).join(' ');
},
// Compiles an "insert" query, allowing for multiple
// inserts using a single query statement.
insert() {
const insertValues = this.single.insert || [];
let sql = this.with() + `insert into ${this.tableName} `;
const { returning } = this.single;
const returningSql = returning
? this._returning('insert', returning) + ' '
: '';
if (Array.isArray(insertValues)) {
if (insertValues.length === 0) {
return '';
}
} else if (typeof insertValues === 'object' && isEmpty(insertValues)) {
return {
sql: sql + returningSql + this._emptyInsertValue,
returning,
};
}
const insertData = this._prepInsert(insertValues);
if (typeof insertData === 'string') {
sql += insertData;
} else {
if (insertData.columns.length) {
sql += `(${this.formatter.columnize(insertData.columns)}`;
sql += `) ${returningSql}values (`;
let i = -1;
while (++i < insertData.values.length) {
if (i !== 0) sql += '), (';
sql += this.formatter.parameterize(
insertData.values[i],
this.client.valueForUndefined
);
}
sql += ')';
} else if (insertValues.length === 1 && insertValues[0]) {
sql += returningSql + this._emptyInsertValue;
} else {
sql = '';
}
}
return {
sql,
returning,
};
},
// Compiles an `update` query, allowing for a return value.
update() {
const top = this.top();
const withSQL = this.with();
const updates = this._prepUpdate(this.single.update);
const join = this.join();
const where = this.where();
const order = this.order();
const { returning } = this.single;
return {
sql:
withSQL +
`update ${top ? top + ' ' : ''}${this.tableName}` +
' set ' +
updates.join(', ') +
(returning ? ` ${this._returning('update', returning)}` : '') +
(join ? ` from ${this.tableName} ${join}` : '') +
(where ? ` ${where}` : '') +
(order ? ` ${order}` : '') +
(!returning ? this._returning('rowcount', '@@rowcount') : ''),
returning: returning || '@@rowcount',
};
},
// Compiles a `delete` query.
del() {
// Make sure tableName is processed by the formatter first.
const withSQL = this.with();
const { tableName } = this;
const wheres = this.where();
const { returning } = this.single;
return {
sql:
withSQL +
`delete from ${tableName}` +
(returning ? ` ${this._returning('del', returning)}` : '') +
(wheres ? ` ${wheres}` : '') +
(!returning ? this._returning('rowcount', '@@rowcount') : ''),
returning: returning || '@@rowcount',
};
},
// Compiles the columns in the query, specifying if an item was distinct.
columns() {
let distinctClause = '';
if (this.onlyUnions()) return '';
const top = this.top();
const columns = this.grouped.columns || [];
let i = -1,
sql = [];
if (columns) {
while (++i < columns.length) {
const stmt = columns[i];
if (stmt.distinct) distinctClause = 'distinct ';
if (stmt.distinctOn) {
distinctClause = this.distinctOn(stmt.value);
continue;
}
if (stmt.type === 'aggregate') {
sql.push(...this.aggregate(stmt));
} else if (stmt.type === 'aggregateRaw') {
sql.push(this.aggregateRaw(stmt));
} else if (stmt.value && stmt.value.length > 0) {
sql.push(this.formatter.columnize(stmt.value));
}
}
}
if (sql.length === 0) sql = ['*'];
return (
`select ${distinctClause}` +
(top ? top + ' ' : '') +
sql.join(', ') +
(this.tableName ? ` from ${this.tableName}` : '')
);
},
_returning(method, value) {
switch (method) {
case 'update':
case 'insert':
return value
? `output ${this.formatter.columnizeWithPrefix('inserted.', value)}`
: '';
case 'del':
return value
? `output ${this.formatter.columnizeWithPrefix('deleted.', value)}`
: '';
case 'rowcount':
return value ? ';select @@rowcount' : '';
}
},
// Compiles a `truncate` query.
truncate() {
return `truncate table ${this.tableName}`;
},
forUpdate() {
// this doesn't work exacltly as it should, one should also mention index while locking
// https://stackoverflow.com/a/9818448/360060
return 'with (UPDLOCK)';
},
forShare() {
// http://www.sqlteam.com/article/introduction-to-locking-in-sql-server
return 'with (HOLDLOCK)';
},
// Compiles a `columnInfo` query.
columnInfo() {
const column = this.single.columnInfo;
let schema = this.single.schema;
// The user may have specified a custom wrapIdentifier function in the config. We
// need to run the identifiers through that function, but not format them as
// identifiers otherwise.
const table = this.client.customWrapIdentifier(this.single.table, identity);
if (schema) {
schema = this.client.customWrapIdentifier(schema, identity);
}
let sql = `select * from information_schema.columns where table_name = ? and table_catalog = ?`;
const bindings = [table, this.client.database()];
if (schema) {
sql += ' and table_schema = ?';
bindings.push(schema);
} else {
sql += ` and table_schema = 'dbo'`;
}
return {
sql,
bindings: bindings,
output(resp) {
const out = resp.reduce(function(columns, val) {
columns[val.COLUMN_NAME] = {
defaultValue: val.COLUMN_DEFAULT,
type: val.DATA_TYPE,
maxLength: val.CHARACTER_MAXIMUM_LENGTH,
nullable: val.IS_NULLABLE === 'YES',
};
return columns;
}, {});
return (column && out[column]) || out;
},
};
},
top() {
const noLimit = !this.single.limit && this.single.limit !== 0;
const noOffset = !this.single.offset;
if (noLimit || !noOffset) return '';
return `top (${this.formatter.parameter(this.single.limit)})`;
},
limit() {
return '';
},
offset() {
const noLimit = !this.single.limit && this.single.limit !== 0;
const noOffset = !this.single.offset;
if (noOffset) return '';
let offset = `offset ${
noOffset ? '0' : this.formatter.parameter(this.single.offset)
} rows`;
if (!noLimit) {
offset += ` fetch next ${this.formatter.parameter(
this.single.limit
)} rows only`;
}
return offset;
},
});
// Set the QueryBuilder & QueryCompiler on the client object,
// in case anyone wants to modify things to suit their own purposes.
module.exports = QueryCompiler_MSSQL;

View File

@@ -0,0 +1,103 @@
// MySQL Column Compiler
// -------
const inherits = require('inherits');
const ColumnCompiler = require('../../../schema/columncompiler');
function ColumnCompiler_MSSQL() {
ColumnCompiler.apply(this, arguments);
this.modifiers = ['nullable', 'defaultTo', 'first', 'after', 'comment'];
}
inherits(ColumnCompiler_MSSQL, ColumnCompiler);
// Types
// ------
Object.assign(ColumnCompiler_MSSQL.prototype, {
increments: 'int identity(1,1) not null primary key',
bigincrements: 'bigint identity(1,1) not null primary key',
bigint: 'bigint',
double(precision, scale) {
return 'float';
},
floating(precision, scale) {
// ignore precicion / scale which is mysql specific stuff
return `float`;
},
integer() {
// mssql does not support length
return 'int';
},
mediumint: 'int',
smallint: 'smallint',
tinyint() {
// mssql does not support length
return 'tinyint';
},
varchar(length) {
return `nvarchar(${this._num(length, 255)})`;
},
text: 'nvarchar(max)',
mediumtext: 'nvarchar(max)',
longtext: 'nvarchar(max)',
// TODO: mssql supports check constraints as of SQL Server 2008
// so make enu here more like postgres
enu: 'nvarchar(100)',
uuid: 'uniqueidentifier',
datetime: 'datetime2',
timestamp({ useTz = false } = {}) {
return useTz ? 'datetimeoffset' : 'datetime2';
},
bit(length) {
if (length > 1) {
this.client.logger.warn('Bit field is exactly 1 bit length for MSSQL');
}
return 'bit';
},
binary(length) {
return length ? `varbinary(${this._num(length)})` : 'varbinary(max)';
},
bool: 'bit',
// Modifiers
// ------
first() {
this.client.logger.warn('Column first modifier not available for MSSQL');
return '';
},
after(column) {
this.client.logger.warn('Column after modifier not available for MSSQL');
return '';
},
comment(comment) {
if (comment && comment.length > 255) {
this.client.logger.warn(
'Your comment is longer than the max comment length for MSSQL'
);
}
return '';
},
});
module.exports = ColumnCompiler_MSSQL;

View File

@@ -0,0 +1,59 @@
// MySQL Schema Compiler
// -------
const inherits = require('inherits');
const SchemaCompiler = require('../../../schema/compiler');
function SchemaCompiler_MSSQL(client, builder) {
SchemaCompiler.call(this, client, builder);
}
inherits(SchemaCompiler_MSSQL, SchemaCompiler);
Object.assign(SchemaCompiler_MSSQL.prototype, {
dropTablePrefix: 'DROP TABLE ',
dropTableIfExists(tableName) {
const name = this.formatter.wrap(prefixedTableName(this.schema, tableName));
this.pushQuery(
`if object_id('${name}', 'U') is not null DROP TABLE ${name}`
);
},
// Rename a table on the schema.
renameTable(tableName, to) {
this.pushQuery(
`exec sp_rename ${this.formatter.parameter(
prefixedTableName(this.schema, tableName)
)}, ${this.formatter.parameter(to)}`
);
},
// Check whether a table exists on the query.
hasTable(tableName) {
const formattedTable = this.formatter.parameter(
this.formatter.wrap(prefixedTableName(this.schema, tableName))
);
const sql =
`select object_id from sys.tables ` +
`where object_id = object_id(${formattedTable})`;
this.pushQuery({ sql, output: (resp) => resp.length > 0 });
},
// Check whether a column exists on the schema.
hasColumn(tableName, column) {
const formattedColumn = this.formatter.parameter(column);
const formattedTable = this.formatter.parameter(
this.formatter.wrap(prefixedTableName(this.schema, tableName))
);
const sql =
`select object_id from sys.columns ` +
`where name = ${formattedColumn} ` +
`and object_id = object_id(${formattedTable})`;
this.pushQuery({ sql, output: (resp) => resp.length > 0 });
},
});
function prefixedTableName(prefix, table) {
return prefix ? `${prefix}.${table}` : table;
}
module.exports = SchemaCompiler_MSSQL;

View File

@@ -0,0 +1,228 @@
/* eslint max-len:0 */
// MSSQL Table Builder & Compiler
// -------
const inherits = require('inherits');
const TableCompiler = require('../../../schema/tablecompiler');
const helpers = require('../../../helpers');
// Table Compiler
// ------
function TableCompiler_MSSQL() {
TableCompiler.apply(this, arguments);
}
inherits(TableCompiler_MSSQL, TableCompiler);
Object.assign(TableCompiler_MSSQL.prototype, {
createAlterTableMethods: ['foreign', 'primary'],
createQuery(columns, ifNot) {
const createStatement = ifNot
? `if object_id('${this.tableName()}', 'U') is null CREATE TABLE `
: 'CREATE TABLE ';
const sql =
createStatement +
this.tableName() +
(this._formatting ? ' (\n ' : ' (') +
columns.sql.join(this._formatting ? ',\n ' : ', ') +
')';
if (this.single.comment) {
const { comment } = this.single;
if (comment.length > 60)
this.client.logger.warn(
'The max length for a table comment is 60 characters'
);
}
this.pushQuery(sql);
},
lowerCase: false,
addColumnsPrefix: 'ADD ',
dropColumnPrefix: 'DROP COLUMN ',
alterColumnPrefix: 'ALTER COLUMN ',
// Compiles column add. Multiple columns need only one ADD clause (not one ADD per column) so core addColumns doesn't work. #1348
addColumns(columns, prefix) {
prefix = prefix || this.addColumnsPrefix;
if (columns.sql.length > 0) {
this.pushQuery({
sql:
(this.lowerCase ? 'alter table ' : 'ALTER TABLE ') +
this.tableName() +
' ' +
prefix +
columns.sql.join(', '),
bindings: columns.bindings,
});
}
},
// Compiles column drop. Multiple columns need only one DROP clause (not one DROP per column) so core dropColumn doesn't work. #1348
dropColumn() {
const _this2 = this;
const columns = helpers.normalizeArr.apply(null, arguments);
const drops = (Array.isArray(columns) ? columns : [columns]).map((column) =>
_this2.formatter.wrap(column)
);
this.pushQuery(
(this.lowerCase ? 'alter table ' : 'ALTER TABLE ') +
this.tableName() +
' ' +
this.dropColumnPrefix +
drops.join(', ')
);
},
// Compiles the comment on the table.
comment() {},
changeType() {},
// Renames a column on the table.
renameColumn(from, to) {
this.pushQuery(
`exec sp_rename ${this.formatter.parameter(
this.tableName() + '.' + from
)}, ${this.formatter.parameter(to)}, 'COLUMN'`
);
},
dropFKRefs(runner, refs) {
const formatter = this.client.formatter(this.tableBuilder);
return Promise.all(
refs.map(function(ref) {
const constraintName = formatter.wrap(ref.CONSTRAINT_NAME);
const tableName = formatter.wrap(ref.TABLE_NAME);
return runner.query({
sql: `ALTER TABLE ${tableName} DROP CONSTRAINT ${constraintName}`,
});
})
);
},
createFKRefs(runner, refs) {
const formatter = this.client.formatter(this.tableBuilder);
return Promise.all(
refs.map(function(ref) {
const tableName = formatter.wrap(ref.TABLE_NAME);
const keyName = formatter.wrap(ref.CONSTRAINT_NAME);
const column = formatter.columnize(ref.COLUMN_NAME);
const references = formatter.columnize(ref.REFERENCED_COLUMN_NAME);
const inTable = formatter.wrap(ref.REFERENCED_TABLE_NAME);
const onUpdate = ` ON UPDATE ${ref.UPDATE_RULE}`;
const onDelete = ` ON DELETE ${ref.DELETE_RULE}`;
return runner.query({
sql:
`ALTER TABLE ${tableName} ADD CONSTRAINT ${keyName}` +
' FOREIGN KEY (' +
column +
') REFERENCES ' +
inTable +
' (' +
references +
')' +
onUpdate +
onDelete,
});
})
);
},
index(columns, indexName) {
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('index', this.tableNameRaw, columns);
this.pushQuery(
`CREATE INDEX ${indexName} ON ${this.tableName()} (${this.formatter.columnize(
columns
)})`
);
},
primary(columns, constraintName) {
constraintName = constraintName
? this.formatter.wrap(constraintName)
: this.formatter.wrap(`${this.tableNameRaw}_pkey`);
if (!this.forCreate) {
this.pushQuery(
`ALTER TABLE ${this.tableName()} ADD CONSTRAINT ${constraintName} PRIMARY KEY (${this.formatter.columnize(
columns
)})`
);
} else {
this.pushQuery(
`CONSTRAINT ${constraintName} PRIMARY KEY (${this.formatter.columnize(
columns
)})`
);
}
},
unique(columns, indexName) {
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('unique', this.tableNameRaw, columns);
if (!Array.isArray(columns)) {
columns = [columns];
}
const whereAllTheColumnsAreNotNull = columns
.map((column) => this.formatter.columnize(column) + ' IS NOT NULL')
.join(' AND ');
// make unique constraint that allows null https://stackoverflow.com/a/767702/360060
// to be more or less compatible with other DBs (if any of the columns is NULL then "duplicates" are allowed)
this.pushQuery(
`CREATE UNIQUE INDEX ${indexName} ON ${this.tableName()} (${this.formatter.columnize(
columns
)}) WHERE ${whereAllTheColumnsAreNotNull}`
);
},
// Compile a drop index command.
dropIndex(columns, indexName) {
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('index', this.tableNameRaw, columns);
this.pushQuery(`DROP INDEX ${indexName} ON ${this.tableName()}`);
},
// Compile a drop foreign key command.
dropForeign(columns, indexName) {
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('foreign', this.tableNameRaw, columns);
this.pushQuery(
`ALTER TABLE ${this.tableName()} DROP CONSTRAINT ${indexName}`
);
},
// Compile a drop primary key command.
dropPrimary(constraintName) {
constraintName = constraintName
? this.formatter.wrap(constraintName)
: this.formatter.wrap(`${this.tableNameRaw}_pkey`);
this.pushQuery(
`ALTER TABLE ${this.tableName()} DROP CONSTRAINT ${constraintName}`
);
},
// Compile a drop unique key command.
dropUnique(column, indexName) {
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('unique', this.tableNameRaw, column);
this.pushQuery(`DROP INDEX ${indexName} ON ${this.tableName()}`);
},
});
module.exports = TableCompiler_MSSQL;

107
node_modules/knex/lib/dialects/mssql/transaction.js generated vendored Normal file
View File

@@ -0,0 +1,107 @@
const Bluebird = require('bluebird');
const Transaction = require('../../transaction');
const { isUndefined } = require('lodash');
const debug = require('debug')('knex:tx');
module.exports = class Transaction_MSSQL extends Transaction {
begin(conn) {
debug('%s: begin', this.txid);
return conn.tx_.begin().then(this._resolver, this._rejecter);
}
savepoint(conn) {
debug('%s: savepoint at', this.txid);
return Bluebird.resolve().then(() =>
this.query(conn, `SAVE TRANSACTION ${this.txid}`)
);
}
commit(conn, value) {
this._completed = true;
debug('%s: commit', this.txid);
return conn.tx_.commit().then(() => this._resolver(value), this._rejecter);
}
release(conn, value) {
return this._resolver(value);
}
rollback(conn, error) {
this._completed = true;
debug('%s: rolling back', this.txid);
return conn.tx_.rollback().then(
() => {
let err = error;
if (isUndefined(error)) {
if (this.doNotRejectOnRollback) {
this._resolver();
return;
}
err = new Error(`Transaction rejected with non-error: ${error}`);
}
this._rejecter(err);
},
(err) => {
if (error) err.originalError = error;
return this._rejecter(err);
}
);
}
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));
}
// Acquire a connection and create a disposer - either using the one passed
// via config or getting one off the client. The disposer will be called once
// the original promise is marked completed.
acquireConnection(config, cb) {
const configConnection = config && config.connection;
return new Bluebird((resolve, reject) => {
try {
resolve(
(this.outerTx ? this.outerTx.conn : null) ||
configConnection ||
this.client.acquireConnection()
);
} catch (e) {
reject(e);
}
})
.then((conn) => {
conn.__knexTxId = this.txid;
if (!this.outerTx) {
this.conn = conn;
conn.tx_ = conn.transaction();
}
return conn;
})
.then(async (conn) => {
try {
return await cb(conn);
} finally {
if (!this.outerTx) {
if (conn.tx_) {
if (!this._completed) {
debug('%s: unreleased transaction', this.txid);
conn.tx_.rollback();
}
conn.tx_ = null;
}
this.conn = null;
if (!configConnection) {
debug('%s: releasing connection', this.txid);
this.client.releaseConnection(conn);
} else {
debug('%s: not releasing external connection', this.txid);
}
}
}
});
}
};