8 lines
14 KiB
Plaintext
8 lines
14 KiB
Plaintext
{
|
|
"version": 3,
|
|
"sources": ["../../../src/dialects/snowflake/query.js"],
|
|
"sourcesContent": ["'use strict';\n\nconst AbstractQuery = require('../abstract/query');\nconst sequelizeErrors = require('../../errors');\nconst _ = require('lodash');\nconst { logger } = require('../../utils/logger');\n\nconst ER_DUP_ENTRY = 1062;\nconst ER_DEADLOCK = 1213;\nconst ER_ROW_IS_REFERENCED = 1451;\nconst ER_NO_REFERENCED_ROW = 1452;\n\nconst debug = logger.debugContext('sql:snowflake');\n\nclass Query extends AbstractQuery {\n static formatBindParameters(sql, values, dialect) {\n const bindParam = [];\n const replacementFunc = (_match, key, values_) => {\n if (values_[key] !== undefined) {\n bindParam.push(values_[key]);\n return '?';\n }\n return undefined;\n };\n sql = AbstractQuery.formatBindParameters(sql, values, dialect, replacementFunc)[0];\n return [sql, bindParam.length > 0 ? bindParam : undefined];\n }\n\n async run(sql, parameters) {\n this.sql = sql;\n const { connection, options } = this;\n\n const showWarnings = this.sequelize.options.showWarnings || options.showWarnings;\n\n const complete = this._logQuery(sql, debug, parameters);\n\n if (parameters) {\n debug('parameters(%j)', parameters);\n }\n\n let results;\n\n try {\n results = await new Promise((resolve, reject) => {\n connection.execute({\n sqlText: sql,\n binds: parameters,\n complete(err, _stmt, rows) {\n if (err) {\n reject(err);\n } else {\n resolve(rows);\n }\n }\n });\n });\n } catch (error) {\n if (options.transaction && error.errno === ER_DEADLOCK) {\n try {\n await options.transaction.rollback();\n } catch (error_) {\n // ignore errors\n }\n\n options.transaction.finished = 'rollback';\n }\n\n error.sql = sql;\n error.parameters = parameters;\n throw this.formatError(error);\n } finally {\n complete();\n }\n\n if (showWarnings && results && results.warningStatus > 0) {\n await this.logWarnings(results);\n }\n return this.formatResults(results);\n }\n\n /**\n * High level function that handles the results of a query execution.\n *\n *\n * Example:\n * query.formatResults([\n * {\n * id: 1, // this is from the main table\n * attr2: 'snafu', // this is from the main table\n * Tasks.id: 1, // this is from the associated table\n * Tasks.title: 'task' // this is from the associated table\n * }\n * ])\n *\n * @param {Array} data - The result of the query execution.\n * @private\n */\n formatResults(data) {\n let result = this.instance;\n\n if (this.isInsertQuery(data)) {\n this.handleInsertQuery(data);\n\n if (!this.instance) {\n // handle bulkCreate AI primary key\n if (\n data.constructor.name === 'ResultSetHeader'\n && this.model\n && this.model.autoIncrementAttribute\n && this.model.autoIncrementAttribute === this.model.primaryKeyAttribute\n && this.model.rawAttributes[this.model.primaryKeyAttribute]\n ) {\n const startId = data[this.getInsertIdField()];\n result = [];\n for (let i = startId; i < startId + data.affectedRows; i++) {\n result.push({ [this.model.rawAttributes[this.model.primaryKeyAttribute].field]: i });\n }\n } else {\n result = data[this.getInsertIdField()];\n }\n }\n }\n\n if (this.isSelectQuery()) {\n // Snowflake will treat tables as case-insensitive, so fix the case\n // of the returned values to match attributes\n if (this.options.raw === false && this.sequelize.options.quoteIdentifiers === false) {\n const sfAttrMap = _.reduce(this.model.rawAttributes, (m, v, k) => {\n m[k.toUpperCase()] = k;\n return m;\n }, {});\n\n data = data.map(data => _.reduce(data, (prev, value, key) => {\n if ( value !== undefined && sfAttrMap[key] ) {\n prev[sfAttrMap[key]] = value;\n delete prev[key];\n }\n return prev;\n }, data));\n }\n\n this.options.fieldMap = _.mapKeys(this.options.fieldMap, (v, k) => { return k.toUpperCase(); });\n\n return this.handleSelectQuery(data);\n }\n\n if (this.isShowTablesQuery()) {\n return this.handleShowTablesQuery(data);\n }\n\n if (this.isDescribeQuery()) {\n result = {};\n\n for (const _result of data) {\n result[_result.Field] = {\n type: _result.Type.toUpperCase(),\n allowNull: _result.Null === 'YES',\n defaultValue: _result.Default,\n primaryKey: _result.Key === 'PRI',\n autoIncrement: Object.prototype.hasOwnProperty.call(_result, 'Extra')\n && _result.Extra.toLowerCase() === 'auto_increment',\n comment: _result.Comment ? _result.Comment : null\n };\n }\n return result;\n }\n if (this.isShowIndexesQuery()) {\n return this.handleShowIndexesQuery(data);\n }\n if (this.isCallQuery()) {\n return data[0];\n }\n if (this.isBulkUpdateQuery() || this.isBulkDeleteQuery()) {\n return data[0]['number of rows updated'];\n }\n if (this.isVersionQuery()) {\n return data[0].version;\n }\n if (this.isForeignKeysQuery()) {\n return data;\n }\n if (this.isUpsertQuery()) {\n return [result, data.affectedRows === 1];\n }\n if (this.isInsertQuery() || this.isUpdateQuery()) {\n return [result, data.affectedRows];\n }\n if (this.isShowConstraintsQuery()) {\n return data;\n }\n if (this.isRawQuery()) {\n return [data, data];\n }\n\n return result;\n }\n\n async logWarnings(results) {\n const warningResults = await this.run('SHOW WARNINGS');\n const warningMessage = `Snowflake Warnings (${this.connection.uuid || 'default'}): `;\n const messages = [];\n for (const _warningRow of warningResults) {\n if (_warningRow === undefined || typeof _warningRow[Symbol.iterator] !== 'function') {\n continue;\n }\n for (const _warningResult of _warningRow) {\n if (Object.prototype.hasOwnProperty.call(_warningResult, 'Message')) {\n messages.push(_warningResult.Message);\n } else {\n for (const _objectKey of _warningResult.keys()) {\n messages.push([_objectKey, _warningResult[_objectKey]].join(': '));\n }\n }\n }\n }\n\n this.sequelize.log(warningMessage + messages.join('; '), this.options);\n\n return results;\n }\n\n formatError(err) {\n const errCode = err.errno || err.code;\n\n switch (errCode) {\n case ER_DUP_ENTRY: {\n const match = err.message.match(/Duplicate entry '([\\s\\S]*)' for key '?((.|\\s)*?)'?$/);\n let fields = {};\n let message = 'Validation error';\n const values = match ? match[1].split('-') : undefined;\n const fieldKey = match ? match[2] : undefined;\n const fieldVal = match ? match[1] : undefined;\n const uniqueKey = this.model && this.model.uniqueKeys[fieldKey];\n\n if (uniqueKey) {\n if (uniqueKey.msg) message = uniqueKey.msg;\n fields = _.zipObject(uniqueKey.fields, values);\n } else {\n fields[fieldKey] = fieldVal;\n }\n\n const errors = [];\n _.forOwn(fields, (value, field) => {\n errors.push(new sequelizeErrors.ValidationErrorItem(\n this.getUniqueConstraintErrorMessage(field),\n 'unique violation', // sequelizeErrors.ValidationErrorItem.Origins.DB,\n field,\n value,\n this.instance,\n 'not_unique'\n ));\n });\n\n return new sequelizeErrors.UniqueConstraintError({ message, errors, parent: err, fields });\n }\n\n case ER_ROW_IS_REFERENCED:\n case ER_NO_REFERENCED_ROW: {\n // e.g. CONSTRAINT `example_constraint_name` FOREIGN KEY (`example_id`) REFERENCES `examples` (`id`)\n const match = err.message.match(\n /CONSTRAINT ([`\"])(.*)\\1 FOREIGN KEY \\(\\1(.*)\\1\\) REFERENCES \\1(.*)\\1 \\(\\1(.*)\\1\\)/\n );\n const quoteChar = match ? match[1] : '`';\n const fields = match ? match[3].split(new RegExp(`${quoteChar}, *${quoteChar}`)) : undefined;\n\n return new sequelizeErrors.ForeignKeyConstraintError({\n reltype: String(errCode) === String(ER_ROW_IS_REFERENCED) ? 'parent' : 'child',\n table: match ? match[4] : undefined,\n fields,\n value: fields && fields.length && this.instance && this.instance[fields[0]] || undefined,\n index: match ? match[2] : undefined,\n parent: err\n });\n }\n\n default:\n return new sequelizeErrors.DatabaseError(err);\n }\n }\n\n handleShowIndexesQuery(data) {\n // Group by index name, and collect all fields\n data = data.reduce((acc, item) => {\n if (!(item.Key_name in acc)) {\n acc[item.Key_name] = item;\n item.fields = [];\n }\n\n acc[item.Key_name].fields[item.Seq_in_index - 1] = {\n attribute: item.Column_name,\n length: item.Sub_part || undefined,\n order: item.Collation === 'A' ? 'ASC' : undefined\n };\n delete item.column_name;\n\n return acc;\n }, {});\n\n return _.map(data, item => ({\n primary: item.Key_name === 'PRIMARY',\n fields: item.fields,\n name: item.Key_name,\n tableName: item.Table,\n unique: item.Non_unique !== 1,\n type: item.Index_type\n }));\n }\n}\n\nmodule.exports = Query;\nmodule.exports.Query = Query;\nmodule.exports.default = Query;\n"],
|
|
"mappings": ";AAEA,MAAM,gBAAgB,QAAQ;AAC9B,MAAM,kBAAkB,QAAQ;AAChC,MAAM,IAAI,QAAQ;AAClB,MAAM,EAAE,WAAW,QAAQ;AAE3B,MAAM,eAAe;AACrB,MAAM,cAAc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