primer cambio

This commit is contained in:
beseira13
2026-01-19 12:12:38 -03:00
parent 5f59dba52d
commit 44990f015a
4759 changed files with 588702 additions and 0 deletions

View File

@@ -0,0 +1,147 @@
"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;
};
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __export = (target, all) => {
__markAsModule(target);
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
__export(exports, {
OracleConnectionManager: () => OracleConnectionManager
});
const AbstractConnectionManager = require("../abstract/connection-manager");
const SequelizeErrors = require("../../errors");
const parserStore = require("../parserStore")("oracle");
const { logger } = require("../../utils/logger");
const semver = require("semver");
const debug = logger.debugContext("connection:oracle");
const DataTypes = require("../../data-types").oracle;
const { promisify } = require("util");
class OracleConnectionManager extends AbstractConnectionManager {
constructor(dialect, sequelize) {
super(dialect, sequelize);
this.sequelize = sequelize;
this.sequelize.config.port = this.sequelize.config.port || 1521;
this.lib = this._loadDialectModule("oracledb");
this.extendLib();
this.refreshTypeParser(DataTypes);
}
extendLib() {
if (this.sequelize.config && "dialectOptions" in this.sequelize.config) {
const dialectOptions = this.sequelize.config.dialectOptions;
if (dialectOptions && "maxRows" in dialectOptions) {
this.lib.maxRows = this.sequelize.config.dialectOptions.maxRows;
}
if (dialectOptions && "fetchAsString" in dialectOptions) {
this.lib.fetchAsString = this.sequelize.config.dialectOptions.fetchAsString;
} else {
this.lib.fetchAsString = [this.lib.CLOB];
}
}
this.lib.fetchAsBuffer = [this.lib.BLOB];
}
buildConnectString(config) {
if (!config.host || config.host.length === 0)
return config.database;
let connectString = config.host;
if (config.port && config.port > 0) {
connectString += `:${config.port}`;
} else {
connectString += ":1521";
}
if (config.database && config.database.length > 0) {
connectString += `/${config.database}`;
}
return connectString;
}
_refreshTypeParser(dataType) {
parserStore.refresh(dataType);
}
_clearTypeParser() {
parserStore.clear();
}
async connect(config) {
const connectionConfig = __spreadValues({
user: config.username,
password: config.password,
externalAuth: config.externalAuth,
stmtCacheSize: 0,
connectString: this.buildConnectString(config)
}, config.dialectOptions);
try {
const connection = await this.lib.getConnection(connectionConfig);
this.sequelize.options.databaseVersion = semver.coerce(connection.oracleServerVersionString).version;
debug("connection acquired");
connection.on("error", (error) => {
switch (error.code) {
case "ESOCKET":
case "ECONNRESET":
case "EPIPE":
case "PROTOCOL_CONNECTION_LOST":
this.pool.destroy(connection);
}
});
return connection;
} catch (err) {
let errorCode = err.message.split(":");
errorCode = errorCode[0];
switch (errorCode) {
case "ORA-12560":
case "ORA-12154":
case "ORA-12505":
case "ORA-12514":
case "NJS-511":
case "NJS-516":
case "NJS-517":
case "NJS-520":
throw new SequelizeErrors.ConnectionRefusedError(err);
case "ORA-28000":
case "ORA-28040":
case "ORA-01017":
case "NJS-506":
throw new SequelizeErrors.AccessDeniedError(err);
case "ORA-12541":
case "NJS-503":
case "NJS-508":
case "NJS-507":
throw new SequelizeErrors.HostNotReachableError(err);
case "NJS-512":
case "NJS-515":
case "NJS-518":
case "NJS-519":
throw new SequelizeErrors.InvalidConnectionError(err);
case "ORA-12170":
case "NJS-510":
throw new SequelizeErrors.ConnectionTimedOutError(err);
default:
throw new SequelizeErrors.ConnectionError(err);
}
}
}
async disconnect(connection) {
if (!connection.isHealthy()) {
debug("connection tried to disconnect but was already at CLOSED state");
return;
}
return await promisify((callback) => connection.close(callback))();
}
validate(connection) {
return connection && connection.isHealthy();
}
}
//# sourceMappingURL=connection-manager.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,377 @@
"use strict";
const moment = require("moment");
const momentTz = require("moment-timezone");
module.exports = (BaseTypes) => {
const warn = BaseTypes.ABSTRACT.warn.bind(void 0, "https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-D424D23B-0933-425F-BC69-9C0E6724693C");
BaseTypes.DATE.types.oracle = ["TIMESTAMP", "TIMESTAMP WITH LOCAL TIME ZONE"];
BaseTypes.STRING.types.oracle = ["VARCHAR2", "NVARCHAR2"];
BaseTypes.CHAR.types.oracle = ["CHAR", "RAW"];
BaseTypes.TEXT.types.oracle = ["CLOB"];
BaseTypes.TINYINT.types.oracle = ["NUMBER"];
BaseTypes.SMALLINT.types.oracle = ["NUMBER"];
BaseTypes.MEDIUMINT.types.oracle = ["NUMBER"];
BaseTypes.INTEGER.types.oracle = ["INTEGER"];
BaseTypes.BIGINT.types.oracle = ["NUMBER"];
BaseTypes.FLOAT.types.oracle = ["BINARY_FLOAT"];
BaseTypes.DATEONLY.types.oracle = ["DATE"];
BaseTypes.BOOLEAN.types.oracle = ["CHAR(1)"];
BaseTypes.BLOB.types.oracle = ["BLOB"];
BaseTypes.DECIMAL.types.oracle = ["NUMBER"];
BaseTypes.UUID.types.oracle = ["VARCHAR2"];
BaseTypes.ENUM.types.oracle = ["VARCHAR2"];
BaseTypes.REAL.types.oracle = ["BINARY_DOUBLE"];
BaseTypes.DOUBLE.types.oracle = ["BINARY_DOUBLE"];
BaseTypes.JSON.types.oracle = ["BLOB"];
BaseTypes.GEOMETRY.types.oracle = false;
class STRING extends BaseTypes.STRING {
toSql() {
if (this.length > 4e3 || this._binary && this._length > 2e3) {
warn("Oracle supports length up to 32764 bytes or characters; Be sure that your administrator has extended the MAX_STRING_SIZE parameter. Check https://docs.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-7B72E154-677A-4342-A1EA-C74C1EA928E6");
}
if (!this._binary) {
return `NVARCHAR2(${this._length})`;
}
return `RAW(${this._length})`;
}
_stringify(value, options) {
if (this._binary) {
return options.escape(value.toString("hex"));
}
return options.escape(value);
}
_getBindDef(oracledb) {
if (this._binary) {
return { type: oracledb.DB_TYPE_RAW, maxSize: this._length };
}
return { type: oracledb.DB_TYPE_VARCHAR, maxSize: this._length };
}
_bindParam(value, options) {
return options.bindParam(value);
}
}
STRING.prototype.escape = false;
class BOOLEAN extends BaseTypes.BOOLEAN {
toSql() {
return "CHAR(1)";
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_CHAR, maxSize: 1 };
}
_stringify(value) {
return value === true ? "1" : value === false ? "0" : value;
}
_sanitize(value) {
if (typeof value === "string") {
return value === "1" || value === "true" ? true : value === "0" || value === "false" ? false : value;
}
return super._sanitize(value);
}
}
class UUID extends BaseTypes.UUID {
toSql() {
return "VARCHAR2(36)";
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_VARCHAR, maxSize: 36 };
}
}
class NOW extends BaseTypes.NOW {
toSql() {
return "SYSDATE";
}
_stringify() {
return "SYSDATE";
}
}
class ENUM extends BaseTypes.ENUM {
toSql() {
return "VARCHAR2(512)";
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_VARCHAR, maxSize: 512 };
}
}
class TEXT extends BaseTypes.TEXT {
toSql() {
return "CLOB";
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_CLOB };
}
}
class CHAR extends BaseTypes.CHAR {
toSql() {
if (this._binary) {
warn("Oracle CHAR.BINARY datatype is not of Fixed Length.");
return `RAW(${this._length})`;
}
return super.toSql();
}
_getBindDef(oracledb) {
if (this._binary) {
return { type: oracledb.DB_TYPE_RAW, maxSize: this._length };
}
return { type: oracledb.DB_TYPE_CHAR, maxSize: this._length };
}
_bindParam(value, options) {
return options.bindParam(value);
}
}
class DATE extends BaseTypes.DATE {
toSql() {
return "TIMESTAMP WITH LOCAL TIME ZONE";
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_TIMESTAMP_LTZ };
}
_stringify(date, options) {
const format = "YYYY-MM-DD HH24:MI:SS.FFTZH:TZM";
date = this._applyTimezone(date, options);
const formatedDate = date.format("YYYY-MM-DD HH:mm:ss.SSS Z");
return `TO_TIMESTAMP_TZ('${formatedDate}','${format}')`;
}
_applyTimezone(date, options) {
if (options.timezone) {
if (momentTz.tz.zone(options.timezone)) {
date = momentTz(date).tz(options.timezone);
} else {
date = moment(date).utcOffset(options.timezone);
}
} else {
date = momentTz(date);
}
return date;
}
static parse(value, options) {
if (value === null) {
return value;
}
if (options && moment.tz.zone(options.timezone)) {
value = moment.tz(value.toString(), options.timezone).toDate();
}
return value;
}
_bindParam(value, options) {
return options.bindParam(value);
}
}
DATE.prototype.escape = false;
class DECIMAL extends BaseTypes.DECIMAL {
toSql() {
let result = "";
if (this._length) {
result += `(${this._length}`;
if (typeof this._decimals === "number") {
result += `,${this._decimals}`;
}
result += ")";
}
if (!this._length && this._precision) {
result += `(${this._precision}`;
if (typeof this._scale === "number") {
result += `,${this._scale}`;
}
result += ")";
}
return `NUMBER${result}`;
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_NUMBER };
}
}
class TINYINT extends BaseTypes.TINYINT {
toSql() {
return "NUMBER(3)";
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_NUMBER };
}
}
class SMALLINT extends BaseTypes.SMALLINT {
toSql() {
if (this._length) {
return `NUMBER(${this._length},0)`;
}
return "SMALLINT";
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_NUMBER };
}
}
class MEDIUMINT extends BaseTypes.MEDIUMINT {
toSql() {
return "NUMBER(8)";
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_NUMBER };
}
}
class BIGINT extends BaseTypes.BIGINT {
constructor(length) {
super(length);
if (!(this instanceof BIGINT))
return new BIGINT(length);
BaseTypes.BIGINT.apply(this, arguments);
if (this._length || this.options.length || this._unsigned || this._zerofill) {
warn("Oracle does not support BIGINT with options");
this._length = void 0;
this.options.length = void 0;
this._unsigned = void 0;
this._zerofill = void 0;
}
}
toSql() {
return "NUMBER(19)";
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_NUMBER };
}
_sanitize(value) {
if (typeof value === "bigint" || typeof value === "number") {
return value.toString();
}
return value;
}
}
class NUMBER extends BaseTypes.NUMBER {
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_NUMBER };
}
}
class INTEGER extends BaseTypes.INTEGER {
toSql() {
if (this._length) {
return `NUMBER(${this._length},0)`;
}
return "INTEGER";
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_NUMBER };
}
}
class FLOAT extends BaseTypes.FLOAT {
toSql() {
return "BINARY_FLOAT";
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_BINARY_FLOAT };
}
}
class REAL extends BaseTypes.REAL {
toSql() {
return "BINARY_DOUBLE";
}
_stringify(value) {
if (value === Number.POSITIVE_INFINITY) {
return "inf";
}
if (value === Number.NEGATIVE_INFINITY) {
return "-inf";
}
return value;
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_BINARY_DOUBLE };
}
}
class BLOB extends BaseTypes.BLOB {
_hexify(hex) {
return `'${hex}'`;
}
toSql() {
return "BLOB";
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_BLOB };
}
}
class JSONTYPE extends BaseTypes.JSON {
toSql() {
return "BLOB";
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_BLOB };
}
_stringify(value, options) {
return options.operation === "where" && typeof value === "string" ? value : JSON.stringify(value);
}
_bindParam(value, options) {
return options.bindParam(Buffer.from(JSON.stringify(value)));
}
}
class DOUBLE extends BaseTypes.DOUBLE {
constructor(length, decimals) {
super(length, decimals);
if (!(this instanceof DOUBLE))
return new BaseTypes.DOUBLE(length, decimals);
BaseTypes.DOUBLE.apply(this, arguments);
if (this._length || this._unsigned || this._zerofill) {
warn("Oracle does not support DOUBLE with options.");
this._length = void 0;
this.options.length = void 0;
this._unsigned = void 0;
this._zerofill = void 0;
}
this.key = "DOUBLE PRECISION";
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_BINARY_DOUBLE };
}
toSql() {
return "BINARY_DOUBLE";
}
}
class DATEONLY extends BaseTypes.DATEONLY {
parse(value) {
return moment(value).format("YYYY-MM-DD");
}
_sanitize(value) {
if (value) {
return moment(value).format("YYYY-MM-DD");
}
return value;
}
_stringify(date, options) {
if (date) {
const format = "YYYY/MM/DD";
return options.escape(`TO_DATE('${date}','${format}')`);
}
return options.escape(date);
}
_getBindDef(oracledb) {
return { type: oracledb.DB_TYPE_DATE };
}
_bindParam(value, options) {
if (typeof value === "string") {
return options.bindParam(new Date(value));
}
return options.bindParam(value);
}
}
DATEONLY.prototype.escape = false;
return {
BOOLEAN,
"DOUBLE PRECISION": DOUBLE,
DOUBLE,
STRING,
TINYINT,
SMALLINT,
MEDIUMINT,
BIGINT,
NUMBER,
INTEGER,
FLOAT,
UUID,
DATEONLY,
DATE,
NOW,
BLOB,
ENUM,
TEXT,
CHAR,
JSON: JSONTYPE,
REAL,
DECIMAL
};
};
//# sourceMappingURL=data-types.js.map

File diff suppressed because one or more lines are too long

62
node_modules/sequelize/lib/dialects/oracle/index.js generated vendored Normal file
View File

@@ -0,0 +1,62 @@
"use strict";
const _ = require("lodash");
const { AbstractDialect } = require("../abstract");
const { OracleConnectionManager } = require("./connection-manager");
const { OracleQuery } = require("./query");
const { OracleQueryGenerator } = require("./query-generator");
const DataTypes = require("../../data-types").oracle;
const { OracleQueryInterface } = require("./query-interface");
class OracleDialect extends AbstractDialect {
constructor(sequelize) {
super();
this.sequelize = sequelize;
this.connectionManager = new OracleConnectionManager(this, sequelize);
this.connectionManager.initPools();
this.queryGenerator = new OracleQueryGenerator({
_dialect: this,
sequelize
});
this.queryInterface = new OracleQueryInterface(sequelize, this.queryGenerator);
}
}
OracleDialect.prototype.supports = _.merge(_.cloneDeep(AbstractDialect.prototype.supports), {
"VALUES ()": true,
"LIMIT ON UPDATE": true,
IGNORE: " IGNORE",
lock: true,
lockOuterJoinFailure: true,
forShare: "FOR UPDATE",
skipLocked: true,
index: {
collate: false,
length: false,
parser: false,
type: false,
using: false
},
constraints: {
restrict: false
},
returnValues: false,
returnIntoValues: true,
"ORDER NULLS": true,
schemas: true,
updateOnDuplicate: false,
indexViaAlter: false,
NUMERIC: true,
JSON: true,
upserts: true,
bulkDefault: true,
topLevelOrderByRequired: true,
GEOMETRY: false
});
OracleDialect.prototype.defaultVersion = "18.0.0";
OracleDialect.prototype.Query = OracleQuery;
OracleDialect.prototype.queryGenerator = OracleQueryGenerator;
OracleDialect.prototype.DataTypes = DataTypes;
OracleDialect.prototype.name = "oracle";
OracleDialect.prototype.TICK_CHAR = '"';
OracleDialect.prototype.TICK_CHAR_LEFT = OracleDialect.prototype.TICK_CHAR;
OracleDialect.prototype.TICK_CHAR_RIGHT = OracleDialect.prototype.TICK_CHAR;
module.exports = OracleDialect;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/oracle/index.js"],
"sourcesContent": ["// Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved\n\n'use strict';\n\nconst _ = require('lodash');\nconst { AbstractDialect } = require('../abstract');\nconst { OracleConnectionManager } = require('./connection-manager');\nconst { OracleQuery } = require('./query');\nconst { OracleQueryGenerator } = require('./query-generator');\nconst DataTypes = require('../../data-types').oracle;\nconst { OracleQueryInterface } = require('./query-interface');\n\nclass OracleDialect extends AbstractDialect {\n constructor(sequelize) {\n super();\n this.sequelize = sequelize;\n this.connectionManager = new OracleConnectionManager(this, sequelize);\n this.connectionManager.initPools();\n this.queryGenerator = new OracleQueryGenerator({\n _dialect: this,\n sequelize\n });\n this.queryInterface = new OracleQueryInterface(sequelize, this.queryGenerator);\n }\n}\n\nOracleDialect.prototype.supports = _.merge(_.cloneDeep(AbstractDialect.prototype.supports), {\n 'VALUES ()': true,\n 'LIMIT ON UPDATE': true,\n IGNORE: ' IGNORE',\n lock: true,\n lockOuterJoinFailure: true,\n forShare: 'FOR UPDATE',\n skipLocked: true,\n index: {\n collate: false,\n length: false,\n parser: false,\n type: false,\n using: false\n },\n constraints: {\n restrict: false\n },\n returnValues: false,\n returnIntoValues: true,\n 'ORDER NULLS': true,\n schemas: true,\n updateOnDuplicate: false,\n indexViaAlter: false,\n NUMERIC: true,\n JSON: true,\n upserts: true,\n bulkDefault: true,\n topLevelOrderByRequired: true,\n GEOMETRY: false\n});\n\nOracleDialect.prototype.defaultVersion = '18.0.0';\nOracleDialect.prototype.Query = OracleQuery;\nOracleDialect.prototype.queryGenerator = OracleQueryGenerator;\nOracleDialect.prototype.DataTypes = DataTypes;\nOracleDialect.prototype.name = 'oracle';\nOracleDialect.prototype.TICK_CHAR = '\"';\nOracleDialect.prototype.TICK_CHAR_LEFT = OracleDialect.prototype.TICK_CHAR;\nOracleDialect.prototype.TICK_CHAR_RIGHT = OracleDialect.prototype.TICK_CHAR;\n\nmodule.exports = OracleDialect;\n"],
"mappings": ";AAIA,MAAM,IAAI,QAAQ;AAClB,MAAM,EAAE,oBAAoB,QAAQ;AACpC,MAAM,EAAE,4BAA4B,QAAQ;AAC5C,MAAM,EAAE,gBAAgB,QAAQ;AAChC,MAAM,EAAE,yBAAyB,QAAQ;AACzC,MAAM,YAAY,QAAQ,oBAAoB;AAC9C,MAAM,EAAE,yBAAyB,QAAQ;AAEzC,4BAA4B,gBAAgB;AAAA,EAC1C,YAAY,WAAW;AACrB;AACA,SAAK,YAAY;AACjB,SAAK,oBAAoB,IAAI,wBAAwB,MAAM;AAC3D,SAAK,kBAAkB;AACvB,SAAK,iBAAiB,IAAI,qBAAqB;AAAA,MAC7C,UAAU;AAAA,MACV;AAAA;AAEF,SAAK,iBAAiB,IAAI,qBAAqB,WAAW,KAAK;AAAA;AAAA;AAInE,cAAc,UAAU,WAAW,EAAE,MAAM,EAAE,UAAU,gBAAgB,UAAU,WAAW;AAAA,EAC1F,aAAa;AAAA,EACb,mBAAmB;AAAA,EACnB,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,sBAAsB;AAAA,EACtB,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,OAAO;AAAA,IACL,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,OAAO;AAAA;AAAA,EAET,aAAa;AAAA,IACX,UAAU;AAAA;AAAA,EAEZ,cAAc;AAAA,EACd,kBAAkB;AAAA,EAClB,eAAe;AAAA,EACf,SAAS;AAAA,EACT,mBAAmB;AAAA,EACnB,eAAe;AAAA,EACf,SAAS;AAAA,EACT,MAAM;AAAA,EACN,SAAS;AAAA,EACT,aAAa;AAAA,EACb,yBAAyB;AAAA,EACzB,UAAU;AAAA;AAGZ,cAAc,UAAU,iBAAiB;AACzC,cAAc,UAAU,QAAQ;AAChC,cAAc,UAAU,iBAAiB;AACzC,cAAc,UAAU,YAAY;AACpC,cAAc,UAAU,OAAO;AAC/B,cAAc,UAAU,YAAY;AACpC,cAAc,UAAU,iBAAiB,cAAc,UAAU;AACjE,cAAc,UAAU,kBAAkB,cAAc,UAAU;AAElE,OAAO,UAAU;",
"names": []
}

View File

@@ -0,0 +1,938 @@
"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;
};
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __export = (target, all) => {
__markAsModule(target);
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
__export(exports, {
OracleQueryGenerator: () => OracleQueryGenerator
});
const Utils = require("../../utils");
const DataTypes = require("../../data-types");
const AbstractQueryGenerator = require("../abstract/query-generator");
const _ = require("lodash");
const util = require("util");
const Transaction = require("../../transaction");
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"];
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;
class OracleQueryGenerator extends AbstractQueryGenerator {
constructor(options) {
super(options);
}
getCatalogName(value) {
if (value) {
if (this.options.quoteIdentifiers === false) {
const quotedValue = this.quoteIdentifier(value);
if (quotedValue === value) {
value = value.toUpperCase();
}
}
}
return value;
}
getSchemaNameAndTableName(table) {
const tableName = this.getCatalogName(table.tableName || table);
const schemaName = this.getCatalogName(table.schema);
return [tableName, schemaName];
}
createSchema(schema) {
const quotedSchema = this.quoteIdentifier(schema);
return [
"DECLARE",
"USER_FOUND BOOLEAN := FALSE;",
"BEGIN",
" BEGIN",
" EXECUTE IMMEDIATE ",
this.escape(`CREATE USER ${quotedSchema} IDENTIFIED BY 12345 DEFAULT TABLESPACE USERS`),
";",
" EXCEPTION WHEN OTHERS THEN",
" IF SQLCODE != -1920 THEN",
" RAISE;",
" ELSE",
" USER_FOUND := TRUE;",
" END IF;",
" END;",
" IF NOT USER_FOUND THEN",
" EXECUTE IMMEDIATE ",
this.escape(`GRANT "CONNECT" TO ${quotedSchema}`),
";",
" EXECUTE IMMEDIATE ",
this.escape(`GRANT CREATE TABLE TO ${quotedSchema}`),
";",
" EXECUTE IMMEDIATE ",
this.escape(`GRANT CREATE VIEW TO ${quotedSchema}`),
";",
" EXECUTE IMMEDIATE ",
this.escape(`GRANT CREATE ANY TRIGGER TO ${quotedSchema}`),
";",
" EXECUTE IMMEDIATE ",
this.escape(`GRANT CREATE ANY PROCEDURE TO ${quotedSchema}`),
";",
" EXECUTE IMMEDIATE ",
this.escape(`GRANT CREATE SEQUENCE TO ${quotedSchema}`),
";",
" EXECUTE IMMEDIATE ",
this.escape(`GRANT CREATE SYNONYM TO ${quotedSchema}`),
";",
" EXECUTE IMMEDIATE ",
this.escape(`ALTER USER ${quotedSchema} QUOTA UNLIMITED ON USERS`),
";",
" END IF;",
"END;"
].join(" ");
}
showSchemasQuery() {
return `SELECT USERNAME AS "schema_name" FROM ALL_USERS WHERE COMMON = ('NO') AND USERNAME != user`;
}
dropSchema(schema) {
return [
"BEGIN",
"EXECUTE IMMEDIATE ",
this.escape(`DROP USER ${this.quoteTable(schema)} CASCADE`),
";",
"EXCEPTION WHEN OTHERS THEN",
" IF SQLCODE != -1918 THEN",
" RAISE;",
" END IF;",
"END;"
].join(" ");
}
versionQuery() {
return "SELECT VERSION_FULL FROM PRODUCT_COMPONENT_VERSION WHERE PRODUCT LIKE 'Oracle%'";
}
createTableQuery(tableName, attributes, options) {
const primaryKeys = [], foreignKeys = Object.create(null), attrStr = [], checkStr = [];
const values = {
table: this.quoteTable(tableName)
};
for (let attr in attributes) {
if (!Object.prototype.hasOwnProperty.call(attributes, attr))
continue;
const dataType = attributes[attr];
attr = this.quoteIdentifier(attr);
if (dataType.includes("PRIMARY KEY")) {
primaryKeys.push(attr);
if (dataType.includes("REFERENCES")) {
const match = dataType.match(/^(.+) (REFERENCES.*)$/);
attrStr.push(`${attr} ${match[1].replace(/PRIMARY KEY/, "")}`);
foreignKeys[attr] = match[2];
} else {
attrStr.push(`${attr} ${dataType.replace(/PRIMARY KEY/, "").trim()}`);
}
} else if (dataType.includes("REFERENCES")) {
const match = dataType.match(/^(.+) (REFERENCES.*)$/);
attrStr.push(`${attr} ${match[1]}`);
foreignKeys[attr] = match[2];
} else {
attrStr.push(`${attr} ${dataType}`);
}
}
values["attributes"] = attrStr.join(", ");
const pkString = primaryKeys.map((pk) => this.quoteIdentifier(pk)).join(", ");
if (pkString.length > 0) {
values.attributes += `,PRIMARY KEY (${pkString})`;
}
for (const fkey in foreignKeys) {
if (!Object.prototype.hasOwnProperty.call(foreignKeys, fkey))
continue;
if (foreignKeys[fkey].indexOf("ON DELETE NO ACTION") > -1) {
foreignKeys[fkey] = foreignKeys[fkey].replace("ON DELETE NO ACTION", "");
}
values.attributes += `,FOREIGN KEY (${this.quoteIdentifier(fkey)}) ${foreignKeys[fkey]}`;
}
if (checkStr.length > 0) {
values.attributes += `, ${checkStr.join(", ")}`;
}
if (options && options.indexes && options.indexes.length > 0) {
const idxToDelete = [];
options.indexes.forEach((index, idx) => {
if ("unique" in index && (index.unique === true || index.unique.length > 0 && index.unique !== false)) {
const fields = index.fields.map((field) => {
if (typeof field === "string") {
return field;
}
return field.attribute;
});
let canContinue = true;
if (options.uniqueKeys) {
const keys = Object.keys(options.uniqueKeys);
for (let fieldIdx = 0; fieldIdx < keys.length; fieldIdx++) {
const currUnique = options.uniqueKeys[keys[fieldIdx]];
if (currUnique.fields.length === fields.length) {
for (let i = 0; i < currUnique.fields.length; i++) {
const field = currUnique.fields[i];
if (_.includes(fields, field)) {
canContinue = false;
} else {
canContinue = true;
break;
}
}
}
}
if (canContinue) {
const indexName = "name" in index ? index.name : "";
const constraintToAdd = {
name: indexName,
fields
};
if (!("uniqueKeys" in options)) {
options.uniqueKeys = {};
}
options.uniqueKeys[indexName] = constraintToAdd;
idxToDelete.push(idx);
} else {
idxToDelete.push(idx);
}
}
}
});
idxToDelete.forEach((idx) => {
options.indexes.splice(idx, 1);
});
}
if (options && !!options.uniqueKeys) {
_.each(options.uniqueKeys, (columns, indexName) => {
let canBeUniq = false;
primaryKeys.forEach((primaryKey) => {
primaryKey = primaryKey.replace(/"/g, "");
if (!_.includes(columns.fields, primaryKey)) {
canBeUniq = true;
}
});
columns.fields.forEach((field) => {
let currField = "";
if (!_.isString(field)) {
currField = field.attribute.replace(/[.,"\s]/g, "");
} else {
currField = field.replace(/[.,"\s]/g, "");
}
if (currField in attributes) {
if (attributes[currField].toUpperCase().indexOf("UNIQUE") > -1 && canBeUniq) {
const attrToReplace = attributes[currField].replace("UNIQUE", "");
values.attributes = values.attributes.replace(attributes[currField], attrToReplace);
}
}
});
if (canBeUniq) {
const index = options.uniqueKeys[columns.name];
delete options.uniqueKeys[columns.name];
indexName = indexName.replace(/[.,\s]/g, "");
columns.name = indexName;
options.uniqueKeys[indexName] = index;
if (indexName.length === 0) {
values.attributes += `,UNIQUE (${columns.fields.map((field) => this.quoteIdentifier(field)).join(", ")})`;
} else {
values.attributes += `, CONSTRAINT ${this.quoteIdentifier(indexName)} UNIQUE (${columns.fields.map((field) => this.quoteIdentifier(field)).join(", ")})`;
}
}
});
}
const query = Utils.joinSQLFragments([
"CREATE TABLE",
values.table,
`(${values.attributes})`
]);
return Utils.joinSQLFragments([
"BEGIN",
"EXECUTE IMMEDIATE",
`${this.escape(query)};`,
"EXCEPTION WHEN OTHERS THEN",
"IF SQLCODE != -955 THEN",
"RAISE;",
"END IF;",
"END;"
]);
}
tableExistsQuery(table) {
const [tableName, schemaName] = this.getSchemaNameAndTableName(table);
return `SELECT TABLE_NAME FROM ALL_TABLES WHERE TABLE_NAME = ${this.escape(tableName)} AND OWNER = ${table.schema ? this.escape(schemaName) : "USER"}`;
}
describeTableQuery(tableName, schema) {
const currTableName = this.getCatalogName(tableName.tableName || tableName);
schema = this.getCatalogName(schema);
return [
"SELECT atc.COLUMN_NAME, atc.DATA_TYPE, atc.DATA_LENGTH, atc.CHAR_LENGTH, atc.DEFAULT_LENGTH, atc.NULLABLE, ucc.constraint_type ",
"FROM all_tab_columns atc ",
"LEFT OUTER JOIN ",
"(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 ",
"ON (atc.table_name = ucc.table_name AND atc.COLUMN_NAME = ucc.COLUMN_NAME) ",
schema ? `WHERE (atc.OWNER = ${this.escape(schema)}) ` : "WHERE atc.OWNER = USER ",
`AND (atc.TABLE_NAME = ${this.escape(currTableName)})`,
"ORDER BY atc.COLUMN_NAME, CONSTRAINT_TYPE DESC"
].join("");
}
renameTableQuery(before, after) {
return Utils.joinSQLFragments([
"ALTER TABLE",
this.quoteTable(before),
"RENAME TO",
this.quoteTable(after)
]);
}
showConstraintsQuery(table) {
const tableName = this.getCatalogName(table.tableName || table);
return `SELECT CONSTRAINT_NAME constraint_name FROM user_cons_columns WHERE table_name = ${this.escape(tableName)}`;
}
showTablesQuery() {
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')`;
}
dropTableQuery(tableName) {
return Utils.joinSQLFragments([
"BEGIN ",
"EXECUTE IMMEDIATE 'DROP TABLE",
this.quoteTable(tableName),
"CASCADE CONSTRAINTS PURGE';",
"EXCEPTION WHEN OTHERS THEN",
" IF SQLCODE != -942 THEN",
" RAISE;",
" END IF;",
"END;"
]);
}
addIndexQuery(tableName, attributes, options, rawTablename) {
if (typeof tableName !== "string" && attributes.name) {
attributes.name = `${tableName.schema}.${attributes.name}`;
}
return super.addIndexQuery(tableName, attributes, options, rawTablename);
}
addConstraintQuery(tableName, options) {
options = options || {};
if (options.onUpdate) {
delete options.onUpdate;
}
if (options.onDelete && options.onDelete.toUpperCase() === "NO ACTION") {
delete options.onDelete;
}
const constraintSnippet = this.getConstraintSnippet(tableName, options);
tableName = this.quoteTable(tableName);
return `ALTER TABLE ${tableName} ADD ${constraintSnippet};`;
}
addColumnQuery(table, key, dataType) {
dataType.field = key;
const attribute = Utils.joinSQLFragments([
this.quoteIdentifier(key),
this.attributeToSQL(dataType, {
attributeName: key,
context: "addColumn"
})
]);
return Utils.joinSQLFragments([
"ALTER TABLE",
this.quoteTable(table),
"ADD",
attribute
]);
}
removeColumnQuery(tableName, attributeName) {
return Utils.joinSQLFragments([
"ALTER TABLE",
this.quoteTable(tableName),
"DROP COLUMN",
this.quoteIdentifier(attributeName),
";"
]);
}
_alterForeignKeyConstraint(definition, table, attributeName) {
const [tableName, schemaName] = this.getSchemaNameAndTableName(table);
const attributeNameConstant = this.escape(this.getCatalogName(attributeName));
const schemaNameConstant = table.schema ? this.escape(this.getCatalogName(schemaName)) : "USER";
const tableNameConstant = this.escape(this.getCatalogName(tableName));
const getConsNameQuery = [
"SELECT constraint_name INTO cons_name",
"FROM (",
" SELECT DISTINCT cc.owner, cc.table_name, cc.constraint_name, cc.column_name AS cons_columns",
" FROM all_cons_columns cc, all_constraints c",
" WHERE cc.owner = c.owner",
" AND cc.table_name = c.table_name",
" AND cc.constraint_name = c.constraint_name",
" AND c.constraint_type = 'R'",
" GROUP BY cc.owner, cc.table_name, cc.constraint_name, cc.column_name",
")",
"WHERE owner =",
schemaNameConstant,
"AND table_name =",
tableNameConstant,
"AND cons_columns =",
attributeNameConstant,
";"
].join(" ");
const secondQuery = Utils.joinSQLFragments([
`ALTER TABLE ${this.quoteIdentifier(tableName)}`,
"ADD FOREIGN KEY",
`(${this.quoteIdentifier(attributeName)})`,
definition.replace(/.+?(?=REFERENCES)/, "")
]);
return [
"BEGIN",
getConsNameQuery,
"EXCEPTION",
"WHEN NO_DATA_FOUND THEN",
" CONS_NAME := NULL;",
"END;",
"IF CONS_NAME IS NOT NULL THEN",
` EXECUTE IMMEDIATE 'ALTER TABLE ${this.quoteTable(table)} DROP CONSTRAINT "'||CONS_NAME||'"';`,
"END IF;",
`EXECUTE IMMEDIATE ${this.escape(secondQuery)};`
].join(" ");
}
_modifyQuery(definition, table, attributeName) {
const query = Utils.joinSQLFragments([
"ALTER TABLE",
this.quoteTable(table),
"MODIFY",
this.quoteIdentifier(attributeName),
definition
]);
const secondQuery = query.replace("NOT NULL", "").replace("NULL", "");
return [
"BEGIN",
`EXECUTE IMMEDIATE ${this.escape(query)};`,
"EXCEPTION",
"WHEN OTHERS THEN",
" IF SQLCODE = -1442 OR SQLCODE = -1451 THEN",
` EXECUTE IMMEDIATE ${this.escape(secondQuery)};`,
" ELSE",
" RAISE;",
" END IF;",
"END;"
].join(" ");
}
changeColumnQuery(table, attributes) {
const sql = [
"DECLARE",
"CONS_NAME VARCHAR2(200);",
"BEGIN"
];
for (const attributeName in attributes) {
if (!Object.prototype.hasOwnProperty.call(attributes, attributeName))
continue;
const definition = attributes[attributeName];
if (definition.match(/REFERENCES/)) {
sql.push(this._alterForeignKeyConstraint(definition, table, attributeName));
} else {
sql.push(this._modifyQuery(definition, table, attributeName));
}
}
sql.push("END;");
return sql.join(" ");
}
renameColumnQuery(tableName, attrBefore, attributes) {
const newName = Object.keys(attributes)[0];
return `ALTER TABLE ${this.quoteTable(tableName)} RENAME COLUMN ${this.quoteIdentifier(attrBefore)} TO ${this.quoteIdentifier(newName)}`;
}
populateInsertQueryReturnIntoBinds(returningModelAttributes, returnTypes, inbindLength, returnAttributes, options) {
const oracledb = this.sequelize.connectionManager.lib;
const outBindAttributes = Object.create(null);
const outbind = [];
const outbindParam = this.bindParam(outbind, inbindLength);
returningModelAttributes.forEach((element, index) => {
if (element.startsWith('"')) {
element = element.substring(1, element.length - 1);
}
outBindAttributes[element] = Object.assign(returnTypes[index]._getBindDef(oracledb), { dir: oracledb.BIND_OUT });
const returnAttribute = `${this.format(void 0, void 0, { context: "INSERT" }, outbindParam)}`;
returnAttributes.push(returnAttribute);
});
options.outBindAttributes = outBindAttributes;
}
upsertQuery(tableName, insertValues, updateValues, where, model, options) {
const rawAttributes = model.rawAttributes;
const updateQuery = this.updateQuery(tableName, updateValues, where, options, rawAttributes);
options.bind = updateQuery.bind;
const insertQuery = this.insertQuery(tableName, insertValues, rawAttributes, options);
const sql = [
"DECLARE ",
"BEGIN ",
updateQuery.query ? [
updateQuery.query,
"; ",
" IF ( SQL%ROWCOUNT = 0 ) THEN ",
insertQuery.query,
" :isUpdate := 0; ",
"ELSE ",
" :isUpdate := 1; ",
" END IF; "
].join("") : [
insertQuery.query,
" :isUpdate := 0; ",
"EXCEPTION WHEN OTHERS THEN",
" IF SQLCODE != -1 THEN",
" RAISE;",
" END IF;"
].join(""),
"END;"
];
const query = sql.join("");
const result = { query };
if (options.bindParam !== false) {
result.bind = updateQuery.bind || insertQuery.bind;
}
return result;
}
bulkInsertQuery(tableName, fieldValueHashes, options, fieldMappedAttributes) {
options = options || {};
options.executeMany = true;
fieldMappedAttributes = fieldMappedAttributes || {};
const tuples = [];
const allColumns = {};
const inBindBindDefMap = {};
const outBindBindDefMap = {};
const oracledb = this.sequelize.connectionManager.lib;
for (const fieldValueHash of fieldValueHashes) {
_.forOwn(fieldValueHash, (value, key) => {
allColumns[key] = fieldMappedAttributes[key] && fieldMappedAttributes[key].autoIncrement === true && value === null;
});
}
let inBindPosition;
for (const fieldValueHash of fieldValueHashes) {
const tuple = [];
const inbindParam = options.bindParam === void 0 ? this.bindParam(tuple) : options.bindParam;
const tempBindPositions = Object.keys(allColumns).map((key) => {
if (allColumns[key] === true) {
if (fieldValueHash[key] !== null) {
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!");
}
return "DEFAULT";
}
return this.format(fieldValueHash[key], fieldMappedAttributes[key], { context: "INSERT" }, inbindParam);
});
if (!inBindPosition) {
inBindPosition = tempBindPositions;
}
tuples.push(tuple);
}
const returnColumn = [];
const returnColumnBindPositions = [];
const insertColumns = [];
for (const key of Object.keys(allColumns)) {
if (fieldMappedAttributes[key]) {
const bindDef = fieldMappedAttributes[key].type._getBindDef(oracledb);
if (allColumns[key]) {
bindDef.dir = oracledb.BIND_OUT;
outBindBindDefMap[key] = bindDef;
returnColumn.push(this.quoteIdentifier(key));
returnColumnBindPositions.push(`:${tuples[0].length + returnColumn.length}`);
} else {
bindDef.dir = oracledb.BIND_IN;
inBindBindDefMap[key] = bindDef;
}
}
insertColumns.push(this.quoteIdentifier(key));
}
let query = Utils.joinSQLFragments([
"INSERT",
"INTO",
this.quoteTable(tableName),
`(${insertColumns.join(",")})`,
"VALUES",
`(${inBindPosition})`
]);
if (returnColumn.length > 0) {
options.outBindAttributes = outBindBindDefMap;
query = Utils.joinSQLFragments([
query,
"RETURNING",
`${returnColumn.join(",")}`,
"INTO",
`${returnColumnBindPositions}`
]);
}
const result = { query };
result.bind = tuples;
options.inbindAttributes = inBindBindDefMap;
return result;
}
truncateTableQuery(tableName) {
return `TRUNCATE TABLE ${this.quoteTable(tableName)}`;
}
deleteQuery(tableName, where, options, model) {
options = options || {};
const table = tableName;
where = this.getWhereConditions(where, null, model, options);
let queryTmpl;
if (options.limit) {
const whereTmpl = where ? ` AND ${where}` : "";
queryTmpl = `DELETE FROM ${this.quoteTable(table)} WHERE rowid IN (SELECT rowid FROM ${this.quoteTable(table)} WHERE rownum <= ${this.escape(options.limit)}${whereTmpl})`;
} else {
const whereTmpl = where ? ` WHERE ${where}` : "";
queryTmpl = `DELETE FROM ${this.quoteTable(table)}${whereTmpl}`;
}
return queryTmpl;
}
showIndexesQuery(table) {
const [tableName, owner] = this.getSchemaNameAndTableName(table);
const sql = [
"SELECT i.index_name,i.table_name, i.column_name, u.uniqueness, i.descend, c.constraint_type ",
"FROM all_ind_columns i ",
"INNER JOIN all_indexes u ",
"ON (u.table_name = i.table_name AND u.index_name = i.index_name) ",
"LEFT OUTER JOIN all_constraints c ",
"ON (c.table_name = i.table_name AND c.index_name = i.index_name) ",
`WHERE i.table_name = ${this.escape(tableName)}`,
" AND u.table_owner = ",
owner ? this.escape(owner) : "USER",
" ORDER BY index_name, column_position"
];
return sql.join("");
}
removeIndexQuery(tableName, indexNameOrAttributes) {
let indexName = indexNameOrAttributes;
if (typeof indexName !== "string") {
indexName = Utils.underscore(`${tableName}_${indexNameOrAttributes.join("_")}`);
}
return `DROP INDEX ${this.quoteIdentifier(indexName)}`;
}
attributeToSQL(attribute, options) {
if (!_.isPlainObject(attribute)) {
attribute = {
type: attribute
};
}
attribute.onUpdate = "";
if (attribute.references) {
if (attribute.Model && attribute.Model.tableName === attribute.references.model) {
this.sequelize.log("Oracle does not support self referencial constraints, we will remove it but we recommend restructuring your query");
attribute.onDelete = "";
}
}
let template;
template = attribute.type.toSql ? attribute.type.toSql() : "";
if (attribute.type instanceof DataTypes.JSON) {
template += ` CHECK (${this.quoteIdentifier(options.attributeName)} IS JSON)`;
return template;
}
if (Utils.defaultValueSchemable(attribute.defaultValue)) {
template += ` DEFAULT ${this.escape(attribute.defaultValue)}`;
}
if (attribute.allowNull === false) {
template += " NOT NULL";
}
if (attribute.type instanceof DataTypes.ENUM) {
if (attribute.type.values && !attribute.values)
attribute.values = attribute.type.values;
template += ` CHECK (${this.quoteIdentifier(options.attributeName)} IN(${_.map(attribute.values, (value) => {
return this.escape(value);
}).join(", ")}))`;
return template;
}
if (attribute.type instanceof DataTypes.BOOLEAN) {
template += ` CHECK (${this.quoteIdentifier(options.attributeName)} IN('1', '0'))`;
return template;
}
if (attribute.autoIncrement) {
template = " NUMBER(*,0) GENERATED BY DEFAULT ON NULL AS IDENTITY";
} else if (attribute.type && attribute.type.key === DataTypes.DOUBLE.key) {
template = attribute.type.toSql();
} else if (attribute.type) {
let unsignedTemplate = "";
if (attribute.type._unsigned) {
attribute.type._unsigned = false;
unsignedTemplate += ` check(${this.quoteIdentifier(options.attributeName)} >= 0)`;
}
template = attribute.type.toString();
if (attribute.type && attribute.type !== "TEXT" && attribute.type._binary !== true && Utils.defaultValueSchemable(attribute.defaultValue)) {
template += ` DEFAULT ${this.escape(attribute.defaultValue)}`;
}
if (!attribute.autoIncrement) {
if (attribute.allowNull === false) {
template += " NOT NULL";
} else if (!attribute.primaryKey && !Utils.defaultValueSchemable(attribute.defaultValue)) {
template += " NULL";
}
}
template += unsignedTemplate;
} else {
template = "";
}
if (attribute.unique === true && !attribute.primaryKey) {
template += " UNIQUE";
}
if (attribute.primaryKey) {
template += " PRIMARY KEY";
}
if ((!options || !options.withoutForeignKeyConstraints) && attribute.references) {
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 && attribute.onDelete.toUpperCase() !== "NO ACTION") {
template += ` ON DELETE ${attribute.onDelete.toUpperCase()}`;
}
}
return template;
}
attributesToSQL(attributes, options) {
const result = {};
for (const key in attributes) {
const attribute = attributes[key];
const attributeName = attribute.field || key;
result[attributeName] = this.attributeToSQL(attribute, __spreadValues({ attributeName }, options));
}
return result;
}
createTrigger() {
throwMethodUndefined("createTrigger");
}
dropTrigger() {
throwMethodUndefined("dropTrigger");
}
renameTrigger() {
throwMethodUndefined("renameTrigger");
}
createFunction() {
throwMethodUndefined("createFunction");
}
dropFunction() {
throwMethodUndefined("dropFunction");
}
renameFunction() {
throwMethodUndefined("renameFunction");
}
getConstraintsOnColumn(table, column) {
const [tableName, schemaName] = this.getSchemaNameAndTableName(table);
column = this.getCatalogName(column);
const sql = [
"SELECT CONSTRAINT_NAME FROM user_cons_columns WHERE TABLE_NAME = ",
this.escape(tableName),
" and OWNER = ",
table.schema ? this.escape(schemaName) : "USER",
" and COLUMN_NAME = ",
this.escape(column),
" AND POSITION IS NOT NULL ORDER BY POSITION"
].join("");
return sql;
}
getForeignKeysQuery(table) {
const [tableName, schemaName] = this.getSchemaNameAndTableName(table);
const sql = [
'SELECT DISTINCT a.table_name "tableName", a.constraint_name "constraintName", a.owner "owner", a.column_name "columnName",',
' b.table_name "referencedTableName", b.column_name "referencedColumnName"',
" FROM all_cons_columns a",
" JOIN all_constraints c ON a.owner = c.owner AND a.constraint_name = c.constraint_name",
" JOIN all_cons_columns b ON c.owner = b.owner AND c.r_constraint_name = b.constraint_name",
" WHERE c.constraint_type = 'R'",
" AND a.table_name = ",
this.escape(tableName),
" AND a.owner = ",
table.schema ? this.escape(schemaName) : "USER",
" ORDER BY a.table_name, a.constraint_name"
].join("");
return sql;
}
dropForeignKeyQuery(tableName, foreignKey) {
return this.dropConstraintQuery(tableName, foreignKey);
}
getPrimaryKeyConstraintQuery(table) {
const [tableName, schemaName] = this.getSchemaNameAndTableName(table);
const sql = [
"SELECT cols.column_name, atc.identity_column ",
"FROM all_constraints cons, all_cons_columns cols ",
"INNER JOIN all_tab_columns atc ON(atc.table_name = cols.table_name AND atc.COLUMN_NAME = cols.COLUMN_NAME )",
"WHERE cols.table_name = ",
this.escape(tableName),
"AND cols.owner = ",
table.schema ? this.escape(schemaName) : "USER ",
"AND cons.constraint_type = 'P' ",
"AND cons.constraint_name = cols.constraint_name ",
"AND cons.owner = cols.owner ",
"ORDER BY cols.table_name, cols.position"
].join("");
return sql;
}
dropConstraintQuery(tableName, constraintName) {
return `ALTER TABLE ${this.quoteTable(tableName)} DROP CONSTRAINT ${constraintName}`;
}
setIsolationLevelQuery(value, options) {
if (options.parent) {
return;
}
switch (value) {
case Transaction.ISOLATION_LEVELS.READ_UNCOMMITTED:
case Transaction.ISOLATION_LEVELS.READ_COMMITTED:
return "SET TRANSACTION ISOLATION LEVEL READ COMMITTED;";
case Transaction.ISOLATION_LEVELS.REPEATABLE_READ:
return "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;";
default:
throw new Error(`isolation level "${value}" is not supported`);
}
}
getAliasToken() {
return "";
}
startTransactionQuery(transaction) {
if (transaction.parent) {
return `SAVEPOINT ${this.quoteIdentifier(transaction.name)}`;
}
return "BEGIN TRANSACTION";
}
commitTransactionQuery(transaction) {
if (transaction.parent) {
return;
}
return "COMMIT TRANSACTION";
}
rollbackTransactionQuery(transaction) {
if (transaction.parent) {
return `ROLLBACK TO SAVEPOINT ${this.quoteIdentifier(transaction.name)}`;
}
return "ROLLBACK TRANSACTION";
}
handleSequelizeMethod(smth, tableName, factory, options, prepend) {
let str;
if (smth instanceof Utils.Json) {
if (smth.conditions) {
const conditions = this.parseConditionObject(smth.conditions).map((condition) => `${this.jsonPathExtractionQuery(condition.path[0], _.tail(condition.path))} = '${condition.value}'`);
return conditions.join(" AND ");
}
if (smth.path) {
if (this._checkValidJsonStatement(smth.path)) {
str = smth.path;
} else {
const paths = _.toPath(smth.path);
const column = paths.shift();
str = this.jsonPathExtractionQuery(column, paths);
}
if (smth.value) {
str += util.format(" = %s", this.escape(smth.value));
}
return str;
}
}
if (smth instanceof Utils.Cast) {
if (smth.val instanceof Utils.SequelizeMethod) {
str = this.handleSequelizeMethod(smth.val, tableName, factory, options, prepend);
if (smth.type === "boolean") {
str = `(CASE WHEN ${str}='true' THEN 1 ELSE 0 END)`;
return `CAST(${str} AS NUMBER)`;
}
if (smth.type === "timestamptz" && /json_value\(/.test(str)) {
str = str.slice(0, -1);
return `${str} RETURNING TIMESTAMP WITH TIME ZONE)`;
}
}
}
return super.handleSequelizeMethod(smth, tableName, factory, options, prepend);
}
_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;
}
jsonPathExtractionQuery(column, path) {
let paths = _.toPath(path);
const quotedColumn = this.isIdentifierQuoted(column) ? column : this.quoteIdentifier(column);
paths = paths.map((subPath) => {
return /\D/.test(subPath) ? Utils.addTicks(subPath, '"') : subPath;
});
const pathStr = this.escape(["$"].concat(paths).join(".").replace(/\.(\d+)(?:(?=\.)|$)/g, (__, digit) => `[${digit}]`));
return `json_value(${quotedColumn},${pathStr})`;
}
addLimitAndOffset(options, model) {
let fragment = "";
const offset = options.offset || 0, isSubQuery = options.hasIncludeWhere || options.hasIncludeRequired || options.hasMultiAssociation;
let orders = {};
if (options.order) {
orders = this.getQueryOrders(options, model, isSubQuery);
}
if (options.limit || options.offset) {
if (!orders.mainQueryOrder || !orders.mainQueryOrder.length || isSubQuery && (!orders.subQueryOrder || !orders.subQueryOrder.length)) {
const tablePkFragment = `${this.quoteTable(options.tableAs || model.name)}.${this.quoteIdentifier(model.primaryKeyField)}`;
fragment += ` ORDER BY ${tablePkFragment}`;
}
if (options.offset || options.limit) {
fragment += ` OFFSET ${this.escape(offset)} ROWS`;
}
if (options.limit) {
fragment += ` FETCH NEXT ${this.escape(options.limit)} ROWS ONLY`;
}
}
return fragment;
}
booleanValue(value) {
return value ? 1 : 0;
}
quoteIdentifier(identifier, force = false) {
const optForceQuote = force;
const optQuoteIdentifiers = this.options.quoteIdentifiers !== false;
const rawIdentifier = Utils.removeTicks(identifier, '"');
const regExp = /^(([\w][\w\d_]*))$/g;
if (optForceQuote !== true && optQuoteIdentifiers === false && regExp.test(rawIdentifier) && !ORACLE_RESERVED_WORDS.includes(rawIdentifier.toUpperCase())) {
return rawIdentifier;
}
return Utils.addTicks(rawIdentifier, '"');
}
bindParam(bind, posOffset = 0) {
return (value) => {
bind.push(value);
return `:${bind.length + posOffset}`;
};
}
authTestQuery() {
return "SELECT 1+1 AS result FROM DUAL";
}
}
function throwMethodUndefined(methodName) {
throw new Error(`The method "${methodName}" is not defined! Please add it to your sql dialect.`);
}
//# sourceMappingURL=query-generator.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,75 @@
"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;
};
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __export = (target, all) => {
__markAsModule(target);
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
__export(exports, {
OracleQueryInterface: () => OracleQueryInterface
});
const { QueryInterface } = require("../abstract/query-interface");
const QueryTypes = require("../../query-types");
const _ = require("lodash");
class OracleQueryInterface extends QueryInterface {
async upsert(tableName, insertValues, updateValues, where, options) {
options = __spreadValues({}, options);
const model = options.model;
const primaryKeys = Object.values(model.primaryKeys).map((item) => item.field);
const uniqueKeys = Object.values(model.uniqueKeys).filter((c) => c.fields.length > 0).map((c) => c.fields);
const indexKeys = Object.values(model._indexes).filter((c) => c.unique && c.fields.length > 0).map((c) => c.fields);
options.type = QueryTypes.UPSERT;
options.updateOnDuplicate = Object.keys(updateValues);
options.upsertKeys = [];
for (const field of options.updateOnDuplicate) {
const uniqueKey = uniqueKeys.find((fields) => fields.includes(field));
if (uniqueKey) {
options.upsertKeys = uniqueKey;
break;
}
const indexKey = indexKeys.find((fields) => fields.includes(field));
if (indexKey) {
options.upsertKeys = indexKey;
break;
}
}
if (options.upsertKeys.length === 0 || _.intersection(options.updateOnDuplicate, primaryKeys).length) {
options.upsertKeys = primaryKeys;
}
options.upsertKeys = _.uniq(options.upsertKeys);
let whereHasNull = false;
primaryKeys.forEach((element) => {
if (where[element] === null) {
whereHasNull = true;
}
});
if (whereHasNull === true) {
where = options.upsertKeys.reduce((result, attribute) => {
result[attribute] = insertValues[attribute];
return result;
}, {});
}
const sql = this.queryGenerator.upsertQuery(tableName, insertValues, updateValues, where, model, options);
if (sql.bind) {
options.bind = void 0;
}
return await this.sequelize.query(sql, options);
}
}
//# sourceMappingURL=query-interface.js.map

View File

@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../src/dialects/oracle/query-interface.js"],
"sourcesContent": ["// Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved\n\n'use strict';\nconst { QueryInterface } = require('../abstract/query-interface');\nconst QueryTypes = require('../../query-types');\n\nconst _ = require('lodash');\n/**\n * The interface that Sequelize uses to talk with Oracle database\n */\nexport class OracleQueryInterface extends QueryInterface {\n\n /**\n * Upsert\n *\n * @param {string} tableName table to upsert on\n * @param {object} insertValues values to be inserted, mapped to field name\n * @param {object} updateValues values to be updated, mapped to field name\n * @param {object} where where conditions, which can be used for UPDATE part when INSERT fails\n * @param {object} options query options\n *\n * @returns {Promise<boolean,?number>} Resolves an array with <created, primaryKey>\n */\n async upsert(tableName, insertValues, updateValues, where, options) {\n options = { ...options };\n\n const model = options.model;\n const primaryKeys = Object.values(model.primaryKeys).map(item => item.field);\n const uniqueKeys = Object.values(model.uniqueKeys).filter(c => c.fields.length > 0).map(c => c.fields);\n const indexKeys = Object.values(model._indexes).filter(c => c.unique && c.fields.length > 0).map(c => c.fields);\n\n options.type = QueryTypes.UPSERT;\n options.updateOnDuplicate = Object.keys(updateValues);\n options.upsertKeys = [];\n\n // For fields in updateValues, try to find a constraint or unique index\n // that includes given field. Only first matching upsert key is used.\n for (const field of options.updateOnDuplicate) {\n const uniqueKey = uniqueKeys.find(fields => fields.includes(field));\n if (uniqueKey) {\n options.upsertKeys = uniqueKey;\n break;\n }\n\n const indexKey = indexKeys.find(fields => fields.includes(field));\n if (indexKey) {\n options.upsertKeys = indexKey;\n break;\n }\n }\n\n // Always use PK, if no constraint available OR update data contains PK\n if (\n options.upsertKeys.length === 0\n || _.intersection(options.updateOnDuplicate, primaryKeys).length\n ) {\n options.upsertKeys = primaryKeys;\n }\n\n options.upsertKeys = _.uniq(options.upsertKeys);\n\n let whereHasNull = false;\n\n primaryKeys.forEach(element => {\n if (where[element] === null) {\n whereHasNull = true;\n }\n });\n\n if (whereHasNull === true) {\n where = options.upsertKeys.reduce((result, attribute) => {\n result[attribute] = insertValues[attribute];\n return result;\n }, {}); \n }\n\n const sql = this.queryGenerator.upsertQuery(tableName, insertValues, updateValues, where, model, options);\n // we need set this to undefined otherwise sequelize would raise an error\n // Error: Both `sql.bind` and `options.bind` cannot be set at the same time\n if (sql.bind) {\n options.bind = undefined;\n }\n return await this.sequelize.query(sql, options);\n }\n}\n"],
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAGA,MAAM,EAAE,mBAAmB,QAAQ;AACnC,MAAM,aAAa,QAAQ;AAE3B,MAAM,IAAI,QAAQ;AAIX,mCAAmC,eAAe;AAAA,QAajD,OAAO,WAAW,cAAc,cAAc,OAAO,SAAS;AAClE,cAAU,mBAAK;AAEf,UAAM,QAAQ,QAAQ;AACtB,UAAM,cAAc,OAAO,OAAO,MAAM,aAAa,IAAI,UAAQ,KAAK;AACtE,UAAM,aAAa,OAAO,OAAO,MAAM,YAAY,OAAO,OAAK,EAAE,OAAO,SAAS,GAAG,IAAI,OAAK,EAAE;AAC/F,UAAM,YAAY,OAAO,OAAO,MAAM,UAAU,OAAO,OAAK,EAAE,UAAU,EAAE,OAAO,SAAS,GAAG,IAAI,OAAK,EAAE;AAExG,YAAQ,OAAO,WAAW;AAC1B,YAAQ,oBAAoB,OAAO,KAAK;AACxC,YAAQ,aAAa;AAIrB,eAAW,SAAS,QAAQ,mBAAmB;AAC7C,YAAM,YAAY,WAAW,KAAK,YAAU,OAAO,SAAS;AAC5D,UAAI,WAAW;AACb,gBAAQ,aAAa;AACrB;AAAA;AAGF,YAAM,WAAW,UAAU,KAAK,YAAU,OAAO,SAAS;AAC1D,UAAI,UAAU;AACZ,gBAAQ,aAAa;AACrB;AAAA;AAAA;AAKJ,QACE,QAAQ,WAAW,WAAW,KAC3B,EAAE,aAAa,QAAQ,mBAAmB,aAAa,QAC1D;AACA,cAAQ,aAAa;AAAA;AAGvB,YAAQ,aAAa,EAAE,KAAK,QAAQ;AAEpC,QAAI,eAAe;AAEnB,gBAAY,QAAQ,aAAW;AAC7B,UAAI,MAAM,aAAa,MAAM;AAC3B,uBAAe;AAAA;AAAA;AAInB,QAAI,iBAAiB,MAAM;AACzB,cAAQ,QAAQ,WAAW,OAAO,CAAC,QAAQ,cAAc;AACvD,eAAO,aAAa,aAAa;AACjC,eAAO;AAAA,SACN;AAAA;AAGL,UAAM,MAAM,KAAK,eAAe,YAAY,WAAW,cAAc,cAAc,OAAO,OAAO;AAGjG,QAAI,IAAI,MAAM;AACZ,cAAQ,OAAO;AAAA;AAEjB,WAAO,MAAM,KAAK,UAAU,MAAM,KAAK;AAAA;AAAA;",
"names": []
}

518
node_modules/sequelize/lib/dialects/oracle/query.js generated vendored Normal file
View File

@@ -0,0 +1,518 @@
"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));
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __export = (target, all) => {
__markAsModule(target);
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
__export(exports, {
OracleQuery: () => OracleQuery
});
const AbstractQuery = require("../abstract/query");
const SequelizeErrors = require("../../errors");
const parserStore = require("../parserStore")("oracle");
const _ = require("lodash");
const Utils = require("../../utils");
const { logger } = require("../../utils/logger");
const debug = logger.debugContext("sql:oracle");
class OracleQuery extends AbstractQuery {
constructor(connection, sequelize, options) {
super(connection, sequelize, options);
this.options = _.extend({
logging: console.log,
plain: false,
raw: false
}, options || {});
this.checkLoggingOption();
this.outFormat = options.outFormat || this.sequelize.connectionManager.lib.OBJECT;
}
getInsertIdField() {
return "id";
}
getExecOptions() {
const execOpts = { outFormat: this.outFormat, autoCommit: this.autoCommit };
const oracledb = this.sequelize.connectionManager.lib;
if (this.model && this.isSelectQuery()) {
const fInfo = {};
const keys = Object.keys(this.model.tableAttributes);
for (const key of keys) {
const keyValue = this.model.tableAttributes[key];
if (keyValue.type.key === "DECIMAL") {
fInfo[key] = { type: oracledb.STRING };
}
if (keyValue.type.key === "BIGINT") {
fInfo[key] = { type: oracledb.STRING };
}
}
if (fInfo) {
execOpts.fetchInfo = fInfo;
}
}
return execOpts;
}
_convertBindAttributes(bindingDictionary, oracledb) {
if (this.model && this.options[bindingDictionary]) {
const keys = Object.keys(this.model.tableAttributes);
for (const key of keys) {
const keyValue = this.model.tableAttributes[key];
if (keyValue.type.key === "BIGINT") {
const oldBinding = this.options[bindingDictionary][key];
if (oldBinding) {
this.options[bindingDictionary][key] = __spreadProps(__spreadValues({}, oldBinding), {
type: oracledb.STRING,
maxSize: 1e7
});
}
}
}
}
}
async run(sql, parameters) {
const oracledb = this.sequelize.connectionManager.lib;
const complete = this._logQuery(sql, debug, parameters);
const outParameters = [];
const bindParameters = [];
const bindDef = [];
if (!sql.match(/END;$/)) {
this.sql = sql.replace(/; *$/, "");
} else {
this.sql = sql;
}
if (this.options.outBindAttributes && (Array.isArray(parameters) || _.isPlainObject(parameters))) {
this._convertBindAttributes("outBindAttributes", oracledb);
outParameters.push(...Object.values(this.options.outBindAttributes));
if (this.isUpsertQuery()) {
outParameters.push({ dir: oracledb.BIND_OUT });
}
}
this.bindParameters = outParameters;
if (Array.isArray(parameters) || _.isPlainObject(parameters)) {
if (this.options.executeMany) {
this._convertBindAttributes("inbindAttributes", oracledb);
bindDef.push(...Object.values(this.options.inbindAttributes));
bindDef.push(...outParameters);
this.bindParameters = parameters;
} else if (this.isRawQuery()) {
this.bindParameters = parameters;
} else {
Object.values(parameters).forEach((value) => {
bindParameters.push(value);
});
bindParameters.push(...outParameters);
Object.assign(this.bindParameters, bindParameters);
}
}
if (this.sql.startsWith("BEGIN TRANSACTION")) {
this.autocommit = false;
return Promise.resolve();
}
if (this.sql.startsWith("SET AUTOCOMMIT ON")) {
this.autocommit = true;
return Promise.resolve();
}
if (this.sql.startsWith("SET AUTOCOMMIT OFF")) {
this.autocommit = false;
return Promise.resolve();
}
if (this.sql.startsWith("DECLARE x NUMBER")) {
if (this.autoCommit === void 0) {
if (this.connection.uuid) {
this.autoCommit = false;
} else {
this.autoCommit = true;
}
}
try {
await this.connection.execute(this.sql, this.bindParameters, { autoCommit: this.autoCommit });
return Object.create(null);
} catch (error) {
throw this.formatError(error);
} finally {
complete();
}
}
if (this.sql.startsWith("BEGIN")) {
if (this.autoCommit === void 0) {
if (this.connection.uuid) {
this.autoCommit = false;
} else {
this.autoCommit = true;
}
}
try {
const result = await this.connection.execute(this.sql, this.bindParameters, {
outFormat: this.outFormat,
autoCommit: this.autoCommit
});
if (!Array.isArray(result.outBinds)) {
return [result.outBinds];
}
return result.outBinds;
} catch (error) {
throw this.formatError(error);
} finally {
complete();
}
}
if (this.sql.startsWith("COMMIT TRANSACTION")) {
try {
await this.connection.commit();
return Object.create(null);
} catch (error) {
throw this.formatError(error);
} finally {
complete();
}
}
if (this.sql.startsWith("ROLLBACK TRANSACTION")) {
try {
await this.connection.rollback();
return Object.create(null);
} catch (error) {
throw this.formatError(error);
} finally {
complete();
}
}
if (this.sql.startsWith("SET TRANSACTION")) {
try {
await this.connection.execute(this.sql, [], { autoCommit: false });
return Object.create(null);
} catch (error) {
throw this.formatError(error);
} finally {
complete();
}
}
if (this.autoCommit === void 0) {
if (this.connection.uuid) {
this.autoCommit = false;
} else {
this.autoCommit = true;
}
}
if ("inputParameters" in this.options && this.options.inputParameters !== null) {
Object.assign(this.bindParameters, this.options.inputParameters);
}
const execOpts = this.getExecOptions();
if (this.options.executeMany && bindDef.length > 0) {
execOpts.bindDefs = bindDef;
}
const executePromise = this.options.executeMany ? this.connection.executeMany(this.sql, this.bindParameters, execOpts) : this.connection.execute(this.sql, this.bindParameters, execOpts);
try {
const result = await executePromise;
return this.formatResults(result);
} catch (error) {
throw this.formatError(error);
} finally {
complete();
}
}
static formatBindParameters(sql, values, dialect) {
const replacementFunc = (match, key, values2) => {
if (values2[key] !== void 0) {
return `:${key}`;
}
return void 0;
};
sql = AbstractQuery.formatBindParameters(sql, values, dialect, replacementFunc)[0];
return [sql, values];
}
_getAttributeMap(attrsMap, rawAttributes) {
attrsMap = Object.assign(attrsMap, _.reduce(rawAttributes, (mp, _2, key) => {
const catalogKey = this.sequelize.queryInterface.queryGenerator.getCatalogName(key);
mp[catalogKey] = key;
return mp;
}, {}));
}
_processRows(rows) {
let result = rows;
let attrsMap = {};
if (this.sequelize.options.quoteIdentifiers === false) {
attrsMap = _.reduce(this.options.attributes, (mp, v) => {
if (typeof v === "object") {
v = v[1];
}
const catalogv = this.sequelize.queryInterface.queryGenerator.getCatalogName(v);
mp[catalogv] = v;
return mp;
}, {});
if (this.model) {
this._getAttributeMap(attrsMap, this.model.rawAttributes);
}
if (this.options.aliasesMapping) {
const obj = Object.fromEntries(this.options.aliasesMapping);
rows = rows.map((row) => _.toPairs(row).reduce((acc, [key, value]) => {
const mapping = Object.values(obj).find((element) => {
const catalogElement = this.sequelize.queryInterface.queryGenerator.getCatalogName(element);
return catalogElement === key;
});
if (mapping)
acc[mapping || key] = value;
return acc;
}, {}));
}
result = rows.map((row) => {
return _.mapKeys(row, (value, key) => {
const targetAttr = attrsMap[key];
if (typeof targetAttr === "string" && targetAttr !== key) {
return targetAttr;
}
return key;
});
});
}
if (this.model) {
result = result.map((row) => {
return _.mapValues(row, (value, key) => {
if (this.model.rawAttributes[key] && this.model.rawAttributes[key].type) {
let typeid = this.model.rawAttributes[key].type.toLocaleString();
if (this.model.rawAttributes[key].type.key === "JSON") {
value = JSON.parse(value);
}
if (typeid.indexOf("(") > -1 && this.model.rawAttributes[key].type.key !== "BOOLEAN") {
typeid = typeid.substr(0, typeid.indexOf("("));
}
const parse = parserStore.get(typeid);
if (value !== null & !!parse) {
value = parse(value);
}
}
return value;
});
});
}
return result;
}
formatResults(data) {
let result = this.instance;
if (this.isInsertQuery(data)) {
let insertData;
if (data.outBinds) {
const keys = Object.keys(this.options.outBindAttributes);
insertData = data.outBinds;
if (this.instance) {
insertData = [insertData];
}
const res = insertData.map((row) => {
const obj = {};
row.forEach((element, index) => {
obj[keys[index]] = element[0];
});
return obj;
});
insertData = res;
if (!this.instance) {
result = res;
}
}
this.handleInsertQuery(insertData);
return [result, data.rowsAffected];
}
if (this.isShowTablesQuery()) {
result = this.handleShowTablesQuery(data.rows);
} else if (this.isDescribeQuery()) {
result = {};
const table = Object.keys(this.sequelize.models);
const modelAttributes = {};
if (this.sequelize.models && table.length > 0) {
this._getAttributeMap(modelAttributes, this.sequelize.models[table[0]].rawAttributes);
}
data.rows.forEach((_result) => {
if (_result.Default) {
_result.Default = _result.Default.replace("('", "").replace("')", "").replace(/'/g, "");
}
if (!(modelAttributes[_result.COLUMN_NAME] in result)) {
let key = modelAttributes[_result.COLUMN_NAME];
if (!key) {
key = _result.COLUMN_NAME;
}
result[key] = {
type: _result.DATA_TYPE.toUpperCase(),
allowNull: _result.NULLABLE === "N" ? false : true,
defaultValue: void 0,
primaryKey: _result.CONSTRAINT_TYPE === "P"
};
}
});
} else if (this.isShowIndexesQuery()) {
result = this.handleShowIndexesQuery(data.rows);
} else if (this.isSelectQuery()) {
const rows = data.rows;
const result2 = this._processRows(rows);
return this.handleSelectQuery(result2);
} else if (this.isCallQuery()) {
result = data.rows[0];
} else if (this.isUpdateQuery()) {
result = [result, data.rowsAffected];
} else if (this.isBulkUpdateQuery()) {
result = data.rowsAffected;
} else if (this.isBulkDeleteQuery()) {
result = data.rowsAffected;
} else if (this.isVersionQuery()) {
const version = data.rows[0].VERSION_FULL;
if (version) {
const versions = version.split(".");
result = `${versions[0]}.${versions[1]}.${versions[2]}`;
} else {
result = "0.0.0";
}
} else if (this.isForeignKeysQuery()) {
result = data.rows;
} else if (this.isUpsertQuery()) {
data = data.outBinds;
const keys = Object.keys(this.options.outBindAttributes);
const obj = {};
for (const k in keys) {
obj[keys[k]] = data[k];
}
obj.isUpdate = data[data.length - 1];
data = obj;
result = [{ isNewRecord: data.isUpdate, value: data }, data.isUpdate == 0];
} else if (this.isShowConstraintsQuery()) {
result = this.handleShowConstraintsQuery(data);
} else if (this.isRawQuery()) {
if (data && data.rows) {
return [data.rows, data.metaData];
}
return [data, data];
}
return result;
}
handleShowConstraintsQuery(data) {
return data.rows.map((result) => {
const constraint = {};
for (const key in result) {
constraint[_.camelCase(key)] = result[key].toLowerCase();
}
return constraint;
});
}
handleShowTablesQuery(results) {
return results.map((resultSet) => {
return {
tableName: resultSet.TABLE_NAME,
schema: resultSet.TABLE_SCHEMA
};
});
}
formatError(err) {
let match;
match = err.message.match(/unique constraint ([\s\S]*) violated/);
if (match && match.length > 1) {
match[1] = match[1].replace("(", "").replace(")", "").split(".")[1];
const errors = [];
let fields = [], message = "Validation error", uniqueKey = null;
if (this.model) {
const uniqueKeys = Object.keys(this.model.uniqueKeys);
const currKey = uniqueKeys.find((key) => {
return key.toUpperCase() === match[1].toUpperCase() || key.toUpperCase() === `"${match[1].toUpperCase()}"`;
});
if (currKey) {
uniqueKey = this.model.uniqueKeys[currKey];
fields = uniqueKey.fields;
}
if (uniqueKey && !!uniqueKey.msg) {
message = uniqueKey.msg;
}
fields.forEach((field) => {
errors.push(new SequelizeErrors.ValidationErrorItem(this.getUniqueConstraintErrorMessage(field), "unique violation", field, null));
});
}
return new SequelizeErrors.UniqueConstraintError({
message,
errors,
err,
fields
});
}
match = err.message.match(/ORA-02291/) || err.message.match(/ORA-02292/);
if (match && match.length > 0) {
return new SequelizeErrors.ForeignKeyConstraintError({
fields: null,
index: match[1],
parent: err
});
}
match = err.message.match(/ORA-02443/);
if (match && match.length > 0) {
return new SequelizeErrors.UnknownConstraintError(match[1]);
}
return new SequelizeErrors.DatabaseError(err);
}
isShowIndexesQuery() {
return this.sql.indexOf("SELECT i.index_name,i.table_name, i.column_name, u.uniqueness") > -1;
}
isSelectCountQuery() {
return this.sql.toUpperCase().indexOf("SELECT COUNT(") > -1;
}
handleShowIndexesQuery(data) {
const acc = [];
data.forEach((indexRecord) => {
if (!acc[indexRecord.INDEX_NAME]) {
acc[indexRecord.INDEX_NAME] = {
unique: indexRecord.UNIQUENESS === "UNIQUE" ? true : false,
primary: indexRecord.CONSTRAINT_TYPE === "P",
name: indexRecord.INDEX_NAME.toLowerCase(),
tableName: indexRecord.TABLE_NAME.toLowerCase(),
type: void 0
};
acc[indexRecord.INDEX_NAME].fields = [];
}
acc[indexRecord.INDEX_NAME].fields.push({
attribute: indexRecord.COLUMN_NAME,
length: void 0,
order: indexRecord.DESCEND,
collate: void 0
});
});
const returnIndexes = [];
const accKeys = Object.keys(acc);
for (const accKey of accKeys) {
const columns = {};
columns.fields = acc[accKey].fields;
if (acc[accKey].name.match(/sys_c[0-9]*/)) {
acc[accKey].name = Utils.nameIndex(columns, acc[accKey].tableName).name;
}
returnIndexes.push(acc[accKey]);
}
return returnIndexes;
}
handleInsertQuery(results, metaData) {
if (this.instance && results.length > 0) {
if ("pkReturnVal" in results[0]) {
results[0][this.model.primaryKeyAttribute] = results[0].pkReturnVal;
delete results[0].pkReturnVal;
}
const autoIncrementField = this.model.autoIncrementAttribute;
let autoIncrementFieldAlias = null, id = null;
if (Object.prototype.hasOwnProperty.call(this.model.rawAttributes, autoIncrementField) && this.model.rawAttributes[autoIncrementField].field !== void 0)
autoIncrementFieldAlias = this.model.rawAttributes[autoIncrementField].field;
id = id || results && results[0][this.getInsertIdField()];
id = id || metaData && metaData[this.getInsertIdField()];
id = id || results && results[0][autoIncrementField];
id = id || autoIncrementFieldAlias && results && results[0][autoIncrementFieldAlias];
this.instance[autoIncrementField] = id;
}
}
}
//# sourceMappingURL=query.js.map

File diff suppressed because one or more lines are too long