template and back

This commit is contained in:
romantarkin committed 2025-01-29 15:09:27 +05:00
commit 07ef7e9b8f
3773 files changed
+422508

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __export = (target, all) => {
__markAsModule(target);
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __reExport = (target, module2, desc) => {
if (module2 && typeof module2 === "object" || typeof module2 === "function") {
for (let key of __getOwnPropNames(module2))
if (!__hasOwnProp.call(target, key) && key !== "default")
__defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
}
return target;
};
var __toModule = (module2) => {
return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
};
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
__export(exports, {
AsyncQueueError: () => AsyncQueueError,
default: () => async_queue_default
});
var import_base_error = __toModule(require("../../errors/base-error"));
var import_connection_error = __toModule(require("../../errors/connection-error"));
class AsyncQueueError extends import_base_error.default {
constructor(message) {
super(message);
this.name = "SequelizeAsyncQueueError";
}
}
class AsyncQueue {
constructor() {
__publicField(this, "previous");
__publicField(this, "closed");
__publicField(this, "rejectCurrent");
this.previous = Promise.resolve();
this.closed = false;
this.rejectCurrent = () => {
};
}
close() {
this.closed = true;
this.rejectCurrent(new import_connection_error.default(new AsyncQueueError("the connection was closed before this query could finish executing")));
}
enqueue(asyncFunction) {
return new Promise((resolve, reject) => {
this.previous = this.previous.then(() => {
this.rejectCurrent = reject;
if (this.closed) {
return reject(new import_connection_error.default(new AsyncQueueError("the connection was closed before this query could be executed")));
}
return asyncFunction().then(resolve, reject);
});
});
}
}
var async_queue_default = AsyncQueue;
//# sourceMappingURL=async-queue.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/mssql/async-queue.ts"],
"sourcesContent": ["import BaseError from '../../errors/base-error';\nimport ConnectionError from '../../errors/connection-error';\n\n/**\n * Thrown when a connection to a database is closed while an operation is in progress\n */\nexport class AsyncQueueError extends BaseError {\n constructor(message: string) {\n super(message);\n this.name = 'SequelizeAsyncQueueError';\n }\n}\n\nclass AsyncQueue {\n previous: Promise<unknown>;\n closed: boolean;\n rejectCurrent: (reason?: any) => void;\n\n constructor() {\n this.previous = Promise.resolve();\n this.closed = false;\n this.rejectCurrent = () => {\n /** do nothing */\n };\n }\n\n close() {\n this.closed = true;\n this.rejectCurrent(\n new ConnectionError(\n new AsyncQueueError(\n 'the connection was closed before this query could finish executing'\n )\n )\n );\n }\n\n enqueue(asyncFunction: (...args: any[]) => Promise<unknown>) {\n // This outer promise might seems superflous since down below we return asyncFunction().then(resolve, reject).\n // However, this ensures that this.previous will never be a rejected promise so the queue will\n // always keep going, while still communicating rejection from asyncFunction to the user.\n return new Promise((resolve, reject) => {\n this.previous = this.previous.then(() => {\n this.rejectCurrent = reject;\n if (this.closed) {\n return reject(\n new ConnectionError(\n new AsyncQueueError(\n 'the connection was closed before this query could be executed'\n )\n )\n );\n }\n return asyncFunction().then(resolve, reject);\n });\n });\n }\n}\n\nexport default AsyncQueue;\n"],
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAsB;AACtB,8BAA4B;AAKrB,8BAA8B,0BAAU;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM;AACN,SAAK,OAAO;AAAA;AAAA;AAIhB,iBAAiB;AAAA,EAKf,cAAc;AAJd;AACA;AACA;AAGE,SAAK,WAAW,QAAQ;AACxB,SAAK,SAAS;AACd,SAAK,gBAAgB,MAAM;AAAA;AAAA;AAAA,EAK7B,QAAQ;AACN,SAAK,SAAS;AACd,SAAK,cACH,IAAI,gCACF,IAAI,gBACF;AAAA;AAAA,EAMR,QAAQ,eAAqD;AAI3D,WAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,WAAK,WAAW,KAAK,SAAS,KAAK,MAAM;AACvC,aAAK,gBAAgB;AACrB,YAAI,KAAK,QAAQ;AACf,iBAAO,OACL,IAAI,gCACF,IAAI,gBACF;AAAA;AAKR,eAAO,gBAAgB,KAAK,SAAS;AAAA;AAAA;AAAA;AAAA;AAM7C,IAAO,sBAAQ;",
"names": []
}
+141
View File
@@ -0,0 +1,141 @@
"use strict";
const AbstractConnectionManager = require("../abstract/connection-manager");
const AsyncQueue = require("./async-queue").default;
const { logger } = require("../../utils/logger");
const sequelizeErrors = require("../../errors");
const DataTypes = require("../../data-types").mssql;
const parserStore = require("../parserStore")("mssql");
const debug = logger.debugContext("connection:mssql");
const debugTedious = logger.debugContext("connection:mssql:tedious");
class ConnectionManager extends AbstractConnectionManager {
constructor(dialect, sequelize) {
sequelize.config.port = sequelize.config.port || 1433;
super(dialect, sequelize);
this.lib = this._loadDialectModule("tedious");
this.refreshTypeParser(DataTypes);
}
_refreshTypeParser(dataType) {
parserStore.refresh(dataType);
}
_clearTypeParser() {
parserStore.clear();
}
async connect(config) {
const connectionConfig = {
server: config.host,
authentication: {
type: "default",
options: {
userName: config.username || void 0,
password: config.password || void 0
}
},
options: {
port: parseInt(config.port, 10),
database: config.database,
trustServerCertificate: true
}
};
if (config.dialectOptions) {
if (config.dialectOptions.options && config.dialectOptions.options.instanceName) {
delete connectionConfig.options.port;
}
if (config.dialectOptions.authentication) {
Object.assign(connectionConfig.authentication, config.dialectOptions.authentication);
}
Object.assign(connectionConfig.options, config.dialectOptions.options);
}
try {
return await new Promise((resolve, reject) => {
const connection = new this.lib.Connection(connectionConfig);
if (connection.state === connection.STATE.INITIALIZED) {
connection.connect();
}
connection.queue = new AsyncQueue();
connection.lib = this.lib;
const connectHandler = (error) => {
connection.removeListener("end", endHandler);
connection.removeListener("error", errorHandler);
if (error)
return reject(error);
debug("connection acquired");
resolve(connection);
};
const endHandler = () => {
connection.removeListener("connect", connectHandler);
connection.removeListener("error", errorHandler);
reject(new Error("Connection was closed by remote server"));
};
const errorHandler = (error) => {
connection.removeListener("connect", connectHandler);
connection.removeListener("end", endHandler);
reject(error);
};
connection.once("error", errorHandler);
connection.once("end", endHandler);
connection.once("connect", connectHandler);
connection.on("error", (error) => {
switch (error.code) {
case "ESOCKET":
case "ECONNRESET":
this.pool.destroy(connection);
}
});
if (config.dialectOptions && config.dialectOptions.debug) {
connection.on("debug", debugTedious.log.bind(debugTedious));
}
});
} catch (error) {
if (!error.code) {
throw new sequelizeErrors.ConnectionError(error);
}
switch (error.code) {
case "ESOCKET":
if (error.message.includes("connect EHOSTUNREACH")) {
throw new sequelizeErrors.HostNotReachableError(error);
}
if (error.message.includes("connect ENETUNREACH")) {
throw new sequelizeErrors.HostNotReachableError(error);
}
if (error.message.includes("connect EADDRNOTAVAIL")) {
throw new sequelizeErrors.HostNotReachableError(error);
}
if (error.message.includes("connect EAFNOSUPPORT")) {
throw new sequelizeErrors.HostNotReachableError(error);
}
if (error.message.includes("getaddrinfo ENOTFOUND")) {
throw new sequelizeErrors.HostNotFoundError(error);
}
if (error.message.includes("connect ECONNREFUSED")) {
throw new sequelizeErrors.ConnectionRefusedError(error);
}
throw new sequelizeErrors.ConnectionError(error);
case "ER_ACCESS_DENIED_ERROR":
case "ELOGIN":
throw new sequelizeErrors.AccessDeniedError(error);
case "EINVAL":
throw new sequelizeErrors.InvalidConnectionError(error);
default:
throw new sequelizeErrors.ConnectionError(error);
}
}
}
async disconnect(connection) {
if (connection.closed) {
return;
}
connection.queue.close();
return new Promise((resolve) => {
connection.on("end", resolve);
connection.close();
debug("connection closed");
});
}
validate(connection) {
return connection && (connection.loggedIn || connection.state.name === "LoggedIn");
}
}
module.exports = ConnectionManager;
module.exports.ConnectionManager = ConnectionManager;
module.exports.default = ConnectionManager;
//# sourceMappingURL=connection-manager.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/mssql/connection-manager.js"],
"sourcesContent": ["'use strict';\n\nconst AbstractConnectionManager = require('../abstract/connection-manager');\nconst AsyncQueue = require('./async-queue').default;\nconst { logger } = require('../../utils/logger');\nconst sequelizeErrors = require('../../errors');\nconst DataTypes = require('../../data-types').mssql;\nconst parserStore = require('../parserStore')('mssql');\nconst debug = logger.debugContext('connection:mssql');\nconst debugTedious = logger.debugContext('connection:mssql:tedious');\n\nclass ConnectionManager extends AbstractConnectionManager {\n constructor(dialect, sequelize) {\n sequelize.config.port = sequelize.config.port || 1433;\n super(dialect, sequelize);\n this.lib = this._loadDialectModule('tedious');\n this.refreshTypeParser(DataTypes);\n }\n\n _refreshTypeParser(dataType) {\n parserStore.refresh(dataType);\n }\n\n _clearTypeParser() {\n parserStore.clear();\n }\n\n async connect(config) {\n const connectionConfig = {\n server: config.host,\n authentication: {\n type: 'default',\n options: {\n userName: config.username || undefined,\n password: config.password || undefined\n }\n },\n options: {\n port: parseInt(config.port, 10),\n database: config.database,\n trustServerCertificate: true\n }\n };\n\n if (config.dialectOptions) {\n // only set port if no instance name was provided\n if (\n config.dialectOptions.options &&\n config.dialectOptions.options.instanceName\n ) {\n delete connectionConfig.options.port;\n }\n\n if (config.dialectOptions.authentication) {\n Object.assign(connectionConfig.authentication, config.dialectOptions.authentication);\n }\n\n Object.assign(connectionConfig.options, config.dialectOptions.options);\n }\n\n try {\n return await new Promise((resolve, reject) => {\n const connection = new this.lib.Connection(connectionConfig);\n if (connection.state === connection.STATE.INITIALIZED) {\n connection.connect();\n }\n connection.queue = new AsyncQueue();\n connection.lib = this.lib;\n\n const connectHandler = error => {\n connection.removeListener('end', endHandler);\n connection.removeListener('error', errorHandler);\n\n if (error) return reject(error);\n\n debug('connection acquired');\n resolve(connection);\n };\n\n const endHandler = () => {\n connection.removeListener('connect', connectHandler);\n connection.removeListener('error', errorHandler);\n reject(new Error('Connection was closed by remote server'));\n };\n\n const errorHandler = error => {\n connection.removeListener('connect', connectHandler);\n connection.removeListener('end', endHandler);\n reject(error);\n };\n\n connection.once('error', errorHandler);\n connection.once('end', endHandler);\n connection.once('connect', connectHandler);\n\n /*\n * Permanently attach this event before connection is even acquired\n * tedious sometime emits error even after connect(with error).\n *\n * If we dont attach this even that unexpected error event will crash node process\n *\n * E.g. connectTimeout is set higher than requestTimeout\n */\n connection.on('error', error => {\n switch (error.code) {\n case 'ESOCKET':\n case 'ECONNRESET':\n this.pool.destroy(connection);\n }\n });\n\n if (config.dialectOptions && config.dialectOptions.debug) {\n connection.on('debug', debugTedious.log.bind(debugTedious));\n }\n });\n } catch (error) {\n if (!error.code) {\n throw new sequelizeErrors.ConnectionError(error);\n }\n\n switch (error.code) {\n case 'ESOCKET':\n if (error.message.includes('connect EHOSTUNREACH')) {\n throw new sequelizeErrors.HostNotReachableError(error);\n }\n if (error.message.includes('connect ENETUNREACH')) {\n throw new sequelizeErrors.HostNotReachableError(error);\n }\n if (error.message.includes('connect EADDRNOTAVAIL')) {\n throw new sequelizeErrors.HostNotReachableError(error);\n }\n if (error.message.includes('connect EAFNOSUPPORT')) {\n throw new sequelizeErrors.HostNotReachableError(error);\n }\n if (error.message.includes('getaddrinfo ENOTFOUND')) {\n throw new sequelizeErrors.HostNotFoundError(error);\n }\n if (error.message.includes('connect ECONNREFUSED')) {\n throw new sequelizeErrors.ConnectionRefusedError(error);\n }\n throw new sequelizeErrors.ConnectionError(error);\n case 'ER_ACCESS_DENIED_ERROR':\n Line truncated
"mappings": ";AAEA,MAAM,4BAA4B,QAAQ;AAC1C,MAAM,aAAa,QAAQ,iBAAiB;AAC5C,MAAM,EAAE,WAAW,QAAQ;AAC3B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,gBAAM,IAAI,gBAAgB,gBAAgB;AAAA,aACvC;AAAA,aACA;AACH,gBAAM,IAAI,gBAAgB,kBAAkB;AAAA,aACzC;AACH,gBAAM,IAAI,gBAAgB,uBAAuB;AAAA;AAEjD,gBAAM,IAAI,gBAAgB,gBAAgB;AAAA;AAAA;AAAA;AAAA,QAK5C,WAAW,YAAY;AAE3B,QAAI,WAAW,QAAQ;AACrB;AAAA;AAGF,eAAW,MAAM;AAEjB,WAAO,IAAI,QAAQ,aAAW;AAC5B,iBAAW,GAAG,OAAO;AACrB,iBAAW;AACX,YAAM;AAAA;AAAA;AAAA,EAIV,SAAS,YAAY;AACnB,WAAO,cAAe,YAAW,YAAY,WAAW,MAAM,SAAS;AAAA;AAAA;AAI3E,OAAO,UAAU;AACjB,OAAO,QAAQ,oBAAoB;AACnC,OAAO,QAAQ,UAAU;",
"names": []
}
+181
View File
@@ -0,0 +1,181 @@
"use strict";
const moment = require("moment");
module.exports = (BaseTypes) => {
const warn = BaseTypes.ABSTRACT.warn.bind(void 0, "https://msdn.microsoft.com/en-us/library/ms187752%28v=sql.110%29.aspx");
function removeUnsupportedIntegerOptions(dataType) {
if (dataType._length || dataType.options.length || dataType._unsigned || dataType._zerofill) {
warn(`MSSQL does not support '${dataType.key}' with options. Plain '${dataType.key}' will be used instead.`);
dataType._length = void 0;
dataType.options.length = void 0;
dataType._unsigned = void 0;
dataType._zerofill = void 0;
}
}
BaseTypes.DATE.types.mssql = [43];
BaseTypes.STRING.types.mssql = [231, 173];
BaseTypes.CHAR.types.mssql = [175];
BaseTypes.TEXT.types.mssql = false;
BaseTypes.TINYINT.types.mssql = [30];
BaseTypes.SMALLINT.types.mssql = [34];
BaseTypes.MEDIUMINT.types.mssql = false;
BaseTypes.INTEGER.types.mssql = [38];
BaseTypes.BIGINT.types.mssql = false;
BaseTypes.FLOAT.types.mssql = [109];
BaseTypes.TIME.types.mssql = [41];
BaseTypes.DATEONLY.types.mssql = [40];
BaseTypes.BOOLEAN.types.mssql = [104];
BaseTypes.BLOB.types.mssql = [165];
BaseTypes.DECIMAL.types.mssql = [106];
BaseTypes.UUID.types.mssql = false;
BaseTypes.ENUM.types.mssql = false;
BaseTypes.REAL.types.mssql = [109];
BaseTypes.DOUBLE.types.mssql = [109];
BaseTypes.GEOMETRY.types.mssql = false;
class BLOB extends BaseTypes.BLOB {
toSql() {
if (this._length) {
if (this._length.toLowerCase() === "tiny") {
warn("MSSQL does not support BLOB with the `length` = `tiny` option. `VARBINARY(256)` will be used instead.");
return "VARBINARY(256)";
}
warn("MSSQL does not support BLOB with the `length` option. `VARBINARY(MAX)` will be used instead.");
}
return "VARBINARY(MAX)";
}
_hexify(hex) {
return `0x${hex}`;
}
}
class STRING extends BaseTypes.STRING {
toSql() {
if (!this._binary) {
return `NVARCHAR(${this._length})`;
}
return `BINARY(${this._length})`;
}
_stringify(value, options) {
if (this._binary) {
return BLOB.prototype._stringify(value);
}
return options.escape(value);
}
_bindParam(value, options) {
return options.bindParam(this._binary ? Buffer.from(value) : value);
}
}
STRING.prototype.escape = false;
class TEXT extends BaseTypes.TEXT {
toSql() {
if (this._length) {
if (this._length.toLowerCase() === "tiny") {
warn("MSSQL does not support TEXT with the `length` = `tiny` option. `NVARCHAR(256)` will be used instead.");
return "NVARCHAR(256)";
}
warn("MSSQL does not support TEXT with the `length` option. `NVARCHAR(MAX)` will be used instead.");
}
return "NVARCHAR(MAX)";
}
}
class BOOLEAN extends BaseTypes.BOOLEAN {
toSql() {
return "BIT";
}
}
class UUID extends BaseTypes.UUID {
toSql() {
return "CHAR(36)";
}
}
class NOW extends BaseTypes.NOW {
toSql() {
return "GETDATE()";
}
}
class DATE extends BaseTypes.DATE {
toSql() {
return "DATETIMEOFFSET";
}
}
class DATEONLY extends BaseTypes.DATEONLY {
static parse(value) {
return moment(value).format("YYYY-MM-DD");
}
}
class INTEGER extends BaseTypes.INTEGER {
constructor(length) {
super(length);
removeUnsupportedIntegerOptions(this);
}
}
class TINYINT extends BaseTypes.TINYINT {
constructor(length) {
super(length);
removeUnsupportedIntegerOptions(this);
}
}
class SMALLINT extends BaseTypes.SMALLINT {
constructor(length) {
super(length);
removeUnsupportedIntegerOptions(this);
}
}
class BIGINT extends BaseTypes.BIGINT {
constructor(length) {
super(length);
removeUnsupportedIntegerOptions(this);
}
}
class REAL extends BaseTypes.REAL {
constructor(length, decimals) {
super(length, decimals);
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn("MSSQL does not support REAL with options. Plain `REAL` will be used instead.");
this._length = void 0;
this.options.length = void 0;
this._unsigned = void 0;
this._zerofill = void 0;
}
}
}
class FLOAT extends BaseTypes.FLOAT {
constructor(length, decimals) {
super(length, decimals);
if (this._decimals) {
warn("MSSQL does not support Float with decimals. Plain `FLOAT` will be used instead.");
this._length = void 0;
this.options.length = void 0;
}
if (this._unsigned) {
warn("MSSQL does not support Float unsigned. `UNSIGNED` was removed.");
this._unsigned = void 0;
}
if (this._zerofill) {
warn("MSSQL does not support Float zerofill. `ZEROFILL` was removed.");
this._zerofill = void 0;
}
}
}
class ENUM extends BaseTypes.ENUM {
toSql() {
return "VARCHAR(255)";
}
}
return {
BLOB,
BOOLEAN,
ENUM,
STRING,
UUID,
DATE,
DATEONLY,
NOW,
TINYINT,
SMALLINT,
INTEGER,
BIGINT,
REAL,
FLOAT,
TEXT
};
};
//# sourceMappingURL=data-types.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/mssql/data-types.js"],
"sourcesContent": ["'use strict';\n\nconst moment = require('moment');\n\nmodule.exports = BaseTypes => {\n const warn = BaseTypes.ABSTRACT.warn.bind(undefined, 'https://msdn.microsoft.com/en-us/library/ms187752%28v=sql.110%29.aspx');\n\n /**\n * Removes unsupported MSSQL options, i.e., LENGTH, UNSIGNED and ZEROFILL, for the integer data types.\n *\n * @param {object} dataType The base integer data type.\n * @private\n */\n function removeUnsupportedIntegerOptions(dataType) {\n if (dataType._length || dataType.options.length || dataType._unsigned || dataType._zerofill) {\n warn(`MSSQL does not support '${dataType.key}' with options. Plain '${dataType.key}' will be used instead.`);\n dataType._length = undefined;\n dataType.options.length = undefined;\n dataType._unsigned = undefined;\n dataType._zerofill = undefined;\n }\n }\n\n /**\n * types: [hex, ...]\n *\n * @see hex here https://github.com/tediousjs/tedious/blob/master/src/data-type.ts\n */\n\n BaseTypes.DATE.types.mssql = [43];\n BaseTypes.STRING.types.mssql = [231, 173];\n BaseTypes.CHAR.types.mssql = [175];\n BaseTypes.TEXT.types.mssql = false;\n // https://msdn.microsoft.com/en-us/library/ms187745(v=sql.110).aspx\n BaseTypes.TINYINT.types.mssql = [30];\n BaseTypes.SMALLINT.types.mssql = [34];\n BaseTypes.MEDIUMINT.types.mssql = false;\n BaseTypes.INTEGER.types.mssql = [38];\n BaseTypes.BIGINT.types.mssql = false;\n BaseTypes.FLOAT.types.mssql = [109];\n BaseTypes.TIME.types.mssql = [41];\n BaseTypes.DATEONLY.types.mssql = [40];\n BaseTypes.BOOLEAN.types.mssql = [104];\n BaseTypes.BLOB.types.mssql = [165];\n BaseTypes.DECIMAL.types.mssql = [106];\n BaseTypes.UUID.types.mssql = false;\n BaseTypes.ENUM.types.mssql = false;\n BaseTypes.REAL.types.mssql = [109];\n BaseTypes.DOUBLE.types.mssql = [109];\n // BaseTypes.GEOMETRY.types.mssql = [240]; // not yet supported\n BaseTypes.GEOMETRY.types.mssql = false;\n\n class BLOB extends BaseTypes.BLOB {\n toSql() {\n if (this._length) {\n if (this._length.toLowerCase() === 'tiny') { // tiny = 2^8\n warn('MSSQL does not support BLOB with the `length` = `tiny` option. `VARBINARY(256)` will be used instead.');\n return 'VARBINARY(256)';\n }\n warn('MSSQL does not support BLOB with the `length` option. `VARBINARY(MAX)` will be used instead.');\n }\n return 'VARBINARY(MAX)';\n }\n _hexify(hex) {\n return `0x${hex}`;\n }\n }\n\n\n class STRING extends BaseTypes.STRING {\n toSql() {\n if (!this._binary) {\n return `NVARCHAR(${this._length})`;\n }\n return `BINARY(${this._length})`;\n }\n _stringify(value, options) {\n if (this._binary) {\n return BLOB.prototype._stringify(value);\n }\n return options.escape(value);\n }\n _bindParam(value, options) {\n return options.bindParam(this._binary ? Buffer.from(value) : value);\n }\n }\n\n STRING.prototype.escape = false;\n\n class TEXT extends BaseTypes.TEXT {\n toSql() {\n // TEXT is deprecated in mssql and it would normally be saved as a non-unicode string.\n // Using unicode is just future proof\n if (this._length) {\n if (this._length.toLowerCase() === 'tiny') { // tiny = 2^8\n warn('MSSQL does not support TEXT with the `length` = `tiny` option. `NVARCHAR(256)` will be used instead.');\n return 'NVARCHAR(256)';\n }\n warn('MSSQL does not support TEXT with the `length` option. `NVARCHAR(MAX)` will be used instead.');\n }\n return 'NVARCHAR(MAX)';\n }\n }\n\n class BOOLEAN extends BaseTypes.BOOLEAN {\n toSql() {\n return 'BIT';\n }\n }\n\n class UUID extends BaseTypes.UUID {\n toSql() {\n return 'CHAR(36)';\n }\n }\n\n class NOW extends BaseTypes.NOW {\n toSql() {\n return 'GETDATE()';\n }\n }\n\n class DATE extends BaseTypes.DATE {\n toSql() {\n return 'DATETIMEOFFSET';\n }\n }\n\n class DATEONLY extends BaseTypes.DATEONLY {\n static parse(value) {\n return moment(value).format('YYYY-MM-DD');\n }\n }\n\n class INTEGER extends BaseTypes.INTEGER {\n constructor(length) {\n super(length);\n removeUnsupportedIntegerOptions(this);\n }\n }\n class TINYINT extends BaseTypes.TINYINT {\n constructor(length) {\n super(length);\n removeUnsupportedIntegerOptions(this);\n }\n }\n class SMALLINT extends BaseTypes.SMALLINT {\n constructor(length) {\n super(length);\n removeUnsupportedIntegerOptions(this);\n }\n }\n class BIGINT extends BaseTypes.BIGINT {\n constructor(length) {\n super(length);\n removeUnsupportedIntegerOptions(this);\n }\n }\n class REAL extends BaseTypes.REAL {\n constructor(length, decimals) {\n super(length, decimals);\n // MSSQL does not support any options for real\n if (this._length || this.options.length || this._unsigneLine truncated
"mappings": ";AAEA,MAAM,SAAS,QAAQ;AAEvB,OA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GpC,uBAAqB,UAAU,OAAO;AAAA,IACpC,YAAY,QAAQ;AAClB,YAAM;AACN,sCAAgC;AAAA;AAAA;AAGpC,qBAAmB,UAAU,KAAK;AAAA,IAChC,YAAY,QAAQ,UAAU;AAC5B,YAAM,QAAQ;AAEd,UAAI,KAAK,WAAW,KAAK,QAAQ,UAAU,KAAK,aAAa,KAAK,WAAW;AAC3E,aAAK;AACL,aAAK,UAAU;AACf,aAAK,QAAQ,SAAS;AACtB,aAAK,YAAY;AACjB,aAAK,YAAY;AAAA;AAAA;AAAA;AAIvB,sBAAoB,UAAU,MAAM;AAAA,IAClC,YAAY,QAAQ,UAAU;AAC5B,YAAM,QAAQ;AAKd,UAAI,KAAK,WAAW;AAClB,aAAK;AACL,aAAK,UAAU;AACf,aAAK,QAAQ,SAAS;AAAA;AAExB,UAAI,KAAK,WAAW;AAClB,aAAK;AACL,aAAK,YAAY;AAAA;AAEnB,UAAI,KAAK,WAAW;AAClB,aAAK;AACL,aAAK,YAAY;AAAA;AAAA;AAAA;AAIvB,qBAAmB,UAAU,KAAK;AAAA,IAChC,QAAQ;AACN,aAAO;AAAA;AAAA;AAIX,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA;",
"names": []
}
+61
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").mssql;
const { MSSqlQueryInterface } = require("./query-interface");
class MssqlDialect extends AbstractDialect {
constructor(sequelize) {
super();
this.sequelize = sequelize;
this.connectionManager = new ConnectionManager(this, sequelize);
this.queryGenerator = new QueryGenerator({
_dialect: this,
sequelize
});
this.queryInterface = new MSSqlQueryInterface(sequelize, this.queryGenerator);
}
}
MssqlDialect.prototype.supports = _.merge(_.cloneDeep(AbstractDialect.prototype.supports), {
DEFAULT: true,
"DEFAULT VALUES": true,
"LIMIT ON UPDATE": true,
"ORDER NULLS": false,
lock: false,
transactions: true,
migrations: false,
returnValues: {
output: true
},
schemas: true,
autoIncrement: {
identityInsert: true,
defaultValue: false,
update: false
},
constraints: {
restrict: false,
default: true
},
index: {
collate: false,
length: false,
parser: false,
type: true,
using: false,
where: true
},
NUMERIC: true,
tmpTableTrigger: true
});
MssqlDialect.prototype.defaultVersion = "12.0.2000";
MssqlDialect.prototype.Query = Query;
MssqlDialect.prototype.name = "mssql";
MssqlDialect.prototype.TICK_CHAR = '"';
MssqlDialect.prototype.TICK_CHAR_LEFT = "[";
MssqlDialect.prototype.TICK_CHAR_RIGHT = "]";
MssqlDialect.prototype.DataTypes = DataTypes;
module.exports = MssqlDialect;
//# sourceMappingURL=index.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/mssql/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').mssql;\nconst { MSSqlQueryInterface } = require('./query-interface');\n\nclass MssqlDialect 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 MSSqlQueryInterface(\n sequelize,\n this.queryGenerator\n );\n }\n}\n\nMssqlDialect.prototype.supports = _.merge(\n _.cloneDeep(AbstractDialect.prototype.supports),\n {\n DEFAULT: true,\n 'DEFAULT VALUES': true,\n 'LIMIT ON UPDATE': true,\n 'ORDER NULLS': false,\n lock: false,\n transactions: true,\n migrations: false,\n returnValues: {\n output: true\n },\n schemas: true,\n autoIncrement: {\n identityInsert: true,\n defaultValue: false,\n update: false\n },\n constraints: {\n restrict: false,\n default: true\n },\n index: {\n collate: false,\n length: false,\n parser: false,\n type: true,\n using: false,\n where: true\n },\n NUMERIC: true,\n tmpTableTrigger: true\n }\n);\n\nMssqlDialect.prototype.defaultVersion = '12.0.2000'; // SQL Server 2014 Express, minimum supported version\nMssqlDialect.prototype.Query = Query;\nMssqlDialect.prototype.name = 'mssql';\nMssqlDialect.prototype.TICK_CHAR = '\"';\nMssqlDialect.prototype.TICK_CHAR_LEFT = '[';\nMssqlDialect.prototype.TICK_CHAR_RIGHT = ']';\nMssqlDialect.prototype.DataTypes = DataTypes;\n\nmodule.exports = MssqlDialect;\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;AAKX,aAAa,UAAU,WAAW,EAAE,MAClC,EAAE,UAAU,gBAAgB,UAAU,WACtC;AAAA,EACE,SAAS;AAAA,EACT,kBAAkB;AAAA,EAClB,mBAAmB;AAAA,EACnB,eAAe;AAAA,EACf,MAAM;AAAA,EACN,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,cAAc;AAAA,IACZ,QAAQ;AAAA;AAAA,EAEV,SAAS;AAAA,EACT,eAAe;AAAA,IACb,gBAAgB;AAAA,IAChB,cAAc;AAAA,IACd,QAAQ;AAAA;AAAA,EAEV,aAAa;AAAA,IACX,UAAU;AAAA,IACV,SAAS;AAAA;AAAA,EAEX,OAAO;AAAA,IACL,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,OAAO;AAAA,IACP,OAAO;AAAA;AAAA,EAET,SAAS;AAAA,EACT,iBAAiB;AAAA;AAIrB,aAAa,UAAU,iBAAiB;AACxC,aAAa,UAAU,QAAQ;AAC/B,aAAa,UAAU,OAAO;AAC9B,aAAa,UAAU,YAAY;AACnC,aAAa,UAAU,iBAAiB;AACxC,aAAa,UAAU,kBAAkB;AACzC,aAAa,UAAU,YAAY;AAEnC,OAAO,UAAU;",
"names": []
}
+826
View File
@@ -0,0 +1,826 @@
"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 _ = require("lodash");
const Utils = require("../../utils");
const DataTypes = require("../../data-types");
const TableHints = require("../../table-hints");
const AbstractQueryGenerator = require("../abstract/query-generator");
const randomBytes = require("crypto").randomBytes;
const semver = require("semver");
const Op = require("../../operators");
const throwMethodUndefined = function(methodName) {
throw new Error(`The method "${methodName}" is not defined! Please add it to your sql dialect.`);
};
class MSSQLQueryGenerator extends AbstractQueryGenerator {
createDatabaseQuery(databaseName, options) {
options = __spreadValues({ collate: null }, options);
const collation = options.collate ? `COLLATE ${this.escape(options.collate)}` : "";
return [
"IF NOT EXISTS (SELECT * FROM sys.databases WHERE name =",
wrapSingleQuote(databaseName),
")",
"BEGIN",
"CREATE DATABASE",
this.quoteIdentifier(databaseName),
`${collation};`,
"END;"
].join(" ");
}
dropDatabaseQuery(databaseName) {
return [
"IF EXISTS (SELECT * FROM sys.databases WHERE name =",
wrapSingleQuote(databaseName),
")",
"BEGIN",
"DROP DATABASE",
this.quoteIdentifier(databaseName),
";",
"END;"
].join(" ");
}
createSchema(schema) {
return [
"IF NOT EXISTS (SELECT schema_name",
"FROM information_schema.schemata",
"WHERE schema_name =",
wrapSingleQuote(schema),
")",
"BEGIN",
"EXEC sp_executesql N'CREATE SCHEMA",
this.quoteIdentifier(schema),
";'",
"END;"
].join(" ");
}
dropSchema(schema) {
const quotedSchema = wrapSingleQuote(schema);
return [
"IF EXISTS (SELECT schema_name",
"FROM information_schema.schemata",
"WHERE schema_name =",
quotedSchema,
")",
"BEGIN",
"DECLARE @id INT, @ms_sql NVARCHAR(2000);",
"DECLARE @cascade TABLE (",
"id INT NOT NULL IDENTITY PRIMARY KEY,",
"ms_sql NVARCHAR(2000) NOT NULL );",
"INSERT INTO @cascade ( ms_sql )",
"SELECT CASE WHEN o.type IN ('F','PK')",
"THEN N'ALTER TABLE ['+ s.name + N'].[' + p.name + N'] DROP CONSTRAINT [' + o.name + N']'",
"ELSE N'DROP TABLE ['+ s.name + N'].[' + o.name + N']' END",
"FROM sys.objects o",
"JOIN sys.schemas s on o.schema_id = s.schema_id",
"LEFT OUTER JOIN sys.objects p on o.parent_object_id = p.object_id",
"WHERE o.type IN ('F', 'PK', 'U') AND s.name = ",
quotedSchema,
"ORDER BY o.type ASC;",
"SELECT TOP 1 @id = id, @ms_sql = ms_sql FROM @cascade ORDER BY id;",
"WHILE @id IS NOT NULL",
"BEGIN",
"BEGIN TRY EXEC sp_executesql @ms_sql; END TRY",
"BEGIN CATCH BREAK; THROW; END CATCH;",
"DELETE FROM @cascade WHERE id = @id;",
"SELECT @id = NULL, @ms_sql = NULL;",
"SELECT TOP 1 @id = id, @ms_sql = ms_sql FROM @cascade ORDER BY id;",
"END",
"EXEC sp_executesql N'DROP SCHEMA",
this.quoteIdentifier(schema),
";'",
"END;"
].join(" ");
}
showSchemasQuery() {
return [
'SELECT "name" as "schema_name" FROM sys.schemas as s',
'WHERE "s"."name" NOT IN (',
"'INFORMATION_SCHEMA', 'dbo', 'guest', 'sys', 'archive'",
")",
"AND",
'"s"."name" NOT LIKE',
"'db_%'"
].join(" ");
}
versionQuery() {
return [
"DECLARE @ms_ver NVARCHAR(20);",
"SET @ms_ver = REVERSE(CONVERT(NVARCHAR(20), SERVERPROPERTY('ProductVersion')));",
"SELECT REVERSE(SUBSTRING(@ms_ver, CHARINDEX('.', @ms_ver)+1, 20)) AS 'version'"
].join(" ");
}
createTableQuery(tableName, attributes, options) {
const primaryKeys = [], foreignKeys = {}, attributesClauseParts = [];
let commentStr = "";
for (const attr in attributes) {
if (Object.prototype.hasOwnProperty.call(attributes, attr)) {
let dataType = attributes[attr];
let match;
if (dataType.includes("COMMENT ")) {
const commentMatch = dataType.match(/^(.+) (COMMENT.*)$/);
const commentText = commentMatch[2].replace("COMMENT", "").trim();
commentStr += this.commentTemplate(commentText, tableName, attr);
dataType = commentMatch[1];
}
if (dataType.includes("PRIMARY KEY")) {
primaryKeys.push(attr);
if (dataType.includes("REFERENCES")) {
match = dataType.match(/^(.+) (REFERENCES.*)$/);
attributesClauseParts.push(`${this.quoteIdentifier(attr)} ${match[1].replace("PRIMARY KEY", "")}`);
foreignKeys[attr] = match[2];
} else {
attributesClauseParts.push(`${this.quoteIdentifier(attr)} ${dataType.replace("PRIMARY KEY", "")}`);
}
} else if (dataType.includes("REFERENCES")) {
match = dataType.match(/^(.+) (REFERENCES.*)$/);
attributesClauseParts.push(`${this.quoteIdentifier(attr)} ${match[1]}`);
foreignKeys[attr] = match[2];
} else {
attributesClauseParts.push(`${this.quoteIdentifier(attr)} ${dataType}`);
}
}
}
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("_")}`;
}
attributesClauseParts.push(`CONSTRAINT ${this.quoteIdentifier(indexName)} UNIQUE (${columns.fields.map((field) => this.quoteIdentifier(field)).join(", ")})`);
}
});
}
if (pkString.length > 0) {
attributesClauseParts.push(`PRIMARY KEY (${pkString})`);
}
for (const fkey in foreignKeys) {
if (Object.prototype.hasOwnProperty.call(foreignKeys, fkey)) {
attributesClauseParts.push(`FOREIGN KEY (${this.quoteIdentifier(fkey)}) ${foreignKeys[fkey]}`);
}
}
const quotedTableName = this.quoteTable(tableName);
return Utils.joinSQLFragments([
`IF OBJECT_ID('${quotedTableName}', 'U') IS NULL`,
`CREATE TABLE ${quotedTableName} (${attributesClauseParts.join(", ")})`,
";",
commentStr
]);
}
describeTableQuery(tableName, schema) {
let sql = [
"SELECT",
"c.COLUMN_NAME AS 'Name',",
"c.DATA_TYPE AS 'Type',",
"c.CHARACTER_MAXIMUM_LENGTH AS 'Length',",
"c.IS_NULLABLE as 'IsNull',",
"COLUMN_DEFAULT AS 'Default',",
"pk.CONSTRAINT_TYPE AS 'Constraint',",
"COLUMNPROPERTY(OBJECT_ID('[' + c.TABLE_SCHEMA + '].[' + c.TABLE_NAME + ']'), c.COLUMN_NAME, 'IsIdentity') as 'IsIdentity',",
"CAST(prop.value AS NVARCHAR) AS 'Comment'",
"FROM",
"INFORMATION_SCHEMA.TABLES t",
"INNER JOIN",
"INFORMATION_SCHEMA.COLUMNS c ON t.TABLE_NAME = c.TABLE_NAME AND t.TABLE_SCHEMA = c.TABLE_SCHEMA",
"LEFT JOIN (SELECT tc.table_schema, tc.table_name, ",
"cu.column_name, tc.CONSTRAINT_TYPE ",
"FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc ",
"JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE cu ",
"ON tc.table_schema=cu.table_schema and tc.table_name=cu.table_name ",
"and tc.constraint_name=cu.constraint_name ",
"and tc.CONSTRAINT_TYPE='PRIMARY KEY') pk ",
"ON pk.table_schema=c.table_schema ",
"AND pk.table_name=c.table_name ",
"AND pk.column_name=c.column_name ",
"INNER JOIN sys.columns AS sc",
"ON sc.object_id = OBJECT_ID('[' + t.TABLE_SCHEMA + '].[' + t.TABLE_NAME + ']') AND sc.name = c.column_name",
"LEFT JOIN sys.extended_properties prop ON prop.major_id = sc.object_id",
"AND prop.minor_id = sc.column_id",
"AND prop.name = 'MS_Description'",
"WHERE t.TABLE_NAME =",
wrapSingleQuote(tableName)
].join(" ");
if (schema) {
sql += `AND t.TABLE_SCHEMA =${wrapSingleQuote(schema)}`;
}
return sql;
}
renameTableQuery(before, after) {
return `EXEC sp_rename ${this.quoteTable(before)}, ${this.quoteTable(after)};`;
}
showTablesQuery() {
return "SELECT TABLE_NAME, TABLE_SCHEMA FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE';";
}
tableExistsQuery(table) {
const tableName = table.tableName || table;
const schemaName = table.schema || "dbo";
return `SELECT TABLE_NAME, TABLE_SCHEMA FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = ${this.escape(tableName)} AND TABLE_SCHEMA = ${this.escape(schemaName)}`;
}
dropTableQuery(tableName) {
const quoteTbl = this.quoteTable(tableName);
return Utils.joinSQLFragments([
`IF OBJECT_ID('${quoteTbl}', 'U') IS NOT NULL`,
"DROP TABLE",
quoteTbl,
";"
]);
}
addColumnQuery(table, key, dataType) {
dataType.field = key;
let commentStr = "";
if (dataType.comment && _.isString(dataType.comment)) {
commentStr = this.commentTemplate(dataType.comment, table, key);
delete dataType["comment"];
}
return Utils.joinSQLFragments([
"ALTER TABLE",
this.quoteTable(table),
"ADD",
this.quoteIdentifier(key),
this.attributeToSQL(dataType, { context: "addColumn" }),
";",
commentStr
]);
}
commentTemplate(comment, table, column) {
return ` EXEC sp_addextendedproperty @name = N'MS_Description', @value = ${this.escape(comment)}, @level0type = N'Schema', @level0name = 'dbo', @level1type = N'Table', @level1name = ${this.quoteIdentifier(table)}, @level2type = N'Column', @level2name = ${this.quoteIdentifier(column)};`;
}
removeColumnQuery(tableName, attributeName) {
return Utils.joinSQLFragments([
"ALTER TABLE",
this.quoteTable(tableName),
"DROP COLUMN",
this.quoteIdentifier(attributeName),
";"
]);
}
changeColumnQuery(tableName, attributes) {
const attrString = [], constraintString = [];
let commentString = "";
for (const attributeName in attributes) {
const quotedAttrName = this.quoteIdentifier(attributeName);
let definition = attributes[attributeName];
if (definition.includes("COMMENT ")) {
const commentMatch = definition.match(/^(.+) (COMMENT.*)$/);
const commentText = commentMatch[2].replace("COMMENT", "").trim();
commentString += this.commentTemplate(commentText, tableName, attributeName);
definition = commentMatch[1];
}
if (definition.includes("REFERENCES")) {
constraintString.push(`FOREIGN KEY (${quotedAttrName}) ${definition.replace(/.+?(?=REFERENCES)/, "")}`);
} else {
attrString.push(`${quotedAttrName} ${definition}`);
}
}
return Utils.joinSQLFragments([
"ALTER TABLE",
this.quoteTable(tableName),
attrString.length && `ALTER COLUMN ${attrString.join(", ")}`,
constraintString.length && `ADD ${constraintString.join(", ")}`,
";",
commentString
]);
}
renameColumnQuery(tableName, attrBefore, attributes) {
const newName = Object.keys(attributes)[0];
return Utils.joinSQLFragments([
"EXEC sp_rename",
`'${this.quoteTable(tableName)}.${attrBefore}',`,
`'${newName}',`,
"'COLUMN'",
";"
]);
}
bulkInsertQuery(tableName, attrValueHashes, options, attributes) {
const quotedTable = this.quoteTable(tableName);
options = options || {};
attributes = attributes || {};
const tuples = [];
const allAttributes = [];
const allQueries = [];
let needIdentityInsertWrapper = false, outputFragment = "";
if (options.returning) {
const returnValues = this.generateReturnValues(attributes, options);
outputFragment = returnValues.outputFragment;
}
const emptyQuery = `INSERT INTO ${quotedTable}${outputFragment} DEFAULT VALUES`;
attrValueHashes.forEach((attrValueHash) => {
const fields = Object.keys(attrValueHash);
const firstAttr = attributes[fields[0]];
if (fields.length === 1 && firstAttr && firstAttr.autoIncrement && attrValueHash[fields[0]] === null) {
allQueries.push(emptyQuery);
return;
}
_.forOwn(attrValueHash, (value, key) => {
if (value !== null && attributes[key] && attributes[key].autoIncrement) {
needIdentityInsertWrapper = true;
}
if (!allAttributes.includes(key)) {
if (value === null && attributes[key] && attributes[key].autoIncrement)
return;
allAttributes.push(key);
}
});
});
if (allAttributes.length > 0) {
attrValueHashes.forEach((attrValueHash) => {
tuples.push(`(${allAttributes.map((key) => this.escape(attrValueHash[key])).join(",")})`);
});
const quotedAttributes = allAttributes.map((attr) => this.quoteIdentifier(attr)).join(",");
allQueries.push((tupleStr) => `INSERT INTO ${quotedTable} (${quotedAttributes})${outputFragment} VALUES ${tupleStr};`);
}
const commands = [];
let offset = 0;
const batch = Math.floor(250 / (allAttributes.length + 1)) + 1;
while (offset < Math.max(tuples.length, 1)) {
const tupleStr = tuples.slice(offset, Math.min(tuples.length, offset + batch));
let generatedQuery = allQueries.map((v) => typeof v === "string" ? v : v(tupleStr)).join(";");
if (needIdentityInsertWrapper) {
generatedQuery = `SET IDENTITY_INSERT ${quotedTable} ON; ${generatedQuery}; SET IDENTITY_INSERT ${quotedTable} OFF;`;
}
commands.push(generatedQuery);
offset += batch;
}
return commands.join(";");
}
updateQuery(tableName, attrValueHash, where, options, attributes) {
const sql = super.updateQuery(tableName, attrValueHash, where, options, attributes);
if (options.limit) {
const updateArgs = `UPDATE TOP(${this.escape(options.limit)})`;
sql.query = sql.query.replace("UPDATE", updateArgs);
}
return sql;
}
upsertQuery(tableName, insertValues, updateValues, where, model) {
const targetTableAlias = this.quoteTable(`${tableName}_target`);
const sourceTableAlias = this.quoteTable(`${tableName}_source`);
const primaryKeysAttrs = [];
const identityAttrs = [];
const uniqueAttrs = [];
const tableNameQuoted = this.quoteTable(tableName);
let needIdentityInsertWrapper = false;
for (const key in model.rawAttributes) {
if (model.rawAttributes[key].primaryKey) {
primaryKeysAttrs.push(model.rawAttributes[key].field || key);
}
if (model.rawAttributes[key].unique) {
uniqueAttrs.push(model.rawAttributes[key].field || key);
}
if (model.rawAttributes[key].autoIncrement) {
identityAttrs.push(model.rawAttributes[key].field || key);
}
}
for (const index of model._indexes) {
if (index.unique && index.fields) {
for (const field of index.fields) {
const fieldName = typeof field === "string" ? field : field.name || field.attribute;
if (!uniqueAttrs.includes(fieldName) && model.rawAttributes[fieldName]) {
uniqueAttrs.push(fieldName);
}
}
}
}
const updateKeys = Object.keys(updateValues);
const insertKeys = Object.keys(insertValues);
const insertKeysQuoted = insertKeys.map((key) => this.quoteIdentifier(key)).join(", ");
const insertValuesEscaped = insertKeys.map((key) => this.escape(insertValues[key])).join(", ");
const sourceTableQuery = `VALUES(${insertValuesEscaped})`;
let joinCondition;
identityAttrs.forEach((key) => {
if (insertValues[key] && insertValues[key] !== null) {
needIdentityInsertWrapper = true;
}
});
const clauses = where[Op.or].filter((clause) => {
let valid = true;
for (const key in clause) {
if (typeof clause[key] === "undefined" || clause[key] == null) {
valid = false;
break;
}
}
return valid;
});
const getJoinSnippet = (array) => {
return array.map((key) => {
key = this.quoteIdentifier(key);
return `${targetTableAlias}.${key} = ${sourceTableAlias}.${key}`;
});
};
if (clauses.length === 0) {
throw new Error("Primary Key or Unique key should be passed to upsert query");
} else {
for (const key in clauses) {
const keys = Object.keys(clauses[key]);
if (primaryKeysAttrs.includes(keys[0])) {
joinCondition = getJoinSnippet(primaryKeysAttrs).join(" AND ");
break;
}
}
if (!joinCondition) {
joinCondition = getJoinSnippet(uniqueAttrs).join(" AND ");
}
}
const filteredUpdateClauses = updateKeys.filter((key) => !identityAttrs.includes(key)).map((key) => {
const value = this.escape(updateValues[key]);
key = this.quoteIdentifier(key);
return `${targetTableAlias}.${key} = ${value}`;
});
const updateSnippet = filteredUpdateClauses.length > 0 ? `WHEN MATCHED THEN UPDATE SET ${filteredUpdateClauses.join(", ")}` : "";
const insertSnippet = `(${insertKeysQuoted}) VALUES(${insertValuesEscaped})`;
let query = `MERGE INTO ${tableNameQuoted} WITH(HOLDLOCK) AS ${targetTableAlias} USING (${sourceTableQuery}) AS ${sourceTableAlias}(${insertKeysQuoted}) ON ${joinCondition}`;
query += ` ${updateSnippet} WHEN NOT MATCHED THEN INSERT ${insertSnippet} OUTPUT $action, INSERTED.*;`;
if (needIdentityInsertWrapper) {
query = `SET IDENTITY_INSERT ${tableNameQuoted} ON; ${query} SET IDENTITY_INSERT ${tableNameQuoted} OFF;`;
}
return query;
}
truncateTableQuery(tableName) {
return `TRUNCATE TABLE ${this.quoteTable(tableName)}`;
}
deleteQuery(tableName, where, options = {}, model) {
const table = this.quoteTable(tableName);
const whereClause = this.getWhereConditions(where, null, model, options);
return Utils.joinSQLFragments([
"DELETE",
options.limit && `TOP(${this.escape(options.limit)})`,
"FROM",
table,
whereClause && `WHERE ${whereClause}`,
";",
"SELECT @@ROWCOUNT AS AFFECTEDROWS",
";"
]);
}
showIndexesQuery(tableName) {
return `EXEC sys.sp_helpindex @objname = N'${this.quoteTable(tableName)}';`;
}
showConstraintsQuery(tableName) {
return `EXEC sp_helpconstraint @objname = ${this.escape(this.quoteTable(tableName))};`;
}
removeIndexQuery(tableName, indexNameOrAttributes) {
let indexName = indexNameOrAttributes;
if (typeof indexName !== "string") {
indexName = Utils.underscore(`${tableName}_${indexNameOrAttributes.join("_")}`);
}
return `DROP INDEX ${this.quoteIdentifiers(indexName)} ON ${this.quoteIdentifiers(tableName)}`;
}
attributeToSQL(attribute, options) {
if (!_.isPlainObject(attribute)) {
attribute = {
type: attribute
};
}
if (attribute.references) {
if (attribute.Model && attribute.Model.tableName === attribute.references.model) {
this.sequelize.log("MSSQL does not support self referencial constraints, we will remove it but we recommend restructuring your query");
attribute.onDelete = "";
attribute.onUpdate = "";
}
}
let template;
if (attribute.type instanceof DataTypes.ENUM) {
if (attribute.type.values && !attribute.values)
attribute.values = attribute.type.values;
template = attribute.type.toSql();
template += ` CHECK (${this.quoteIdentifier(attribute.field)} IN(${attribute.values.map((value) => {
return this.escape(value);
}).join(", ")}))`;
return template;
}
template = attribute.type.toString();
if (attribute.allowNull === false) {
template += " NOT NULL";
} else if (!attribute.primaryKey && !Utils.defaultValueSchemable(attribute.defaultValue)) {
template += " NULL";
}
if (attribute.autoIncrement) {
template += " IDENTITY(1,1)";
}
if (attribute.type !== "TEXT" && 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 ((!options || !options.withoutForeignKeyConstraints) && attribute.references) {
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()}`;
}
}
if (attribute.comment && typeof attribute.comment === "string") {
template += ` COMMENT ${attribute.comment}`;
}
return template;
}
attributesToSQL(attributes, options) {
const result = {}, existingConstraints = [];
let key, attribute;
for (key in attributes) {
attribute = attributes[key];
if (attribute.references) {
if (existingConstraints.includes(attribute.references.model.toString())) {
attribute.onDelete = "";
attribute.onUpdate = "";
} else {
existingConstraints.push(attribute.references.model.toString());
attribute.onUpdate = "";
}
}
if (key && !attribute.field)
attribute.field = key;
result[attribute.field || key] = this.attributeToSQL(attribute, options);
}
return result;
}
createTrigger() {
throwMethodUndefined("createTrigger");
}
dropTrigger() {
throwMethodUndefined("dropTrigger");
}
renameTrigger() {
throwMethodUndefined("renameTrigger");
}
createFunction() {
throwMethodUndefined("createFunction");
}
dropFunction() {
throwMethodUndefined("dropFunction");
}
renameFunction() {
throwMethodUndefined("renameFunction");
}
_getForeignKeysQueryPrefix(catalogName) {
return `${"SELECT constraint_name = OBJ.NAME, constraintName = OBJ.NAME, "}${catalogName ? `constraintCatalog = '${catalogName}', ` : ""}constraintSchema = SCHEMA_NAME(OBJ.SCHEMA_ID), tableName = TB.NAME, tableSchema = SCHEMA_NAME(TB.SCHEMA_ID), ${catalogName ? `tableCatalog = '${catalogName}', ` : ""}columnName = COL.NAME, referencedTableSchema = SCHEMA_NAME(RTB.SCHEMA_ID), ${catalogName ? `referencedCatalog = '${catalogName}', ` : ""}referencedTableName = RTB.NAME, referencedColumnName = RCOL.NAME FROM sys.foreign_key_columns FKC INNER JOIN sys.objects OBJ ON OBJ.OBJECT_ID = FKC.CONSTRAINT_OBJECT_ID INNER JOIN sys.tables TB ON TB.OBJECT_ID = FKC.PARENT_OBJECT_ID INNER JOIN sys.columns COL ON COL.COLUMN_ID = PARENT_COLUMN_ID AND COL.OBJECT_ID = TB.OBJECT_ID INNER JOIN sys.tables RTB ON RTB.OBJECT_ID = FKC.REFERENCED_OBJECT_ID INNER JOIN sys.columns RCOL ON RCOL.COLUMN_ID = REFERENCED_COLUMN_ID AND RCOL.OBJECT_ID = RTB.OBJECT_ID`;
}
getForeignKeysQuery(table, catalogName) {
const tableName = table.tableName || table;
let sql = `${this._getForeignKeysQueryPrefix(catalogName)} WHERE TB.NAME =${wrapSingleQuote(tableName)}`;
if (table.schema) {
sql += ` AND SCHEMA_NAME(TB.SCHEMA_ID) =${wrapSingleQuote(table.schema)}`;
}
return sql;
}
getForeignKeyQuery(table, attributeName) {
const tableName = table.tableName || table;
return Utils.joinSQLFragments([
this._getForeignKeysQueryPrefix(),
"WHERE",
`TB.NAME =${wrapSingleQuote(tableName)}`,
"AND",
`COL.NAME =${wrapSingleQuote(attributeName)}`,
table.schema && `AND SCHEMA_NAME(TB.SCHEMA_ID) =${wrapSingleQuote(table.schema)}`
]);
}
getPrimaryKeyConstraintQuery(table, attributeName) {
const tableName = wrapSingleQuote(table.tableName || table);
return Utils.joinSQLFragments([
"SELECT K.TABLE_NAME AS tableName,",
"K.COLUMN_NAME AS columnName,",
"K.CONSTRAINT_NAME AS constraintName",
"FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C",
"JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K",
"ON C.TABLE_NAME = K.TABLE_NAME",
"AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG",
"AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA",
"AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME",
"WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'",
`AND K.COLUMN_NAME = ${wrapSingleQuote(attributeName)}`,
`AND K.TABLE_NAME = ${tableName}`,
";"
]);
}
dropForeignKeyQuery(tableName, foreignKey) {
return Utils.joinSQLFragments([
"ALTER TABLE",
this.quoteTable(tableName),
"DROP",
this.quoteIdentifier(foreignKey)
]);
}
getDefaultConstraintQuery(tableName, attributeName) {
const quotedTable = this.quoteTable(tableName);
return Utils.joinSQLFragments([
"SELECT name FROM sys.default_constraints",
`WHERE PARENT_OBJECT_ID = OBJECT_ID('${quotedTable}', 'U')`,
`AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns WHERE NAME = ('${attributeName}')`,
`AND object_id = OBJECT_ID('${quotedTable}', 'U'))`,
";"
]);
}
dropConstraintQuery(tableName, constraintName) {
return Utils.joinSQLFragments([
"ALTER TABLE",
this.quoteTable(tableName),
"DROP CONSTRAINT",
this.quoteIdentifier(constraintName),
";"
]);
}
setIsolationLevelQuery() {
}
generateTransactionId() {
return randomBytes(10).toString("hex");
}
startTransactionQuery(transaction) {
if (transaction.parent) {
return `SAVE TRANSACTION ${this.quoteIdentifier(transaction.name)};`;
}
return "BEGIN TRANSACTION;";
}
commitTransactionQuery(transaction) {
if (transaction.parent) {
return;
}
return "COMMIT TRANSACTION;";
}
rollbackTransactionQuery(transaction) {
if (transaction.parent) {
return `ROLLBACK TRANSACTION ${this.quoteIdentifier(transaction.name)};`;
}
return "ROLLBACK TRANSACTION;";
}
selectFromTableFragment(options, model, attributes, tables, mainTableAs, where) {
this._throwOnEmptyAttributes(attributes, { modelName: model && model.name, as: mainTableAs });
const dbVersion = this.sequelize.options.databaseVersion;
const isSQLServer2008 = semver.valid(dbVersion) && semver.lt(dbVersion, "11.0.0");
if (isSQLServer2008 && options.offset) {
const offset = options.offset || 0;
const isSubQuery = options.hasIncludeWhere || options.hasIncludeRequired || options.hasMultiAssociation;
let orders = { mainQueryOrder: [] };
if (options.order) {
orders = this.getQueryOrders(options, model, isSubQuery);
}
if (orders.mainQueryOrder.length === 0) {
orders.mainQueryOrder.push(this.quoteIdentifier(model.primaryKeyField));
}
const tmpTable = mainTableAs || "OffsetTable";
if (options.include) {
const subQuery = options.subQuery === void 0 ? options.limit && options.hasMultiAssociation : options.subQuery;
const mainTable = {
name: mainTableAs,
quotedName: null,
as: null,
model
};
const topLevelInfo = {
names: mainTable,
options,
subQuery
};
let mainJoinQueries = [];
for (const include of options.include) {
if (include.separate) {
continue;
}
const joinQueries = this.generateInclude(include, { externalAs: mainTableAs, internalAs: mainTableAs }, topLevelInfo);
mainJoinQueries = mainJoinQueries.concat(joinQueries.mainQuery);
}
return Utils.joinSQLFragments([
"SELECT TOP 100 PERCENT",
attributes.join(", "),
"FROM (",
[
"SELECT",
options.limit && `TOP ${options.limit}`,
"* FROM (",
[
"SELECT ROW_NUMBER() OVER (",
[
"ORDER BY",
orders.mainQueryOrder.join(", ")
],
`) as row_num, ${tmpTable}.* FROM (`,
[
"SELECT DISTINCT",
`${tmpTable}.* FROM ${tables} AS ${tmpTable}`,
mainJoinQueries,
where && `WHERE ${where}`
],
`) AS ${tmpTable}`
],
`) AS ${tmpTable} WHERE row_num > ${offset}`
],
`) AS ${tmpTable}`
]);
}
return Utils.joinSQLFragments([
"SELECT TOP 100 PERCENT",
attributes.join(", "),
"FROM (",
[
"SELECT",
options.limit && `TOP ${options.limit}`,
"* FROM (",
[
"SELECT ROW_NUMBER() OVER (",
[
"ORDER BY",
orders.mainQueryOrder.join(", ")
],
`) as row_num, * FROM ${tables} AS ${tmpTable}`,
where && `WHERE ${where}`
],
`) AS ${tmpTable} WHERE row_num > ${offset}`
],
`) AS ${tmpTable}`
]);
}
return Utils.joinSQLFragments([
"SELECT",
isSQLServer2008 && options.limit && `TOP ${options.limit}`,
attributes.join(", "),
`FROM ${tables}`,
mainTableAs && `AS ${mainTableAs}`,
options.tableHint && TableHints[options.tableHint] && `WITH (${TableHints[options.tableHint]})`
]);
}
addLimitAndOffset(options, model) {
if (semver.valid(this.sequelize.options.databaseVersion) && semver.lt(this.sequelize.options.databaseVersion, "11.0.0")) {
return "";
}
const offset = options.offset || 0;
const isSubQuery = options.subQuery === void 0 ? options.hasIncludeWhere || options.hasIncludeRequired || options.hasMultiAssociation : options.subQuery;
let fragment = "";
let orders = {};
if (options.order) {
orders = this.getQueryOrders(options, model, isSubQuery);
}
if (options.limit || options.offset) {
if (!options.order || options.order.length === 0 || options.include && orders.subQueryOrder.length === 0) {
let primaryKey = model.primaryKeyField;
const tablePkFragment = `${this.quoteTable(options.tableAs || model.name)}.${this.quoteIdentifier(primaryKey)}`;
const aliasedAttribute = (options.attributes || []).find((attr) => Array.isArray(attr) && attr[1] && (attr[0] === primaryKey || attr[1] === primaryKey));
if (aliasedAttribute) {
const modelName = this.quoteIdentifier(options.tableAs || model.name);
const alias = this._getAliasForField(modelName, aliasedAttribute[1], options);
primaryKey = new Utils.Col(alias || aliasedAttribute[1]);
}
if (!options.order || !options.order.length) {
fragment += ` ORDER BY ${tablePkFragment}`;
} else {
const orderFieldNames = (options.order || []).map((order) => {
const value = Array.isArray(order) ? order[0] : order;
if (value instanceof Utils.Col) {
return value.col;
}
if (value instanceof Utils.Literal) {
return value.val;
}
return value;
});
const primaryKeyFieldAlreadyPresent = orderFieldNames.some((fieldName) => fieldName === (primaryKey.col || primaryKey));
if (!primaryKeyFieldAlreadyPresent) {
fragment += options.order && !isSubQuery ? ", " : " ORDER BY ";
fragment += tablePkFragment;
}
}
}
if (options.offset || options.limit) {
fragment += ` OFFSET ${this.escape(offset)} ROWS`;
}
if (options.limit) {
fragment += ` FETCH NEXT ${this.escape(options.limit)} ROWS ONLY`;
}
}
return fragment;
}
booleanValue(value) {
return value ? 1 : 0;
}
quoteIdentifier(identifier, force) {
return `[${identifier.replace(/[[\]']+/g, "")}]`;
}
}
function wrapSingleQuote(identifier) {
return Utils.addTicks(Utils.removeTicks(identifier, "'"), "'");
}
module.exports = MSSQLQueryGenerator;
//# sourceMappingURL=query-generator.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/mssql/query-generator.js"],
"sourcesContent": ["'use strict';\n\nconst _ = require('lodash');\nconst Utils = require('../../utils');\nconst DataTypes = require('../../data-types');\nconst TableHints = require('../../table-hints');\nconst AbstractQueryGenerator = require('../abstract/query-generator');\nconst randomBytes = require('crypto').randomBytes;\nconst semver = require('semver');\nconst Op = require('../../operators');\n\n/* istanbul ignore next */\nconst throwMethodUndefined = function(methodName) {\n throw new Error(`The method \"${methodName}\" is not defined! Please add it to your sql dialect.`);\n};\n\nclass MSSQLQueryGenerator extends AbstractQueryGenerator {\n createDatabaseQuery(databaseName, options) {\n options = { collate: null, ...options };\n\n const collation = options.collate ? `COLLATE ${this.escape(options.collate)}` : '';\n\n return [\n 'IF NOT EXISTS (SELECT * FROM sys.databases WHERE name =', wrapSingleQuote(databaseName), ')',\n 'BEGIN',\n 'CREATE DATABASE', this.quoteIdentifier(databaseName),\n `${collation};`,\n 'END;'\n ].join(' ');\n }\n\n dropDatabaseQuery(databaseName) {\n return [\n 'IF EXISTS (SELECT * FROM sys.databases WHERE name =', wrapSingleQuote(databaseName), ')',\n 'BEGIN',\n 'DROP DATABASE', this.quoteIdentifier(databaseName), ';',\n 'END;'\n ].join(' ');\n }\n\n createSchema(schema) {\n return [\n 'IF NOT EXISTS (SELECT schema_name',\n 'FROM information_schema.schemata',\n 'WHERE schema_name =', wrapSingleQuote(schema), ')',\n 'BEGIN',\n \"EXEC sp_executesql N'CREATE SCHEMA\",\n this.quoteIdentifier(schema),\n \";'\",\n 'END;'\n ].join(' ');\n }\n\n dropSchema(schema) {\n // Mimics Postgres CASCADE, will drop objects belonging to the schema\n const quotedSchema = wrapSingleQuote(schema);\n return [\n 'IF EXISTS (SELECT schema_name',\n 'FROM information_schema.schemata',\n 'WHERE schema_name =', quotedSchema, ')',\n 'BEGIN',\n 'DECLARE @id INT, @ms_sql NVARCHAR(2000);',\n 'DECLARE @cascade TABLE (',\n 'id INT NOT NULL IDENTITY PRIMARY KEY,',\n 'ms_sql NVARCHAR(2000) NOT NULL );',\n 'INSERT INTO @cascade ( ms_sql )',\n \"SELECT CASE WHEN o.type IN ('F','PK')\",\n \"THEN N'ALTER TABLE ['+ s.name + N'].[' + p.name + N'] DROP CONSTRAINT [' + o.name + N']'\",\n \"ELSE N'DROP TABLE ['+ s.name + N'].[' + o.name + N']' END\",\n 'FROM sys.objects o',\n 'JOIN sys.schemas s on o.schema_id = s.schema_id',\n 'LEFT OUTER JOIN sys.objects p on o.parent_object_id = p.object_id',\n \"WHERE o.type IN ('F', 'PK', 'U') AND s.name = \", quotedSchema,\n 'ORDER BY o.type ASC;',\n 'SELECT TOP 1 @id = id, @ms_sql = ms_sql FROM @cascade ORDER BY id;',\n 'WHILE @id IS NOT NULL',\n 'BEGIN',\n 'BEGIN TRY EXEC sp_executesql @ms_sql; END TRY',\n 'BEGIN CATCH BREAK; THROW; END CATCH;',\n 'DELETE FROM @cascade WHERE id = @id;',\n 'SELECT @id = NULL, @ms_sql = NULL;',\n 'SELECT TOP 1 @id = id, @ms_sql = ms_sql FROM @cascade ORDER BY id;',\n 'END',\n \"EXEC sp_executesql N'DROP SCHEMA\", this.quoteIdentifier(schema), \";'\",\n 'END;'\n ].join(' ');\n }\n\n showSchemasQuery() {\n return [\n 'SELECT \"name\" as \"schema_name\" FROM sys.schemas as s',\n 'WHERE \"s\".\"name\" NOT IN (',\n \"'INFORMATION_SCHEMA', 'dbo', 'guest', 'sys', 'archive'\",\n ')', 'AND', '\"s\".\"name\" NOT LIKE', \"'db_%'\"\n ].join(' ');\n }\n\n versionQuery() {\n // Uses string manipulation to convert the MS Maj.Min.Patch.Build to semver Maj.Min.Patch\n return [\n 'DECLARE @ms_ver NVARCHAR(20);',\n \"SET @ms_ver = REVERSE(CONVERT(NVARCHAR(20), SERVERPROPERTY('ProductVersion')));\",\n \"SELECT REVERSE(SUBSTRING(@ms_ver, CHARINDEX('.', @ms_ver)+1, 20)) AS 'version'\"\n ].join(' ');\n }\n\n createTableQuery(tableName, attributes, options) {\n const primaryKeys = [],\n foreignKeys = {},\n attributesClauseParts = [];\n\n let commentStr = '';\n\n for (const attr in attributes) {\n if (Object.prototype.hasOwnProperty.call(attributes, attr)) {\n let dataType = attributes[attr];\n let match;\n\n if (dataType.includes('COMMENT ')) {\n const commentMatch = dataType.match(/^(.+) (COMMENT.*)$/);\n const commentText = commentMatch[2].replace('COMMENT', '').trim();\n commentStr += this.commentTemplate(commentText, tableName, attr);\n // remove comment related substring from dataType\n dataType = commentMatch[1];\n }\n\n if (dataType.includes('PRIMARY KEY')) {\n primaryKeys.push(attr);\n\n if (dataType.includes('REFERENCES')) {\n // MSSQL doesn't support inline REFERENCES declarations: move to the end\n match = dataType.match(/^(.+) (REFERENCES.*)$/);\n attributesClauseParts.push(`${this.quoteILine truncated
"mappings": ";;;;;;;;;;;;;;;;;AAEA,MAAM,IAAI,QAAQ;AAClB,MAAM,QAAQ,QAAQ;AACtB,MAAM,YAAY,QAAQ;AAC1B,MAAM,aAAa,QAAQ;AAC3B,MAAM,yBAAyB,QAAQ;AACvC,MAAM,cAAc,QAAQ,UAAU;AACtC,MAAM,SAAS,QAAQ;AACvB,MAAM,KAAK,QAAQ;AAGnB,MAAM,uBAAuB,SAAS,YAAY;AAChD,QAAM,IAAI,MAAM,eAAe;AAAA;AAGjC,kCAAkC,uBAAuB;AAAA,EACvD,oBAAoB,cAAc,SAAS;AACzC,cAAU,iBAAE,SAAS,QAAS;AAE9B,UAAM,Y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BAAqB;AAAA,aAC5F;AACL,mBAAW,KAAK,GAAG,kBAAkB;AAAA;AAAA;AAIzC,WAAO,MAAM,iBAAiB;AAAA,MAC5B;AAAA,MACA,KAAK,WAAW;AAAA,MAChB,WAAW,UAAU,gBAAgB,WAAW,KAAK;AAAA,MACrD,iBAAiB,UAAU,OAAO,iBAAiB,KAAK;AAAA,MACxD;AAAA,MACA;AAAA;AAAA;AAAA,EAIJ,kBAAkB,WAAW,YAAY,YAAY;AACnD,UAAM,UAAU,OAAO,KAAK,YAAY;AACxC,WAAO,MAAM,iBAAiB;AAAA,MAC5B;AAAA,MACA,IAAI,KAAK,WAAW,cAAc;AAAA,MAClC,IAAI;AAAA,MACJ;AAAA,MACA;AAAA;AAAA;AAAA,EAIJ,gBAAgB,WAAW,iBAAiB,SAAS,YAAY;AAC/D,UALine truncated
"names": []
}
+74
View File
@@ -0,0 +1,74 @@
"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 _ = require("lodash");
const Utils = require("../../utils");
const QueryTypes = require("../../query-types");
const Op = require("../../operators");
const { QueryInterface } = require("../abstract/query-interface");
class MSSqlQueryInterface extends QueryInterface {
async removeColumn(tableName, attributeName, options) {
options = __spreadValues({ raw: true }, options || {});
const findConstraintSql = this.queryGenerator.getDefaultConstraintQuery(tableName, attributeName);
const [results0] = await this.sequelize.query(findConstraintSql, options);
if (results0.length) {
const dropConstraintSql = this.queryGenerator.dropConstraintQuery(tableName, results0[0].name);
await this.sequelize.query(dropConstraintSql, options);
}
const findForeignKeySql = this.queryGenerator.getForeignKeyQuery(tableName, attributeName);
const [results] = await this.sequelize.query(findForeignKeySql, options);
if (results.length) {
const dropForeignKeySql = this.queryGenerator.dropForeignKeyQuery(tableName, results[0].constraint_name);
await this.sequelize.query(dropForeignKeySql, options);
}
const primaryKeyConstraintSql = this.queryGenerator.getPrimaryKeyConstraintQuery(tableName, attributeName);
const [result] = await this.sequelize.query(primaryKeyConstraintSql, options);
if (result.length) {
const dropConstraintSql = this.queryGenerator.dropConstraintQuery(tableName, result[0].constraintName);
await this.sequelize.query(dropConstraintSql, options);
}
const removeSql = this.queryGenerator.removeColumnQuery(tableName, attributeName);
return this.sequelize.query(removeSql, options);
}
async upsert(tableName, insertValues, updateValues, where, options) {
const model = options.model;
const wheres = [];
options = __spreadValues({}, options);
if (!Utils.isWhereEmpty(where)) {
wheres.push(where);
}
let indexes = Object.values(model.uniqueKeys).map((item) => item.fields);
indexes = indexes.concat(Object.values(model._indexes).filter((item) => item.unique).map((item) => item.fields));
const attributes = Object.keys(insertValues);
for (const index of indexes) {
if (_.intersection(attributes, index).length === index.length) {
where = {};
for (const field of index) {
where[field] = insertValues[field];
}
wheres.push(where);
}
}
where = { [Op.or]: wheres };
options.type = QueryTypes.UPSERT;
options.raw = true;
const sql = this.queryGenerator.upsertQuery(tableName, insertValues, updateValues, where, model, options);
return await this.sequelize.query(sql, options);
}
}
exports.MSSqlQueryInterface = MSSqlQueryInterface;
//# sourceMappingURL=query-interface.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/mssql/query-interface.js"],
"sourcesContent": ["'use strict';\n\nconst _ = require('lodash');\n\nconst Utils = require('../../utils');\nconst QueryTypes = require('../../query-types');\nconst Op = require('../../operators');\nconst { QueryInterface } = require('../abstract/query-interface');\n\n/**\n * The interface that Sequelize uses to talk with MSSQL database\n */\nclass MSSqlQueryInterface extends QueryInterface {\n /**\n * A wrapper that fixes MSSQL's inability to cleanly remove columns from existing tables if they have a default constraint.\n *\n * @override\n */\n async removeColumn(tableName, attributeName, options) {\n options = { raw: true, ...options || {} };\n\n const findConstraintSql = this.queryGenerator.getDefaultConstraintQuery(tableName, attributeName);\n const [results0] = await this.sequelize.query(findConstraintSql, options);\n if (results0.length) {\n // No default constraint found -- we can cleanly remove the column\n const dropConstraintSql = this.queryGenerator.dropConstraintQuery(tableName, results0[0].name);\n await this.sequelize.query(dropConstraintSql, options);\n }\n const findForeignKeySql = this.queryGenerator.getForeignKeyQuery(tableName, attributeName);\n const [results] = await this.sequelize.query(findForeignKeySql, options);\n if (results.length) {\n // No foreign key constraints found, so we can remove the column\n const dropForeignKeySql = this.queryGenerator.dropForeignKeyQuery(tableName, results[0].constraint_name);\n await this.sequelize.query(dropForeignKeySql, options);\n }\n //Check if the current column is a primaryKey\n const primaryKeyConstraintSql = this.queryGenerator.getPrimaryKeyConstraintQuery(tableName, attributeName);\n const [result] = await this.sequelize.query(primaryKeyConstraintSql, options);\n if (result.length) {\n const dropConstraintSql = this.queryGenerator.dropConstraintQuery(tableName, result[0].constraintName);\n await this.sequelize.query(dropConstraintSql, options);\n }\n const removeSql = this.queryGenerator.removeColumnQuery(tableName, attributeName);\n return this.sequelize.query(removeSql, options);\n }\n\n /**\n * @override\n */\n async upsert(tableName, insertValues, updateValues, where, options) {\n const model = options.model;\n const wheres = [];\n\n options = { ...options };\n\n if (!Utils.isWhereEmpty(where)) {\n wheres.push(where);\n }\n\n // Lets combine unique keys and indexes into one\n let indexes = Object.values(model.uniqueKeys).map(item => item.fields);\n indexes = indexes.concat(Object.values(model._indexes).filter(item => item.unique).map(item => item.fields));\n\n const attributes = Object.keys(insertValues);\n for (const index of indexes) {\n if (_.intersection(attributes, index).length === index.length) {\n where = {};\n for (const field of index) {\n where[field] = insertValues[field];\n }\n wheres.push(where);\n }\n }\n\n where = { [Op.or]: wheres };\n\n options.type = QueryTypes.UPSERT;\n options.raw = true;\n\n const sql = this.queryGenerator.upsertQuery(tableName, insertValues, updateValues, where, model, options);\n return await this.sequelize.query(sql, options);\n }\n}\n\nexports.MSSqlQueryInterface = MSSqlQueryInterface;\n"],
"mappings": ";;;;;;;;;;;;;;;;;AAEA,MAAM,IAAI,QAAQ;AAElB,MAAM,QAAQ,QAAQ;AACtB,MAAM,aAAa,QAAQ;AAC3B,MAAM,KAAK,QAAQ;AACnB,MAAM,EAAE,mBAAmB,QAAQ;AAKnC,kCAAkC,eAAe;AAAA,QAMzC,aAAa,WAAW,eAAe,SAAS;AACpD,cAAU,iBAAE,KAAK,QAAS,WAAW;AAErC,UAAM,oBAAoB,KAAK,eAAe,0BAA0B,WAAW;AACnF,UAAM,CAAC,YAAY,MAAM,KAAK,UAAU,MAAM,mBAAmB;AACjE,QAAI,SAAS,QAAQ;AAEnB,YAAM,oBAAoB,KAAK,eAAe,oBAAoB,WAAW,SAAS,GAAG;AACzF,YAAM,KAAK,UAAU,MAAM,mBAAmB;AAAA;AAEhD,UAAM,oBAAoB,KAAK,eAAe,mBAAmB,WAAW;AAC5E,UAAM,CAAC,WAAW,MAAM,KAAK,UAAU,MAAM,mBAAmB;AAChE,QAAI,QAAQ,QAAQ;AAElB,YAAM,oBAAoB,KAAK,eAAe,oBAAoB,WAAW,QAAQ,GAAG;AACxF,YAAM,KAAK,UAAU,MAAM,mBAAmB;AAAA;AAGhD,UAAM,0BAA0B,KAAK,eAAe,6BAA6B,WAAW;AAC5F,UAAM,CAAC,UAAU,MAAM,KAAK,UAAU,MAAM,yBAAyB;AACrE,QAAI,OAAO,QAAQ;AACjB,YAAM,oBAAoB,KAAK,eAAe,oBAAoB,WAAW,OAAO,GAAG;AACvF,YAAM,KAAK,UAAU,MAAM,mBAAmB;AAAA;AAEhD,UAAM,YAAY,KAAK,eAAe,kBAAkB,WAAW;AACnE,WAAO,KAAK,UAAU,MAAM,WAAW;AAAA;AAAA,QAMnC,OAAO,WAAW,cAAc,cAAc,OAAO,SAAS;AAClE,UAAM,QAAQ,QAAQ;AACtB,UAAM,SAAS;AAEf,cAAU,mBAAK;AAEf,QAAI,CAAC,MAAM,aAAa,QAAQ;AAC9B,aAAO,KAAK;AAAA;AAId,QAAI,UAAU,OAAO,OAAO,MAAM,YAAY,IAAI,UAAQ,KAAK;AAC/D,cAAU,QAAQ,OAAO,OAAO,OAAO,MAAM,UAAU,OAAO,UAAQ,KAAK,QAAQ,IAAI,UAAQ,KAAK;AAEpG,UAAM,aAAa,OAAO,KAAK;AAC/B,eAAW,SAAS,SAAS;AAC3B,UAAI,EAAE,aAAa,YAAY,OAAO,WAAW,MAAM,QAAQ;AAC7D,gBAAQ;AACR,mBAAW,SAAS,OAAO;AACzB,gBAAM,SAAS,aAAa;AAAA;AAE9B,eAAO,KAAK;AAAA;AAAA;AAIhB,YAAQ,GAAG,GAAG,KAAK;AAEnB,YAAQ,OAAO,WAAW;AAC1B,YAAQ,MAAM;AAEd,UAAM,MAAM,KAAK,eAAe,YAAY,WAAW,cAAc,cAAc,OAAO,OAAO;AACjG,WAAO,MAAM,KAAK,UAAU,MAAM,KAAK;AAAA;AAAA;AAI3C,QAAQ,sBAAsB;",
"names": []
}
+330
View File
@@ -0,0 +1,330 @@
"use strict";
const AbstractQuery = require("../abstract/query");
const sequelizeErrors = require("../../errors");
const parserStore = require("../parserStore")("mssql");
const _ = require("lodash");
const { logger } = require("../../utils/logger");
const debug = logger.debugContext("sql:mssql");
const minSafeIntegerAsBigInt = BigInt(Number.MIN_SAFE_INTEGER);
const maxSafeIntegerAsBigInt = BigInt(Number.MAX_SAFE_INTEGER);
function getScale(aNum) {
if (!Number.isFinite(aNum))
return 0;
let e = 1;
while (Math.round(aNum * e) / e !== aNum)
e *= 10;
return Math.log10(e);
}
class Query extends AbstractQuery {
getInsertIdField() {
return "id";
}
getSQLTypeFromJsType(value, TYPES) {
const paramType = { type: TYPES.NVarChar, typeOptions: {}, value };
if (typeof value === "number") {
if (Number.isInteger(value)) {
if (value >= -2147483648 && value <= 2147483647) {
paramType.type = TYPES.Int;
} else {
paramType.type = TYPES.BigInt;
}
} else {
paramType.type = TYPES.Numeric;
paramType.typeOptions = { precision: 30, scale: getScale(value) };
}
} else if (typeof value === "bigint") {
if (value < minSafeIntegerAsBigInt || value > maxSafeIntegerAsBigInt) {
paramType.type = TYPES.VarChar;
paramType.value = value.toString();
} else {
return this.getSQLTypeFromJsType(Number(value), TYPES);
}
} else if (typeof value === "boolean") {
paramType.type = TYPES.Bit;
}
if (Buffer.isBuffer(value)) {
paramType.type = TYPES.VarBinary;
}
return paramType;
}
async _run(connection, sql, parameters, errStack) {
this.sql = sql;
const { options } = this;
const complete = this._logQuery(sql, debug, parameters);
const query = new Promise((resolve, reject) => {
if (sql.startsWith("BEGIN TRANSACTION")) {
return connection.beginTransaction((error) => error ? reject(error) : resolve([]), options.transaction.name, connection.lib.ISOLATION_LEVEL[options.isolationLevel]);
}
if (sql.startsWith("COMMIT TRANSACTION")) {
return connection.commitTransaction((error) => error ? reject(error) : resolve([]));
}
if (sql.startsWith("ROLLBACK TRANSACTION")) {
return connection.rollbackTransaction((error) => error ? reject(error) : resolve([]), options.transaction.name);
}
if (sql.startsWith("SAVE TRANSACTION")) {
return connection.saveTransaction((error) => error ? reject(error) : resolve([]), options.transaction.name);
}
const rows2 = [];
const request = new connection.lib.Request(sql, (err, rowCount2) => err ? reject(err) : resolve([rows2, rowCount2]));
if (parameters) {
_.forOwn(parameters, (value, key) => {
const paramType = this.getSQLTypeFromJsType(value, connection.lib.TYPES);
request.addParameter(key, paramType.type, value, paramType.typeOptions);
});
}
request.on("row", (columns) => {
rows2.push(columns);
});
connection.execSql(request);
});
let rows, rowCount;
try {
[rows, rowCount] = await query;
} catch (err) {
err.sql = sql;
err.parameters = parameters;
throw this.formatError(err, errStack);
}
complete();
if (Array.isArray(rows)) {
rows = rows.map((columns) => {
const row = {};
for (const column of columns) {
const typeid = column.metadata.type.id;
const parse = parserStore.get(typeid);
let value = column.value;
if (value !== null & !!parse) {
value = parse(value);
}
row[column.metadata.colName] = value;
}
return row;
});
}
return this.formatResults(rows, rowCount);
}
run(sql, parameters) {
const errForStack = new Error();
return this.connection.queue.enqueue(() => this._run(this.connection, sql, parameters, errForStack.stack));
}
static formatBindParameters(sql, values, dialect) {
const bindParam = {};
const replacementFunc = (match, key, values2) => {
if (values2[key] !== void 0) {
bindParam[key] = values2[key];
return `@${key}`;
}
return void 0;
};
sql = AbstractQuery.formatBindParameters(sql, values, dialect, replacementFunc)[0];
return [sql, bindParam];
}
formatResults(data, rowCount) {
if (this.isInsertQuery(data)) {
this.handleInsertQuery(data);
return [this.instance || data, rowCount];
}
if (this.isShowTablesQuery()) {
return this.handleShowTablesQuery(data);
}
if (this.isDescribeQuery()) {
const result = {};
for (const _result of data) {
if (_result.Default) {
_result.Default = _result.Default.replace("('", "").replace("')", "").replace(/'/g, "");
}
result[_result.Name] = {
type: _result.Type.toUpperCase(),
allowNull: _result.IsNull === "YES" ? true : false,
defaultValue: _result.Default,
primaryKey: _result.Constraint === "PRIMARY KEY",
autoIncrement: _result.IsIdentity === 1,
comment: _result.Comment
};
if (result[_result.Name].type.includes("CHAR") && _result.Length) {
if (_result.Length === -1) {
result[_result.Name].type += "(MAX)";
} else {
result[_result.Name].type += `(${_result.Length})`;
}
}
}
return result;
}
if (this.isSelectQuery()) {
return this.handleSelectQuery(data);
}
if (this.isShowIndexesQuery()) {
return this.handleShowIndexesQuery(data);
}
if (this.isCallQuery()) {
return data[0];
}
if (this.isBulkUpdateQuery()) {
if (this.options.returning) {
return this.handleSelectQuery(data);
}
return rowCount;
}
if (this.isBulkDeleteQuery()) {
return data[0] ? data[0].AFFECTEDROWS : 0;
}
if (this.isVersionQuery()) {
return data[0].version;
}
if (this.isForeignKeysQuery()) {
return data;
}
if (this.isUpsertQuery()) {
if (data && data.length === 0) {
return [this.instance || data, false];
}
this.handleInsertQuery(data);
return [this.instance || data, data[0].$action === "INSERT"];
}
if (this.isUpdateQuery()) {
return [this.instance || data, rowCount];
}
if (this.isShowConstraintsQuery()) {
return this.handleShowConstraintsQuery(data);
}
if (this.isRawQuery()) {
return [data, rowCount];
}
return data;
}
handleShowTablesQuery(results) {
return results.map((resultSet) => {
return {
tableName: resultSet.TABLE_NAME,
schema: resultSet.TABLE_SCHEMA
};
});
}
handleShowConstraintsQuery(data) {
return data.slice(1).map((result) => {
const constraint = {};
for (const key in result) {
constraint[_.camelCase(key)] = result[key];
}
return constraint;
});
}
formatError(err, errStack) {
let match;
match = err.message.match(/Violation of (?:UNIQUE|PRIMARY) KEY constraint '([^']*)'. Cannot insert duplicate key in object '.*'.(:? The duplicate key value is \((.*)\).)?/);
match = match || err.message.match(/Cannot insert duplicate key row in object .* with unique index '(.*)'/);
if (match && match.length > 1) {
let fields = {};
const uniqueKey = this.model && this.model.uniqueKeys[match[1]];
let message = "Validation error";
if (uniqueKey && !!uniqueKey.msg) {
message = uniqueKey.msg;
}
if (match[3]) {
const values = match[3].split(",").map((part) => part.trim());
if (uniqueKey) {
fields = _.zipObject(uniqueKey.fields, values);
} else {
fields[match[1]] = match[3];
}
}
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 });
}
match = err.message.match(/Failed on step '(.*)'.Could not create constraint. See previous errors./) || err.message.match(/The DELETE statement conflicted with the REFERENCE constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./) || err.message.match(/The (?:INSERT|MERGE|UPDATE) statement conflicted with the FOREIGN KEY constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./);
if (match && match.length > 0) {
return new sequelizeErrors.ForeignKeyConstraintError({
fields: null,
index: match[1],
parent: err,
stack: errStack
});
}
match = err.message.match(/Could not drop constraint. See previous errors./);
if (match && match.length > 0) {
let constraint = err.sql.match(/(?:constraint|index) \[(.+?)\]/i);
constraint = constraint ? constraint[1] : void 0;
let table = err.sql.match(/table \[(.+?)\]/i);
table = table ? table[1] : void 0;
return new sequelizeErrors.UnknownConstraintError({
message: match[1],
constraint,
table,
parent: err,
stack: errStack
});
}
return new sequelizeErrors.DatabaseError(err, { stack: errStack });
}
isShowOrDescribeQuery() {
let result = false;
result = result || this.sql.toLowerCase().startsWith("select c.column_name as 'name', c.data_type as 'type', c.is_nullable as 'isnull'");
result = result || this.sql.toLowerCase().startsWith("select tablename = t.name, name = ind.name,");
result = result || this.sql.toLowerCase().startsWith("exec sys.sp_helpindex @objname");
return result;
}
isShowIndexesQuery() {
return this.sql.toLowerCase().startsWith("exec sys.sp_helpindex @objname");
}
handleShowIndexesQuery(data) {
data = data.reduce((acc, item) => {
if (!(item.index_name in acc)) {
acc[item.index_name] = item;
item.fields = [];
}
item.index_keys.split(",").forEach((column) => {
let columnName = column.trim();
if (columnName.includes("(-)")) {
columnName = columnName.replace("(-)", "");
}
acc[item.index_name].fields.push({
attribute: columnName,
length: void 0,
order: column.includes("(-)") ? "DESC" : "ASC",
collate: void 0
});
});
delete item.index_keys;
return acc;
}, {});
return _.map(data, (item) => ({
primary: item.index_name.toLowerCase().startsWith("pk"),
fields: item.fields,
name: item.index_name,
tableName: void 0,
unique: item.index_description.toLowerCase().includes("unique"),
type: void 0
}));
}
handleInsertQuery(results, metaData) {
if (this.instance) {
const autoIncrementAttribute = this.model.autoIncrementAttribute;
let id = null;
let autoIncrementAttributeAlias = null;
if (Object.prototype.hasOwnProperty.call(this.model.rawAttributes, autoIncrementAttribute) && this.model.rawAttributes[autoIncrementAttribute].field !== void 0)
autoIncrementAttributeAlias = this.model.rawAttributes[autoIncrementAttribute].field;
id = id || results && results[0][this.getInsertIdField()];
id = id || metaData && metaData[this.getInsertIdField()];
id = id || results && results[0][autoIncrementAttribute];
id = id || autoIncrementAttributeAlias && results && results[0][autoIncrementAttributeAlias];
this.instance[autoIncrementAttribute] = id;
if (this.instance.dataValues) {
for (const key in results[0]) {
if (Object.prototype.hasOwnProperty.call(results[0], key)) {
const record = results[0][key];
const attr = _.find(this.model.rawAttributes, (attribute) => attribute.fieldName === key || attribute.field === key);
this.instance.dataValues[attr && attr.fieldName || key] = record;
}
}
}
}
}
}
module.exports = Query;
module.exports.Query = Query;
module.exports.default = Query;
//# sourceMappingURL=query.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/mssql/query.js"],
"sourcesContent": ["'use strict';\n\nconst AbstractQuery = require('../abstract/query');\nconst sequelizeErrors = require('../../errors');\nconst parserStore = require('../parserStore')('mssql');\nconst _ = require('lodash');\nconst { logger } = require('../../utils/logger');\n\nconst debug = logger.debugContext('sql:mssql');\n\nconst minSafeIntegerAsBigInt = BigInt(Number.MIN_SAFE_INTEGER);\nconst maxSafeIntegerAsBigInt = BigInt(Number.MAX_SAFE_INTEGER);\n\nfunction getScale(aNum) {\n if (!Number.isFinite(aNum)) return 0;\n let e = 1;\n while (Math.round(aNum * e) / e !== aNum) e *= 10;\n return Math.log10(e);\n}\n\nclass Query extends AbstractQuery {\n getInsertIdField() {\n return 'id';\n }\n\n getSQLTypeFromJsType(value, TYPES) {\n const paramType = { type: TYPES.NVarChar, typeOptions: {}, value };\n if (typeof value === 'number') {\n if (Number.isInteger(value)) {\n if (value >= -2147483648 && value <= 2147483647) {\n paramType.type = TYPES.Int;\n } else {\n paramType.type = TYPES.BigInt;\n }\n } else {\n paramType.type = TYPES.Numeric;\n //Default to a reasonable numeric precision/scale pending more sophisticated logic\n paramType.typeOptions = { precision: 30, scale: getScale(value) };\n }\n } else if (typeof value === 'bigint') {\n if (value < minSafeIntegerAsBigInt || value > maxSafeIntegerAsBigInt) {\n paramType.type = TYPES.VarChar;\n paramType.value = value.toString();\n } else {\n return this.getSQLTypeFromJsType(Number(value), TYPES);\n }\n } else if (typeof value === 'boolean') {\n paramType.type = TYPES.Bit;\n }\n if (Buffer.isBuffer(value)) {\n paramType.type = TYPES.VarBinary;\n }\n return paramType;\n }\n\n async _run(connection, sql, parameters, errStack) {\n this.sql = sql;\n const { options } = this;\n\n const complete = this._logQuery(sql, debug, parameters);\n\n const query = new Promise((resolve, reject) => {\n // TRANSACTION SUPPORT\n if (sql.startsWith('BEGIN TRANSACTION')) {\n return connection.beginTransaction(error => error ? reject(error) : resolve([]), options.transaction.name, connection.lib.ISOLATION_LEVEL[options.isolationLevel]);\n }\n if (sql.startsWith('COMMIT TRANSACTION')) {\n return connection.commitTransaction(error => error ? reject(error) : resolve([]));\n }\n if (sql.startsWith('ROLLBACK TRANSACTION')) {\n return connection.rollbackTransaction(error => error ? reject(error) : resolve([]), options.transaction.name);\n }\n if (sql.startsWith('SAVE TRANSACTION')) {\n return connection.saveTransaction(error => error ? reject(error) : resolve([]), options.transaction.name);\n }\n\n const rows = [];\n const request = new connection.lib.Request(sql, (err, rowCount) => err ? reject(err) : resolve([rows, rowCount]));\n\n if (parameters) {\n _.forOwn(parameters, (value, key) => {\n const paramType = this.getSQLTypeFromJsType(value, connection.lib.TYPES);\n request.addParameter(key, paramType.type, value, paramType.typeOptions);\n });\n }\n\n request.on('row', columns => {\n rows.push(columns);\n });\n\n connection.execSql(request);\n });\n\n let rows, rowCount;\n\n try {\n [rows, rowCount] = await query;\n } catch (err) {\n err.sql = sql;\n err.parameters = parameters;\n\n throw this.formatError(err, errStack);\n }\n\n complete();\n\n if (Array.isArray(rows)) {\n rows = rows.map(columns => {\n const row = {};\n for (const column of columns) {\n const typeid = column.metadata.type.id;\n const parse = parserStore.get(typeid);\n let value = column.value;\n\n if (value !== null & !!parse) {\n value = parse(value);\n }\n row[column.metadata.colName] = value;\n }\n return row;\n });\n }\n\n return this.formatResults(rows, rowCount);\n }\n\n run(sql, parameters) {\n const errForStack = new Error();\n return this.connection.queue.enqueue(() =>\n this._run(this.connection, sql, parameters, errForStack.stack)\n );\n }\n\n static formatBindParameters(sql, values, dialect) {\n const bindParam = {};\n const replacementFunc = (match, key, values) => {\n if (values[key] !== undefined) {\n bindParam[key] = values[key];\n return `@${key}`;\n }\n return undefined;\n };\n sql = AbstractQuery.formatBindParameters(sql, values, dialect, replacementFunc)[0];\n\n return [sql, bindParam];\n }\n\n /**\n * High level function that handles the results of a query execution.\n *\n * @param {Array} data - The result of the query execution.\n * @param {number} rowCount\n * @private\n * @example\n * Example:\n * query.formatResults([\n * {\n * id: 1, Line truncated
"mappings": ";AAEA,MAAM,gBAAgB,QAAQ;AAC9B,MAAM,kBAAkB,QAAQ;AAChC,MAAM,cAAc,QAAQ,kBAAkB;AAC9C,MAAM,IAAI,QAAQ;AAClB,MAAM,EAAE,WAAW,QAAQ;AAE3B,MAAM,QAAQ,OAAO,aAAa;AAElC,MAAM,yBAAyB,OAAO,OAAO;AAC7C,MAAM,yBAAyB,OAAO,OAAO;AAE7C,kBAAkB,MAAM;AACtB,MAAI,CAAC,OAAO,SAAS;AAAO,WAAO;AACnC,MAAI,IAAI;AACR,SAAO,KAAK,MAAM,OAAO,KAAK,MAAM;AAAM,SAAK;AAC/C,SAAO,KAAK,MAAM;AAAA;AAGpB,oBAAoB,cAAc;AAAA,EAChC,mBAAmB;AACjB,WAAO;AAAA;AAAA,EAGT,qBAAqB,OAAO,OAAO;AACjC,UAAM,YAAY,EAAE,MAAM,MAAM,UAAU,aAAa,IAAI;AAC3D,QAAI,OAAO,UAAU,UAAU;AAC7B,UAAI,OAAO,UAAU,QAAQ;AAC3B,YAAI,SAAS,eAAe,SAAS,YAAY;AAC/C,oBAAU,OAAO,MAAM;AAAA,eAClB;AACL,oBAAU,OAAO,MAAM;AAAA;AAAA,aAEpB;AACL,kBAAU,OAAO,MAAM;AAEvB,kBAAU,cAAc,EAAE,WAAW,IAAI,OAAO,SAAS;AAAA;AAAA,eAElD,OAAO,UAAU,UAAU;AACpC,UAAI,QAAQ,0BAA0B,QAAQ,wBAAwB;AACpE,kBAAU,OAAO,MAAM;AACvB,kBAAU,QAAQ,MAAM;AAAA,aACnB;AACL,eAAO,KAAK,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