query-generator.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  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. var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
  19. var __export = (target, all) => {
  20. __markAsModule(target);
  21. for (var name in all)
  22. __defProp(target, name, { get: all[name], enumerable: true });
  23. };
  24. __export(exports, {
  25. OracleQueryGenerator: () => OracleQueryGenerator
  26. });
  27. const Utils = require("../../utils");
  28. const DataTypes = require("../../data-types");
  29. const AbstractQueryGenerator = require("../abstract/query-generator");
  30. const _ = require("lodash");
  31. const util = require("util");
  32. const Transaction = require("../../transaction");
  33. const ORACLE_RESERVED_WORDS = ["ACCESS", "ADD", "ALL", "ALTER", "AND", "ANY", "ARRAYLEN", "AS", "ASC", "AUDIT", "BETWEEN", "BY", "CHAR", "CHECK", "CLUSTER", "COLUMN", "COMMENT", "COMPRESS", "CONNECT", "CREATE", "CURRENT", "DATE", "DECIMAL", "DEFAULT", "DELETE", "DESC", "DISTINCT", "DROP", "ELSE", "EXCLUSIVE", "EXISTS", "FILE", "FLOAT", "FOR", "FROM", "GRANT", "GROUP", "HAVING", "IDENTIFIED", "IMMEDIATE", "IN", "INCREMENT", "INDEX", "INITIAL", "INSERT", "INTEGER", "INTERSECT", "INTO", "IS", "LEVEL", "LIKE", "LOCK", "LONG", "MAXEXTENTS", "MINUS", "MODE", "MODIFY", "NOAUDIT", "NOCOMPRESS", "NOT", "NOTFOUND", "NOWAIT", "NULL", "NUMBER", "OF", "OFFLINE", "ON", "ONLINE", "OPTION", "OR", "ORDER", "PCTFREE", "PRIOR", "PRIVILEGES", "PUBLIC", "RAW", "RENAME", "RESOURCE", "REVOKE", "ROW", "ROWID", "ROWLABEL", "ROWNUM", "ROWS", "SELECT", "SESSION", "SET", "SHARE", "SIZE", "SMALLINT", "SQLBUF", "START", "SUCCESSFUL", "SYNONYM", "SYSDATE", "TABLE", "THEN", "TO", "TRIGGER", "UID", "UNION", "UNIQUE", "UPDATE", "USER", "VALIDATE", "VALUES", "VARCHAR", "VARCHAR2", "VIEW", "WHENEVER", "WHERE", "WITH"];
  34. const JSON_FUNCTION_REGEX = /^\s*((?:[a-z]+_){0,2}jsonb?(?:_[a-z]+){0,2})\([^)]*\)/i;
  35. const JSON_OPERATOR_REGEX = /^\s*(->>?|@>|<@|\?[|&]?|\|{2}|#-)/i;
  36. const TOKEN_CAPTURE_REGEX = /^\s*((?:([`"'])(?:(?!\2).|\2{2})*\2)|[\w\d\s]+|[().,;+-])/i;
  37. class OracleQueryGenerator extends AbstractQueryGenerator {
  38. constructor(options) {
  39. super(options);
  40. }
  41. getCatalogName(value) {
  42. if (value) {
  43. if (this.options.quoteIdentifiers === false) {
  44. const quotedValue = this.quoteIdentifier(value);
  45. if (quotedValue === value) {
  46. value = value.toUpperCase();
  47. }
  48. }
  49. }
  50. return value;
  51. }
  52. getSchemaNameAndTableName(table) {
  53. const tableName = this.getCatalogName(table.tableName || table);
  54. const schemaName = this.getCatalogName(table.schema);
  55. return [tableName, schemaName];
  56. }
  57. createSchema(schema) {
  58. const quotedSchema = this.quoteIdentifier(schema);
  59. return [
  60. "DECLARE",
  61. "USER_FOUND BOOLEAN := FALSE;",
  62. "BEGIN",
  63. " BEGIN",
  64. " EXECUTE IMMEDIATE ",
  65. this.escape(`CREATE USER ${quotedSchema} IDENTIFIED BY 12345 DEFAULT TABLESPACE USERS`),
  66. ";",
  67. " EXCEPTION WHEN OTHERS THEN",
  68. " IF SQLCODE != -1920 THEN",
  69. " RAISE;",
  70. " ELSE",
  71. " USER_FOUND := TRUE;",
  72. " END IF;",
  73. " END;",
  74. " IF NOT USER_FOUND THEN",
  75. " EXECUTE IMMEDIATE ",
  76. this.escape(`GRANT "CONNECT" TO ${quotedSchema}`),
  77. ";",
  78. " EXECUTE IMMEDIATE ",
  79. this.escape(`GRANT CREATE TABLE TO ${quotedSchema}`),
  80. ";",
  81. " EXECUTE IMMEDIATE ",
  82. this.escape(`GRANT CREATE VIEW TO ${quotedSchema}`),
  83. ";",
  84. " EXECUTE IMMEDIATE ",
  85. this.escape(`GRANT CREATE ANY TRIGGER TO ${quotedSchema}`),
  86. ";",
  87. " EXECUTE IMMEDIATE ",
  88. this.escape(`GRANT CREATE ANY PROCEDURE TO ${quotedSchema}`),
  89. ";",
  90. " EXECUTE IMMEDIATE ",
  91. this.escape(`GRANT CREATE SEQUENCE TO ${quotedSchema}`),
  92. ";",
  93. " EXECUTE IMMEDIATE ",
  94. this.escape(`GRANT CREATE SYNONYM TO ${quotedSchema}`),
  95. ";",
  96. " EXECUTE IMMEDIATE ",
  97. this.escape(`ALTER USER ${quotedSchema} QUOTA UNLIMITED ON USERS`),
  98. ";",
  99. " END IF;",
  100. "END;"
  101. ].join(" ");
  102. }
  103. showSchemasQuery() {
  104. return `SELECT USERNAME AS "schema_name" FROM ALL_USERS WHERE COMMON = ('NO') AND USERNAME != user`;
  105. }
  106. dropSchema(schema) {
  107. return [
  108. "BEGIN",
  109. "EXECUTE IMMEDIATE ",
  110. this.escape(`DROP USER ${this.quoteTable(schema)} CASCADE`),
  111. ";",
  112. "EXCEPTION WHEN OTHERS THEN",
  113. " IF SQLCODE != -1918 THEN",
  114. " RAISE;",
  115. " END IF;",
  116. "END;"
  117. ].join(" ");
  118. }
  119. versionQuery() {
  120. return "SELECT VERSION_FULL FROM PRODUCT_COMPONENT_VERSION WHERE PRODUCT LIKE 'Oracle%'";
  121. }
  122. createTableQuery(tableName, attributes, options) {
  123. const primaryKeys = [], foreignKeys = Object.create(null), attrStr = [], checkStr = [];
  124. const values = {
  125. table: this.quoteTable(tableName)
  126. };
  127. for (let attr in attributes) {
  128. if (!Object.prototype.hasOwnProperty.call(attributes, attr))
  129. continue;
  130. const dataType = attributes[attr];
  131. attr = this.quoteIdentifier(attr);
  132. if (dataType.includes("PRIMARY KEY")) {
  133. primaryKeys.push(attr);
  134. if (dataType.includes("REFERENCES")) {
  135. const match = dataType.match(/^(.+) (REFERENCES.*)$/);
  136. attrStr.push(`${attr} ${match[1].replace(/PRIMARY KEY/, "")}`);
  137. foreignKeys[attr] = match[2];
  138. } else {
  139. attrStr.push(`${attr} ${dataType.replace(/PRIMARY KEY/, "").trim()}`);
  140. }
  141. } else if (dataType.includes("REFERENCES")) {
  142. const match = dataType.match(/^(.+) (REFERENCES.*)$/);
  143. attrStr.push(`${attr} ${match[1]}`);
  144. foreignKeys[attr] = match[2];
  145. } else {
  146. attrStr.push(`${attr} ${dataType}`);
  147. }
  148. }
  149. values["attributes"] = attrStr.join(", ");
  150. const pkString = primaryKeys.map((pk) => this.quoteIdentifier(pk)).join(", ");
  151. if (pkString.length > 0) {
  152. values.attributes += `,PRIMARY KEY (${pkString})`;
  153. }
  154. for (const fkey in foreignKeys) {
  155. if (!Object.prototype.hasOwnProperty.call(foreignKeys, fkey))
  156. continue;
  157. if (foreignKeys[fkey].indexOf("ON DELETE NO ACTION") > -1) {
  158. foreignKeys[fkey] = foreignKeys[fkey].replace("ON DELETE NO ACTION", "");
  159. }
  160. values.attributes += `,FOREIGN KEY (${this.quoteIdentifier(fkey)}) ${foreignKeys[fkey]}`;
  161. }
  162. if (checkStr.length > 0) {
  163. values.attributes += `, ${checkStr.join(", ")}`;
  164. }
  165. if (options && options.indexes && options.indexes.length > 0) {
  166. const idxToDelete = [];
  167. options.indexes.forEach((index, idx) => {
  168. if ("unique" in index && (index.unique === true || index.unique.length > 0 && index.unique !== false)) {
  169. const fields = index.fields.map((field) => {
  170. if (typeof field === "string") {
  171. return field;
  172. }
  173. return field.attribute;
  174. });
  175. let canContinue = true;
  176. if (options.uniqueKeys) {
  177. const keys = Object.keys(options.uniqueKeys);
  178. for (let fieldIdx = 0; fieldIdx < keys.length; fieldIdx++) {
  179. const currUnique = options.uniqueKeys[keys[fieldIdx]];
  180. if (currUnique.fields.length === fields.length) {
  181. for (let i = 0; i < currUnique.fields.length; i++) {
  182. const field = currUnique.fields[i];
  183. if (_.includes(fields, field)) {
  184. canContinue = false;
  185. } else {
  186. canContinue = true;
  187. break;
  188. }
  189. }
  190. }
  191. }
  192. if (canContinue) {
  193. const indexName = "name" in index ? index.name : "";
  194. const constraintToAdd = {
  195. name: indexName,
  196. fields
  197. };
  198. if (!("uniqueKeys" in options)) {
  199. options.uniqueKeys = {};
  200. }
  201. options.uniqueKeys[indexName] = constraintToAdd;
  202. idxToDelete.push(idx);
  203. } else {
  204. idxToDelete.push(idx);
  205. }
  206. }
  207. }
  208. });
  209. idxToDelete.forEach((idx) => {
  210. options.indexes.splice(idx, 1);
  211. });
  212. }
  213. if (options && !!options.uniqueKeys) {
  214. _.each(options.uniqueKeys, (columns, indexName) => {
  215. let canBeUniq = false;
  216. primaryKeys.forEach((primaryKey) => {
  217. primaryKey = primaryKey.replace(/"/g, "");
  218. if (!_.includes(columns.fields, primaryKey)) {
  219. canBeUniq = true;
  220. }
  221. });
  222. columns.fields.forEach((field) => {
  223. let currField = "";
  224. if (!_.isString(field)) {
  225. currField = field.attribute.replace(/[.,"\s]/g, "");
  226. } else {
  227. currField = field.replace(/[.,"\s]/g, "");
  228. }
  229. if (currField in attributes) {
  230. if (attributes[currField].toUpperCase().indexOf("UNIQUE") > -1 && canBeUniq) {
  231. const attrToReplace = attributes[currField].replace("UNIQUE", "");
  232. values.attributes = values.attributes.replace(attributes[currField], attrToReplace);
  233. }
  234. }
  235. });
  236. if (canBeUniq) {
  237. const index = options.uniqueKeys[columns.name];
  238. delete options.uniqueKeys[columns.name];
  239. indexName = indexName.replace(/[.,\s]/g, "");
  240. columns.name = indexName;
  241. options.uniqueKeys[indexName] = index;
  242. if (indexName.length === 0) {
  243. values.attributes += `,UNIQUE (${columns.fields.map((field) => this.quoteIdentifier(field)).join(", ")})`;
  244. } else {
  245. values.attributes += `, CONSTRAINT ${this.quoteIdentifier(indexName)} UNIQUE (${columns.fields.map((field) => this.quoteIdentifier(field)).join(", ")})`;
  246. }
  247. }
  248. });
  249. }
  250. const query = Utils.joinSQLFragments([
  251. "CREATE TABLE",
  252. values.table,
  253. `(${values.attributes})`
  254. ]);
  255. return Utils.joinSQLFragments([
  256. "BEGIN",
  257. "EXECUTE IMMEDIATE",
  258. `${this.escape(query)};`,
  259. "EXCEPTION WHEN OTHERS THEN",
  260. "IF SQLCODE != -955 THEN",
  261. "RAISE;",
  262. "END IF;",
  263. "END;"
  264. ]);
  265. }
  266. tableExistsQuery(table) {
  267. const [tableName, schemaName] = this.getSchemaNameAndTableName(table);
  268. return `SELECT TABLE_NAME FROM ALL_TABLES WHERE TABLE_NAME = ${this.escape(tableName)} AND OWNER = ${table.schema ? this.escape(schemaName) : "USER"}`;
  269. }
  270. describeTableQuery(tableName, schema) {
  271. const currTableName = this.getCatalogName(tableName.tableName || tableName);
  272. schema = this.getCatalogName(schema);
  273. return [
  274. "SELECT atc.COLUMN_NAME, atc.DATA_TYPE, atc.DATA_LENGTH, atc.CHAR_LENGTH, atc.DEFAULT_LENGTH, atc.NULLABLE, ucc.constraint_type ",
  275. "FROM all_tab_columns atc ",
  276. "LEFT OUTER JOIN ",
  277. "(SELECT acc.column_name, acc.table_name, ac.constraint_type FROM all_cons_columns acc INNER JOIN all_constraints ac ON acc.constraint_name = ac.constraint_name) ucc ",
  278. "ON (atc.table_name = ucc.table_name AND atc.COLUMN_NAME = ucc.COLUMN_NAME) ",
  279. schema ? `WHERE (atc.OWNER = ${this.escape(schema)}) ` : "WHERE atc.OWNER = USER ",
  280. `AND (atc.TABLE_NAME = ${this.escape(currTableName)})`,
  281. "ORDER BY atc.COLUMN_NAME, CONSTRAINT_TYPE DESC"
  282. ].join("");
  283. }
  284. renameTableQuery(before, after) {
  285. return Utils.joinSQLFragments([
  286. "ALTER TABLE",
  287. this.quoteTable(before),
  288. "RENAME TO",
  289. this.quoteTable(after)
  290. ]);
  291. }
  292. showConstraintsQuery(table) {
  293. const tableName = this.getCatalogName(table.tableName || table);
  294. return `SELECT CONSTRAINT_NAME constraint_name FROM user_cons_columns WHERE table_name = ${this.escape(tableName)}`;
  295. }
  296. showTablesQuery() {
  297. return `SELECT owner as table_schema, table_name, 0 as lvl FROM all_tables where OWNER IN(SELECT USERNAME AS "schema_name" FROM ALL_USERS WHERE ORACLE_MAINTAINED = 'N')`;
  298. }
  299. dropTableQuery(tableName) {
  300. return Utils.joinSQLFragments([
  301. "BEGIN ",
  302. "EXECUTE IMMEDIATE 'DROP TABLE",
  303. this.quoteTable(tableName),
  304. "CASCADE CONSTRAINTS PURGE';",
  305. "EXCEPTION WHEN OTHERS THEN",
  306. " IF SQLCODE != -942 THEN",
  307. " RAISE;",
  308. " END IF;",
  309. "END;"
  310. ]);
  311. }
  312. addIndexQuery(tableName, attributes, options, rawTablename) {
  313. if (typeof tableName !== "string" && attributes.name) {
  314. attributes.name = `${tableName.schema}.${attributes.name}`;
  315. }
  316. return super.addIndexQuery(tableName, attributes, options, rawTablename);
  317. }
  318. addConstraintQuery(tableName, options) {
  319. options = options || {};
  320. const constraintSnippet = this.getConstraintSnippet(tableName, options);
  321. tableName = this.quoteTable(tableName);
  322. return `ALTER TABLE ${tableName} ADD ${constraintSnippet};`;
  323. }
  324. addColumnQuery(table, key, dataType) {
  325. dataType.field = key;
  326. const attribute = Utils.joinSQLFragments([
  327. this.quoteIdentifier(key),
  328. this.attributeToSQL(dataType, {
  329. attributeName: key,
  330. context: "addColumn"
  331. })
  332. ]);
  333. return Utils.joinSQLFragments([
  334. "ALTER TABLE",
  335. this.quoteTable(table),
  336. "ADD",
  337. attribute
  338. ]);
  339. }
  340. removeColumnQuery(tableName, attributeName) {
  341. return Utils.joinSQLFragments([
  342. "ALTER TABLE",
  343. this.quoteTable(tableName),
  344. "DROP COLUMN",
  345. this.quoteIdentifier(attributeName),
  346. ";"
  347. ]);
  348. }
  349. _alterForeignKeyConstraint(definition, table, attributeName) {
  350. const [tableName, schemaName] = this.getSchemaNameAndTableName(table);
  351. const attributeNameConstant = this.escape(this.getCatalogName(attributeName));
  352. const schemaNameConstant = table.schema ? this.escape(this.getCatalogName(schemaName)) : "USER";
  353. const tableNameConstant = this.escape(this.getCatalogName(tableName));
  354. const getConsNameQuery = [
  355. "SELECT constraint_name INTO cons_name",
  356. "FROM (",
  357. " SELECT DISTINCT cc.owner, cc.table_name, cc.constraint_name, cc.column_name AS cons_columns",
  358. " FROM all_cons_columns cc, all_constraints c",
  359. " WHERE cc.owner = c.owner",
  360. " AND cc.table_name = c.table_name",
  361. " AND cc.constraint_name = c.constraint_name",
  362. " AND c.constraint_type = 'R'",
  363. " GROUP BY cc.owner, cc.table_name, cc.constraint_name, cc.column_name",
  364. ")",
  365. "WHERE owner =",
  366. schemaNameConstant,
  367. "AND table_name =",
  368. tableNameConstant,
  369. "AND cons_columns =",
  370. attributeNameConstant,
  371. ";"
  372. ].join(" ");
  373. const secondQuery = Utils.joinSQLFragments([
  374. `ALTER TABLE ${this.quoteIdentifier(tableName)}`,
  375. "ADD FOREIGN KEY",
  376. `(${this.quoteIdentifier(attributeName)})`,
  377. definition.replace(/.+?(?=REFERENCES)/, "")
  378. ]);
  379. return [
  380. "BEGIN",
  381. getConsNameQuery,
  382. "EXCEPTION",
  383. "WHEN NO_DATA_FOUND THEN",
  384. " CONS_NAME := NULL;",
  385. "END;",
  386. "IF CONS_NAME IS NOT NULL THEN",
  387. ` EXECUTE IMMEDIATE 'ALTER TABLE ${this.quoteTable(table)} DROP CONSTRAINT "'||CONS_NAME||'"';`,
  388. "END IF;",
  389. `EXECUTE IMMEDIATE ${this.escape(secondQuery)};`
  390. ].join(" ");
  391. }
  392. _modifyQuery(definition, table, attributeName) {
  393. const query = Utils.joinSQLFragments([
  394. "ALTER TABLE",
  395. this.quoteTable(table),
  396. "MODIFY",
  397. this.quoteIdentifier(attributeName),
  398. definition
  399. ]);
  400. const secondQuery = query.replace("NOT NULL", "").replace("NULL", "");
  401. return [
  402. "BEGIN",
  403. `EXECUTE IMMEDIATE ${this.escape(query)};`,
  404. "EXCEPTION",
  405. "WHEN OTHERS THEN",
  406. " IF SQLCODE = -1442 OR SQLCODE = -1451 THEN",
  407. ` EXECUTE IMMEDIATE ${this.escape(secondQuery)};`,
  408. " ELSE",
  409. " RAISE;",
  410. " END IF;",
  411. "END;"
  412. ].join(" ");
  413. }
  414. changeColumnQuery(table, attributes) {
  415. const sql = [
  416. "DECLARE",
  417. "CONS_NAME VARCHAR2(200);",
  418. "BEGIN"
  419. ];
  420. for (const attributeName in attributes) {
  421. if (!Object.prototype.hasOwnProperty.call(attributes, attributeName))
  422. continue;
  423. const definition = attributes[attributeName];
  424. if (definition.match(/REFERENCES/)) {
  425. sql.push(this._alterForeignKeyConstraint(definition, table, attributeName));
  426. } else {
  427. sql.push(this._modifyQuery(definition, table, attributeName));
  428. }
  429. }
  430. sql.push("END;");
  431. return sql.join(" ");
  432. }
  433. renameColumnQuery(tableName, attrBefore, attributes) {
  434. const newName = Object.keys(attributes)[0];
  435. return `ALTER TABLE ${this.quoteTable(tableName)} RENAME COLUMN ${this.quoteIdentifier(attrBefore)} TO ${this.quoteIdentifier(newName)}`;
  436. }
  437. populateInsertQueryReturnIntoBinds(returningModelAttributes, returnTypes, inbindLength, returnAttributes, options) {
  438. const oracledb = this.sequelize.connectionManager.lib;
  439. const outBindAttributes = Object.create(null);
  440. const outbind = [];
  441. const outbindParam = this.bindParam(outbind, inbindLength);
  442. returningModelAttributes.forEach((element, index) => {
  443. if (element.startsWith('"')) {
  444. element = element.substring(1, element.length - 1);
  445. }
  446. outBindAttributes[element] = Object.assign(returnTypes[index]._getBindDef(oracledb), { dir: oracledb.BIND_OUT });
  447. const returnAttribute = `${this.format(void 0, void 0, { context: "INSERT" }, outbindParam)}`;
  448. returnAttributes.push(returnAttribute);
  449. });
  450. options.outBindAttributes = outBindAttributes;
  451. }
  452. upsertQuery(tableName, insertValues, updateValues, where, model, options) {
  453. const rawAttributes = model.rawAttributes;
  454. const updateQuery = this.updateQuery(tableName, updateValues, where, options, rawAttributes);
  455. options.bind = updateQuery.bind;
  456. const insertQuery = this.insertQuery(tableName, insertValues, rawAttributes, options);
  457. const sql = [
  458. "DECLARE ",
  459. "BEGIN ",
  460. updateQuery.query ? [
  461. updateQuery.query,
  462. "; ",
  463. " IF ( SQL%ROWCOUNT = 0 ) THEN ",
  464. insertQuery.query,
  465. " :isUpdate := 0; ",
  466. "ELSE ",
  467. " :isUpdate := 1; ",
  468. " END IF; "
  469. ].join("") : [
  470. insertQuery.query,
  471. " :isUpdate := 0; ",
  472. "EXCEPTION WHEN OTHERS THEN",
  473. " IF SQLCODE != -1 THEN",
  474. " RAISE;",
  475. " END IF;"
  476. ].join(""),
  477. "END;"
  478. ];
  479. const query = sql.join("");
  480. const result = { query };
  481. if (options.bindParam !== false) {
  482. result.bind = updateQuery.bind || insertQuery.bind;
  483. }
  484. return result;
  485. }
  486. bulkInsertQuery(tableName, fieldValueHashes, options, fieldMappedAttributes) {
  487. options = options || {};
  488. options.executeMany = true;
  489. fieldMappedAttributes = fieldMappedAttributes || {};
  490. const tuples = [];
  491. const allColumns = {};
  492. const inBindBindDefMap = {};
  493. const outBindBindDefMap = {};
  494. const oracledb = this.sequelize.connectionManager.lib;
  495. for (const fieldValueHash of fieldValueHashes) {
  496. _.forOwn(fieldValueHash, (value, key) => {
  497. allColumns[key] = fieldMappedAttributes[key] && fieldMappedAttributes[key].autoIncrement === true && value === null;
  498. });
  499. }
  500. let inBindPosition;
  501. for (const fieldValueHash of fieldValueHashes) {
  502. const tuple = [];
  503. const inbindParam = options.bindParam === void 0 ? this.bindParam(tuple) : options.bindParam;
  504. const tempBindPositions = Object.keys(allColumns).map((key) => {
  505. if (allColumns[key] === true) {
  506. if (fieldValueHash[key] !== null) {
  507. throw Error("For an auto-increment column either all row must be null or non-null, a mix of null and non-null is not allowed!");
  508. }
  509. return "DEFAULT";
  510. }
  511. return this.format(fieldValueHash[key], fieldMappedAttributes[key], { context: "INSERT" }, inbindParam);
  512. });
  513. if (!inBindPosition) {
  514. inBindPosition = tempBindPositions;
  515. }
  516. tuples.push(tuple);
  517. }
  518. const returnColumn = [];
  519. const returnColumnBindPositions = [];
  520. const insertColumns = [];
  521. for (const key of Object.keys(allColumns)) {
  522. if (fieldMappedAttributes[key]) {
  523. const bindDef = fieldMappedAttributes[key].type._getBindDef(oracledb);
  524. if (allColumns[key]) {
  525. bindDef.dir = oracledb.BIND_OUT;
  526. outBindBindDefMap[key] = bindDef;
  527. returnColumn.push(this.quoteIdentifier(key));
  528. returnColumnBindPositions.push(`:${tuples[0].length + returnColumn.length}`);
  529. } else {
  530. bindDef.dir = oracledb.BIND_IN;
  531. inBindBindDefMap[key] = bindDef;
  532. }
  533. }
  534. insertColumns.push(this.quoteIdentifier(key));
  535. }
  536. let query = Utils.joinSQLFragments([
  537. "INSERT",
  538. "INTO",
  539. this.quoteTable(tableName),
  540. `(${insertColumns.join(",")})`,
  541. "VALUES",
  542. `(${inBindPosition})`
  543. ]);
  544. if (returnColumn.length > 0) {
  545. options.outBindAttributes = outBindBindDefMap;
  546. query = Utils.joinSQLFragments([
  547. query,
  548. "RETURNING",
  549. `${returnColumn.join(",")}`,
  550. "INTO",
  551. `${returnColumnBindPositions}`
  552. ]);
  553. }
  554. const result = { query };
  555. result.bind = tuples;
  556. options.inbindAttributes = inBindBindDefMap;
  557. return result;
  558. }
  559. truncateTableQuery(tableName) {
  560. return `TRUNCATE TABLE ${this.quoteTable(tableName)}`;
  561. }
  562. deleteQuery(tableName, where, options, model) {
  563. options = options || {};
  564. const table = tableName;
  565. where = this.getWhereConditions(where, null, model, options);
  566. let queryTmpl;
  567. if (options.limit) {
  568. const whereTmpl = where ? ` AND ${where}` : "";
  569. queryTmpl = `DELETE FROM ${this.quoteTable(table)} WHERE rowid IN (SELECT rowid FROM ${this.quoteTable(table)} WHERE rownum <= ${this.escape(options.limit)}${whereTmpl})`;
  570. } else {
  571. const whereTmpl = where ? ` WHERE ${where}` : "";
  572. queryTmpl = `DELETE FROM ${this.quoteTable(table)}${whereTmpl}`;
  573. }
  574. return queryTmpl;
  575. }
  576. showIndexesQuery(table) {
  577. const [tableName, owner] = this.getSchemaNameAndTableName(table);
  578. const sql = [
  579. "SELECT i.index_name,i.table_name, i.column_name, u.uniqueness, i.descend, c.constraint_type ",
  580. "FROM all_ind_columns i ",
  581. "INNER JOIN all_indexes u ",
  582. "ON (u.table_name = i.table_name AND u.index_name = i.index_name) ",
  583. "LEFT OUTER JOIN all_constraints c ",
  584. "ON (c.table_name = i.table_name AND c.index_name = i.index_name) ",
  585. `WHERE i.table_name = ${this.escape(tableName)}`,
  586. " AND u.table_owner = ",
  587. owner ? this.escape(owner) : "USER",
  588. " ORDER BY index_name, column_position"
  589. ];
  590. return sql.join("");
  591. }
  592. removeIndexQuery(tableName, indexNameOrAttributes) {
  593. let indexName = indexNameOrAttributes;
  594. if (typeof indexName !== "string") {
  595. indexName = Utils.underscore(`${tableName}_${indexNameOrAttributes.join("_")}`);
  596. }
  597. return `DROP INDEX ${this.quoteIdentifier(indexName)}`;
  598. }
  599. attributeToSQL(attribute, options) {
  600. if (!_.isPlainObject(attribute)) {
  601. attribute = {
  602. type: attribute
  603. };
  604. }
  605. attribute.onUpdate = "";
  606. if (attribute.references) {
  607. if (attribute.Model && attribute.Model.tableName === attribute.references.model) {
  608. this.sequelize.log("Oracle does not support self referencial constraints, we will remove it but we recommend restructuring your query");
  609. attribute.onDelete = "";
  610. }
  611. }
  612. let template;
  613. if (attribute.type instanceof DataTypes.ENUM) {
  614. if (attribute.type.values && !attribute.values)
  615. attribute.values = attribute.type.values;
  616. template = attribute.type.toSql();
  617. template += ` CHECK (${this.quoteIdentifier(options.attributeName)} IN(${_.map(attribute.values, (value) => {
  618. return this.escape(value);
  619. }).join(", ")}))`;
  620. return template;
  621. }
  622. if (attribute.type instanceof DataTypes.JSON) {
  623. template = attribute.type.toSql();
  624. template += ` CHECK (${this.quoteIdentifier(options.attributeName)} IS JSON)`;
  625. return template;
  626. }
  627. if (attribute.type instanceof DataTypes.BOOLEAN) {
  628. template = attribute.type.toSql();
  629. template += ` CHECK (${this.quoteIdentifier(options.attributeName)} IN('1', '0'))`;
  630. return template;
  631. }
  632. if (attribute.autoIncrement) {
  633. template = " NUMBER(*,0) GENERATED BY DEFAULT ON NULL AS IDENTITY";
  634. } else if (attribute.type && attribute.type.key === DataTypes.DOUBLE.key) {
  635. template = attribute.type.toSql();
  636. } else if (attribute.type) {
  637. let unsignedTemplate = "";
  638. if (attribute.type._unsigned) {
  639. attribute.type._unsigned = false;
  640. unsignedTemplate += ` check(${this.quoteIdentifier(options.attributeName)} >= 0)`;
  641. }
  642. template = attribute.type.toString();
  643. if (attribute.type && attribute.type !== "TEXT" && attribute.type._binary !== true && Utils.defaultValueSchemable(attribute.defaultValue)) {
  644. template += ` DEFAULT ${this.escape(attribute.defaultValue)}`;
  645. }
  646. if (!attribute.autoIncrement) {
  647. if (attribute.allowNull === false) {
  648. template += " NOT NULL";
  649. } else if (!attribute.primaryKey && !Utils.defaultValueSchemable(attribute.defaultValue)) {
  650. template += " NULL";
  651. }
  652. }
  653. template += unsignedTemplate;
  654. } else {
  655. template = "";
  656. }
  657. if (attribute.unique === true && !attribute.primaryKey) {
  658. template += " UNIQUE";
  659. }
  660. if (attribute.primaryKey) {
  661. template += " PRIMARY KEY";
  662. }
  663. if ((!options || !options.withoutForeignKeyConstraints) && attribute.references) {
  664. template += ` REFERENCES ${this.quoteTable(attribute.references.model)}`;
  665. if (attribute.references.key) {
  666. template += ` (${this.quoteIdentifier(attribute.references.key)})`;
  667. } else {
  668. template += ` (${this.quoteIdentifier("id")})`;
  669. }
  670. if (attribute.onDelete && attribute.onDelete.toUpperCase() !== "NO ACTION") {
  671. template += ` ON DELETE ${attribute.onDelete.toUpperCase()}`;
  672. }
  673. }
  674. return template;
  675. }
  676. attributesToSQL(attributes, options) {
  677. const result = {};
  678. for (const key in attributes) {
  679. const attribute = attributes[key];
  680. const attributeName = attribute.field || key;
  681. result[attributeName] = this.attributeToSQL(attribute, __spreadValues({ attributeName }, options));
  682. }
  683. return result;
  684. }
  685. createTrigger() {
  686. throwMethodUndefined("createTrigger");
  687. }
  688. dropTrigger() {
  689. throwMethodUndefined("dropTrigger");
  690. }
  691. renameTrigger() {
  692. throwMethodUndefined("renameTrigger");
  693. }
  694. createFunction() {
  695. throwMethodUndefined("createFunction");
  696. }
  697. dropFunction() {
  698. throwMethodUndefined("dropFunction");
  699. }
  700. renameFunction() {
  701. throwMethodUndefined("renameFunction");
  702. }
  703. getConstraintsOnColumn(table, column) {
  704. const [tableName, schemaName] = this.getSchemaNameAndTableName(table);
  705. column = this.getCatalogName(column);
  706. const sql = [
  707. "SELECT CONSTRAINT_NAME FROM user_cons_columns WHERE TABLE_NAME = ",
  708. this.escape(tableName),
  709. " and OWNER = ",
  710. table.schema ? this.escape(schemaName) : "USER",
  711. " and COLUMN_NAME = ",
  712. this.escape(column),
  713. " AND POSITION IS NOT NULL ORDER BY POSITION"
  714. ].join("");
  715. return sql;
  716. }
  717. getForeignKeysQuery(table) {
  718. const [tableName, schemaName] = this.getSchemaNameAndTableName(table);
  719. const sql = [
  720. 'SELECT DISTINCT a.table_name "tableName", a.constraint_name "constraintName", a.owner "owner", a.column_name "columnName",',
  721. ' b.table_name "referencedTableName", b.column_name "referencedColumnName"',
  722. " FROM all_cons_columns a",
  723. " JOIN all_constraints c ON a.owner = c.owner AND a.constraint_name = c.constraint_name",
  724. " JOIN all_cons_columns b ON c.owner = b.owner AND c.r_constraint_name = b.constraint_name",
  725. " WHERE c.constraint_type = 'R'",
  726. " AND a.table_name = ",
  727. this.escape(tableName),
  728. " AND a.owner = ",
  729. table.schema ? this.escape(schemaName) : "USER",
  730. " ORDER BY a.table_name, a.constraint_name"
  731. ].join("");
  732. return sql;
  733. }
  734. dropForeignKeyQuery(tableName, foreignKey) {
  735. return this.dropConstraintQuery(tableName, foreignKey);
  736. }
  737. getPrimaryKeyConstraintQuery(table) {
  738. const [tableName, schemaName] = this.getSchemaNameAndTableName(table);
  739. const sql = [
  740. "SELECT cols.column_name, atc.identity_column ",
  741. "FROM all_constraints cons, all_cons_columns cols ",
  742. "INNER JOIN all_tab_columns atc ON(atc.table_name = cols.table_name AND atc.COLUMN_NAME = cols.COLUMN_NAME )",
  743. "WHERE cols.table_name = ",
  744. this.escape(tableName),
  745. "AND cols.owner = ",
  746. table.schema ? this.escape(schemaName) : "USER ",
  747. "AND cons.constraint_type = 'P' ",
  748. "AND cons.constraint_name = cols.constraint_name ",
  749. "AND cons.owner = cols.owner ",
  750. "ORDER BY cols.table_name, cols.position"
  751. ].join("");
  752. return sql;
  753. }
  754. dropConstraintQuery(tableName, constraintName) {
  755. return `ALTER TABLE ${this.quoteTable(tableName)} DROP CONSTRAINT ${constraintName}`;
  756. }
  757. setIsolationLevelQuery(value, options) {
  758. if (options.parent) {
  759. return;
  760. }
  761. switch (value) {
  762. case Transaction.ISOLATION_LEVELS.READ_UNCOMMITTED:
  763. case Transaction.ISOLATION_LEVELS.READ_COMMITTED:
  764. return "SET TRANSACTION ISOLATION LEVEL READ COMMITTED;";
  765. case Transaction.ISOLATION_LEVELS.REPEATABLE_READ:
  766. return "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;";
  767. default:
  768. throw new Error(`isolation level "${value}" is not supported`);
  769. }
  770. }
  771. getAliasToken() {
  772. return "";
  773. }
  774. startTransactionQuery(transaction) {
  775. if (transaction.parent) {
  776. return `SAVEPOINT ${this.quoteIdentifier(transaction.name)}`;
  777. }
  778. return "BEGIN TRANSACTION";
  779. }
  780. commitTransactionQuery(transaction) {
  781. if (transaction.parent) {
  782. return;
  783. }
  784. return "COMMIT TRANSACTION";
  785. }
  786. rollbackTransactionQuery(transaction) {
  787. if (transaction.parent) {
  788. return `ROLLBACK TO SAVEPOINT ${this.quoteIdentifier(transaction.name)}`;
  789. }
  790. return "ROLLBACK TRANSACTION";
  791. }
  792. handleSequelizeMethod(smth, tableName, factory, options, prepend) {
  793. let str;
  794. if (smth instanceof Utils.Json) {
  795. if (smth.conditions) {
  796. const conditions = this.parseConditionObject(smth.conditions).map((condition) => `${this.jsonPathExtractionQuery(condition.path[0], _.tail(condition.path))} = '${condition.value}'`);
  797. return conditions.join(" AND ");
  798. }
  799. if (smth.path) {
  800. if (this._checkValidJsonStatement(smth.path)) {
  801. str = smth.path;
  802. } else {
  803. const paths = _.toPath(smth.path);
  804. const column = paths.shift();
  805. str = this.jsonPathExtractionQuery(column, paths);
  806. }
  807. if (smth.value) {
  808. str += util.format(" = %s", this.escape(smth.value));
  809. }
  810. return str;
  811. }
  812. }
  813. if (smth instanceof Utils.Cast) {
  814. if (smth.val instanceof Utils.SequelizeMethod) {
  815. str = this.handleSequelizeMethod(smth.val, tableName, factory, options, prepend);
  816. if (smth.type === "boolean") {
  817. str = `(CASE WHEN ${str}='true' THEN 1 ELSE 0 END)`;
  818. return `CAST(${str} AS NUMBER)`;
  819. }
  820. if (smth.type === "timestamptz" && /json_value\(/.test(str)) {
  821. str = str.slice(0, -1);
  822. return `${str} RETURNING TIMESTAMP WITH TIME ZONE)`;
  823. }
  824. }
  825. }
  826. return super.handleSequelizeMethod(smth, tableName, factory, options, prepend);
  827. }
  828. _checkValidJsonStatement(stmt) {
  829. if (typeof stmt !== "string") {
  830. return false;
  831. }
  832. let currentIndex = 0;
  833. let openingBrackets = 0;
  834. let closingBrackets = 0;
  835. let hasJsonFunction = false;
  836. let hasInvalidToken = false;
  837. while (currentIndex < stmt.length) {
  838. const string = stmt.substr(currentIndex);
  839. const functionMatches = JSON_FUNCTION_REGEX.exec(string);
  840. if (functionMatches) {
  841. currentIndex += functionMatches[0].indexOf("(");
  842. hasJsonFunction = true;
  843. continue;
  844. }
  845. const operatorMatches = JSON_OPERATOR_REGEX.exec(string);
  846. if (operatorMatches) {
  847. currentIndex += operatorMatches[0].length;
  848. hasJsonFunction = true;
  849. continue;
  850. }
  851. const tokenMatches = TOKEN_CAPTURE_REGEX.exec(string);
  852. if (tokenMatches) {
  853. const capturedToken = tokenMatches[1];
  854. if (capturedToken === "(") {
  855. openingBrackets++;
  856. } else if (capturedToken === ")") {
  857. closingBrackets++;
  858. } else if (capturedToken === ";") {
  859. hasInvalidToken = true;
  860. break;
  861. }
  862. currentIndex += tokenMatches[0].length;
  863. continue;
  864. }
  865. break;
  866. }
  867. if (hasJsonFunction && (hasInvalidToken || openingBrackets !== closingBrackets)) {
  868. throw new Error(`Invalid json statement: ${stmt}`);
  869. }
  870. return hasJsonFunction;
  871. }
  872. jsonPathExtractionQuery(column, path) {
  873. let paths = _.toPath(path);
  874. const quotedColumn = this.isIdentifierQuoted(column) ? column : this.quoteIdentifier(column);
  875. paths = paths.map((subPath) => {
  876. return /\D/.test(subPath) ? Utils.addTicks(subPath, '"') : subPath;
  877. });
  878. const pathStr = this.escape(["$"].concat(paths).join(".").replace(/\.(\d+)(?:(?=\.)|$)/g, (__, digit) => `[${digit}]`));
  879. return `json_value(${quotedColumn},${pathStr})`;
  880. }
  881. addLimitAndOffset(options, model) {
  882. let fragment = "";
  883. const offset = options.offset || 0, isSubQuery = options.hasIncludeWhere || options.hasIncludeRequired || options.hasMultiAssociation;
  884. let orders = {};
  885. if (options.order) {
  886. orders = this.getQueryOrders(options, model, isSubQuery);
  887. }
  888. if (options.limit || options.offset) {
  889. if (!orders.mainQueryOrder || !orders.mainQueryOrder.length || isSubQuery && (!orders.subQueryOrder || !orders.subQueryOrder.length)) {
  890. const tablePkFragment = `${this.quoteTable(options.tableAs || model.name)}.${this.quoteIdentifier(model.primaryKeyField)}`;
  891. fragment += ` ORDER BY ${tablePkFragment}`;
  892. }
  893. if (options.offset || options.limit) {
  894. fragment += ` OFFSET ${this.escape(offset)} ROWS`;
  895. }
  896. if (options.limit) {
  897. fragment += ` FETCH NEXT ${this.escape(options.limit)} ROWS ONLY`;
  898. }
  899. }
  900. return fragment;
  901. }
  902. booleanValue(value) {
  903. return value ? 1 : 0;
  904. }
  905. quoteIdentifier(identifier, force = false) {
  906. const optForceQuote = force;
  907. const optQuoteIdentifiers = this.options.quoteIdentifiers !== false;
  908. const rawIdentifier = Utils.removeTicks(identifier, '"');
  909. const regExp = /^(([\w][\w\d_]*))$/g;
  910. if (optForceQuote !== true && optQuoteIdentifiers === false && regExp.test(rawIdentifier) && !ORACLE_RESERVED_WORDS.includes(rawIdentifier.toUpperCase())) {
  911. return rawIdentifier;
  912. }
  913. return Utils.addTicks(rawIdentifier, '"');
  914. }
  915. bindParam(bind, posOffset = 0) {
  916. return (value) => {
  917. bind.push(value);
  918. return `:${bind.length + posOffset}`;
  919. };
  920. }
  921. authTestQuery() {
  922. return "SELECT 1+1 AS result FROM DUAL";
  923. }
  924. }
  925. function throwMethodUndefined(methodName) {
  926. throw new Error(`The method "${methodName}" is not defined! Please add it to your sql dialect.`);
  927. }
  928. //# sourceMappingURL=query-generator.js.map