Initial commit

This commit is contained in:
2025-12-07 14:32:46 +00:00
commit 0a0969b8af
4726 changed files with 536089 additions and 0 deletions

5
node_modules/knex/lib/dialects/oracle/DEAD_CODE.md generated vendored Executable file
View File

@@ -0,0 +1,5 @@
# Warning: Dead Code
The `oracle` dialect is mostly dead code at this point. However, a handful of its methods are still referenced by the `oracledb` dialect. So, we are in the process of migrating those methods over to the `oracledb` dialect where they belong. Once that task is completed, we will officially remove the `oracle` dialect.
In short: do not use the `oracle` dialect. Use the `oracledb` dialect instead.

92
node_modules/knex/lib/dialects/oracle/index.js generated vendored Executable file
View File

@@ -0,0 +1,92 @@
// Oracle Client
// -------
const { ReturningHelper } = require('./utils');
const { isConnectionError } = require('./utils');
const Client = require('../../client');
const SchemaCompiler = require('./schema/oracle-compiler');
const ColumnBuilder = require('./schema/oracle-columnbuilder');
const ColumnCompiler = require('./schema/oracle-columncompiler');
const TableCompiler = require('./schema/oracle-tablecompiler');
// Always initialize with the "QueryBuilder" and "QueryCompiler"
// objects, which extend the base 'lib/query/builder' and
// 'lib/query/compiler', respectively.
class Client_Oracle extends Client {
schemaCompiler() {
return new SchemaCompiler(this, ...arguments);
}
columnBuilder() {
return new ColumnBuilder(this, ...arguments);
}
columnCompiler() {
return new ColumnCompiler(this, ...arguments);
}
tableCompiler() {
return new TableCompiler(this, ...arguments);
}
// Return the database for the Oracle client.
database() {
return this.connectionSettings.database;
}
// Position the bindings for the query.
positionBindings(sql) {
let questionCount = 0;
return sql.replace(/\?/g, function () {
questionCount += 1;
return `:${questionCount}`;
});
}
_stream(connection, obj, stream, options) {
if (!obj.sql) throw new Error('The query is empty');
return new Promise(function (resolver, rejecter) {
stream.on('error', (err) => {
if (isConnectionError(err)) {
connection.__knex__disposed = err;
}
rejecter(err);
});
stream.on('end', resolver);
const queryStream = connection.queryStream(
obj.sql,
obj.bindings,
options
);
queryStream.pipe(stream);
queryStream.on('error', function (error) {
rejecter(error);
stream.emit('error', error);
});
});
}
// Formatter part
alias(first, second) {
return first + ' ' + second;
}
parameter(value, builder, formatter) {
// Returning helper uses always ROWID as string
if (value instanceof ReturningHelper && this.driver) {
value = new this.driver.OutParam(this.driver.OCCISTRING);
} else if (typeof value === 'boolean') {
value = value ? 1 : 0;
}
return super.parameter(value, builder, formatter);
}
}
Object.assign(Client_Oracle.prototype, {
dialect: 'oracle',
driverName: 'oracle',
});
module.exports = Client_Oracle;

View File

@@ -0,0 +1,343 @@
/* eslint max-len:0 */
// Oracle Query Builder & Compiler
// ------
const compact = require('lodash/compact');
const identity = require('lodash/identity');
const isEmpty = require('lodash/isEmpty');
const isPlainObject = require('lodash/isPlainObject');
const reduce = require('lodash/reduce');
const QueryCompiler = require('../../../query/querycompiler');
const { ReturningHelper } = require('../utils');
const { isString } = require('../../../util/is');
const components = [
'comments',
'columns',
'join',
'where',
'union',
'group',
'having',
'order',
'lock',
];
// Query Compiler
// -------
// Set the "Formatter" to use for the queries,
// ensuring that all parameterized values (even across sub-queries)
// are properly built into the same query.
class QueryCompiler_Oracle extends QueryCompiler {
constructor(client, builder, formatter) {
super(client, builder, formatter);
const { onConflict } = this.single;
if (onConflict) {
throw new Error('.onConflict() is not supported for oracledb.');
}
// Compiles the `select` statement, or nested sub-selects
// by calling each of the component compilers, trimming out
// the empties, and returning a generated query string.
this.first = this.select;
}
// Compiles an "insert" query, allowing for multiple
// inserts using a single query statement.
insert() {
let insertValues = this.single.insert || [];
let { returning } = this.single;
if (!Array.isArray(insertValues) && isPlainObject(this.single.insert)) {
insertValues = [this.single.insert];
}
// always wrap returning argument in array
if (returning && !Array.isArray(returning)) {
returning = [returning];
}
if (
Array.isArray(insertValues) &&
insertValues.length === 1 &&
isEmpty(insertValues[0])
) {
return this._addReturningToSqlAndConvert(
`insert into ${this.tableName} (${this.formatter.wrap(
this.single.returning
)}) values (default)`,
returning,
this.tableName
);
}
if (
isEmpty(this.single.insert) &&
typeof this.single.insert !== 'function'
) {
return '';
}
const insertData = this._prepInsert(insertValues);
const sql = {};
if (isString(insertData)) {
return this._addReturningToSqlAndConvert(
`insert into ${this.tableName} ${insertData}`,
returning
);
}
if (insertData.values.length === 1) {
return this._addReturningToSqlAndConvert(
`insert into ${this.tableName} (${this.formatter.columnize(
insertData.columns
)}) values (${this.client.parameterize(
insertData.values[0],
undefined,
this.builder,
this.bindingsHolder
)})`,
returning,
this.tableName
);
}
const insertDefaultsOnly = insertData.columns.length === 0;
sql.sql =
'begin ' +
insertData.values
.map((value) => {
let returningHelper;
const parameterizedValues = !insertDefaultsOnly
? this.client.parameterize(
value,
this.client.valueForUndefined,
this.builder,
this.bindingsHolder
)
: '';
const returningValues = Array.isArray(returning)
? returning
: [returning];
let subSql = `insert into ${this.tableName} `;
if (returning) {
returningHelper = new ReturningHelper(returningValues.join(':'));
sql.outParams = (sql.outParams || []).concat(returningHelper);
}
if (insertDefaultsOnly) {
// no columns given so only the default value
subSql += `(${this.formatter.wrap(
this.single.returning
)}) values (default)`;
} else {
subSql += `(${this.formatter.columnize(
insertData.columns
)}) values (${parameterizedValues})`;
}
subSql += returning
? ` returning ROWID into ${this.client.parameter(
returningHelper,
this.builder,
this.bindingsHolder
)}`
: '';
// pre bind position because subSql is an execute immediate parameter
// later position binding will only convert the ? params
subSql = this.formatter.client.positionBindings(subSql);
const parameterizedValuesWithoutDefault = parameterizedValues
.replace('DEFAULT, ', '')
.replace(', DEFAULT', '');
return (
`execute immediate '${subSql.replace(/'/g, "''")}` +
(parameterizedValuesWithoutDefault || returning ? "' using " : '') +
parameterizedValuesWithoutDefault +
(parameterizedValuesWithoutDefault && returning ? ', ' : '') +
(returning ? 'out ?' : '') +
';'
);
})
.join(' ') +
'end;';
if (returning) {
sql.returning = returning;
// generate select statement with special order by to keep the order because 'in (..)' may change the order
sql.returningSql =
`select ${this.formatter.columnize(returning)}` +
' from ' +
this.tableName +
' where ROWID in (' +
sql.outParams.map((v, i) => `:${i + 1}`).join(', ') +
')' +
' order by case ROWID ' +
sql.outParams
.map((v, i) => `when CHARTOROWID(:${i + 1}) then ${i}`)
.join(' ') +
' end';
}
return sql;
}
// Update method, including joins, wheres, order & limits.
update() {
const updates = this._prepUpdate(this.single.update);
const where = this.where();
let { returning } = this.single;
const sql =
`update ${this.tableName}` +
' set ' +
updates.join(', ') +
(where ? ` ${where}` : '');
if (!returning) {
return sql;
}
// always wrap returning argument in array
if (!Array.isArray(returning)) {
returning = [returning];
}
return this._addReturningToSqlAndConvert(sql, returning, this.tableName);
}
// Compiles a `truncate` query.
truncate() {
return `truncate table ${this.tableName}`;
}
forUpdate() {
return 'for update';
}
forShare() {
// lock for share is not directly supported by oracle
// use LOCK TABLE .. IN SHARE MODE; instead
this.client.logger.warn(
'lock for share is not supported by oracle dialect'
);
return '';
}
// Compiles a `columnInfo` query.
columnInfo() {
const column = this.single.columnInfo;
// The user may have specified a custom wrapIdentifier function in the config. We
// need to run the identifiers through that function, but not format them as
// identifiers otherwise.
const table = this.client.customWrapIdentifier(this.single.table, identity);
// Node oracle drivers doesn't support LONG type (which is data_default type)
const sql = `select * from xmltable( '/ROWSET/ROW'
passing dbms_xmlgen.getXMLType('
select char_col_decl_length, column_name, data_type, data_default, nullable
from all_tab_columns where table_name = ''${table}'' ')
columns
CHAR_COL_DECL_LENGTH number, COLUMN_NAME varchar2(200), DATA_TYPE varchar2(106),
DATA_DEFAULT clob, NULLABLE varchar2(1))`;
return {
sql: sql,
output(resp) {
const out = reduce(
resp,
function (columns, val) {
columns[val.COLUMN_NAME] = {
type: val.DATA_TYPE,
defaultValue: val.DATA_DEFAULT,
maxLength: val.CHAR_COL_DECL_LENGTH,
nullable: val.NULLABLE === 'Y',
};
return columns;
},
{}
);
return (column && out[column]) || out;
},
};
}
select() {
let query = this.with();
const statements = components.map((component) => {
return this[component]();
});
query += compact(statements).join(' ');
return this._surroundQueryWithLimitAndOffset(query);
}
aggregate(stmt) {
return this._aggregate(stmt, { aliasSeparator: ' ' });
}
// for single commands only
_addReturningToSqlAndConvert(sql, returning, tableName) {
const res = {
sql,
};
if (!returning) {
return res;
}
const returningValues = Array.isArray(returning) ? returning : [returning];
const returningHelper = new ReturningHelper(returningValues.join(':'));
res.sql =
sql +
' returning ROWID into ' +
this.client.parameter(returningHelper, this.builder, this.bindingsHolder);
res.returningSql = `select ${this.formatter.columnize(
returning
)} from ${tableName} where ROWID = :1`;
res.outParams = [returningHelper];
res.returning = returning;
return res;
}
_surroundQueryWithLimitAndOffset(query) {
let { limit } = this.single;
const { offset } = this.single;
const hasLimit = limit || limit === 0 || limit === '0';
limit = +limit;
if (!hasLimit && !offset) return query;
query = query || '';
if (hasLimit && !offset) {
return `select * from (${query}) where rownum <= ${this._getValueOrParameterFromAttribute(
'limit',
limit
)}`;
}
const endRow = +offset + (hasLimit ? limit : 10000000000000);
return (
'select * from ' +
'(select row_.*, ROWNUM rownum_ from (' +
query +
') row_ ' +
'where rownum <= ' +
(this.single.skipBinding['offset']
? endRow
: this.client.parameter(endRow, this.builder, this.bindingsHolder)) +
') ' +
'where rownum_ > ' +
this._getValueOrParameterFromAttribute('offset', offset)
);
}
}
module.exports = QueryCompiler_Oracle;

View File

@@ -0,0 +1,22 @@
const Trigger = require('./trigger');
// helper function for pushAdditional in increments() and bigincrements()
function createAutoIncrementTriggerAndSequence(columnCompiler) {
const trigger = new Trigger(columnCompiler.client.version);
// TODO Add warning that sequence etc is created
columnCompiler.pushAdditional(function () {
const tableName = this.tableCompiler.tableNameRaw;
const schemaName = this.tableCompiler.schemaNameRaw;
const createTriggerSQL = trigger.createAutoIncrementTrigger(
this.client.logger,
tableName,
schemaName
);
this.pushQuery(createTriggerSQL);
});
}
module.exports = {
createAutoIncrementTriggerAndSequence,
};

View File

@@ -0,0 +1,155 @@
const { NameHelper } = require('../../utils');
class Trigger {
constructor(oracleVersion) {
this.nameHelper = new NameHelper(oracleVersion);
}
renameColumnTrigger(logger, tableName, columnName, to) {
const triggerName = this.nameHelper.generateCombinedName(
logger,
'autoinc_trg',
tableName
);
const sequenceName = this.nameHelper.generateCombinedName(
logger,
'seq',
tableName
);
return (
`DECLARE ` +
`PK_NAME VARCHAR(200); ` +
`IS_AUTOINC NUMBER := 0; ` +
`BEGIN` +
` EXECUTE IMMEDIATE ('ALTER TABLE "${tableName}" RENAME COLUMN "${columnName}" TO "${to}"');` +
` SELECT COUNT(*) INTO IS_AUTOINC from "USER_TRIGGERS" where trigger_name = '${triggerName}';` +
` IF (IS_AUTOINC > 0) THEN` +
` SELECT cols.column_name INTO PK_NAME` +
` FROM all_constraints cons, all_cons_columns cols` +
` WHERE cons.constraint_type = 'P'` +
` AND cons.constraint_name = cols.constraint_name` +
` AND cons.owner = cols.owner` +
` AND cols.table_name = '${tableName}';` +
` IF ('${to}' = PK_NAME) THEN` +
` EXECUTE IMMEDIATE ('DROP TRIGGER "${triggerName}"');` +
` EXECUTE IMMEDIATE ('create or replace trigger "${triggerName}"` +
` BEFORE INSERT on "${tableName}" for each row` +
` declare` +
` checking number := 1;` +
` begin` +
` if (:new."${to}" is null) then` +
` while checking >= 1 loop` +
` select "${sequenceName}".nextval into :new."${to}" from dual;` +
` select count("${to}") into checking from "${tableName}"` +
` where "${to}" = :new."${to}";` +
` end loop;` +
` end if;` +
` end;');` +
` end if;` +
` end if;` +
`END;`
);
}
createAutoIncrementTrigger(logger, tableName, schemaName) {
const tableQuoted = `"${tableName}"`;
const tableUnquoted = tableName;
const schemaQuoted = schemaName ? `"${schemaName}".` : '';
const constraintOwner = schemaName ? `'${schemaName}'` : 'cols.owner';
const triggerName = this.nameHelper.generateCombinedName(
logger,
'autoinc_trg',
tableName
);
const sequenceNameUnquoted = this.nameHelper.generateCombinedName(
logger,
'seq',
tableName
);
const sequenceNameQuoted = `"${sequenceNameUnquoted}"`;
return (
`DECLARE ` +
`PK_NAME VARCHAR(200); ` +
`BEGIN` +
` EXECUTE IMMEDIATE ('CREATE SEQUENCE ${schemaQuoted}${sequenceNameQuoted}');` +
` SELECT cols.column_name INTO PK_NAME` + // TODO : support autoincrement on table with multiple primary keys
` FROM all_constraints cons, all_cons_columns cols` +
` WHERE cons.constraint_type = 'P'` +
` AND cons.constraint_name = cols.constraint_name` +
` AND cons.owner = ${constraintOwner}` +
` AND cols.table_name = '${tableUnquoted}';` +
` execute immediate ('create or replace trigger ${schemaQuoted}"${triggerName}"` +
` BEFORE INSERT on ${schemaQuoted}${tableQuoted}` +
` for each row` +
` declare` +
` checking number := 1;` +
` begin` +
` if (:new."' || PK_NAME || '" is null) then` +
` while checking >= 1 loop` +
` select ${schemaQuoted}${sequenceNameQuoted}.nextval into :new."' || PK_NAME || '" from dual;` +
` select count("' || PK_NAME || '") into checking from ${schemaQuoted}${tableQuoted}` +
` where "' || PK_NAME || '" = :new."' || PK_NAME || '";` +
` end loop;` +
` end if;` +
` end;'); ` +
`END;`
);
}
renameTableAndAutoIncrementTrigger(logger, tableName, to) {
const triggerName = this.nameHelper.generateCombinedName(
logger,
'autoinc_trg',
tableName
);
const sequenceName = this.nameHelper.generateCombinedName(
logger,
'seq',
tableName
);
const toTriggerName = this.nameHelper.generateCombinedName(
logger,
'autoinc_trg',
to
);
const toSequenceName = this.nameHelper.generateCombinedName(
logger,
'seq',
to
);
return (
`DECLARE ` +
`PK_NAME VARCHAR(200); ` +
`IS_AUTOINC NUMBER := 0; ` +
`BEGIN` +
` EXECUTE IMMEDIATE ('RENAME "${tableName}" TO "${to}"');` +
` SELECT COUNT(*) INTO IS_AUTOINC from "USER_TRIGGERS" where trigger_name = '${triggerName}';` +
` IF (IS_AUTOINC > 0) THEN` +
` EXECUTE IMMEDIATE ('DROP TRIGGER "${triggerName}"');` +
` EXECUTE IMMEDIATE ('RENAME "${sequenceName}" TO "${toSequenceName}"');` +
` SELECT cols.column_name INTO PK_NAME` +
` FROM all_constraints cons, all_cons_columns cols` +
` WHERE cons.constraint_type = 'P'` +
` AND cons.constraint_name = cols.constraint_name` +
` AND cons.owner = cols.owner` +
` AND cols.table_name = '${to}';` +
` EXECUTE IMMEDIATE ('create or replace trigger "${toTriggerName}"` +
` BEFORE INSERT on "${to}" for each row` +
` declare` +
` checking number := 1;` +
` begin` +
` if (:new."' || PK_NAME || '" is null) then` +
` while checking >= 1 loop` +
` select "${toSequenceName}".nextval into :new."' || PK_NAME || '" from dual;` +
` select count("' || PK_NAME || '") into checking from "${to}"` +
` where "' || PK_NAME || '" = :new."' || PK_NAME || '";` +
` end loop;` +
` end if;` +
` end;');` +
` end if;` +
`END;`
);
}
}
module.exports = Trigger;

View File

@@ -0,0 +1,17 @@
const ColumnBuilder = require('../../../schema/columnbuilder');
const toArray = require('lodash/toArray');
class ColumnBuilder_Oracle extends ColumnBuilder {
constructor() {
super(...arguments);
}
// checkIn added to the builder to allow the column compiler to change the
// order via the modifiers ("check" must be after "default")
checkIn() {
this._modifiers.checkIn = toArray(arguments);
return this;
}
}
module.exports = ColumnBuilder_Oracle;

View File

@@ -0,0 +1,126 @@
const uniq = require('lodash/uniq');
const Raw = require('../../../raw');
const ColumnCompiler = require('../../../schema/columncompiler');
const {
createAutoIncrementTriggerAndSequence,
} = require('./internal/incrementUtils');
const { toNumber } = require('../../../util/helpers');
// Column Compiler
// -------
class ColumnCompiler_Oracle extends ColumnCompiler {
constructor() {
super(...arguments);
this.modifiers = ['defaultTo', 'checkIn', 'nullable', 'comment'];
}
increments(options = { primaryKey: true }) {
createAutoIncrementTriggerAndSequence(this);
return (
'integer not null' +
(this.tableCompiler._canBeAddPrimaryKey(options) ? ' primary key' : '')
);
}
bigincrements(options = { primaryKey: true }) {
createAutoIncrementTriggerAndSequence(this);
return (
'number(20, 0) not null' +
(this.tableCompiler._canBeAddPrimaryKey(options) ? ' primary key' : '')
);
}
floating(precision) {
const parsedPrecision = toNumber(precision, 0);
return `float${parsedPrecision ? `(${parsedPrecision})` : ''}`;
}
double(precision, scale) {
// if (!precision) return 'number'; // TODO: Check If default is ok
return `number(${toNumber(precision, 8)}, ${toNumber(scale, 2)})`;
}
decimal(precision, scale) {
if (precision === null) return 'decimal';
return `decimal(${toNumber(precision, 8)}, ${toNumber(scale, 2)})`;
}
integer(length) {
return length ? `number(${toNumber(length, 11)})` : 'integer';
}
enu(allowed) {
allowed = uniq(allowed);
const maxLength = (allowed || []).reduce(
(maxLength, name) => Math.max(maxLength, String(name).length),
1
);
// implicitly add the enum values as checked values
this.columnBuilder._modifiers.checkIn = [allowed];
return `varchar2(${maxLength})`;
}
datetime(without) {
return without ? 'timestamp' : 'timestamp with time zone';
}
timestamp(without) {
return without ? 'timestamp' : 'timestamp with time zone';
}
bool() {
// implicitly add the check for 0 and 1
this.columnBuilder._modifiers.checkIn = [[0, 1]];
return 'number(1, 0)';
}
varchar(length) {
return `varchar2(${toNumber(length, 255)})`;
}
// Modifiers
// ------
comment(comment) {
const columnName = this.args[0] || this.defaults('columnName');
this.pushAdditional(function () {
this.pushQuery(
`comment on column ${this.tableCompiler.tableName()}.` +
this.formatter.wrap(columnName) +
" is '" +
(comment || '') +
"'"
);
}, comment);
}
checkIn(value) {
// TODO: Maybe accept arguments also as array
// TODO: value(s) should be escaped properly
if (value === undefined) {
return '';
} else if (value instanceof Raw) {
value = value.toQuery();
} else if (Array.isArray(value)) {
value = value.map((v) => `'${v}'`).join(', ');
} else {
value = `'${value}'`;
}
return `check (${this.formatter.wrap(this.args[0])} in (${value}))`;
}
}
ColumnCompiler_Oracle.prototype.tinyint = 'smallint';
ColumnCompiler_Oracle.prototype.smallint = 'smallint';
ColumnCompiler_Oracle.prototype.mediumint = 'integer';
ColumnCompiler_Oracle.prototype.biginteger = 'number(20, 0)';
ColumnCompiler_Oracle.prototype.text = 'clob';
ColumnCompiler_Oracle.prototype.time = 'timestamp with time zone';
ColumnCompiler_Oracle.prototype.bit = 'clob';
ColumnCompiler_Oracle.prototype.json = 'clob';
module.exports = ColumnCompiler_Oracle;

View File

@@ -0,0 +1,124 @@
// Oracle Schema Compiler
// -------
const SchemaCompiler = require('../../../schema/compiler');
const utils = require('../utils');
const Trigger = require('./internal/trigger');
class SchemaCompiler_Oracle extends SchemaCompiler {
constructor() {
super(...arguments);
}
// Rename a table on the schema.
renameTable(tableName, to) {
const trigger = new Trigger(this.client.version);
const renameTable = trigger.renameTableAndAutoIncrementTrigger(
this.client.logger,
tableName,
to
);
this.pushQuery(renameTable);
}
// Check whether a table exists on the query.
hasTable(tableName) {
this.pushQuery({
sql:
'select TABLE_NAME from USER_TABLES where TABLE_NAME = ' +
this.client.parameter(tableName, this.builder, this.bindingsHolder),
output(resp) {
return resp.length > 0;
},
});
}
// Check whether a column exists on the schema.
hasColumn(tableName, column) {
const sql =
`select COLUMN_NAME from ALL_TAB_COLUMNS ` +
`where TABLE_NAME = ${this.client.parameter(
tableName,
this.builder,
this.bindingsHolder
)} ` +
`and COLUMN_NAME = ${this.client.parameter(
column,
this.builder,
this.bindingsHolder
)}`;
this.pushQuery({ sql, output: (resp) => resp.length > 0 });
}
dropSequenceIfExists(sequenceName) {
const prefix = this.schema ? `"${this.schema}".` : '';
this.pushQuery(
utils.wrapSqlWithCatch(
`drop sequence ${prefix}${this.formatter.wrap(sequenceName)}`,
-2289
)
);
}
_dropRelatedSequenceIfExists(tableName) {
// removing the sequence that was possibly generated by increments() column
const nameHelper = new utils.NameHelper(this.client.version);
const sequenceName = nameHelper.generateCombinedName(
this.client.logger,
'seq',
tableName
);
this.dropSequenceIfExists(sequenceName);
}
dropTable(tableName) {
const prefix = this.schema ? `"${this.schema}".` : '';
this.pushQuery(`drop table ${prefix}${this.formatter.wrap(tableName)}`);
// removing the sequence that was possibly generated by increments() column
this._dropRelatedSequenceIfExists(tableName);
}
dropTableIfExists(tableName) {
this.dropObject(tableName, 'table');
}
dropViewIfExists(viewName) {
this.dropObject(viewName, 'view');
}
dropObject(objectName, type) {
const prefix = this.schema ? `"${this.schema}".` : '';
let errorCode = -942;
if (type === 'materialized view') {
// https://stackoverflow.com/a/1801453
errorCode = -12003;
}
this.pushQuery(
utils.wrapSqlWithCatch(
`drop ${type} ${prefix}${this.formatter.wrap(objectName)}`,
errorCode
)
);
// removing the sequence that was possibly generated by increments() column
this._dropRelatedSequenceIfExists(objectName);
}
refreshMaterializedView(viewName) {
return this.pushQuery({
sql: `BEGIN DBMS_MVIEW.REFRESH('${
this.schemaNameRaw ? this.schemaNameRaw + '.' : ''
}${viewName}'); END;`,
});
}
dropMaterializedView(viewName) {
this._dropView(viewName, false, true);
}
dropMaterializedViewIfExists(viewName) {
this.dropObject(viewName, 'materialized view');
}
}
module.exports = SchemaCompiler_Oracle;

View File

@@ -0,0 +1,197 @@
/* eslint max-len:0 */
const utils = require('../utils');
const TableCompiler = require('../../../schema/tablecompiler');
const helpers = require('../../../util/helpers');
const Trigger = require('./internal/trigger');
const { isObject } = require('../../../util/is');
// Table Compiler
// ------
class TableCompiler_Oracle extends TableCompiler {
constructor() {
super(...arguments);
}
addColumns(columns, prefix) {
if (columns.sql.length > 0) {
prefix = prefix || this.addColumnsPrefix;
const columnSql = columns.sql;
const alter = this.lowerCase ? 'alter table ' : 'ALTER TABLE ';
let sql = `${alter}${this.tableName()} ${prefix}`;
if (columns.sql.length > 1) {
sql += `(${columnSql.join(', ')})`;
} else {
sql += columnSql.join(', ');
}
this.pushQuery({
sql,
bindings: columns.bindings,
});
}
}
// Compile a rename column command.
renameColumn(from, to) {
// Remove quotes around tableName
const tableName = this.tableName().slice(1, -1);
const trigger = new Trigger(this.client.version);
return this.pushQuery(
trigger.renameColumnTrigger(this.client.logger, tableName, from, to)
);
}
compileAdd(builder) {
const table = this.formatter.wrap(builder);
const columns = this.prefixArray('add column', this.getColumns(builder));
return this.pushQuery({
sql: `alter table ${table} ${columns.join(', ')}`,
});
}
// Adds the "create" query to the query sequence.
createQuery(columns, ifNot, like) {
const columnsSql =
like && this.tableNameLike()
? ' as (select * from ' + this.tableNameLike() + ' where 0=1)'
: ' (' + columns.sql.join(', ') + this._addChecks() + ')';
const sql = `create table ${this.tableName()}${columnsSql}`;
this.pushQuery({
// catch "name is already used by an existing object" for workaround for "if not exists"
sql: ifNot ? utils.wrapSqlWithCatch(sql, -955) : sql,
bindings: columns.bindings,
});
if (this.single.comment) this.comment(this.single.comment);
if (like) {
this.addColumns(columns, this.addColumnsPrefix);
}
}
// Compiles the comment on the table.
comment(comment) {
this.pushQuery(`comment on table ${this.tableName()} is '${comment}'`);
}
dropColumn() {
const columns = helpers.normalizeArr.apply(null, arguments);
this.pushQuery(
`alter table ${this.tableName()} drop (${this.formatter.columnize(
columns
)})`
);
}
_indexCommand(type, tableName, columns) {
const nameHelper = new utils.NameHelper(this.client.version);
return this.formatter.wrap(
nameHelper.generateCombinedName(
this.client.logger,
type,
tableName,
columns
)
);
}
primary(columns, constraintName) {
let deferrable;
if (isObject(constraintName)) {
({ constraintName, deferrable } = constraintName);
}
deferrable = deferrable ? ` deferrable initially ${deferrable}` : '';
constraintName = constraintName
? this.formatter.wrap(constraintName)
: this.formatter.wrap(`${this.tableNameRaw}_pkey`);
const primaryCols = columns;
let incrementsCols = [];
if (this.grouped.columns) {
incrementsCols = this._getIncrementsColumnNames();
if (incrementsCols) {
incrementsCols.forEach((c) => {
if (!primaryCols.includes(c)) {
primaryCols.unshift(c);
}
});
}
}
this.pushQuery(
`alter table ${this.tableName()} add constraint ${constraintName} primary key (${this.formatter.columnize(
primaryCols
)})${deferrable}`
);
}
dropPrimary(constraintName) {
constraintName = constraintName
? this.formatter.wrap(constraintName)
: this.formatter.wrap(this.tableNameRaw + '_pkey');
this.pushQuery(
`alter table ${this.tableName()} drop constraint ${constraintName}`
);
}
index(columns, indexName) {
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('index', this.tableNameRaw, columns);
this.pushQuery(
`create index ${indexName} on ${this.tableName()}` +
' (' +
this.formatter.columnize(columns) +
')'
);
}
dropIndex(columns, indexName) {
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('index', this.tableNameRaw, columns);
this.pushQuery(`drop index ${indexName}`);
}
unique(columns, indexName) {
let deferrable;
if (isObject(indexName)) {
({ indexName, deferrable } = indexName);
}
deferrable = deferrable ? ` deferrable initially ${deferrable}` : '';
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('unique', this.tableNameRaw, columns);
this.pushQuery(
`alter table ${this.tableName()} add constraint ${indexName}` +
' unique (' +
this.formatter.columnize(columns) +
')' +
deferrable
);
}
dropUnique(columns, indexName) {
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('unique', this.tableNameRaw, columns);
this.pushQuery(
`alter table ${this.tableName()} drop constraint ${indexName}`
);
}
dropForeign(columns, indexName) {
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('foreign', this.tableNameRaw, columns);
this.pushQuery(
`alter table ${this.tableName()} drop constraint ${indexName}`
);
}
}
TableCompiler_Oracle.prototype.addColumnsPrefix = 'add ';
TableCompiler_Oracle.prototype.alterColumnsPrefix = 'modify ';
module.exports = TableCompiler_Oracle;

106
node_modules/knex/lib/dialects/oracle/utils.js generated vendored Executable file
View File

@@ -0,0 +1,106 @@
class NameHelper {
constructor(oracleVersion) {
this.oracleVersion = oracleVersion;
// In oracle versions prior to 12.2, the maximum length for a database
// object name was 30 characters. 12.2 extended this to 128.
const versionParts = oracleVersion
.split('.')
.map((versionPart) => parseInt(versionPart));
if (
versionParts[0] > 12 ||
(versionParts[0] === 12 && versionParts[1] >= 2)
) {
this.limit = 128;
} else {
this.limit = 30;
}
}
generateCombinedName(logger, postfix, name, subNames) {
const crypto = require('crypto');
if (!Array.isArray(subNames)) subNames = subNames ? [subNames] : [];
const table = name.replace(/\.|-/g, '_');
const subNamesPart = subNames.join('_');
let result = `${table}_${
subNamesPart.length ? subNamesPart + '_' : ''
}${postfix}`.toLowerCase();
if (result.length > this.limit) {
logger.warn(
`Automatically generated name "${result}" exceeds ${this.limit} character ` +
`limit for Oracle Database ${this.oracleVersion}. Using base64 encoded sha1 of that name instead.`
);
// generates the sha1 of the name and encode it with base64
result = crypto
.createHash('sha1')
.update(result)
.digest('base64')
.replace('=', '');
}
return result;
}
}
function wrapSqlWithCatch(sql, errorNumberToCatch) {
return (
`begin execute immediate '${sql.replace(/'/g, "''")}'; ` +
`exception when others then if sqlcode != ${errorNumberToCatch} then raise; ` +
`end if; ` +
`end;`
);
}
function ReturningHelper(columnName) {
this.columnName = columnName;
}
ReturningHelper.prototype.toString = function () {
return `[object ReturningHelper:${this.columnName}]`;
};
// If the error is any of these, we'll assume we need to
// mark the connection as failed
function isConnectionError(err) {
return [
'DPI-1010', // not connected
'DPI-1080', // connection was closed by ORA-%d
'ORA-03114', // not connected to ORACLE
'ORA-03113', // end-of-file on communication channel
'ORA-03135', // connection lost contact
'ORA-12514', // listener does not currently know of service requested in connect descriptor
'ORA-00022', // invalid session ID; access denied
'ORA-00028', // your session has been killed
'ORA-00031', // your session has been marked for kill
'ORA-00045', // your session has been terminated with no replay
'ORA-00378', // buffer pools cannot be created as specified
'ORA-00602', // internal programming exception
'ORA-00603', // ORACLE server session terminated by fatal error
'ORA-00609', // could not attach to incoming connection
'ORA-01012', // not logged on
'ORA-01041', // internal error. hostdef extension doesn't exist
'ORA-01043', // user side memory corruption
'ORA-01089', // immediate shutdown or close in progress
'ORA-01092', // ORACLE instance terminated. Disconnection forced
'ORA-02396', // exceeded maximum idle time, please connect again
'ORA-03122', // attempt to close ORACLE-side window on user side
'ORA-12153', // TNS'not connected
'ORA-12537', // TNS'connection closed
'ORA-12547', // TNS'lost contact
'ORA-12570', // TNS'packet reader failure
'ORA-12583', // TNS'no reader
'ORA-27146', // post/wait initialization failed
'ORA-28511', // lost RPC connection
'ORA-56600', // an illegal OCI function call was issued
'NJS-024',
'NJS-003',
].some(function (prefix) {
return err.message.indexOf(prefix) === 0;
});
}
module.exports = {
NameHelper,
isConnectionError,
wrapSqlWithCatch,
ReturningHelper,
};