query.js 9.3 KB

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