query.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. "use strict";
  2. const AbstractQuery = require("../abstract/query");
  3. const sequelizeErrors = require("../../errors");
  4. const _ = require("lodash");
  5. const { logger } = require("../../utils/logger");
  6. const ER_DUP_ENTRY = 1062;
  7. const ER_DEADLOCK = 1213;
  8. const ER_ROW_IS_REFERENCED = 1451;
  9. const ER_NO_REFERENCED_ROW = 1452;
  10. const debug = logger.debugContext("sql:snowflake");
  11. class Query extends AbstractQuery {
  12. static formatBindParameters(sql, values, dialect) {
  13. const bindParam = [];
  14. const replacementFunc = (_match, key, values_) => {
  15. if (values_[key] !== void 0) {
  16. bindParam.push(values_[key]);
  17. return "?";
  18. }
  19. return void 0;
  20. };
  21. sql = AbstractQuery.formatBindParameters(sql, values, dialect, replacementFunc)[0];
  22. return [sql, bindParam.length > 0 ? bindParam : void 0];
  23. }
  24. async run(sql, parameters) {
  25. this.sql = sql;
  26. const { connection, options } = this;
  27. const showWarnings = this.sequelize.options.showWarnings || options.showWarnings;
  28. const complete = this._logQuery(sql, debug, parameters);
  29. if (parameters) {
  30. debug("parameters(%j)", parameters);
  31. }
  32. let results;
  33. try {
  34. results = await new Promise((resolve, reject) => {
  35. connection.execute({
  36. sqlText: sql,
  37. binds: parameters,
  38. complete(err, _stmt, rows) {
  39. if (err) {
  40. reject(err);
  41. } else {
  42. resolve(rows);
  43. }
  44. }
  45. });
  46. });
  47. } catch (error) {
  48. if (options.transaction && error.errno === ER_DEADLOCK) {
  49. try {
  50. await options.transaction.rollback();
  51. } catch (error_) {
  52. }
  53. options.transaction.finished = "rollback";
  54. }
  55. error.sql = sql;
  56. error.parameters = parameters;
  57. throw this.formatError(error);
  58. } finally {
  59. complete();
  60. }
  61. if (showWarnings && results && results.warningStatus > 0) {
  62. await this.logWarnings(results);
  63. }
  64. return this.formatResults(results);
  65. }
  66. formatResults(data) {
  67. let result = this.instance;
  68. if (this.isInsertQuery(data)) {
  69. this.handleInsertQuery(data);
  70. if (!this.instance) {
  71. if (data.constructor.name === "ResultSetHeader" && this.model && this.model.autoIncrementAttribute && this.model.autoIncrementAttribute === this.model.primaryKeyAttribute && this.model.rawAttributes[this.model.primaryKeyAttribute]) {
  72. const startId = data[this.getInsertIdField()];
  73. result = [];
  74. for (let i = startId; i < startId + data.affectedRows; i++) {
  75. result.push({ [this.model.rawAttributes[this.model.primaryKeyAttribute].field]: i });
  76. }
  77. } else {
  78. result = data[this.getInsertIdField()];
  79. }
  80. }
  81. }
  82. if (this.isSelectQuery()) {
  83. if (this.options.raw === false && this.sequelize.options.quoteIdentifiers === false) {
  84. const sfAttrMap = _.reduce(this.model.rawAttributes, (m, v, k) => {
  85. m[k.toUpperCase()] = k;
  86. return m;
  87. }, {});
  88. data = data.map((data2) => _.reduce(data2, (prev, value, key) => {
  89. if (value !== void 0 && sfAttrMap[key]) {
  90. prev[sfAttrMap[key]] = value;
  91. delete prev[key];
  92. }
  93. return prev;
  94. }, data2));
  95. }
  96. this.options.fieldMap = _.mapKeys(this.options.fieldMap, (v, k) => {
  97. return k.toUpperCase();
  98. });
  99. return this.handleSelectQuery(data);
  100. }
  101. if (this.isShowTablesQuery()) {
  102. return this.handleShowTablesQuery(data);
  103. }
  104. if (this.isDescribeQuery()) {
  105. result = {};
  106. for (const _result of data) {
  107. result[_result.Field] = {
  108. type: _result.Type.toUpperCase(),
  109. allowNull: _result.Null === "YES",
  110. defaultValue: _result.Default,
  111. primaryKey: _result.Key === "PRI",
  112. autoIncrement: Object.prototype.hasOwnProperty.call(_result, "Extra") && _result.Extra.toLowerCase() === "auto_increment",
  113. comment: _result.Comment ? _result.Comment : null
  114. };
  115. }
  116. return result;
  117. }
  118. if (this.isShowIndexesQuery()) {
  119. return this.handleShowIndexesQuery(data);
  120. }
  121. if (this.isCallQuery()) {
  122. return data[0];
  123. }
  124. if (this.isBulkUpdateQuery() || this.isBulkDeleteQuery()) {
  125. return data[0]["number of rows updated"];
  126. }
  127. if (this.isVersionQuery()) {
  128. return data[0].version;
  129. }
  130. if (this.isForeignKeysQuery()) {
  131. return data;
  132. }
  133. if (this.isUpsertQuery()) {
  134. return [result, data.affectedRows === 1];
  135. }
  136. if (this.isInsertQuery() || this.isUpdateQuery()) {
  137. return [result, data.affectedRows];
  138. }
  139. if (this.isShowConstraintsQuery()) {
  140. return data;
  141. }
  142. if (this.isRawQuery()) {
  143. return [data, data];
  144. }
  145. return result;
  146. }
  147. async logWarnings(results) {
  148. const warningResults = await this.run("SHOW WARNINGS");
  149. const warningMessage = `Snowflake Warnings (${this.connection.uuid || "default"}): `;
  150. const messages = [];
  151. for (const _warningRow of warningResults) {
  152. if (_warningRow === void 0 || typeof _warningRow[Symbol.iterator] !== "function") {
  153. continue;
  154. }
  155. for (const _warningResult of _warningRow) {
  156. if (Object.prototype.hasOwnProperty.call(_warningResult, "Message")) {
  157. messages.push(_warningResult.Message);
  158. } else {
  159. for (const _objectKey of _warningResult.keys()) {
  160. messages.push([_objectKey, _warningResult[_objectKey]].join(": "));
  161. }
  162. }
  163. }
  164. }
  165. this.sequelize.log(warningMessage + messages.join("; "), this.options);
  166. return results;
  167. }
  168. formatError(err) {
  169. const errCode = err.errno || err.code;
  170. switch (errCode) {
  171. case ER_DUP_ENTRY: {
  172. const match = err.message.match(/Duplicate entry '([\s\S]*)' for key '?((.|\s)*?)'?$/);
  173. let fields = {};
  174. let message = "Validation error";
  175. const values = match ? match[1].split("-") : void 0;
  176. const fieldKey = match ? match[2] : void 0;
  177. const fieldVal = match ? match[1] : void 0;
  178. const uniqueKey = this.model && this.model.uniqueKeys[fieldKey];
  179. if (uniqueKey) {
  180. if (uniqueKey.msg)
  181. message = uniqueKey.msg;
  182. fields = _.zipObject(uniqueKey.fields, values);
  183. } else {
  184. fields[fieldKey] = fieldVal;
  185. }
  186. const errors = [];
  187. _.forOwn(fields, (value, field) => {
  188. errors.push(new sequelizeErrors.ValidationErrorItem(this.getUniqueConstraintErrorMessage(field), "unique violation", field, value, this.instance, "not_unique"));
  189. });
  190. return new sequelizeErrors.UniqueConstraintError({ message, errors, parent: err, fields });
  191. }
  192. case ER_ROW_IS_REFERENCED:
  193. case ER_NO_REFERENCED_ROW: {
  194. const match = err.message.match(/CONSTRAINT ([`"])(.*)\1 FOREIGN KEY \(\1(.*)\1\) REFERENCES \1(.*)\1 \(\1(.*)\1\)/);
  195. const quoteChar = match ? match[1] : "`";
  196. const fields = match ? match[3].split(new RegExp(`${quoteChar}, *${quoteChar}`)) : void 0;
  197. return new sequelizeErrors.ForeignKeyConstraintError({
  198. reltype: String(errCode) === String(ER_ROW_IS_REFERENCED) ? "parent" : "child",
  199. table: match ? match[4] : void 0,
  200. fields,
  201. value: fields && fields.length && this.instance && this.instance[fields[0]] || void 0,
  202. index: match ? match[2] : void 0,
  203. parent: err
  204. });
  205. }
  206. default:
  207. return new sequelizeErrors.DatabaseError(err);
  208. }
  209. }
  210. handleShowIndexesQuery(data) {
  211. data = data.reduce((acc, item) => {
  212. if (!(item.Key_name in acc)) {
  213. acc[item.Key_name] = item;
  214. item.fields = [];
  215. }
  216. acc[item.Key_name].fields[item.Seq_in_index - 1] = {
  217. attribute: item.Column_name,
  218. length: item.Sub_part || void 0,
  219. order: item.Collation === "A" ? "ASC" : void 0
  220. };
  221. delete item.column_name;
  222. return acc;
  223. }, {});
  224. return _.map(data, (item) => ({
  225. primary: item.Key_name === "PRIMARY",
  226. fields: item.fields,
  227. name: item.Key_name,
  228. tableName: item.Table,
  229. unique: item.Non_unique !== 1,
  230. type: item.Index_type
  231. }));
  232. }
  233. }
  234. module.exports = Query;
  235. module.exports.Query = Query;
  236. module.exports.default = Query;
  237. //# sourceMappingURL=query.js.map