primer cambio

This commit is contained in:
beseira13
2026-01-19 12:12:38 -03:00
parent 5f59dba52d
commit 44990f015a
4759 changed files with 588702 additions and 0 deletions

View File

@@ -0,0 +1,120 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
const AbstractConnectionManager = require("../abstract/connection-manager");
const SequelizeErrors = require("../../errors");
const { logger } = require("../../utils/logger");
const DataTypes = require("../../data-types").mysql;
const momentTz = require("moment-timezone");
const debug = logger.debugContext("connection:mysql");
const parserStore = require("../parserStore")("mysql");
const { promisify } = require("util");
class ConnectionManager extends AbstractConnectionManager {
constructor(dialect, sequelize) {
sequelize.config.port = sequelize.config.port || 3306;
super(dialect, sequelize);
this.lib = this._loadDialectModule("mysql2");
this.refreshTypeParser(DataTypes);
}
_refreshTypeParser(dataType) {
parserStore.refresh(dataType);
}
_clearTypeParser() {
parserStore.clear();
}
static _typecast(field, next) {
if (parserStore.get(field.type)) {
return parserStore.get(field.type)(field, this.sequelize.options, next);
}
return next();
}
async connect(config) {
const connectionConfig = __spreadValues({
host: config.host,
port: config.port,
user: config.username,
flags: "-FOUND_ROWS",
password: config.password,
database: config.database,
timezone: this.sequelize.options.timezone,
typeCast: ConnectionManager._typecast.bind(this),
bigNumberStrings: false,
supportBigNumbers: true
}, config.dialectOptions);
try {
const connection = await new Promise((resolve, reject) => {
const connection2 = this.lib.createConnection(connectionConfig);
const errorHandler = (e) => {
connection2.removeListener("connect", connectHandler);
connection2.removeListener("error", connectHandler);
reject(e);
};
const connectHandler = () => {
connection2.removeListener("error", errorHandler);
resolve(connection2);
};
connection2.on("error", errorHandler);
connection2.once("connect", connectHandler);
});
debug("connection acquired");
connection.on("error", (error) => {
switch (error.code) {
case "ESOCKET":
case "ECONNRESET":
case "EPIPE":
case "PROTOCOL_CONNECTION_LOST":
this.pool.destroy(connection);
}
});
if (!this.sequelize.config.keepDefaultTimezone) {
let tzOffset = this.sequelize.options.timezone;
tzOffset = /\//.test(tzOffset) ? momentTz.tz(tzOffset).format("Z") : tzOffset;
await promisify((cb) => connection.query(`SET time_zone = '${tzOffset}'`, cb))();
}
return connection;
} catch (err) {
switch (err.code) {
case "ECONNREFUSED":
throw new SequelizeErrors.ConnectionRefusedError(err);
case "ER_ACCESS_DENIED_ERROR":
throw new SequelizeErrors.AccessDeniedError(err);
case "ENOTFOUND":
throw new SequelizeErrors.HostNotFoundError(err);
case "EHOSTUNREACH":
throw new SequelizeErrors.HostNotReachableError(err);
case "EINVAL":
throw new SequelizeErrors.InvalidConnectionError(err);
default:
throw new SequelizeErrors.ConnectionError(err);
}
}
}
async disconnect(connection) {
if (connection._closing) {
debug("connection tried to disconnect but was already at CLOSED state");
return;
}
return await promisify((callback) => connection.end(callback))();
}
validate(connection) {
return connection && !connection._fatalError && !connection._protocolError && !connection._closing && !connection.stream.destroyed;
}
}
module.exports = ConnectionManager;
module.exports.ConnectionManager = ConnectionManager;
module.exports.default = ConnectionManager;
//# sourceMappingURL=connection-manager.js.map

File diff suppressed because one or more lines are too long

123
node_modules/sequelize/lib/dialects/mysql/data-types.js generated vendored Normal file
View File

@@ -0,0 +1,123 @@
"use strict";
const wkx = require("wkx");
const _ = require("lodash");
const momentTz = require("moment-timezone");
const moment = require("moment");
module.exports = (BaseTypes) => {
BaseTypes.ABSTRACT.prototype.dialectTypes = "https://dev.mysql.com/doc/refman/5.7/en/data-types.html";
BaseTypes.DATE.types.mysql = ["DATETIME"];
BaseTypes.STRING.types.mysql = ["VAR_STRING"];
BaseTypes.CHAR.types.mysql = ["STRING"];
BaseTypes.TEXT.types.mysql = ["BLOB"];
BaseTypes.TINYINT.types.mysql = ["TINY"];
BaseTypes.SMALLINT.types.mysql = ["SHORT"];
BaseTypes.MEDIUMINT.types.mysql = ["INT24"];
BaseTypes.INTEGER.types.mysql = ["LONG"];
BaseTypes.BIGINT.types.mysql = ["LONGLONG"];
BaseTypes.FLOAT.types.mysql = ["FLOAT"];
BaseTypes.TIME.types.mysql = ["TIME"];
BaseTypes.DATEONLY.types.mysql = ["DATE"];
BaseTypes.BOOLEAN.types.mysql = ["TINY"];
BaseTypes.BLOB.types.mysql = ["TINYBLOB", "BLOB", "LONGBLOB"];
BaseTypes.DECIMAL.types.mysql = ["NEWDECIMAL"];
BaseTypes.UUID.types.mysql = false;
BaseTypes.ENUM.types.mysql = false;
BaseTypes.REAL.types.mysql = ["DOUBLE"];
BaseTypes.DOUBLE.types.mysql = ["DOUBLE"];
BaseTypes.GEOMETRY.types.mysql = ["GEOMETRY"];
BaseTypes.JSON.types.mysql = ["JSON"];
class DECIMAL extends BaseTypes.DECIMAL {
toSql() {
let definition = super.toSql();
if (this._unsigned) {
definition += " UNSIGNED";
}
if (this._zerofill) {
definition += " ZEROFILL";
}
return definition;
}
}
class DATE extends BaseTypes.DATE {
toSql() {
return this._length ? `DATETIME(${this._length})` : "DATETIME";
}
_stringify(date, options) {
if (!moment.isMoment(date)) {
date = this._applyTimezone(date, options);
}
if (this._length) {
return date.format("YYYY-MM-DD HH:mm:ss.SSS");
}
return date.format("YYYY-MM-DD HH:mm:ss");
}
static parse(value, options) {
value = value.string();
if (value === null) {
return value;
}
if (momentTz.tz.zone(options.timezone)) {
value = momentTz.tz(value, options.timezone).toDate();
} else {
value = new Date(`${value} ${options.timezone}`);
}
return value;
}
}
class DATEONLY extends BaseTypes.DATEONLY {
static parse(value) {
return value.string();
}
}
class UUID extends BaseTypes.UUID {
toSql() {
return "CHAR(36) BINARY";
}
}
const SUPPORTED_GEOMETRY_TYPES = ["POINT", "LINESTRING", "POLYGON"];
class GEOMETRY extends BaseTypes.GEOMETRY {
constructor(type, srid) {
super(type, srid);
if (_.isEmpty(this.type)) {
this.sqlType = this.key;
return;
}
if (SUPPORTED_GEOMETRY_TYPES.includes(this.type)) {
this.sqlType = this.type;
return;
}
throw new Error(`Supported geometry types are: ${SUPPORTED_GEOMETRY_TYPES.join(", ")}`);
}
static parse(value) {
value = value.buffer();
if (!value || value.length === 0) {
return null;
}
value = value.slice(4);
return wkx.Geometry.parse(value).toGeoJSON({ shortCrs: true });
}
toSql() {
return this.sqlType;
}
}
class ENUM extends BaseTypes.ENUM {
toSql(options) {
return `ENUM(${this.values.map((value) => options.escape(value)).join(", ")})`;
}
}
class JSONTYPE extends BaseTypes.JSON {
_stringify(value, options) {
return options.operation === "where" && typeof value === "string" ? value : JSON.stringify(value);
}
}
return {
ENUM,
DATE,
DATEONLY,
UUID,
GEOMETRY,
DECIMAL,
JSON: JSONTYPE
};
};
//# sourceMappingURL=data-types.js.map

View File

@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/mysql/data-types.js"],
"sourcesContent": ["'use strict';\n\nconst wkx = require('wkx');\nconst _ = require('lodash');\nconst momentTz = require('moment-timezone');\nconst moment = require('moment');\n\nmodule.exports = BaseTypes => {\n BaseTypes.ABSTRACT.prototype.dialectTypes = 'https://dev.mysql.com/doc/refman/5.7/en/data-types.html';\n\n /**\n * types: [buffer_type, ...]\n *\n * @see buffer_type here https://dev.mysql.com/doc/refman/5.7/en/c-api-prepared-statement-type-codes.html\n * @see hex here https://github.com/sidorares/node-mysql2/blob/master/lib/constants/types.js\n */\n\n BaseTypes.DATE.types.mysql = ['DATETIME'];\n BaseTypes.STRING.types.mysql = ['VAR_STRING'];\n BaseTypes.CHAR.types.mysql = ['STRING'];\n BaseTypes.TEXT.types.mysql = ['BLOB'];\n BaseTypes.TINYINT.types.mysql = ['TINY'];\n BaseTypes.SMALLINT.types.mysql = ['SHORT'];\n BaseTypes.MEDIUMINT.types.mysql = ['INT24'];\n BaseTypes.INTEGER.types.mysql = ['LONG'];\n BaseTypes.BIGINT.types.mysql = ['LONGLONG'];\n BaseTypes.FLOAT.types.mysql = ['FLOAT'];\n BaseTypes.TIME.types.mysql = ['TIME'];\n BaseTypes.DATEONLY.types.mysql = ['DATE'];\n BaseTypes.BOOLEAN.types.mysql = ['TINY'];\n BaseTypes.BLOB.types.mysql = ['TINYBLOB', 'BLOB', 'LONGBLOB'];\n BaseTypes.DECIMAL.types.mysql = ['NEWDECIMAL'];\n BaseTypes.UUID.types.mysql = false;\n BaseTypes.ENUM.types.mysql = false;\n BaseTypes.REAL.types.mysql = ['DOUBLE'];\n BaseTypes.DOUBLE.types.mysql = ['DOUBLE'];\n BaseTypes.GEOMETRY.types.mysql = ['GEOMETRY'];\n BaseTypes.JSON.types.mysql = ['JSON'];\n\n class DECIMAL extends BaseTypes.DECIMAL {\n toSql() {\n let definition = super.toSql();\n if (this._unsigned) {\n definition += ' UNSIGNED';\n }\n if (this._zerofill) {\n definition += ' ZEROFILL';\n }\n return definition;\n }\n }\n\n class DATE extends BaseTypes.DATE {\n toSql() {\n return this._length ? `DATETIME(${this._length})` : 'DATETIME';\n }\n _stringify(date, options) {\n if (!moment.isMoment(date)) {\n date = this._applyTimezone(date, options);\n }\n // Fractional DATETIMEs only supported on MySQL 5.6.4+\n if (this._length) {\n return date.format('YYYY-MM-DD HH:mm:ss.SSS');\n }\n return date.format('YYYY-MM-DD HH:mm:ss');\n }\n static parse(value, options) {\n value = value.string();\n if (value === null) {\n return value;\n }\n if (momentTz.tz.zone(options.timezone)) {\n value = momentTz.tz(value, options.timezone).toDate();\n }\n else {\n value = new Date(`${value} ${options.timezone}`);\n }\n return value;\n }\n }\n\n class DATEONLY extends BaseTypes.DATEONLY {\n static parse(value) {\n return value.string();\n }\n }\n class UUID extends BaseTypes.UUID {\n toSql() {\n return 'CHAR(36) BINARY';\n }\n }\n\n const SUPPORTED_GEOMETRY_TYPES = ['POINT', 'LINESTRING', 'POLYGON'];\n\n class GEOMETRY extends BaseTypes.GEOMETRY {\n constructor(type, srid) {\n super(type, srid);\n if (_.isEmpty(this.type)) {\n this.sqlType = this.key;\n return;\n }\n if (SUPPORTED_GEOMETRY_TYPES.includes(this.type)) {\n this.sqlType = this.type;\n return;\n }\n throw new Error(`Supported geometry types are: ${SUPPORTED_GEOMETRY_TYPES.join(', ')}`);\n }\n static parse(value) {\n value = value.buffer();\n // Empty buffer, MySQL doesn't support POINT EMPTY\n // check, https://dev.mysql.com/worklog/task/?id=2381\n if (!value || value.length === 0) {\n return null;\n }\n // For some reason, discard the first 4 bytes\n value = value.slice(4);\n return wkx.Geometry.parse(value).toGeoJSON({ shortCrs: true });\n }\n toSql() {\n return this.sqlType;\n }\n }\n\n class ENUM extends BaseTypes.ENUM {\n toSql(options) {\n return `ENUM(${this.values.map(value => options.escape(value)).join(', ')})`;\n }\n }\n\n class JSONTYPE extends BaseTypes.JSON {\n _stringify(value, options) {\n return options.operation === 'where' && typeof value === 'string' ? value : JSON.stringify(value);\n }\n }\n\n return {\n ENUM,\n DATE,\n DATEONLY,\n UUID,\n GEOMETRY,\n DECIMAL,\n JSON: JSONTYPE\n };\n};\n"],
"mappings": "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",
"names": []
}

61
node_modules/sequelize/lib/dialects/mysql/index.js generated vendored Normal file
View File

@@ -0,0 +1,61 @@
"use strict";
const _ = require("lodash");
const AbstractDialect = require("../abstract");
const ConnectionManager = require("./connection-manager");
const Query = require("./query");
const QueryGenerator = require("./query-generator");
const DataTypes = require("../../data-types").mysql;
const { MySQLQueryInterface } = require("./query-interface");
class MysqlDialect extends AbstractDialect {
constructor(sequelize) {
super();
this.sequelize = sequelize;
this.connectionManager = new ConnectionManager(this, sequelize);
this.queryGenerator = new QueryGenerator({
_dialect: this,
sequelize
});
this.queryInterface = new MySQLQueryInterface(sequelize, this.queryGenerator);
}
canBackslashEscape() {
return true;
}
}
MysqlDialect.prototype.supports = _.merge(_.cloneDeep(AbstractDialect.prototype.supports), {
"VALUES ()": true,
"LIMIT ON UPDATE": true,
lock: true,
forShare: "LOCK IN SHARE MODE",
settingIsolationLevelDuringTransaction: false,
inserts: {
ignoreDuplicates: " IGNORE",
updateOnDuplicate: " ON DUPLICATE KEY UPDATE"
},
index: {
collate: false,
length: true,
parser: true,
type: true,
using: 1
},
constraints: {
dropConstraint: false,
check: false
},
indexViaAlter: true,
indexHints: true,
NUMERIC: true,
GEOMETRY: true,
JSON: true,
REGEXP: true
});
MysqlDialect.prototype.defaultVersion = "5.7.0";
MysqlDialect.prototype.Query = Query;
MysqlDialect.prototype.QueryGenerator = QueryGenerator;
MysqlDialect.prototype.DataTypes = DataTypes;
MysqlDialect.prototype.name = "mysql";
MysqlDialect.prototype.TICK_CHAR = "`";
MysqlDialect.prototype.TICK_CHAR_LEFT = MysqlDialect.prototype.TICK_CHAR;
MysqlDialect.prototype.TICK_CHAR_RIGHT = MysqlDialect.prototype.TICK_CHAR;
module.exports = MysqlDialect;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/mysql/index.js"],
"sourcesContent": ["'use strict';\n\nconst _ = require('lodash');\nconst AbstractDialect = require('../abstract');\nconst ConnectionManager = require('./connection-manager');\nconst Query = require('./query');\nconst QueryGenerator = require('./query-generator');\nconst DataTypes = require('../../data-types').mysql;\nconst { MySQLQueryInterface } = require('./query-interface');\n\nclass MysqlDialect extends AbstractDialect {\n constructor(sequelize) {\n super();\n this.sequelize = sequelize;\n this.connectionManager = new ConnectionManager(this, sequelize);\n this.queryGenerator = new QueryGenerator({\n _dialect: this,\n sequelize\n });\n this.queryInterface = new MySQLQueryInterface(\n sequelize,\n this.queryGenerator\n );\n }\n\n canBackslashEscape() {\n return true;\n }\n}\n\nMysqlDialect.prototype.supports = _.merge(\n _.cloneDeep(AbstractDialect.prototype.supports),\n {\n 'VALUES ()': true,\n 'LIMIT ON UPDATE': true,\n lock: true,\n forShare: 'LOCK IN SHARE MODE',\n settingIsolationLevelDuringTransaction: false,\n inserts: {\n ignoreDuplicates: ' IGNORE',\n updateOnDuplicate: ' ON DUPLICATE KEY UPDATE'\n },\n index: {\n collate: false,\n length: true,\n parser: true,\n type: true,\n using: 1\n },\n constraints: {\n dropConstraint: false,\n check: false\n },\n indexViaAlter: true,\n indexHints: true,\n NUMERIC: true,\n GEOMETRY: true,\n JSON: true,\n REGEXP: true\n }\n);\n\nMysqlDialect.prototype.defaultVersion = '5.7.0'; // minimum supported version\nMysqlDialect.prototype.Query = Query;\nMysqlDialect.prototype.QueryGenerator = QueryGenerator;\nMysqlDialect.prototype.DataTypes = DataTypes;\nMysqlDialect.prototype.name = 'mysql';\nMysqlDialect.prototype.TICK_CHAR = '`';\nMysqlDialect.prototype.TICK_CHAR_LEFT = MysqlDialect.prototype.TICK_CHAR;\nMysqlDialect.prototype.TICK_CHAR_RIGHT = MysqlDialect.prototype.TICK_CHAR;\n\nmodule.exports = MysqlDialect;\n"],
"mappings": ";AAEA,MAAM,IAAI,QAAQ;AAClB,MAAM,kBAAkB,QAAQ;AAChC,MAAM,oBAAoB,QAAQ;AAClC,MAAM,QAAQ,QAAQ;AACtB,MAAM,iBAAiB,QAAQ;AAC/B,MAAM,YAAY,QAAQ,oBAAoB;AAC9C,MAAM,EAAE,wBAAwB,QAAQ;AAExC,2BAA2B,gBAAgB;AAAA,EACzC,YAAY,WAAW;AACrB;AACA,SAAK,YAAY;AACjB,SAAK,oBAAoB,IAAI,kBAAkB,MAAM;AACrD,SAAK,iBAAiB,IAAI,eAAe;AAAA,MACvC,UAAU;AAAA,MACV;AAAA;AAEF,SAAK,iBAAiB,IAAI,oBACxB,WACA,KAAK;AAAA;AAAA,EAIT,qBAAqB;AACnB,WAAO;AAAA;AAAA;AAIX,aAAa,UAAU,WAAW,EAAE,MAClC,EAAE,UAAU,gBAAgB,UAAU,WACtC;AAAA,EACE,aAAa;AAAA,EACb,mBAAmB;AAAA,EACnB,MAAM;AAAA,EACN,UAAU;AAAA,EACV,wCAAwC;AAAA,EACxC,SAAS;AAAA,IACP,kBAAkB;AAAA,IAClB,mBAAmB;AAAA;AAAA,EAErB,OAAO;AAAA,IACL,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,OAAO;AAAA;AAAA,EAET,aAAa;AAAA,IACX,gBAAgB;AAAA,IAChB,OAAO;AAAA;AAAA,EAET,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,SAAS;AAAA,EACT,UAAU;AAAA,EACV,MAAM;AAAA,EACN,QAAQ;AAAA;AAIZ,aAAa,UAAU,iBAAiB;AACxC,aAAa,UAAU,QAAQ;AAC/B,aAAa,UAAU,iBAAiB;AACxC,aAAa,UAAU,YAAY;AACnC,aAAa,UAAU,OAAO;AAC9B,aAAa,UAAU,YAAY;AACnC,aAAa,UAAU,iBAAiB,aAAa,UAAU;AAC/D,aAAa,UAAU,kBAAkB,aAAa,UAAU;AAEhE,OAAO,UAAU;",
"names": []
}

View File

@@ -0,0 +1,470 @@
"use strict";
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
const _ = require("lodash");
const Utils = require("../../utils");
const AbstractQueryGenerator = require("../abstract/query-generator");
const util = require("util");
const Op = require("../../operators");
const JSON_FUNCTION_REGEX = /^\s*((?:[a-z]+_){0,2}jsonb?(?:_[a-z]+){0,2})\([^)]*\)/i;
const JSON_OPERATOR_REGEX = /^\s*(->>?|@>|<@|\?[|&]?|\|{2}|#-)/i;
const TOKEN_CAPTURE_REGEX = /^\s*((?:([`"'])(?:(?!\2).|\2{2})*\2)|[\w\d\s]+|[().,;+-])/i;
const FOREIGN_KEY_FIELDS = [
"CONSTRAINT_NAME as constraint_name",
"CONSTRAINT_NAME as constraintName",
"CONSTRAINT_SCHEMA as constraintSchema",
"CONSTRAINT_SCHEMA as constraintCatalog",
"TABLE_NAME as tableName",
"TABLE_SCHEMA as tableSchema",
"TABLE_SCHEMA as tableCatalog",
"COLUMN_NAME as columnName",
"REFERENCED_TABLE_SCHEMA as referencedTableSchema",
"REFERENCED_TABLE_SCHEMA as referencedTableCatalog",
"REFERENCED_TABLE_NAME as referencedTableName",
"REFERENCED_COLUMN_NAME as referencedColumnName"
].join(",");
const typeWithoutDefault = /* @__PURE__ */ new Set(["BLOB", "TEXT", "GEOMETRY", "JSON"]);
class MySQLQueryGenerator extends AbstractQueryGenerator {
constructor(options) {
super(options);
this.OperatorMap = __spreadProps(__spreadValues({}, this.OperatorMap), {
[Op.regexp]: "REGEXP",
[Op.notRegexp]: "NOT REGEXP"
});
}
createDatabaseQuery(databaseName, options) {
options = __spreadValues({
charset: null,
collate: null
}, options);
return Utils.joinSQLFragments([
"CREATE DATABASE IF NOT EXISTS",
this.quoteIdentifier(databaseName),
options.charset && `DEFAULT CHARACTER SET ${this.escape(options.charset)}`,
options.collate && `DEFAULT COLLATE ${this.escape(options.collate)}`,
";"
]);
}
dropDatabaseQuery(databaseName) {
return `DROP DATABASE IF EXISTS ${this.quoteIdentifier(databaseName)};`;
}
createSchema() {
return "SHOW TABLES";
}
showSchemasQuery() {
return "SHOW TABLES";
}
versionQuery() {
return "SELECT VERSION() as `version`";
}
createTableQuery(tableName, attributes, options) {
options = __spreadValues({
engine: "InnoDB",
charset: null,
rowFormat: null
}, options);
const primaryKeys = [];
const foreignKeys = {};
const attrStr = [];
for (const attr in attributes) {
if (!Object.prototype.hasOwnProperty.call(attributes, attr))
continue;
const dataType = attributes[attr];
let match;
if (dataType.includes("PRIMARY KEY")) {
primaryKeys.push(attr);
if (dataType.includes("REFERENCES")) {
match = dataType.match(/^(.+) (REFERENCES.*)$/);
attrStr.push(`${this.quoteIdentifier(attr)} ${match[1].replace("PRIMARY KEY", "")}`);
foreignKeys[attr] = match[2];
} else {
attrStr.push(`${this.quoteIdentifier(attr)} ${dataType.replace("PRIMARY KEY", "")}`);
}
} else if (dataType.includes("REFERENCES")) {
match = dataType.match(/^(.+) (REFERENCES.*)$/);
attrStr.push(`${this.quoteIdentifier(attr)} ${match[1]}`);
foreignKeys[attr] = match[2];
} else {
attrStr.push(`${this.quoteIdentifier(attr)} ${dataType}`);
}
}
const table = this.quoteTable(tableName);
let attributesClause = attrStr.join(", ");
const pkString = primaryKeys.map((pk) => this.quoteIdentifier(pk)).join(", ");
if (options.uniqueKeys) {
_.each(options.uniqueKeys, (columns, indexName) => {
if (columns.customIndex) {
if (typeof indexName !== "string") {
indexName = `uniq_${tableName}_${columns.fields.join("_")}`;
}
attributesClause += `, UNIQUE ${this.quoteIdentifier(indexName)} (${columns.fields.map((field) => this.quoteIdentifier(field)).join(", ")})`;
}
});
}
if (pkString.length > 0) {
attributesClause += `, PRIMARY KEY (${pkString})`;
}
for (const fkey in foreignKeys) {
if (Object.prototype.hasOwnProperty.call(foreignKeys, fkey)) {
attributesClause += `, FOREIGN KEY (${this.quoteIdentifier(fkey)}) ${foreignKeys[fkey]}`;
}
}
return Utils.joinSQLFragments([
"CREATE TABLE IF NOT EXISTS",
table,
`(${attributesClause})`,
`ENGINE=${options.engine}`,
options.comment && typeof options.comment === "string" && `COMMENT ${this.escape(options.comment)}`,
options.charset && `DEFAULT CHARSET=${options.charset}`,
options.collate && `COLLATE ${options.collate}`,
options.initialAutoIncrement && `AUTO_INCREMENT=${options.initialAutoIncrement}`,
options.rowFormat && `ROW_FORMAT=${options.rowFormat}`,
";"
]);
}
describeTableQuery(tableName, schema, schemaDelimiter) {
const table = this.quoteTable(this.addSchema({
tableName,
_schema: schema,
_schemaDelimiter: schemaDelimiter
}));
return `SHOW FULL COLUMNS FROM ${table};`;
}
showTablesQuery(database) {
let query = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'";
if (database) {
query += ` AND TABLE_SCHEMA = ${this.escape(database)}`;
} else {
query += " AND TABLE_SCHEMA NOT IN ('MYSQL', 'INFORMATION_SCHEMA', 'PERFORMANCE_SCHEMA', 'SYS', 'mysql', 'information_schema', 'performance_schema', 'sys')";
}
return `${query};`;
}
tableExistsQuery(table) {
const tableName = this.escape(this.quoteTable(table).slice(1, -1));
return `SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = ${tableName} AND TABLE_SCHEMA = ${this.escape(this.sequelize.config.database)}`;
}
addColumnQuery(table, key, dataType) {
return Utils.joinSQLFragments([
"ALTER TABLE",
this.quoteTable(table),
"ADD",
this.quoteIdentifier(key),
this.attributeToSQL(dataType, {
context: "addColumn",
tableName: table,
foreignKey: key
}),
";"
]);
}
removeColumnQuery(tableName, attributeName) {
return Utils.joinSQLFragments([
"ALTER TABLE",
this.quoteTable(tableName),
"DROP",
this.quoteIdentifier(attributeName),
";"
]);
}
changeColumnQuery(tableName, attributes) {
const attrString = [];
const constraintString = [];
for (const attributeName in attributes) {
let definition = attributes[attributeName];
if (definition.includes("REFERENCES")) {
const attrName = this.quoteIdentifier(attributeName);
definition = definition.replace(/.+?(?=REFERENCES)/, "");
constraintString.push(`FOREIGN KEY (${attrName}) ${definition}`);
} else {
attrString.push(`\`${attributeName}\` \`${attributeName}\` ${definition}`);
}
}
return Utils.joinSQLFragments([
"ALTER TABLE",
this.quoteTable(tableName),
attrString.length && `CHANGE ${attrString.join(", ")}`,
constraintString.length && `ADD ${constraintString.join(", ")}`,
";"
]);
}
renameColumnQuery(tableName, attrBefore, attributes) {
const attrString = [];
for (const attrName in attributes) {
const definition = attributes[attrName];
attrString.push(`\`${attrBefore}\` \`${attrName}\` ${definition}`);
}
return Utils.joinSQLFragments([
"ALTER TABLE",
this.quoteTable(tableName),
"CHANGE",
attrString.join(", "),
";"
]);
}
handleSequelizeMethod(smth, tableName, factory, options, prepend) {
if (smth instanceof Utils.Json) {
if (smth.conditions) {
const conditions = this.parseConditionObject(smth.conditions).map((condition) => `${this.jsonPathExtractionQuery(condition.path[0], _.tail(condition.path))} = '${condition.value}'`);
return conditions.join(" AND ");
}
if (smth.path) {
let str;
if (this._checkValidJsonStatement(smth.path)) {
str = smth.path;
} else {
const paths = _.toPath(smth.path);
const column = paths.shift();
str = this.jsonPathExtractionQuery(column, paths);
}
if (smth.value) {
str += util.format(" = %s", this.escape(smth.value));
}
return str;
}
} else if (smth instanceof Utils.Cast) {
if (/timestamp/i.test(smth.type)) {
smth.type = "datetime";
} else if (smth.json && /boolean/i.test(smth.type)) {
smth.type = "char";
} else if (/double precision/i.test(smth.type) || /boolean/i.test(smth.type) || /integer/i.test(smth.type)) {
smth.type = "decimal";
} else if (/text/i.test(smth.type)) {
smth.type = "char";
}
}
return super.handleSequelizeMethod(smth, tableName, factory, options, prepend);
}
_toJSONValue(value) {
if (typeof value === "boolean") {
return value.toString();
}
if (value === null) {
return "null";
}
return value;
}
truncateTableQuery(tableName) {
return `TRUNCATE ${this.quoteTable(tableName)}`;
}
deleteQuery(tableName, where, options = {}, model) {
let limit = "";
let query = `DELETE FROM ${this.quoteTable(tableName)}`;
if (options.limit) {
limit = ` LIMIT ${this.escape(options.limit)}`;
}
where = this.getWhereConditions(where, null, model, options);
if (where) {
query += ` WHERE ${where}`;
}
return query + limit;
}
showIndexesQuery(tableName, options) {
return Utils.joinSQLFragments([
`SHOW INDEX FROM ${this.quoteTable(tableName)}`,
options && options.database && `FROM \`${options.database}\``
]);
}
showConstraintsQuery(table, constraintName) {
const tableName = table.tableName || table;
const schemaName = table.schema;
return Utils.joinSQLFragments([
"SELECT CONSTRAINT_CATALOG AS constraintCatalog,",
"CONSTRAINT_NAME AS constraintName,",
"CONSTRAINT_SCHEMA AS constraintSchema,",
"CONSTRAINT_TYPE AS constraintType,",
"TABLE_NAME AS tableName,",
"TABLE_SCHEMA AS tableSchema",
"from INFORMATION_SCHEMA.TABLE_CONSTRAINTS",
`WHERE table_name='${tableName}'`,
constraintName && `AND constraint_name = '${constraintName}'`,
schemaName && `AND TABLE_SCHEMA = '${schemaName}'`,
";"
]);
}
removeIndexQuery(tableName, indexNameOrAttributes) {
let indexName = indexNameOrAttributes;
if (typeof indexName !== "string") {
indexName = Utils.underscore(`${tableName}_${indexNameOrAttributes.join("_")}`);
}
return Utils.joinSQLFragments([
"DROP INDEX",
this.quoteIdentifier(indexName),
"ON",
this.quoteTable(tableName)
]);
}
attributeToSQL(attribute, options) {
if (!_.isPlainObject(attribute)) {
attribute = {
type: attribute
};
}
const attributeString = attribute.type.toString({ escape: this.escape.bind(this) });
let template = attributeString;
if (attribute.allowNull === false) {
template += " NOT NULL";
}
if (attribute.autoIncrement) {
template += " auto_increment";
}
if (!typeWithoutDefault.has(attributeString) && attribute.type._binary !== true && Utils.defaultValueSchemable(attribute.defaultValue)) {
template += ` DEFAULT ${this.escape(attribute.defaultValue)}`;
}
if (attribute.unique === true) {
template += " UNIQUE";
}
if (attribute.primaryKey) {
template += " PRIMARY KEY";
}
if (attribute.comment) {
template += ` COMMENT ${this.escape(attribute.comment)}`;
}
if (attribute.first) {
template += " FIRST";
}
if (attribute.after) {
template += ` AFTER ${this.quoteIdentifier(attribute.after)}`;
}
if ((!options || !options.withoutForeignKeyConstraints) && attribute.references) {
if (options && options.context === "addColumn" && options.foreignKey) {
const attrName = this.quoteIdentifier(options.foreignKey);
const fkName = this.quoteIdentifier(`${options.tableName}_${attrName}_foreign_idx`);
template += `, ADD CONSTRAINT ${fkName} FOREIGN KEY (${attrName})`;
}
template += ` REFERENCES ${this.quoteTable(attribute.references.model)}`;
if (attribute.references.key) {
template += ` (${this.quoteIdentifier(attribute.references.key)})`;
} else {
template += ` (${this.quoteIdentifier("id")})`;
}
if (attribute.onDelete) {
template += ` ON DELETE ${attribute.onDelete.toUpperCase()}`;
}
if (attribute.onUpdate) {
template += ` ON UPDATE ${attribute.onUpdate.toUpperCase()}`;
}
}
return template;
}
attributesToSQL(attributes, options) {
const result = {};
for (const key in attributes) {
const attribute = attributes[key];
result[attribute.field || key] = this.attributeToSQL(attribute, options);
}
return result;
}
_checkValidJsonStatement(stmt) {
if (typeof stmt !== "string") {
return false;
}
let currentIndex = 0;
let openingBrackets = 0;
let closingBrackets = 0;
let hasJsonFunction = false;
let hasInvalidToken = false;
while (currentIndex < stmt.length) {
const string = stmt.substr(currentIndex);
const functionMatches = JSON_FUNCTION_REGEX.exec(string);
if (functionMatches) {
currentIndex += functionMatches[0].indexOf("(");
hasJsonFunction = true;
continue;
}
const operatorMatches = JSON_OPERATOR_REGEX.exec(string);
if (operatorMatches) {
currentIndex += operatorMatches[0].length;
hasJsonFunction = true;
continue;
}
const tokenMatches = TOKEN_CAPTURE_REGEX.exec(string);
if (tokenMatches) {
const capturedToken = tokenMatches[1];
if (capturedToken === "(") {
openingBrackets++;
} else if (capturedToken === ")") {
closingBrackets++;
} else if (capturedToken === ";") {
hasInvalidToken = true;
break;
}
currentIndex += tokenMatches[0].length;
continue;
}
break;
}
if (hasJsonFunction && (hasInvalidToken || openingBrackets !== closingBrackets)) {
throw new Error(`Invalid json statement: ${stmt}`);
}
return hasJsonFunction;
}
getForeignKeysQuery(table, schemaName) {
const tableName = table.tableName || table;
return Utils.joinSQLFragments([
"SELECT",
FOREIGN_KEY_FIELDS,
`FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = '${tableName}'`,
`AND CONSTRAINT_NAME!='PRIMARY' AND CONSTRAINT_SCHEMA='${schemaName}'`,
"AND REFERENCED_TABLE_NAME IS NOT NULL",
";"
]);
}
getForeignKeyQuery(table, columnName) {
const quotedSchemaName = table.schema ? wrapSingleQuote(table.schema) : "";
const quotedTableName = wrapSingleQuote(table.tableName || table);
const quotedColumnName = wrapSingleQuote(columnName);
return Utils.joinSQLFragments([
"SELECT",
FOREIGN_KEY_FIELDS,
"FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE",
"WHERE (",
[
`REFERENCED_TABLE_NAME = ${quotedTableName}`,
table.schema && `AND REFERENCED_TABLE_SCHEMA = ${quotedSchemaName}`,
`AND REFERENCED_COLUMN_NAME = ${quotedColumnName}`
],
") OR (",
[
`TABLE_NAME = ${quotedTableName}`,
table.schema && `AND TABLE_SCHEMA = ${quotedSchemaName}`,
`AND COLUMN_NAME = ${quotedColumnName}`,
"AND REFERENCED_TABLE_NAME IS NOT NULL"
],
")"
]);
}
dropForeignKeyQuery(tableName, foreignKey) {
return Utils.joinSQLFragments([
"ALTER TABLE",
this.quoteTable(tableName),
"DROP FOREIGN KEY",
this.quoteIdentifier(foreignKey),
";"
]);
}
quoteIdentifier(identifier, force) {
return Utils.addTicks(Utils.removeTicks(identifier, "`"), "`");
}
}
function wrapSingleQuote(identifier) {
return Utils.addTicks(identifier, "'");
}
module.exports = MySQLQueryGenerator;
//# sourceMappingURL=query-generator.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,71 @@
"use strict";
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
const sequelizeErrors = require("../../errors");
const { QueryInterface } = require("../abstract/query-interface");
const QueryTypes = require("../../query-types");
class MySQLQueryInterface extends QueryInterface {
async removeColumn(tableName, columnName, options) {
options = options || {};
const [results] = await this.sequelize.query(this.queryGenerator.getForeignKeyQuery(tableName.tableName ? tableName : {
tableName,
schema: this.sequelize.config.database
}, columnName), __spreadValues({ raw: true }, options));
if (results.length && results[0].constraint_name !== "PRIMARY") {
await Promise.all(results.map((constraint) => this.sequelize.query(this.queryGenerator.dropForeignKeyQuery(tableName, constraint.constraint_name), __spreadValues({ raw: true }, options))));
}
return await this.sequelize.query(this.queryGenerator.removeColumnQuery(tableName, columnName), __spreadValues({ raw: true }, options));
}
async upsert(tableName, insertValues, updateValues, where, options) {
options = __spreadValues({}, options);
options.type = QueryTypes.UPSERT;
options.updateOnDuplicate = Object.keys(updateValues);
options.upsertKeys = Object.values(options.model.primaryKeys).map((item) => item.field);
const model = options.model;
const sql = this.queryGenerator.insertQuery(tableName, insertValues, model.rawAttributes, options);
return await this.sequelize.query(sql, options);
}
async removeConstraint(tableName, constraintName, options) {
const sql = this.queryGenerator.showConstraintsQuery(tableName.tableName ? tableName : {
tableName,
schema: this.sequelize.config.database
}, constraintName);
const constraints = await this.sequelize.query(sql, __spreadProps(__spreadValues({}, options), {
type: this.sequelize.QueryTypes.SHOWCONSTRAINTS
}));
const constraint = constraints[0];
let query;
if (!constraint || !constraint.constraintType) {
throw new sequelizeErrors.UnknownConstraintError({
message: `Constraint ${constraintName} on table ${tableName} does not exist`,
constraint: constraintName,
table: tableName
});
}
if (constraint.constraintType === "FOREIGN KEY") {
query = this.queryGenerator.dropForeignKeyQuery(tableName, constraintName);
} else {
query = this.queryGenerator.removeIndexQuery(constraint.tableName, constraint.constraintName);
}
return await this.sequelize.query(query, options);
}
}
exports.MySQLQueryInterface = MySQLQueryInterface;
//# sourceMappingURL=query-interface.js.map

View File

@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/mysql/query-interface.js"],
"sourcesContent": ["'use strict';\n\nconst sequelizeErrors = require('../../errors');\nconst { QueryInterface } = require('../abstract/query-interface');\nconst QueryTypes = require('../../query-types');\n\n/**\n * The interface that Sequelize uses to talk with MySQL/MariaDB database\n */\nclass MySQLQueryInterface extends QueryInterface {\n /**\n * A wrapper that fixes MySQL's inability to cleanly remove columns from existing tables if they have a foreign key constraint.\n *\n * @override\n */\n async removeColumn(tableName, columnName, options) {\n options = options || {};\n\n const [results] = await this.sequelize.query(\n this.queryGenerator.getForeignKeyQuery(tableName.tableName ? tableName : {\n tableName,\n schema: this.sequelize.config.database\n }, columnName),\n { raw: true, ...options }\n );\n\n //Exclude primary key constraint\n if (results.length && results[0].constraint_name !== 'PRIMARY') {\n await Promise.all(results.map(constraint => this.sequelize.query(\n this.queryGenerator.dropForeignKeyQuery(tableName, constraint.constraint_name),\n { raw: true, ...options }\n )));\n }\n\n return await this.sequelize.query(\n this.queryGenerator.removeColumnQuery(tableName, columnName),\n { raw: true, ...options }\n );\n }\n\n /**\n * @override\n */\n async upsert(tableName, insertValues, updateValues, where, options) {\n options = { ...options };\n\n options.type = QueryTypes.UPSERT;\n options.updateOnDuplicate = Object.keys(updateValues);\n options.upsertKeys = Object.values(options.model.primaryKeys).map(item => item.field);\n\n const model = options.model;\n const sql = this.queryGenerator.insertQuery(tableName, insertValues, model.rawAttributes, options);\n return await this.sequelize.query(sql, options);\n }\n\n /**\n * @override\n */\n async removeConstraint(tableName, constraintName, options) {\n const sql = this.queryGenerator.showConstraintsQuery(\n tableName.tableName ? tableName : {\n tableName,\n schema: this.sequelize.config.database\n }, constraintName);\n\n const constraints = await this.sequelize.query(sql, { ...options,\n type: this.sequelize.QueryTypes.SHOWCONSTRAINTS });\n\n const constraint = constraints[0];\n let query;\n if (!constraint || !constraint.constraintType) {\n throw new sequelizeErrors.UnknownConstraintError(\n {\n message: `Constraint ${constraintName} on table ${tableName} does not exist`,\n constraint: constraintName,\n table: tableName\n });\n }\n\n if (constraint.constraintType === 'FOREIGN KEY') {\n query = this.queryGenerator.dropForeignKeyQuery(tableName, constraintName);\n } else {\n query = this.queryGenerator.removeIndexQuery(constraint.tableName, constraint.constraintName);\n }\n\n return await this.sequelize.query(query, options);\n }\n}\n\nexports.MySQLQueryInterface = MySQLQueryInterface;\n"],
"mappings": ";;;;;;;;;;;;;;;;;;;;AAEA,MAAM,kBAAkB,QAAQ;AAChC,MAAM,EAAE,mBAAmB,QAAQ;AACnC,MAAM,aAAa,QAAQ;AAK3B,kCAAkC,eAAe;AAAA,QAMzC,aAAa,WAAW,YAAY,SAAS;AACjD,cAAU,WAAW;AAErB,UAAM,CAAC,WAAW,MAAM,KAAK,UAAU,MACrC,KAAK,eAAe,mBAAmB,UAAU,YAAY,YAAY;AAAA,MACvE;AAAA,MACA,QAAQ,KAAK,UAAU,OAAO;AAAA,OAC7B,aACH,iBAAE,KAAK,QAAS;AAIlB,QAAI,QAAQ,UAAU,QAAQ,GAAG,oBAAoB,WAAW;AAC9D,YAAM,QAAQ,IAAI,QAAQ,IAAI,gBAAc,KAAK,UAAU,MACzD,KAAK,eAAe,oBAAoB,WAAW,WAAW,kBAC9D,iBAAE,KAAK,QAAS;AAAA;AAIpB,WAAO,MAAM,KAAK,UAAU,MAC1B,KAAK,eAAe,kBAAkB,WAAW,aACjD,iBAAE,KAAK,QAAS;AAAA;AAAA,QAOd,OAAO,WAAW,cAAc,cAAc,OAAO,SAAS;AAClE,cAAU,mBAAK;AAEf,YAAQ,OAAO,WAAW;AAC1B,YAAQ,oBAAoB,OAAO,KAAK;AACxC,YAAQ,aAAa,OAAO,OAAO,QAAQ,MAAM,aAAa,IAAI,UAAQ,KAAK;AAE/E,UAAM,QAAQ,QAAQ;AACtB,UAAM,MAAM,KAAK,eAAe,YAAY,WAAW,cAAc,MAAM,eAAe;AAC1F,WAAO,MAAM,KAAK,UAAU,MAAM,KAAK;AAAA;AAAA,QAMnC,iBAAiB,WAAW,gBAAgB,SAAS;AACzD,UAAM,MAAM,KAAK,eAAe,qBAC9B,UAAU,YAAY,YAAY;AAAA,MAChC;AAAA,MACA,QAAQ,KAAK,UAAU,OAAO;AAAA,OAC7B;AAEL,UAAM,cAAc,MAAM,KAAK,UAAU,MAAM,KAAK,iCAAK,UAAL;AAAA,MAClD,MAAM,KAAK,UAAU,WAAW;AAAA;AAElC,UAAM,aAAa,YAAY;AAC/B,QAAI;AACJ,QAAI,CAAC,cAAc,CAAC,WAAW,gBAAgB;AAC7C,YAAM,IAAI,gBAAgB,uBACxB;AAAA,QACE,SAAS,cAAc,2BAA2B;AAAA,QAClD,YAAY;AAAA,QACZ,OAAO;AAAA;AAAA;AAIb,QAAI,WAAW,mBAAmB,eAAe;AAC/C,cAAQ,KAAK,eAAe,oBAAoB,WAAW;AAAA,WACtD;AACL,cAAQ,KAAK,eAAe,iBAAiB,WAAW,WAAW,WAAW;AAAA;AAGhF,WAAO,MAAM,KAAK,UAAU,MAAM,OAAO;AAAA;AAAA;AAI7C,QAAQ,sBAAsB;",
"names": []
}

239
node_modules/sequelize/lib/dialects/mysql/query.js generated vendored Normal file
View File

@@ -0,0 +1,239 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
const AbstractQuery = require("../abstract/query");
const sequelizeErrors = require("../../errors");
const _ = require("lodash");
const { logger } = require("../../utils/logger");
const ER_DUP_ENTRY = 1062;
const ER_DEADLOCK = 1213;
const ER_ROW_IS_REFERENCED = 1451;
const ER_NO_REFERENCED_ROW = 1452;
const debug = logger.debugContext("sql:mysql");
class Query extends AbstractQuery {
constructor(connection, sequelize, options) {
super(connection, sequelize, __spreadValues({ showWarnings: false }, options));
}
static formatBindParameters(sql, values, dialect) {
const bindParam = [];
const replacementFunc = (match, key, values_) => {
if (values_[key] !== void 0) {
bindParam.push(values_[key]);
return "?";
}
return void 0;
};
sql = AbstractQuery.formatBindParameters(sql, values, dialect, replacementFunc)[0];
return [sql, bindParam.length > 0 ? bindParam : void 0];
}
async run(sql, parameters) {
this.sql = sql;
const { connection, options } = this;
const showWarnings = this.sequelize.options.showWarnings || options.showWarnings;
const complete = this._logQuery(sql, debug, parameters);
if (parameters) {
debug("parameters(%j)", parameters);
}
let results;
const errForStack = new Error();
try {
if (parameters && parameters.length) {
results = await new Promise((resolve, reject) => {
connection.execute(sql, parameters, (error, result) => error ? reject(error) : resolve(result)).setMaxListeners(100);
});
} else {
results = await new Promise((resolve, reject) => {
connection.query({ sql }, (error, result) => error ? reject(error) : resolve(result)).setMaxListeners(100);
});
}
} catch (error) {
if (options.transaction && error.errno === ER_DEADLOCK) {
try {
await options.transaction.rollback();
} catch (error_) {
}
options.transaction.finished = "rollback";
}
error.sql = sql;
error.parameters = parameters;
throw this.formatError(error, errForStack.stack);
} finally {
complete();
}
if (showWarnings && results && results.warningStatus > 0) {
await this.logWarnings(results);
}
return this.formatResults(results);
}
formatResults(data) {
let result = this.instance;
if (this.isInsertQuery(data)) {
this.handleInsertQuery(data);
if (!this.instance) {
if (data.constructor.name === "ResultSetHeader" && this.model && this.model.autoIncrementAttribute && this.model.autoIncrementAttribute === this.model.primaryKeyAttribute && this.model.rawAttributes[this.model.primaryKeyAttribute]) {
const startId = data[this.getInsertIdField()];
result = [];
for (let i = startId; i < startId + data.affectedRows; i++) {
result.push({ [this.model.rawAttributes[this.model.primaryKeyAttribute].field]: i });
}
} else {
result = data[this.getInsertIdField()];
}
}
}
if (this.isSelectQuery()) {
return this.handleSelectQuery(data);
}
if (this.isShowTablesQuery()) {
return this.handleShowTablesQuery(data);
}
if (this.isDescribeQuery()) {
result = {};
for (const _result of data) {
const enumRegex = /^enum/i;
result[_result.Field] = {
type: enumRegex.test(_result.Type) ? _result.Type.replace(enumRegex, "ENUM") : _result.Type.toUpperCase(),
allowNull: _result.Null === "YES",
defaultValue: _result.Default,
primaryKey: _result.Key === "PRI",
autoIncrement: Object.prototype.hasOwnProperty.call(_result, "Extra") && _result.Extra.toLowerCase() === "auto_increment",
comment: _result.Comment ? _result.Comment : null
};
}
return result;
}
if (this.isShowIndexesQuery()) {
return this.handleShowIndexesQuery(data);
}
if (this.isCallQuery()) {
return data[0];
}
if (this.isBulkUpdateQuery() || this.isBulkDeleteQuery()) {
return data.affectedRows;
}
if (this.isVersionQuery()) {
return data[0].version;
}
if (this.isForeignKeysQuery()) {
return data;
}
if (this.isUpsertQuery()) {
return [result, data.affectedRows === 1];
}
if (this.isInsertQuery() || this.isUpdateQuery()) {
return [result, data.affectedRows];
}
if (this.isShowConstraintsQuery()) {
return data;
}
if (this.isRawQuery()) {
return [data, data];
}
return result;
}
async logWarnings(results) {
const warningResults = await this.run("SHOW WARNINGS");
const warningMessage = `MySQL Warnings (${this.connection.uuid || "default"}): `;
const messages = [];
for (const _warningRow of warningResults) {
if (_warningRow === void 0 || typeof _warningRow[Symbol.iterator] !== "function") {
continue;
}
for (const _warningResult of _warningRow) {
if (Object.prototype.hasOwnProperty.call(_warningResult, "Message")) {
messages.push(_warningResult.Message);
} else {
for (const _objectKey of _warningResult.keys()) {
messages.push([_objectKey, _warningResult[_objectKey]].join(": "));
}
}
}
}
this.sequelize.log(warningMessage + messages.join("; "), this.options);
return results;
}
formatError(err, errStack) {
const errCode = err.errno || err.code;
switch (errCode) {
case ER_DUP_ENTRY: {
const match = err.message.match(/Duplicate entry '([\s\S]*)' for key '?((.|\s)*?)'?$/);
let fields = {};
let message = "Validation error";
const values = match ? match[1].split("-") : void 0;
const fieldKey = match ? match[2].split(".").pop() : void 0;
const fieldVal = match ? match[1] : void 0;
const uniqueKey = this.model && this.model.uniqueKeys[fieldKey];
if (uniqueKey) {
if (uniqueKey.msg)
message = uniqueKey.msg;
fields = _.zipObject(uniqueKey.fields, values);
} else {
fields[fieldKey] = fieldVal;
}
const errors = [];
_.forOwn(fields, (value, field) => {
errors.push(new sequelizeErrors.ValidationErrorItem(this.getUniqueConstraintErrorMessage(field), "unique violation", field, value, this.instance, "not_unique"));
});
return new sequelizeErrors.UniqueConstraintError({ message, errors, parent: err, fields, stack: errStack });
}
case ER_ROW_IS_REFERENCED:
case ER_NO_REFERENCED_ROW: {
const match = err.message.match(/CONSTRAINT ([`"])(.*)\1 FOREIGN KEY \(\1(.*)\1\) REFERENCES \1(.*)\1 \(\1(.*)\1\)/);
const quoteChar = match ? match[1] : "`";
const fields = match ? match[3].split(new RegExp(`${quoteChar}, *${quoteChar}`)) : void 0;
return new sequelizeErrors.ForeignKeyConstraintError({
reltype: String(errCode) === String(ER_ROW_IS_REFERENCED) ? "parent" : "child",
table: match ? match[4] : void 0,
fields,
value: fields && fields.length && this.instance && this.instance[fields[0]] || void 0,
index: match ? match[2] : void 0,
parent: err,
stack: errStack
});
}
default:
return new sequelizeErrors.DatabaseError(err, { stack: errStack });
}
}
handleShowIndexesQuery(data) {
data = data.reduce((acc, item) => {
if (!(item.Key_name in acc)) {
acc[item.Key_name] = item;
item.fields = [];
}
acc[item.Key_name].fields[item.Seq_in_index - 1] = {
attribute: item.Column_name,
length: item.Sub_part || void 0,
order: item.Collation === "A" ? "ASC" : void 0
};
delete item.column_name;
return acc;
}, {});
return _.map(data, (item) => ({
primary: item.Key_name === "PRIMARY",
fields: item.fields,
name: item.Key_name,
tableName: item.Table,
unique: item.Non_unique !== 1,
type: item.Index_type
}));
}
}
module.exports = Query;
module.exports.Query = Query;
module.exports.default = Query;
//# sourceMappingURL=query.js.map

File diff suppressed because one or more lines are too long