This commit is contained in:
2025-10-24 17:06:14 -05:00
parent 12d0690b91
commit df8c75603f
11289 changed files with 1209053 additions and 318 deletions

View File

@@ -0,0 +1,127 @@
"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").snowflake;
const debug = logger.debugContext("connection:snowflake");
const parserStore = require("../parserStore")("snowflake");
class ConnectionManager extends AbstractConnectionManager {
constructor(dialect, sequelize) {
sequelize.config.port = sequelize.config.port || 3306;
super(dialect, sequelize);
this.lib = this._loadDialectModule("snowflake-sdk");
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({
account: config.host,
username: config.username,
password: config.password,
database: config.database,
warehouse: config.warehouse,
role: config.role
}, config.dialectOptions);
try {
const connection = await new Promise((resolve, reject) => {
this.lib.createConnection(connectionConfig).connect((err, conn) => {
if (err) {
console.log(err);
reject(err);
} else {
resolve(conn);
}
});
});
debug("connection acquired");
if (!this.sequelize.config.keepDefaultTimezone) {
const tzOffset = this.sequelize.options.timezone === "+00:00" ? "Etc/UTC" : this.sequelize.options.timezone;
const isNamedTzOffset = /\//.test(tzOffset);
if (isNamedTzOffset) {
await new Promise((resolve, reject) => {
connection.execute({
sqlText: `ALTER SESSION SET timezone = '${tzOffset}'`,
complete(err) {
if (err) {
console.log(err);
reject(err);
} else {
resolve();
}
}
});
});
} else {
throw Error("only support time zone name for snowflake!");
}
}
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.isUp()) {
debug("connection tried to disconnect but was already at CLOSED state");
return;
}
return new Promise((resolve, reject) => {
connection.destroy((err) => {
if (err) {
console.error(`Unable to disconnect: ${err.message}`);
reject(err);
} else {
console.log(`Disconnected connection with id: ${connection.getId()}`);
resolve(connection.getId());
}
});
});
}
validate(connection) {
return connection.isUp();
}
}
module.exports = ConnectionManager;
module.exports.ConnectionManager = ConnectionManager;
module.exports.default = ConnectionManager;
//# sourceMappingURL=connection-manager.js.map

View File

@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/snowflake/connection-manager.js"],
"sourcesContent": ["'use strict';\n\nconst AbstractConnectionManager = require('../abstract/connection-manager');\nconst SequelizeErrors = require('../../errors');\nconst { logger } = require('../../utils/logger');\nconst DataTypes = require('../../data-types').snowflake;\nconst debug = logger.debugContext('connection:snowflake');\nconst parserStore = require('../parserStore')('snowflake');\n\n/**\n * Snowflake Connection Manager\n *\n * Get connections, validate and disconnect them.\n *\n * @private\n */\nclass ConnectionManager extends AbstractConnectionManager {\n constructor(dialect, sequelize) {\n sequelize.config.port = sequelize.config.port || 3306;\n super(dialect, sequelize);\n this.lib = this._loadDialectModule('snowflake-sdk');\n this.refreshTypeParser(DataTypes);\n }\n\n _refreshTypeParser(dataType) {\n parserStore.refresh(dataType);\n }\n\n _clearTypeParser() {\n parserStore.clear();\n }\n\n static _typecast(field, next) {\n if (parserStore.get(field.type)) {\n return parserStore.get(field.type)(field, this.sequelize.options, next);\n }\n return next();\n }\n\n /**\n * Connect with a snowflake database based on config, Handle any errors in connection\n * Set the pool handlers on connection.error\n * Also set proper timezone once connection is connected.\n *\n * @param {object} config\n * @returns {Promise<Connection>}\n * @private\n */\n async connect(config) {\n const connectionConfig = {\n account: config.host,\n username: config.username,\n password: config.password,\n database: config.database,\n warehouse: config.warehouse,\n role: config.role,\n /*\n flags: '-FOUND_ROWS',\n timezone: this.sequelize.options.timezone,\n typeCast: ConnectionManager._typecast.bind(this),\n bigNumberStrings: false,\n supportBigNumbers: true,\n */\n ...config.dialectOptions\n };\n\n try {\n\n const connection = await new Promise((resolve, reject) => {\n this.lib.createConnection(connectionConfig).connect((err, conn) => {\n if (err) {\n console.log(err);\n reject(err);\n } else {\n resolve(conn);\n }\n });\n });\n\n debug('connection acquired');\n\n if (!this.sequelize.config.keepDefaultTimezone) {\n // default value is '+00:00', put a quick workaround for it.\n const tzOffset = this.sequelize.options.timezone === '+00:00' ? 'Etc/UTC' : this.sequelize.options.timezone;\n const isNamedTzOffset = /\\//.test(tzOffset);\n if ( isNamedTzOffset ) {\n await new Promise((resolve, reject) => {\n connection.execute({\n sqlText: `ALTER SESSION SET timezone = '${tzOffset}'`,\n complete(err) {\n if (err) {\n console.log(err);\n reject(err);\n } else {\n resolve();\n }\n }\n });\n });\n } else {\n throw Error('only support time zone name for snowflake!');\n }\n }\n\n return connection;\n } catch (err) {\n switch (err.code) {\n case 'ECONNREFUSED':\n throw new SequelizeErrors.ConnectionRefusedError(err);\n case 'ER_ACCESS_DENIED_ERROR':\n throw new SequelizeErrors.AccessDeniedError(err);\n case 'ENOTFOUND':\n throw new SequelizeErrors.HostNotFoundError(err);\n case 'EHOSTUNREACH':\n throw new SequelizeErrors.HostNotReachableError(err);\n case 'EINVAL':\n throw new SequelizeErrors.InvalidConnectionError(err);\n default:\n throw new SequelizeErrors.ConnectionError(err);\n }\n }\n }\n\n async disconnect(connection) {\n // Don't disconnect connections with CLOSED state\n if (!connection.isUp()) {\n debug('connection tried to disconnect but was already at CLOSED state');\n return;\n }\n\n return new Promise((resolve, reject) => {\n connection.destroy(err => {\n if (err) {\n console.error(`Unable to disconnect: ${err.message}`);\n reject(err);\n } else {\n console.log(`Disconnected connection with id: ${connection.getId()}`);\n resolve(connection.getId());\n }\n });\n });\n }\n\n validate(connection) {\n return connection.isUp();\n }\n}\n\nmodule.exports = ConnectionManager;\nmodule.exports.ConnectionManager = ConnectionManager;\nmodule.exports.default = ConnectionManager;\n"],
"mappings": ";;;;;;;;;;;;;;;;;AAEA,MAAM,4BAA4B,QAAQ;AAC1C,MAAM,kBAAkB,QAAQ;AAChC,MAAM,EAAE,WAAW,QAAQ;AAC3B,MAAM,YAAY,QAAQ,oBAAoB;AAC9C,MAAM,QAAQ,OAAO,aAAa;AAClC,MAAM,cAAc,QAAQ,kBAAkB;AAS9C,gCAAgC,0BAA0B;AAAA,EACxD,YAAY,SAAS,WAAW;AAC9B,cAAU,OAAO,OAAO,UAAU,OAAO,QAAQ;AACjD,UAAM,SAAS;AACf,SAAK,MAAM,KAAK,mBAAmB;AACnC,SAAK,kBAAkB;AAAA;AAAA,EAGzB,mBAAmB,UAAU;AAC3B,gBAAY,QAAQ;AAAA;AAAA,EAGtB,mBAAmB;AACjB,gBAAY;AAAA;AAAA,SAGP,UAAU,OAAO,MAAM;AAC5B,QAAI,YAAY,IAAI,MAAM,OAAO;AAC/B,aAAO,YAAY,IAAI,MAAM,MAAM,OAAO,KAAK,UAAU,SAAS;AAAA;AAEpE,WAAO;AAAA;AAAA,QAYH,QAAQ,QAAQ;AACpB,UAAM,mBAAmB;AAAA,MACvB,SAAS,OAAO;AAAA,MAChB,UAAU,OAAO;AAAA,MACjB,UAAU,OAAO;AAAA,MACjB,UAAU,OAAO;AAAA,MACjB,WAAW,OAAO;AAAA,MAClB,MAAM,OAAO;AAAA,OAQV,OAAO;AAGZ,QAAI;AAEF,YAAM,aAAa,MAAM,IAAI,QAAQ,CAAC,SAAS,WAAW;AACxD,aAAK,IAAI,iBAAiB,kBAAkB,QAAQ,CAAC,KAAK,SAAS;AACjE,cAAI,KAAK;AACP,oBAAQ,IAAI;AACZ,mBAAO;AAAA,iBACF;AACL,oBAAQ;AAAA;AAAA;AAAA;AAKd,YAAM;AAEN,UAAI,CAAC,KAAK,UAAU,OAAO,qBAAqB;AAE9C,cAAM,WAAW,KAAK,UAAU,QAAQ,aAAa,WAAW,YAAY,KAAK,UAAU,QAAQ;AACnG,cAAM,kBAAkB,KAAK,KAAK;AAClC,YAAK,iBAAkB;AACrB,gBAAM,IAAI,QAAQ,CAAC,SAAS,WAAW;AACrC,uBAAW,QAAQ;AAAA,cACjB,SAAS,iCAAiC;AAAA,cAC1C,SAAS,KAAK;AACZ,oBAAI,KAAK;AACP,0BAAQ,IAAI;AACZ,yBAAO;AAAA,uBACF;AACL;AAAA;AAAA;AAAA;AAAA;AAAA,eAKH;AACL,gBAAM,MAAM;AAAA;AAAA;AAIhB,aAAO;AAAA,aACA,KAAP;AACA,cAAQ,IAAI;AAAA,aACL;AACH,gBAAM,IAAI,gBAAgB,uBAAuB;AAAA,aAC9C;AACH,gBAAM,IAAI,gBAAgB,kBAAkB;AAAA,aACzC;AACH,gBAAM,IAAI,gBAAgB,kBAAkB;AAAA,aACzC;AACH,gBAAM,IAAI,gBAAgB,sBAAsB;AAAA,aAC7C;AACH,gBAAM,IAAI,gBAAgB,uBAAuB;AAAA;AAEjD,gBAAM,IAAI,gBAAgB,gBAAgB;AAAA;AAAA;AAAA;AAAA,QAK5C,WAAW,YAAY;AAE3B,QAAI,CAAC,WAAW,QAAQ;AACtB,YAAM;AACN;AAAA;AAGF,WAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,iBAAW,QAAQ,SAAO;AACxB,YAAI,KAAK;AACP,kBAAQ,MAAM,yBAAyB,IAAI;AAC3C,iBAAO;AAAA,eACF;AACL,kBAAQ,IAAI,oCAAoC,WAAW;AAC3D,kBAAQ,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA,EAM3B,SAAS,YAAY;AACnB,WAAO,WAAW;AAAA;AAAA;AAItB,OAAO,UAAU;AACjB,OAAO,QAAQ,oBAAoB;AACnC,OAAO,QAAQ,UAAU;",
"names": []
}

View File

@@ -0,0 +1,87 @@
"use strict";
const momentTz = require("moment-timezone");
const moment = require("moment");
module.exports = (BaseTypes) => {
BaseTypes.ABSTRACT.prototype.dialectTypes = "https://dev.snowflake.com/doc/refman/5.7/en/data-types.html";
BaseTypes.DATE.types.snowflake = ["DATETIME"];
BaseTypes.STRING.types.snowflake = ["VAR_STRING"];
BaseTypes.CHAR.types.snowflake = ["STRING"];
BaseTypes.TEXT.types.snowflake = ["BLOB"];
BaseTypes.TINYINT.types.snowflake = ["TINY"];
BaseTypes.SMALLINT.types.snowflake = ["SHORT"];
BaseTypes.MEDIUMINT.types.snowflake = ["INT24"];
BaseTypes.INTEGER.types.snowflake = ["LONG"];
BaseTypes.BIGINT.types.snowflake = ["LONGLONG"];
BaseTypes.FLOAT.types.snowflake = ["FLOAT"];
BaseTypes.TIME.types.snowflake = ["TIME"];
BaseTypes.DATEONLY.types.snowflake = ["DATE"];
BaseTypes.BOOLEAN.types.snowflake = ["TINY"];
BaseTypes.BLOB.types.snowflake = ["TINYBLOB", "BLOB", "LONGBLOB"];
BaseTypes.DECIMAL.types.snowflake = ["NEWDECIMAL"];
BaseTypes.UUID.types.snowflake = false;
BaseTypes.ENUM.types.snowflake = false;
BaseTypes.REAL.types.snowflake = ["DOUBLE"];
BaseTypes.DOUBLE.types.snowflake = ["DOUBLE"];
BaseTypes.GEOMETRY.types.snowflake = ["GEOMETRY"];
BaseTypes.JSON.types.snowflake = ["JSON"];
class DATE extends BaseTypes.DATE {
toSql() {
return "TIMESTAMP";
}
_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 "VARCHAR(36)";
}
}
class TEXT extends BaseTypes.TEXT {
toSql() {
return "TEXT";
}
}
class BOOLEAN extends BaseTypes.BOOLEAN {
toSql() {
return "BOOLEAN";
}
}
class JSONTYPE extends BaseTypes.JSON {
_stringify(value, options) {
return options.operation === "where" && typeof value === "string" ? value : JSON.stringify(value);
}
}
return {
TEXT,
DATE,
BOOLEAN,
DATEONLY,
UUID,
JSON: JSONTYPE
};
};
//# sourceMappingURL=data-types.js.map

View File

@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/snowflake/data-types.js"],
"sourcesContent": ["'use strict';\n\nconst momentTz = require('moment-timezone');\nconst moment = require('moment');\n\nmodule.exports = BaseTypes => {\n BaseTypes.ABSTRACT.prototype.dialectTypes = 'https://dev.snowflake.com/doc/refman/5.7/en/data-types.html';\n\n /**\n * types: [buffer_type, ...]\n *\n * @see buffer_type here https://dev.snowflake.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.snowflake = ['DATETIME'];\n BaseTypes.STRING.types.snowflake = ['VAR_STRING'];\n BaseTypes.CHAR.types.snowflake = ['STRING'];\n BaseTypes.TEXT.types.snowflake = ['BLOB'];\n BaseTypes.TINYINT.types.snowflake = ['TINY'];\n BaseTypes.SMALLINT.types.snowflake = ['SHORT'];\n BaseTypes.MEDIUMINT.types.snowflake = ['INT24'];\n BaseTypes.INTEGER.types.snowflake = ['LONG'];\n BaseTypes.BIGINT.types.snowflake = ['LONGLONG'];\n BaseTypes.FLOAT.types.snowflake = ['FLOAT'];\n BaseTypes.TIME.types.snowflake = ['TIME'];\n BaseTypes.DATEONLY.types.snowflake = ['DATE'];\n BaseTypes.BOOLEAN.types.snowflake = ['TINY'];\n BaseTypes.BLOB.types.snowflake = ['TINYBLOB', 'BLOB', 'LONGBLOB'];\n BaseTypes.DECIMAL.types.snowflake = ['NEWDECIMAL'];\n BaseTypes.UUID.types.snowflake = false;\n // Enum is not supported\n // https://docs.snowflake.com/en/sql-reference/data-types-unsupported.html\n BaseTypes.ENUM.types.snowflake = false;\n BaseTypes.REAL.types.snowflake = ['DOUBLE'];\n BaseTypes.DOUBLE.types.snowflake = ['DOUBLE'];\n BaseTypes.GEOMETRY.types.snowflake = ['GEOMETRY'];\n BaseTypes.JSON.types.snowflake = ['JSON'];\n\n class DATE extends BaseTypes.DATE {\n toSql() {\n return 'TIMESTAMP';\n }\n _stringify(date, options) {\n if (!moment.isMoment(date)) {\n date = this._applyTimezone(date, options);\n }\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 // https://community.snowflake.com/s/question/0D50Z00009LH2fl/what-is-the-best-way-to-store-uuids\n return 'VARCHAR(36)';\n }\n }\n\n class TEXT extends BaseTypes.TEXT {\n toSql() {\n return 'TEXT';\n }\n }\n\n class BOOLEAN extends BaseTypes.BOOLEAN {\n toSql() {\n return 'BOOLEAN';\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 TEXT,\n DATE,\n BOOLEAN,\n DATEONLY,\n UUID,\n JSON: JSONTYPE\n };\n};\n"],
"mappings": ";AAEA,MAAM,WAAW,QAAQ;AACzB,MAAM,SAAS,QAAQ;AAEvB,OAAO,UAAU,eAAa;AAC5B,YAAU,SAAS,UAAU,eAAe;AAS5C,YAAU,KAAK,MAAM,YAAY,CAAC;AAClC,YAAU,OAAO,MAAM,YAAY,CAAC;AACpC,YAAU,KAAK,MAAM,YAAY,CAAC;AAClC,YAAU,KAAK,MAAM,YAAY,CAAC;AAClC,YAAU,QAAQ,MAAM,YAAY,CAAC;AACrC,YAAU,SAAS,MAAM,YAAY,CAAC;AACtC,YAAU,UAAU,MAAM,YAAY,CAAC;AACvC,YAAU,QAAQ,MAAM,YAAY,CAAC;AACrC,YAAU,OAAO,MAAM,YAAY,CAAC;AACpC,YAAU,MAAM,MAAM,YAAY,CAAC;AACnC,YAAU,KAAK,MAAM,YAAY,CAAC;AAClC,YAAU,SAAS,MAAM,YAAY,CAAC;AACtC,YAAU,QAAQ,MAAM,YAAY,CAAC;AACrC,YAAU,KAAK,MAAM,YAAY,CAAC,YAAY,QAAQ;AACtD,YAAU,QAAQ,MAAM,YAAY,CAAC;AACrC,YAAU,KAAK,MAAM,YAAY;AAGjC,YAAU,KAAK,MAAM,YAAY;AACjC,YAAU,KAAK,MAAM,YAAY,CAAC;AAClC,YAAU,OAAO,MAAM,YAAY,CAAC;AACpC,YAAU,SAAS,MAAM,YAAY,CAAC;AACtC,YAAU,KAAK,MAAM,YAAY,CAAC;AAElC,qBAAmB,UAAU,KAAK;AAAA,IAChC,QAAQ;AACN,aAAO;AAAA;AAAA,IAET,WAAW,MAAM,SAAS;AACxB,UAAI,CAAC,OAAO,SAAS,OAAO;AAC1B,eAAO,KAAK,eAAe,MAAM;AAAA;AAEnC,UAAI,KAAK,SAAS;AAChB,eAAO,KAAK,OAAO;AAAA;AAErB,aAAO,KAAK,OAAO;AAAA;AAAA,WAEd,MAAM,OAAO,SAAS;AAC3B,cAAQ,MAAM;AACd,UAAI,UAAU,MAAM;AAClB,eAAO;AAAA;AAET,UAAI,SAAS,GAAG,KAAK,QAAQ,WAAW;AACtC,gBAAQ,SAAS,GAAG,OAAO,QAAQ,UAAU;AAAA,aAE1C;AACH,gBAAQ,IAAI,KAAK,GAAG,SAAS,QAAQ;AAAA;AAEvC,aAAO;AAAA;AAAA;AAIX,yBAAuB,UAAU,SAAS;AAAA,WACjC,MAAM,OAAO;AAClB,aAAO,MAAM;AAAA;AAAA;AAGjB,qBAAmB,UAAU,KAAK;AAAA,IAChC,QAAQ;AAEN,aAAO;AAAA;AAAA;AAIX,qBAAmB,UAAU,KAAK;AAAA,IAChC,QAAQ;AACN,aAAO;AAAA;AAAA;AAIX,wBAAsB,UAAU,QAAQ;AAAA,IACtC,QAAQ;AACN,aAAO;AAAA;AAAA;AAIX,yBAAuB,UAAU,KAAK;AAAA,IACpC,WAAW,OAAO,SAAS;AACzB,aAAO,QAAQ,cAAc,WAAW,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU;AAAA;AAAA;AAI/F,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,MAAM;AAAA;AAAA;",
"names": []
}

View File

@@ -0,0 +1,59 @@
"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").snowflake;
const { SnowflakeQueryInterface } = require("./query-interface");
class SnowflakeDialect extends AbstractDialect {
constructor(sequelize) {
super();
this.sequelize = sequelize;
this.connectionManager = new ConnectionManager(this, sequelize);
this.queryGenerator = new QueryGenerator({
_dialect: this,
sequelize
});
this.queryInterface = new SnowflakeQueryInterface(sequelize, this.queryGenerator);
}
}
SnowflakeDialect.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: false
},
index: {
collate: false,
length: true,
parser: true,
type: true,
using: 1
},
constraints: {
dropConstraint: false,
check: false
},
indexViaAlter: true,
indexHints: true,
NUMERIC: true,
GEOMETRY: false,
JSON: false,
REGEXP: true,
schemas: true
});
SnowflakeDialect.prototype.defaultVersion = "5.7.0";
SnowflakeDialect.prototype.Query = Query;
SnowflakeDialect.prototype.QueryGenerator = QueryGenerator;
SnowflakeDialect.prototype.DataTypes = DataTypes;
SnowflakeDialect.prototype.name = "snowflake";
SnowflakeDialect.prototype.TICK_CHAR = '"';
SnowflakeDialect.prototype.TICK_CHAR_LEFT = SnowflakeDialect.prototype.TICK_CHAR;
SnowflakeDialect.prototype.TICK_CHAR_RIGHT = SnowflakeDialect.prototype.TICK_CHAR;
module.exports = SnowflakeDialect;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/snowflake/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').snowflake;\nconst { SnowflakeQueryInterface } = require('./query-interface');\n\nclass SnowflakeDialect 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 SnowflakeQueryInterface(sequelize, this.queryGenerator);\n }\n}\n\nSnowflakeDialect.prototype.supports = _.merge(_.cloneDeep(AbstractDialect.prototype.supports), {\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 // disable for now, but could be enable by approach below\n // https://stackoverflow.com/questions/54828745/how-to-migrate-on-conflict-do-nothing-from-postgresql-to-snowflake\n updateOnDuplicate: false\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 // disable for now, need more work to enable the GEOGRAPHY MAPPING\n GEOMETRY: false,\n JSON: false,\n REGEXP: true,\n schemas: true\n});\n\nSnowflakeDialect.prototype.defaultVersion = '5.7.0';\nSnowflakeDialect.prototype.Query = Query;\nSnowflakeDialect.prototype.QueryGenerator = QueryGenerator;\nSnowflakeDialect.prototype.DataTypes = DataTypes;\nSnowflakeDialect.prototype.name = 'snowflake';\nSnowflakeDialect.prototype.TICK_CHAR = '\"';\nSnowflakeDialect.prototype.TICK_CHAR_LEFT = SnowflakeDialect.prototype.TICK_CHAR;\nSnowflakeDialect.prototype.TICK_CHAR_RIGHT = SnowflakeDialect.prototype.TICK_CHAR;\n\nmodule.exports = SnowflakeDialect;\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,4BAA4B,QAAQ;AAE5C,+BAA+B,gBAAgB;AAAA,EAC7C,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,wBAAwB,WAAW,KAAK;AAAA;AAAA;AAItE,iBAAiB,UAAU,WAAW,EAAE,MAAM,EAAE,UAAU,gBAAgB,UAAU,WAAW;AAAA,EAC7F,aAAa;AAAA,EACb,mBAAmB;AAAA,EACnB,MAAM;AAAA,EACN,UAAU;AAAA,EACV,wCAAwC;AAAA,EACxC,SAAS;AAAA,IACP,kBAAkB;AAAA,IAGlB,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,EAET,UAAU;AAAA,EACV,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,SAAS;AAAA;AAGX,iBAAiB,UAAU,iBAAiB;AAC5C,iBAAiB,UAAU,QAAQ;AACnC,iBAAiB,UAAU,iBAAiB;AAC5C,iBAAiB,UAAU,YAAY;AACvC,iBAAiB,UAAU,OAAO;AAClC,iBAAiB,UAAU,YAAY;AACvC,iBAAiB,UAAU,iBAAiB,iBAAiB,UAAU;AACvE,iBAAiB,UAAU,kBAAkB,iBAAiB,UAAU;AAExE,OAAO,UAAU;",
"names": []
}

View File

@@ -0,0 +1,540 @@
"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 SNOWFLAKE_RESERVED_WORDS = "account,all,alter,and,any,as,between,by,case,cast,check,column,connect,connections,constraint,create,cross,current,current_date,current_time,current_timestamp,current_user,database,delete,distinct,drop,else,exists,false,following,for,from,full,grant,group,gscluster,having,ilike,in,increment,inner,insert,intersect,into,is,issue,join,lateral,left,like,localtime,localtimestamp,minus,natural,not,null,of,on,or,order,organization,qualify,regexp,revoke,right,rlike,row,rows,sample,schema,select,set,some,start,table,tablesample,then,to,trigger,true,try_cast,union,unique,update,using,values,view,when,whenever,where,with".split(",");
const typeWithoutDefault = /* @__PURE__ */ new Set(["BLOB", "TEXT", "GEOMETRY", "JSON"]);
class SnowflakeQueryGenerator 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 CURRENT_VERSION()";
}
createTableQuery(tableName, attributes, options) {
options = __spreadValues({
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})`,
options.comment && typeof options.comment === "string" && `COMMENT ${this.escape(options.comment)}`,
options.charset && `DEFAULT CHARSET=${options.charset}`,
options.collate && `COLLATE ${options.collate}`,
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) {
return Utils.joinSQLFragments([
"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'",
database ? `AND TABLE_SCHEMA = ${this.escape(database)}` : "AND TABLE_SCHEMA NOT IN ( 'INFORMATION_SCHEMA', 'PERFORMANCE_SCHEMA', 'SYS')",
";"
]);
}
tableExistsQuery(table) {
const tableName = table.tableName || table;
const schema = table.schema;
return Utils.joinSQLFragments([
"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'",
`AND TABLE_SCHEMA = ${schema !== void 0 ? this.escape(schema) : "CURRENT_SCHEMA()"}`,
`AND TABLE_NAME = ${this.escape(tableName)}`,
";"
]);
}
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 query = (...subQuerys) => Utils.joinSQLFragments([
"ALTER TABLE",
this.quoteTable(tableName),
"ALTER COLUMN",
...subQuerys,
";"
]);
const sql = [];
for (const attributeName in attributes) {
let definition = this.dataTypeMapping(tableName, attributeName, attributes[attributeName]);
const attrSql = [];
if (definition.includes("NOT NULL")) {
attrSql.push(query(this.quoteIdentifier(attributeName), "SET NOT NULL"));
definition = definition.replace("NOT NULL", "").trim();
} else if (!definition.includes("REFERENCES")) {
attrSql.push(query(this.quoteIdentifier(attributeName), "DROP NOT NULL"));
}
if (definition.includes("DEFAULT")) {
attrSql.push(query(this.quoteIdentifier(attributeName), "SET DEFAULT", definition.match(/DEFAULT ([^;]+)/)[1]));
definition = definition.replace(/(DEFAULT[^;]+)/, "").trim();
} else if (!definition.includes("REFERENCES")) {
attrSql.push(query(this.quoteIdentifier(attributeName), "DROP DEFAULT"));
}
if (definition.match(/UNIQUE;*$/)) {
definition = definition.replace(/UNIQUE;*$/, "");
attrSql.push(query("ADD UNIQUE (", this.quoteIdentifier(attributeName), ")").replace("ALTER COLUMN", ""));
}
if (definition.includes("REFERENCES")) {
definition = definition.replace(/.+?(?=REFERENCES)/, "");
attrSql.push(query("ADD FOREIGN KEY (", this.quoteIdentifier(attributeName), ")", definition).replace("ALTER COLUMN", ""));
} else {
attrSql.push(query(this.quoteIdentifier(attributeName), "TYPE", definition));
}
sql.push(attrSql.join(""));
}
return sql.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),
"RENAME COLUMN",
attrString.join(" to "),
";"
]);
}
handleSequelizeMethod(attr, tableName, factory, options, prepend) {
if (attr instanceof Utils.Json) {
if (attr.conditions) {
const conditions = this.parseConditionObject(attr.conditions).map((condition) => `${this.jsonPathExtractionQuery(condition.path[0], _.tail(condition.path))} = '${condition.value}'`);
return conditions.join(" AND ");
}
if (attr.path) {
let str;
if (this._checkValidJsonStatement(attr.path)) {
str = attr.path;
} else {
const paths = _.toPath(attr.path);
const column = paths.shift();
str = this.jsonPathExtractionQuery(column, paths);
}
if (attr.value) {
str += util.format(" = %s", this.escape(attr.value));
}
return str;
}
} else if (attr instanceof Utils.Cast) {
if (/timestamp/i.test(attr.type)) {
attr.type = "datetime";
} else if (attr.json && /boolean/i.test(attr.type)) {
attr.type = "char";
} else if (/double precision/i.test(attr.type) || /boolean/i.test(attr.type) || /integer/i.test(attr.type)) {
attr.type = "decimal";
} else if (/text/i.test(attr.type)) {
attr.type = "char";
}
}
return super.handleSequelizeMethod(attr, tableName, factory, options, prepend);
}
truncateTableQuery(tableName) {
return Utils.joinSQLFragments([
"TRUNCATE",
this.quoteTable(tableName)
]);
}
deleteQuery(tableName, where, options = {}, model) {
const table = this.quoteTable(tableName);
let whereClause = this.getWhereConditions(where, null, model, options);
const limit = options.limit && ` LIMIT ${this.escape(options.limit)}`;
let primaryKeys = "";
let primaryKeysSelection = "";
if (whereClause) {
whereClause = `WHERE ${whereClause}`;
}
if (limit) {
if (!model) {
throw new Error("Cannot LIMIT delete without a model.");
}
const pks = Object.values(model.primaryKeys).map((pk) => this.quoteIdentifier(pk.field)).join(",");
primaryKeys = model.primaryKeyAttributes.length > 1 ? `(${pks})` : pks;
primaryKeysSelection = pks;
return Utils.joinSQLFragments([
"DELETE FROM",
table,
"WHERE",
primaryKeys,
"IN (SELECT",
primaryKeysSelection,
"FROM",
table,
whereClause,
limit,
")",
";"
]);
}
return Utils.joinSQLFragments([
"DELETE FROM",
table,
whereClause,
";"
]);
}
showIndexesQuery() {
return "SELECT '' FROM DUAL";
}
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 += " AUTOINCREMENT";
}
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 (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;
}
dataTypeMapping(tableName, attr, dataType) {
if (dataType.includes("PRIMARY KEY")) {
dataType = dataType.replace("PRIMARY KEY", "");
}
if (dataType.includes("SERIAL")) {
if (dataType.includes("BIGINT")) {
dataType = dataType.replace("SERIAL", "BIGSERIAL");
dataType = dataType.replace("BIGINT", "");
} else if (dataType.includes("SMALLINT")) {
dataType = dataType.replace("SERIAL", "SMALLSERIAL");
dataType = dataType.replace("SMALLINT", "");
} else {
dataType = dataType.replace("INTEGER", "");
}
dataType = dataType.replace("NOT NULL", "");
}
return dataType;
}
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),
";"
]);
}
addLimitAndOffset(options) {
let fragment = [];
if (options.offset !== null && options.offset !== void 0 && options.offset !== 0) {
fragment = fragment.concat([" LIMIT ", this.escape(options.limit), " OFFSET ", this.escape(options.offset)]);
} else if (options.limit !== null && options.limit !== void 0) {
fragment = [" LIMIT ", this.escape(options.limit)];
}
return fragment.join("");
}
quoteIdentifier(identifier, force) {
const optForceQuote = force || false;
const optQuoteIdentifiers = this.options.quoteIdentifiers !== false;
const rawIdentifier = Utils.removeTicks(identifier, '"');
if (optForceQuote === true || optQuoteIdentifiers !== false || identifier.includes(".") || identifier.includes("->") || SNOWFLAKE_RESERVED_WORDS.includes(rawIdentifier.toLowerCase())) {
return Utils.addTicks(rawIdentifier, '"');
}
return rawIdentifier;
}
}
function wrapSingleQuote(identifier) {
return Utils.addTicks(identifier, "'");
}
module.exports = SnowflakeQueryGenerator;
//# sourceMappingURL=query-generator.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,70 @@
"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 SnowflakeQueryInterface 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);
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.SnowflakeQueryInterface = SnowflakeQueryInterface;
//# sourceMappingURL=query-interface.js.map

View File

@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/snowflake/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 Snowflake database\n */\nclass SnowflakeQueryInterface extends QueryInterface {\n /**\n * A wrapper that fixes Snowflake'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 /** @override */\n async upsert(tableName, insertValues, updateValues, where, options) {\n options = { ...options };\n\n options.type = QueryTypes.UPSERT;\n options.updateOnDuplicate = Object.keys(updateValues);\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 /** @override */\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.SnowflakeQueryInterface = SnowflakeQueryInterface;\n"],
"mappings": ";;;;;;;;;;;;;;;;;;;;AAEA,MAAM,kBAAkB,QAAQ;AAChC,MAAM,EAAE,mBAAmB,QAAQ;AACnC,MAAM,aAAa,QAAQ;AAK3B,sCAAsC,eAAe;AAAA,QAM7C,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,QAKd,OAAO,WAAW,cAAc,cAAc,OAAO,SAAS;AAClE,cAAU,mBAAK;AAEf,YAAQ,OAAO,WAAW;AAC1B,YAAQ,oBAAoB,OAAO,KAAK;AAExC,UAAM,QAAQ,QAAQ;AACtB,UAAM,MAAM,KAAK,eAAe,YAAY,WAAW,cAAc,MAAM,eAAe;AAC1F,WAAO,MAAM,KAAK,UAAU,MAAM,KAAK;AAAA;AAAA,QAInC,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,0BAA0B;",
"names": []
}

View File

@@ -0,0 +1,237 @@
"use strict";
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:snowflake");
class Query extends AbstractQuery {
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;
try {
results = await new Promise((resolve, reject) => {
connection.execute({
sqlText: sql,
binds: parameters,
complete(err, _stmt, rows) {
if (err) {
reject(err);
} else {
resolve(rows);
}
}
});
});
} 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);
} 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()) {
if (this.options.raw === false && this.sequelize.options.quoteIdentifiers === false) {
const sfAttrMap = _.reduce(this.model.rawAttributes, (m, v, k) => {
m[k.toUpperCase()] = k;
return m;
}, {});
data = data.map((data2) => _.reduce(data2, (prev, value, key) => {
if (value !== void 0 && sfAttrMap[key]) {
prev[sfAttrMap[key]] = value;
delete prev[key];
}
return prev;
}, data2));
}
this.options.fieldMap = _.mapKeys(this.options.fieldMap, (v, k) => {
return k.toUpperCase();
});
return this.handleSelectQuery(data);
}
if (this.isShowTablesQuery()) {
return this.handleShowTablesQuery(data);
}
if (this.isDescribeQuery()) {
result = {};
for (const _result of data) {
result[_result.Field] = {
type: _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[0]["number of rows updated"];
}
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 = `Snowflake 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) {
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] : 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 });
}
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
});
}
default:
return new sequelizeErrors.DatabaseError(err);
}
}
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