Change endpoint from persons to people

This commit is contained in:
xfarrow
2025-03-23 21:00:08 +01:00
parent 4ae263662c
commit d005193f63
7158 changed files with 700476 additions and 735 deletions

View File

@ -0,0 +1,206 @@
// MySQL Client
// -------
const defer = require('lodash/defer');
const map = require('lodash/map');
const { promisify } = require('util');
const Client = require('../../client');
const Transaction = require('./transaction');
const QueryBuilder = require('./query/mysql-querybuilder');
const QueryCompiler = require('./query/mysql-querycompiler');
const SchemaCompiler = require('./schema/mysql-compiler');
const TableCompiler = require('./schema/mysql-tablecompiler');
const ColumnCompiler = require('./schema/mysql-columncompiler');
const { makeEscape } = require('../../util/string');
const ViewCompiler = require('./schema/mysql-viewcompiler');
const ViewBuilder = require('./schema/mysql-viewbuilder');
// Always initialize with the "QueryBuilder" and "QueryCompiler"
// objects, which extend the base 'lib/query/builder' and
// 'lib/query/compiler', respectively.
class Client_MySQL extends Client {
_driver() {
return require('mysql');
}
queryBuilder() {
return new QueryBuilder(this);
}
queryCompiler(builder, formatter) {
return new QueryCompiler(this, builder, formatter);
}
schemaCompiler() {
return new SchemaCompiler(this, ...arguments);
}
tableCompiler() {
return new TableCompiler(this, ...arguments);
}
viewCompiler() {
return new ViewCompiler(this, ...arguments);
}
viewBuilder() {
return new ViewBuilder(this, ...arguments);
}
columnCompiler() {
return new ColumnCompiler(this, ...arguments);
}
transaction() {
return new Transaction(this, ...arguments);
}
wrapIdentifierImpl(value) {
return value !== '*' ? `\`${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 Promise((resolver, rejecter) => {
const connection = this.driver.createConnection(this.connectionSettings);
connection.on('error', (err) => {
connection.__knex__disposed = err;
});
connection.connect((err) => {
if (err) {
// if connection is rejected, remove listener that was registered above...
connection.removeAllListeners();
return rejecter(err);
}
resolver(connection);
});
});
}
// Used to explicitly close a connection, called internally by the pool
// when a connection times out or the pool is shutdown.
async destroyRawConnection(connection) {
try {
const end = promisify((cb) => connection.end(cb));
return await end();
} catch (err) {
connection.__knex__disposed = err;
} finally {
// see discussion https://github.com/knex/knex/pull/3483
defer(() => connection.removeAllListeners());
}
}
validateConnection(connection) {
return (
connection.state === 'connected' || connection.state === 'authenticated'
);
}
// Grab a connection, run the query via the MySQL streaming interface,
// and pass that through to the stream we've sent back to the client.
_stream(connection, obj, stream, options) {
if (!obj.sql) throw new Error('The query is empty');
options = options || {};
const queryOptions = Object.assign({ sql: obj.sql }, obj.options);
return new Promise((resolver, rejecter) => {
stream.on('error', rejecter);
stream.on('end', resolver);
const queryStream = connection
.query(queryOptions, obj.bindings)
.stream(options);
queryStream.on('error', (err) => {
rejecter(err);
stream.emit('error', err);
});
queryStream.pipe(stream);
});
}
// Runs the query on the specified connection, providing the bindings
// and any other necessary prep work.
_query(connection, obj) {
if (!obj || typeof obj === 'string') obj = { sql: obj };
if (!obj.sql) throw new Error('The query is empty');
return new Promise(function (resolver, rejecter) {
if (!obj.sql) {
resolver();
return;
}
const queryOptions = Object.assign({ sql: obj.sql }, obj.options);
connection.query(
queryOptions,
obj.bindings,
function (err, rows, fields) {
if (err) return rejecter(err);
obj.response = [rows, fields];
resolver(obj);
}
);
});
}
// Process the response as returned from the query.
processResponse(obj, runner) {
if (obj == null) return;
const { response } = obj;
const { method } = obj;
const rows = response[0];
const fields = response[1];
if (obj.output) return obj.output.call(runner, rows, fields);
switch (method) {
case 'select':
return rows;
case 'first':
return rows[0];
case 'pluck':
return map(rows, obj.pluck);
case 'insert':
return [rows.insertId];
case 'del':
case 'update':
case 'counter':
return rows.affectedRows;
default:
return response;
}
}
async cancelQuery(connectionToKill) {
const conn = await this.acquireRawConnection();
try {
return await this._wrappedCancelQueryCall(conn, connectionToKill);
} finally {
await this.destroyRawConnection(conn);
if (conn.__knex__disposed) {
this.logger.warn(`Connection Error: ${conn.__knex__disposed}`);
}
}
}
_wrappedCancelQueryCall(conn, connectionToKill) {
return this._query(conn, {
sql: 'KILL QUERY ?',
bindings: [connectionToKill.threadId],
options: {},
});
}
}
Object.assign(Client_MySQL.prototype, {
dialect: 'mysql',
driverName: 'mysql',
_escapeBinding: makeEscape(),
canCancelQuery: true,
});
module.exports = Client_MySQL;

View File

@ -0,0 +1,14 @@
const QueryBuilder = require('../../../query/querybuilder');
const isEmpty = require('lodash/isEmpty');
module.exports = class QueryBuilder_MySQL extends QueryBuilder {
upsert(values, returning, options) {
this._method = 'upsert';
if (!isEmpty(returning)) {
this.returning(returning, options);
}
this._single.upsert = values;
return this;
}
};

View File

@ -0,0 +1,292 @@
// MySQL Query Compiler
// ------
const assert = require('assert');
const identity = require('lodash/identity');
const isPlainObject = require('lodash/isPlainObject');
const isEmpty = require('lodash/isEmpty');
const QueryCompiler = require('../../../query/querycompiler');
const { wrapAsIdentifier } = require('../../../formatter/formatterUtils');
const {
columnize: columnize_,
wrap: wrap_,
} = require('../../../formatter/wrappingFormatter');
const isPlainObjectOrArray = (value) =>
isPlainObject(value) || Array.isArray(value);
class QueryCompiler_MySQL extends QueryCompiler {
constructor(client, builder, formatter) {
super(client, builder, formatter);
const { returning } = this.single;
if (returning) {
this.client.logger.warn(
'.returning() is not supported by mysql and will not have any effect.'
);
}
this._emptyInsertValue = '() values ()';
}
// Compiles an `delete` allowing comments
del() {
const sql = super.del();
if (sql === '') return sql;
const comments = this.comments();
return (comments === '' ? '' : comments + ' ') + sql;
}
// Compiles an `insert` query, allowing for multiple
// inserts using a single query statement.
insert() {
let sql = super.insert();
if (sql === '') return sql;
const comments = this.comments();
sql = (comments === '' ? '' : comments + ' ') + sql;
const { ignore, merge, insert } = this.single;
if (ignore) sql = sql.replace('insert into', 'insert ignore into');
if (merge) {
sql += this._merge(merge.updates, insert);
const wheres = this.where();
if (wheres) {
throw new Error(
'.onConflict().merge().where() is not supported for mysql'
);
}
}
return sql;
}
upsert() {
const upsertValues = this.single.upsert || [];
const sql = this.with() + `replace into ${this.tableName} `;
const body = this._insertBody(upsertValues);
return body === '' ? '' : sql + body;
}
// Compiles merge for onConflict, allowing for different merge strategies
_merge(updates, insert) {
const sql = ' on duplicate key update ';
if (updates && Array.isArray(updates)) {
// update subset of columns
return (
sql +
updates
.map((column) =>
wrapAsIdentifier(column, this.formatter.builder, this.client)
)
.map((column) => `${column} = values(${column})`)
.join(', ')
);
} else if (updates && typeof updates === 'object') {
const updateData = this._prepUpdate(updates);
return sql + updateData.join(',');
} else {
const insertData = this._prepInsert(insert);
if (typeof insertData === 'string') {
throw new Error(
'If using merge with a raw insert query, then updates must be provided'
);
}
return (
sql +
insertData.columns
.map((column) => wrapAsIdentifier(column, this.builder, this.client))
.map((column) => `${column} = values(${column})`)
.join(', ')
);
}
}
// Update method, including joins, wheres, order & limits.
update() {
const comments = this.comments();
const withSQL = this.with();
const join = this.join();
const updates = this._prepUpdate(this.single.update);
const where = this.where();
const order = this.order();
const limit = this.limit();
return (
(comments === '' ? '' : comments + ' ') +
withSQL +
`update ${this.tableName}` +
(join ? ` ${join}` : '') +
' set ' +
updates.join(', ') +
(where ? ` ${where}` : '') +
(order ? ` ${order}` : '') +
(limit ? ` ${limit}` : '')
);
}
forUpdate() {
return 'for update';
}
forShare() {
return 'lock in share mode';
}
// Only supported on MySQL 8.0+
skipLocked() {
return 'skip locked';
}
// Supported on MySQL 8.0+ and MariaDB 10.3.0+
noWait() {
return 'nowait';
}
// Compiles a `columnInfo` query.
columnInfo() {
const column = this.single.columnInfo;
// 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);
return {
sql: 'select * from information_schema.columns where table_name = ? and table_schema = ?',
bindings: [table, this.client.database()],
output(resp) {
const out = resp.reduce(function (columns, val) {
columns[val.COLUMN_NAME] = {
defaultValue:
val.COLUMN_DEFAULT === 'NULL' ? null : val.COLUMN_DEFAULT,
type: val.DATA_TYPE,
maxLength: val.CHARACTER_MAXIMUM_LENGTH,
nullable: val.IS_NULLABLE === 'YES',
};
return columns;
}, {});
return (column && out[column]) || out;
},
};
}
limit() {
const noLimit = !this.single.limit && this.single.limit !== 0;
if (noLimit && !this.single.offset) return '';
// Workaround for offset only.
// see: http://stackoverflow.com/questions/255517/mysql-offset-infinite-rows
const limit =
this.single.offset && noLimit
? '18446744073709551615'
: this._getValueOrParameterFromAttribute('limit');
return `limit ${limit}`;
}
whereBasic(statement) {
assert(
!isPlainObjectOrArray(statement.value),
'The values in where clause must not be object or array.'
);
return super.whereBasic(statement);
}
whereRaw(statement) {
assert(
isEmpty(statement.value.bindings) ||
!Object.values(statement.value.bindings).some(isPlainObjectOrArray),
'The values in where clause must not be object or array.'
);
return super.whereRaw(statement);
}
whereLike(statement) {
return `${this._columnClause(statement)} ${this._not(
statement,
'like '
)}${this._valueClause(statement)} COLLATE utf8_bin`;
}
whereILike(statement) {
return `${this._columnClause(statement)} ${this._not(
statement,
'like '
)}${this._valueClause(statement)}`;
}
// Json functions
jsonExtract(params) {
return this._jsonExtract(['json_extract', 'json_unquote'], params);
}
jsonSet(params) {
return this._jsonSet('json_set', params);
}
jsonInsert(params) {
return this._jsonSet('json_insert', params);
}
jsonRemove(params) {
const jsonCol = `json_remove(${columnize_(
params.column,
this.builder,
this.client,
this.bindingsHolder
)},${this.client.parameter(
params.path,
this.builder,
this.bindingsHolder
)})`;
return params.alias
? this.client.alias(jsonCol, this.formatter.wrap(params.alias))
: jsonCol;
}
whereJsonObject(statement) {
return this._not(
statement,
`json_contains(${this._columnClause(statement)}, ${this._jsonValueClause(
statement
)})`
);
}
whereJsonPath(statement) {
return this._whereJsonPath('json_extract', statement);
}
whereJsonSupersetOf(statement) {
return this._not(
statement,
`json_contains(${wrap_(
statement.column,
undefined,
this.builder,
this.client,
this.bindingsHolder
)},${this._jsonValueClause(statement)})`
);
}
whereJsonSubsetOf(statement) {
return this._not(
statement,
`json_contains(${this._jsonValueClause(statement)},${wrap_(
statement.column,
undefined,
this.builder,
this.client,
this.bindingsHolder
)})`
);
}
onJsonPathEquals(clause) {
return this._onJsonPathEquals('json_extract', clause);
}
}
// Set the QueryBuilder & QueryCompiler on the client object,
// in case anyone wants to modify things to suit their own purposes.
module.exports = QueryCompiler_MySQL;

View File

@ -0,0 +1,193 @@
// MySQL Column Compiler
// -------
const ColumnCompiler = require('../../../schema/columncompiler');
const { isObject } = require('../../../util/is');
const { toNumber } = require('../../../util/helpers');
const commentEscapeRegex = /(?<!\\)'/g;
class ColumnCompiler_MySQL extends ColumnCompiler {
constructor(client, tableCompiler, columnBuilder) {
super(client, tableCompiler, columnBuilder);
this.modifiers = [
'unsigned',
'nullable',
'defaultTo',
'comment',
'collate',
'first',
'after',
];
this._addCheckModifiers();
}
// Types
// ------
double(precision, scale) {
if (!precision) return 'double';
return `double(${toNumber(precision, 8)}, ${toNumber(scale, 2)})`;
}
integer(length) {
length = length ? `(${toNumber(length, 11)})` : '';
return `int${length}`;
}
tinyint(length) {
length = length ? `(${toNumber(length, 1)})` : '';
return `tinyint${length}`;
}
text(column) {
switch (column) {
case 'medium':
case 'mediumtext':
return 'mediumtext';
case 'long':
case 'longtext':
return 'longtext';
default:
return 'text';
}
}
mediumtext() {
return this.text('medium');
}
longtext() {
return this.text('long');
}
enu(allowed) {
return `enum('${allowed.join("', '")}')`;
}
datetime(precision) {
if (isObject(precision)) {
({ precision } = precision);
}
return typeof precision === 'number'
? `datetime(${precision})`
: 'datetime';
}
timestamp(precision) {
if (isObject(precision)) {
({ precision } = precision);
}
return typeof precision === 'number'
? `timestamp(${precision})`
: 'timestamp';
}
time(precision) {
if (isObject(precision)) {
({ precision } = precision);
}
return typeof precision === 'number' ? `time(${precision})` : 'time';
}
bit(length) {
return length ? `bit(${toNumber(length)})` : 'bit';
}
binary(length) {
return length ? `varbinary(${toNumber(length)})` : 'blob';
}
json() {
return 'json';
}
jsonb() {
return 'json';
}
// Modifiers
// ------
defaultTo(value) {
// MySQL defaults to null by default, but breaks down if you pass it explicitly
// Note that in MySQL versions up to 5.7, logic related to updating
// timestamps when no explicit value is passed is quite insane - https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_explicit_defaults_for_timestamp
if (value === null || value === undefined) {
return;
}
if ((this.type === 'json' || this.type === 'jsonb') && isObject(value)) {
// Default value for json will work only it is an expression
return `default ('${JSON.stringify(value)}')`;
}
const defaultVal = super.defaultTo.apply(this, arguments);
if (this.type !== 'blob' && this.type.indexOf('text') === -1) {
return defaultVal;
}
return '';
}
unsigned() {
return 'unsigned';
}
comment(comment) {
if (comment && comment.length > 255) {
this.client.logger.warn(
'Your comment is longer than the max comment length for MySQL'
);
}
return comment && `comment '${comment.replace(commentEscapeRegex, "\\'")}'`;
}
first() {
return 'first';
}
after(column) {
return `after ${this.formatter.wrap(column)}`;
}
collate(collation) {
return collation && `collate '${collation}'`;
}
checkRegex(regex, constraintName) {
return this._check(
`${this.formatter.wrap(
this.getColumnName()
)} REGEXP ${this.client._escapeBinding(regex)}`,
constraintName
);
}
increments(options = { primaryKey: true }) {
return (
'int unsigned not null' +
// In MySQL autoincrement are always a primary key. If you already have a primary key, we
// initialize this column as classic int column then modify it later in table compiler
(this.tableCompiler._canBeAddPrimaryKey(options)
? ' auto_increment primary key'
: '')
);
}
bigincrements(options = { primaryKey: true }) {
return (
'bigint unsigned not null' +
// In MySQL autoincrement are always a primary key. If you already have a primary key, we
// initialize this column as classic int column then modify it later in table compiler
(this.tableCompiler._canBeAddPrimaryKey(options)
? ' auto_increment primary key'
: '')
);
}
}
ColumnCompiler_MySQL.prototype.bigint = 'bigint';
ColumnCompiler_MySQL.prototype.mediumint = 'mediumint';
ColumnCompiler_MySQL.prototype.smallint = 'smallint';
module.exports = ColumnCompiler_MySQL;

View File

@ -0,0 +1,60 @@
// MySQL Schema Compiler
// -------
const SchemaCompiler = require('../../../schema/compiler');
class SchemaCompiler_MySQL extends SchemaCompiler {
constructor(client, builder) {
super(client, builder);
}
// Rename a table on the schema.
renameTable(tableName, to) {
this.pushQuery(
`rename table ${this.formatter.wrap(tableName)} to ${this.formatter.wrap(
to
)}`
);
}
renameView(from, to) {
this.renameTable(from, to);
}
// Check whether a table exists on the query.
hasTable(tableName) {
let sql = 'select * from information_schema.tables where table_name = ?';
const bindings = [tableName];
if (this.schema) {
sql += ' and table_schema = ?';
bindings.push(this.schema);
} else {
sql += ' and table_schema = database()';
}
this.pushQuery({
sql,
bindings,
output: function output(resp) {
return resp.length > 0;
},
});
}
// Check whether a column exists on the schema.
hasColumn(tableName, column) {
this.pushQuery({
sql: `show columns from ${this.formatter.wrap(tableName)}`,
output(resp) {
return resp.some((row) => {
return (
this.client.wrapIdentifier(row.Field.toLowerCase()) ===
this.client.wrapIdentifier(column.toLowerCase())
);
});
},
});
}
}
module.exports = SchemaCompiler_MySQL;

View File

@ -0,0 +1,405 @@
/* eslint max-len:0*/
// MySQL Table Builder & Compiler
// -------
const TableCompiler = require('../../../schema/tablecompiler');
const { isObject, isString } = require('../../../util/is');
// Table Compiler
// ------
class TableCompiler_MySQL extends TableCompiler {
constructor(client, tableBuilder) {
super(client, tableBuilder);
}
createQuery(columns, ifNot, like) {
const createStatement = ifNot
? 'create table if not exists '
: 'create table ';
const { client } = this;
let conn = {};
let columnsSql = ' (' + columns.sql.join(', ');
columnsSql += this.primaryKeys() || '';
columnsSql += this._addChecks();
columnsSql += ')';
let sql =
createStatement +
this.tableName() +
(like && this.tableNameLike()
? ' like ' + this.tableNameLike()
: columnsSql);
// Check if the connection settings are set.
if (client.connectionSettings) {
conn = client.connectionSettings;
}
const charset = this.single.charset || conn.charset || '';
const collation = this.single.collate || conn.collate || '';
const engine = this.single.engine || '';
if (charset && !like) sql += ` default character set ${charset}`;
if (collation) sql += ` collate ${collation}`;
if (engine) sql += ` engine = ${engine}`;
if (this.single.comment) {
const comment = this.single.comment || '';
const MAX_COMMENT_LENGTH = 1024;
if (comment.length > MAX_COMMENT_LENGTH)
this.client.logger.warn(
`The max length for a table comment is ${MAX_COMMENT_LENGTH} characters`
);
sql += ` comment = '${comment}'`;
}
this.pushQuery(sql);
if (like) {
this.addColumns(columns, this.addColumnsPrefix);
}
}
// Compiles the comment on the table.
comment(comment) {
this.pushQuery(`alter table ${this.tableName()} comment = '${comment}'`);
}
changeType() {
// alter table + table + ' modify ' + wrapped + '// type';
}
// Renames a column on the table.
renameColumn(from, to) {
const compiler = this;
const table = this.tableName();
const wrapped = this.formatter.wrap(from) + ' ' + this.formatter.wrap(to);
this.pushQuery({
sql:
`show full fields from ${table} where field = ` +
this.client.parameter(from, this.tableBuilder, this.bindingsHolder),
output(resp) {
const column = resp[0];
const runner = this;
return compiler.getFKRefs(runner).then(([refs]) =>
new Promise((resolve, reject) => {
try {
if (!refs.length) {
resolve();
}
resolve(compiler.dropFKRefs(runner, refs));
} catch (e) {
reject(e);
}
})
.then(function () {
let sql = `alter table ${table} change ${wrapped} ${column.Type}`;
if (String(column.Null).toUpperCase() !== 'YES') {
sql += ` NOT NULL`;
} else {
// This doesn't matter for most cases except Timestamp, where this is important
sql += ` NULL`;
}
if (column.Default !== void 0 && column.Default !== null) {
sql += ` DEFAULT '${column.Default}'`;
}
if (column.Collation !== void 0 && column.Collation !== null) {
sql += ` COLLATE '${column.Collation}'`;
}
// Add back the auto increment if the column it, fix issue #2767
if (column.Extra == 'auto_increment') {
sql += ` AUTO_INCREMENT`;
}
return runner.query({
sql,
});
})
.then(function () {
if (!refs.length) {
return;
}
return compiler.createFKRefs(
runner,
refs.map(function (ref) {
if (ref.REFERENCED_COLUMN_NAME === from) {
ref.REFERENCED_COLUMN_NAME = to;
}
if (ref.COLUMN_NAME === from) {
ref.COLUMN_NAME = to;
}
return ref;
})
);
})
);
},
});
}
primaryKeys() {
const pks = (this.grouped.alterTable || []).filter(
(k) => k.method === 'primary'
);
if (pks.length > 0 && pks[0].args.length > 0) {
const columns = pks[0].args[0];
let constraintName = pks[0].args[1] || '';
if (constraintName) {
constraintName = ' constraint ' + this.formatter.wrap(constraintName);
}
if (this.grouped.columns) {
const incrementsCols = this._getIncrementsColumnNames();
if (incrementsCols.length) {
incrementsCols.forEach((c) => {
if (!columns.includes(c)) {
columns.unshift(c);
}
});
}
const bigIncrementsCols = this._getBigIncrementsColumnNames();
if (bigIncrementsCols.length) {
bigIncrementsCols.forEach((c) => {
if (!columns.includes(c)) {
columns.unshift(c);
}
});
}
}
return `,${constraintName} primary key (${this.formatter.columnize(
columns
)})`;
}
}
getFKRefs(runner) {
const bindingsHolder = {
bindings: [],
};
const sql =
'SELECT KCU.CONSTRAINT_NAME, KCU.TABLE_NAME, KCU.COLUMN_NAME, ' +
' KCU.REFERENCED_TABLE_NAME, KCU.REFERENCED_COLUMN_NAME, ' +
' RC.UPDATE_RULE, RC.DELETE_RULE ' +
'FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU ' +
'JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC ' +
' USING(CONSTRAINT_NAME)' +
'WHERE KCU.REFERENCED_TABLE_NAME = ' +
this.client.parameter(
this.tableNameRaw,
this.tableBuilder,
bindingsHolder
) +
' ' +
' AND KCU.CONSTRAINT_SCHEMA = ' +
this.client.parameter(
this.client.database(),
this.tableBuilder,
bindingsHolder
) +
' ' +
' AND RC.CONSTRAINT_SCHEMA = ' +
this.client.parameter(
this.client.database(),
this.tableBuilder,
bindingsHolder
);
return runner.query({
sql,
bindings: bindingsHolder.bindings,
});
}
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 foreign key ${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, options) {
let storageEngineIndexType;
let indexType;
if (isString(options)) {
indexType = options;
} else if (isObject(options)) {
({ indexType, storageEngineIndexType } = options);
}
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('index', this.tableNameRaw, columns);
storageEngineIndexType = storageEngineIndexType
? ` using ${storageEngineIndexType}`
: '';
this.pushQuery(
`alter table ${this.tableName()} add${
indexType ? ` ${indexType}` : ''
} index ${indexName}(${this.formatter.columnize(
columns
)})${storageEngineIndexType}`
);
}
primary(columns, constraintName) {
let deferrable;
if (isObject(constraintName)) {
({ constraintName, deferrable } = constraintName);
}
if (deferrable && deferrable !== 'not deferrable') {
this.client.logger.warn(
`mysql: primary key constraint \`${constraintName}\` will not be deferrable ${deferrable} because mysql does not support deferred constraints.`
);
}
constraintName = constraintName
? this.formatter.wrap(constraintName)
: this.formatter.wrap(`${this.tableNameRaw}_pkey`);
const primaryCols = columns;
let incrementsCols = [];
let bigIncrementsCols = [];
if (this.grouped.columns) {
incrementsCols = this._getIncrementsColumnNames();
if (incrementsCols) {
incrementsCols.forEach((c) => {
if (!primaryCols.includes(c)) {
primaryCols.unshift(c);
}
});
}
bigIncrementsCols = this._getBigIncrementsColumnNames();
if (bigIncrementsCols) {
bigIncrementsCols.forEach((c) => {
if (!primaryCols.includes(c)) {
primaryCols.unshift(c);
}
});
}
}
if (this.method !== 'create' && this.method !== 'createIfNot') {
this.pushQuery(
`alter table ${this.tableName()} add primary key ${constraintName}(${this.formatter.columnize(
primaryCols
)})`
);
}
if (incrementsCols.length) {
this.pushQuery(
`alter table ${this.tableName()} modify column ${this.formatter.columnize(
incrementsCols
)} int unsigned not null auto_increment`
);
}
if (bigIncrementsCols.length) {
this.pushQuery(
`alter table ${this.tableName()} modify column ${this.formatter.columnize(
bigIncrementsCols
)} bigint unsigned not null auto_increment`
);
}
}
unique(columns, indexName) {
let storageEngineIndexType;
let deferrable;
if (isObject(indexName)) {
({ indexName, deferrable, storageEngineIndexType } = indexName);
}
if (deferrable && deferrable !== 'not deferrable') {
this.client.logger.warn(
`mysql: unique index \`${indexName}\` will not be deferrable ${deferrable} because mysql does not support deferred constraints.`
);
}
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('unique', this.tableNameRaw, columns);
storageEngineIndexType = storageEngineIndexType
? ` using ${storageEngineIndexType}`
: '';
this.pushQuery(
`alter table ${this.tableName()} add unique ${indexName}(${this.formatter.columnize(
columns
)})${storageEngineIndexType}`
);
}
// Compile a drop index command.
dropIndex(columns, indexName) {
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('index', this.tableNameRaw, columns);
this.pushQuery(`alter table ${this.tableName()} drop index ${indexName}`);
}
// 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 foreign key ${indexName}`
);
}
// Compile a drop primary key command.
dropPrimary() {
this.pushQuery(`alter table ${this.tableName()} drop primary key`);
}
// Compile a drop unique key command.
dropUnique(column, indexName) {
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('unique', this.tableNameRaw, column);
this.pushQuery(`alter table ${this.tableName()} drop index ${indexName}`);
}
}
TableCompiler_MySQL.prototype.addColumnsPrefix = 'add ';
TableCompiler_MySQL.prototype.alterColumnsPrefix = 'modify ';
TableCompiler_MySQL.prototype.dropColumnPrefix = 'drop ';
module.exports = TableCompiler_MySQL;

View File

@ -0,0 +1,21 @@
const ViewBuilder = require('../../../schema/viewbuilder.js');
class ViewBuilder_MySQL extends ViewBuilder {
constructor() {
super(...arguments);
}
checkOption() {
this._single.checkOption = 'default_option';
}
localCheckOption() {
this._single.checkOption = 'local';
}
cascadedCheckOption() {
this._single.checkOption = 'cascaded';
}
}
module.exports = ViewBuilder_MySQL;

View File

@ -0,0 +1,15 @@
/* eslint max-len: 0 */
const ViewCompiler = require('../../../schema/viewcompiler.js');
class ViewCompiler_MySQL extends ViewCompiler {
constructor(client, viewCompiler) {
super(client, viewCompiler);
}
createOrReplace() {
this.createQuery(this.columns, this.selectQuery, false, true);
}
}
module.exports = ViewCompiler_MySQL;

View File

@ -0,0 +1,46 @@
const Transaction = require('../../execution/transaction');
const Debug = require('debug');
const debug = Debug('knex:tx');
class Transaction_MySQL extends Transaction {
query(conn, sql, status, value) {
const t = this;
const q = this.trxClient
.query(conn, sql)
.catch((err) => {
if (err.errno === 1305) {
this.trxClient.logger.warn(
'Transaction was implicitly committed, do not mix transactions and ' +
'DDL with MySQL (#805)'
);
return;
}
status = 2;
value = err;
t._completed = true;
debug('%s error running transaction query', t.txid);
})
.then(function (res) {
if (status === 1) t._resolver(value);
if (status === 2) {
if (value === undefined) {
if (t.doNotRejectOnRollback && /^ROLLBACK\b/i.test(sql)) {
t._resolver();
return;
}
value = new Error(`Transaction rejected with non-error: ${value}`);
}
t._rejecter(value);
}
return res;
});
if (status === 1 || status === 2) {
t._completed = true;
}
return q;
}
}
module.exports = Transaction_MySQL;