@mikro-orm/oracledb 7.3.0-dev.2 → 7.3.0-dev.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/OracleDriver.js CHANGED
@@ -1,4 +1,4 @@
1
- import { QueryFlag, ReferenceKind, Utils, } from '@mikro-orm/core';
1
+ import { QueryFlag, ReferenceKind, } from '@mikro-orm/core';
2
2
  import { AbstractSqlDriver } from '@mikro-orm/sql';
3
3
  import { OracleConnection } from './OracleConnection.js';
4
4
  import { OracleMikroORM } from './OracleMikroORM.js';
@@ -24,22 +24,11 @@ export class OracleDriver extends AbstractSqlDriver {
24
24
  options.processCollections ??= true;
25
25
  options.convertCustomTypes ??= true;
26
26
  const meta = this.metadata.get(entityName);
27
- const pks = this.getPrimaryKeyFields(meta);
28
27
  const collections = options.processCollections ? data.map(d => this.extractManyToMany(meta, d)) : [];
29
28
  const qb = this.createQueryBuilder(entityName, options.ctx, 'write', options.convertCustomTypes).withSchema(this.getSchemaName(meta, options));
30
29
  qb.insert(data);
31
30
  const res = await this.rethrow(qb.execute('run'));
32
- let pk;
33
- if (pks.length > 1) {
34
- // owner has composite pk
35
- pk = data.map(d => Utils.getOrderedPrimaryKeys(d, meta));
36
- }
37
- else {
38
- res.row ??= {};
39
- res.rows ??= [];
40
- pk = data.map((d, i) => d[pks[0]] ?? res.rows[i]?.[pks[0]]).map(d => [d]);
41
- res.insertId = res.insertId || res.row[pks[0]];
42
- }
31
+ const pk = this.resolveInsertedPrimaryKeys(meta, data, res);
43
32
  for (let i = 0; i < collections.length; i++) {
44
33
  await this.processManyToMany(meta, pk[i], collections[i], false, options);
45
34
  }
@@ -58,7 +58,9 @@ export class OracleQueryBuilder extends QueryBuilder {
58
58
  }
59
59
  if (this.type === QueryType.INSERT) {
60
60
  const returningProps = meta.hydrateProps
61
- .filter(prop => prop.returning || (prop.persist !== false && ((prop.primary && prop.autoincrement) || prop.defaultRaw)))
61
+ .filter(prop => prop.returning || (prop.persist !== false && (prop.autoincrement || prop.generated || prop.defaultRaw)))
62
+ // a TPT table can only return its own columns
63
+ .filter(prop => meta.inheritanceType !== 'tpt' || prop.primary || meta.ownProps.some(p => p.name === prop.name))
62
64
  .filter(prop => !(prop.fieldNames[0] in arr[0]) || isRaw(arr[0][prop.fieldNames[0]]));
63
65
  if (returningProps.length > 0) {
64
66
  qb.returning(returningProps.map(prop => [prop.fieldNames[0], prop.runtimeType]));
@@ -8,6 +8,8 @@ export declare class OracleSchemaGenerator extends SchemaGenerator {
8
8
  /** Tracks whether the main user has been granted DBA (or equivalent) privileges. */
9
9
  private hasDbaGrant;
10
10
  static register(orm: MikroORM): void;
11
+ /** Ends the batch after a PL/SQL block (e.g. `create trigger ... end;`), so the `;\n` statement split keeps its closing `;`. */
12
+ protected startsBatch(_statement: string, previous: string): boolean;
11
13
  /**
12
14
  * creates new database and connects to it
13
15
  */
@@ -6,6 +6,10 @@ export class OracleSchemaGenerator extends SchemaGenerator {
6
6
  static register(orm) {
7
7
  orm.config.registerExtension('@mikro-orm/schema-generator', () => new OracleSchemaGenerator(orm.em));
8
8
  }
9
+ /** Ends the batch after a PL/SQL block (e.g. `create trigger ... end;`), so the `;\n` statement split keeps its closing `;`. */
10
+ startsBatch(_statement, previous) {
11
+ return /\bend;$/i.test(previous);
12
+ }
9
13
  /**
10
14
  * creates new database and connects to it
11
15
  */
@@ -369,8 +373,10 @@ export class OracleSchemaGenerator extends SchemaGenerator {
369
373
  .join('.');
370
374
  // Use DELETE instead of TRUNCATE to avoid ORA-02266 (FK constraint check regardless of data)
371
375
  stmts.push(`begin execute immediate 'delete from ${quoted}'; exception when others then if sqlcode != -942 then raise; end if; end;`);
372
- for (const pk of meta.getPrimaryProps().filter(p => p.autoincrement)) {
373
- stmts.push(`begin execute immediate 'alter table ${quoted} modify ${this.platform.quoteIdentifier(pk.fieldNames[0])} generated by default as identity (start with limit value)'; exception when others then null; end;`);
376
+ // non-PK identity columns are only reset when they declare `sequence`
377
+ for (const prop of meta.props.filter(p => p.autoincrement && (p.primary || p.sequence))) {
378
+ const startWith = prop.sequence?.startWith ?? 'limit value';
379
+ stmts.push(`begin execute immediate 'alter table ${quoted} modify ${this.platform.quoteIdentifier(prop.fieldNames[0])} generated by default as identity (start with ${startWith})'; exception when others then null; end;`);
374
380
  }
375
381
  }
376
382
  /* v8 ignore next 5: empty stmts branch */
@@ -1,4 +1,4 @@
1
- import { type AbstractSqlConnection, type CheckDef, type Column, type DatabaseSchema, type DatabaseTable, type Dictionary, type ForeignKey, type IndexDef, SchemaHelper, type Table, type TableDifference, type Transaction, type Type, type SqlRoutineDef } from '@mikro-orm/sql';
1
+ import { type AbstractSqlConnection, type CheckDef, type Column, type DatabaseSchema, type DatabaseTable, type Dictionary, type ForeignKey, type IndexDef, SchemaHelper, type Table, type TableDifference, type Transaction, type Type, type SqlRoutineDef, type SqlTriggerDef } from '@mikro-orm/sql';
2
2
  /** Schema introspection helper for Oracle Database. */
3
3
  export declare class OracleSchemaHelper extends SchemaHelper {
4
4
  static readonly DEFAULT_VALUES: Record<string, string[]>;
@@ -27,6 +27,7 @@ export declare class OracleSchemaHelper extends SchemaHelper {
27
27
  getAllChecks(connection: AbstractSqlConnection, tablesBySchemas: Map<string | undefined, Table[]>, ctx?: Transaction): Promise<Dictionary<CheckDef[]>>;
28
28
  getDatabaseCollation(connection: AbstractSqlConnection, ctx?: Transaction): Promise<string | undefined>;
29
29
  loadInformationSchema(schema: DatabaseSchema, connection: AbstractSqlConnection, tables: Table[], schemas?: string[], ctx?: Transaction): Promise<void>;
30
+ getAllTriggers(connection: AbstractSqlConnection, tablesBySchemas: Map<string | undefined, Table[]>, ctx?: Transaction): Promise<Dictionary<SqlTriggerDef[]>>;
30
31
  getPreAlterTable(tableDiff: TableDifference, safe: boolean): string[];
31
32
  getPostAlterTable(tableDiff: TableDifference, safe: boolean): string[];
32
33
  getCreateNamespaceSQL(name: string): string;
@@ -49,6 +50,11 @@ export declare class OracleSchemaHelper extends SchemaHelper {
49
50
  dropForeignKey(tableName: string, constraintName: string): string;
50
51
  dropViewIfExists(name: string, schema?: string): string;
51
52
  dropTableIfExists(name: string, schema?: string): string;
53
+ /** Oracle supports multiple events and both row and statement level in one trigger, but `instead of` works only on views and there is no `truncate` DML event. */
54
+ createTrigger(table: DatabaseTable, trigger: SqlTriggerDef): string;
55
+ /** Uses `IF EXISTS` (Oracle 23c+), same as the other drop statements. */
56
+ dropTrigger(table: DatabaseTable, trigger: SqlTriggerDef): string;
57
+ private getTriggerName;
52
58
  getAddColumnsSQL(table: DatabaseTable, columns: Column[]): string[];
53
59
  appendComments(table: DatabaseTable): string[];
54
60
  inferLengthFromColumnType(type: string): number | undefined;
@@ -145,9 +145,12 @@ export class OracleSchemaHelper extends SchemaHelper {
145
145
  atc.data_length as data_length,
146
146
  atc.identity_column as is_identity,
147
147
  atc.column_id as ordinal_position,
148
- atc.collation as collation_name
148
+ atc.collation as collation_name,
149
+ regexp_substr(aic.identity_options, 'START WITH: (-?\\d+)', 1, 1, null, 1) as sequence_start,
150
+ regexp_substr(aic.identity_options, 'INCREMENT BY: (-?\\d+)', 1, 1, null, 1) as sequence_increment
149
151
  from all_tab_cols atc
150
152
  left join all_col_comments acc on atc.owner = acc.owner and atc.table_name = acc.table_name and atc.column_name = acc.column_name
153
+ left join all_tab_identity_cols aic on atc.owner = aic.owner and atc.table_name = aic.table_name and atc.column_name = aic.column_name
151
154
  where atc.hidden_column = 'NO'
152
155
  and (${[...tablesBySchemas.entries()].map(([schema, tables]) => `(atc.table_name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(', ')}) and atc.owner = ${this.platform.quoteValue(schema)})`).join(' or ')})
153
156
  order by atc.owner, atc.table_name, atc.column_id`;
@@ -198,6 +201,7 @@ export class OracleSchemaHelper extends SchemaHelper {
198
201
  default: increments ? undefined : this.wrap(defaultValue, mappedType),
199
202
  nullable: col.is_nullable === 'Y',
200
203
  autoincrement: increments,
204
+ sequence: increments ? this.getIntrospectedSequence(col.sequence_start, col.sequence_increment) : undefined,
201
205
  precision: col.numeric_precision,
202
206
  scale: col.numeric_scale,
203
207
  comment: col.column_comment,
@@ -234,17 +238,12 @@ export class OracleSchemaHelper extends SchemaHelper {
234
238
  const isPrimary = index.constraint_type === 'P';
235
239
  const isUniqueConstraint = index.constraint_type === 'U';
236
240
  const isConstraintIndex = isPrimary || isUniqueConstraint;
237
- // Skip indexes that back PRIMARY KEY constraints - they're handled as part of the table definition
238
- // and should not be managed as separate indexes
239
- if (isPrimary) {
240
- continue;
241
- }
242
241
  const partialMatch = typeof index.expression === 'string' ? OracleSchemaHelper.PARTIAL_INDEX_RE.exec(index.expression) : null;
243
242
  const indexDef = {
244
243
  columnNames: [partialMatch ? partialMatch[2] : index.column_name],
245
244
  keyName: index.index_name,
246
245
  unique: index.is_unique === 'YES',
247
- primary: false,
246
+ primary: isPrimary,
248
247
  constraint: isConstraintIndex || index.is_unique === 'YES',
249
248
  };
250
249
  /* v8 ignore start: function-based (non-partial) index branches */
@@ -391,6 +390,7 @@ export class OracleSchemaHelper extends SchemaHelper {
391
390
  const indexes = await this.getAllIndexes(connection, tablesBySchema, ctx);
392
391
  const checks = await this.getAllChecks(connection, tablesBySchema, ctx);
393
392
  const fks = await this.getAllForeignKeys(connection, tablesBySchema, ctx);
393
+ const triggers = await this.getAllTriggers(connection, tablesBySchema, ctx);
394
394
  const dbCollation = await this.getDatabaseCollation(connection, ctx);
395
395
  for (const t of tables) {
396
396
  const key = this.getTableKey(t);
@@ -399,8 +399,35 @@ export class OracleSchemaHelper extends SchemaHelper {
399
399
  const pks = await this.getPrimaryKeys(connection, indexes[key], table.name, table.schema);
400
400
  const enums = this.getEnumDefinitions(checks[key] ?? []);
401
401
  table.init(columns[key], indexes[key], checks[key], pks, fks[key], enums);
402
+ if (triggers[key]) {
403
+ table.setTriggers(triggers[key]);
404
+ }
402
405
  }
403
406
  }
407
+ async getAllTriggers(connection, tablesBySchemas, ctx) {
408
+ // `trigger_body` is a LONG column, which node-oracledb fetches as a string
409
+ const sql = `select trigger_name, table_owner as schema_name, table_name, trigger_type, triggering_event, when_clause, trigger_body
410
+ from all_triggers
411
+ where base_object_type = 'TABLE'
412
+ and (${[...tablesBySchemas.entries()].map(([schema, tables]) => `(table_name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(', ')}) and table_owner = ${this.platform.quoteValue(schema)})`).join(' or ')})
413
+ order by table_owner, table_name, trigger_name`;
414
+ const allTriggers = await connection.execute(sql, [], 'all', ctx);
415
+ const ret = {};
416
+ for (const row of allTriggers) {
417
+ const key = this.getTableKey(row);
418
+ ret[key] ??= [];
419
+ ret[key].push({
420
+ name: row.trigger_name,
421
+ // e.g. `BEFORE EACH ROW`, `AFTER STATEMENT`
422
+ timing: row.trigger_type.replace(/\s+(each row|statement)$/i, '').toLowerCase(),
423
+ events: row.triggering_event.toLowerCase().split(/\s+or\s+/),
424
+ forEach: /\beach row$/i.test(row.trigger_type) ? 'row' : 'statement',
425
+ body: this.stripRoutineBody(row.trigger_body),
426
+ when: row.when_clause?.trim() || undefined,
427
+ });
428
+ }
429
+ return ret;
430
+ }
404
431
  getPreAlterTable(tableDiff, safe) {
405
432
  const ret = [];
406
433
  const indexes = tableDiff.fromTable.getIndexes();
@@ -412,7 +439,8 @@ export class OracleSchemaHelper extends SchemaHelper {
412
439
  const changedTypes = Object.values(tableDiff.changedColumns).filter(col => col.changedProperties.has('type'));
413
440
  for (const col of changedTypes) {
414
441
  for (const index of indexes) {
415
- if (index.columnNames.includes(col.column.name)) {
442
+ // the index backing the primary key can't be dropped, the key constraint stays in place
443
+ if (!index.primary && index.columnNames.includes(col.column.name)) {
416
444
  ret.push(this.getDropIndexSQL(name, index));
417
445
  }
418
446
  }
@@ -430,7 +458,7 @@ export class OracleSchemaHelper extends SchemaHelper {
430
458
  const changedTypes = Object.values(tableDiff.changedColumns).filter(col => col.changedProperties.has('type'));
431
459
  for (const col of changedTypes) {
432
460
  for (const index of indexes) {
433
- if (index.columnNames.includes(col.column.name)) {
461
+ if (!index.primary && index.columnNames.includes(col.column.name)) {
434
462
  this.append(ret, this.getCreateIndexSQL(name, index));
435
463
  }
436
464
  }
@@ -457,8 +485,9 @@ export class OracleSchemaHelper extends SchemaHelper {
457
485
  return `drop index ${this.quote(index.keyName)}`;
458
486
  }
459
487
  dropIndex(table, index, oldIndexName = index.keyName) {
488
+ // the primary key constraint name is system generated unless named explicitly
460
489
  if (index.primary) {
461
- return `alter table ${this.quote(table)} drop constraint ${this.quote(oldIndexName)}`;
490
+ return `alter table ${this.quote(table)} drop primary key`;
462
491
  }
463
492
  return `drop index ${this.quote(oldIndexName)}`;
464
493
  }
@@ -496,7 +525,8 @@ export class OracleSchemaHelper extends SchemaHelper {
496
525
  const columnType = column.generated ? `as ${column.generated}` : column.type;
497
526
  const col = [this.quote(column.name), columnType];
498
527
  Utils.runIfNotEmpty(() => col.push(this.getCollateSQL(column.collation)), column.collation);
499
- Utils.runIfNotEmpty(() => col.push('generated by default as identity'), column.autoincrement);
528
+ const sequenceOptions = this.getSequenceOptionsSQL(column);
529
+ Utils.runIfNotEmpty(() => col.push(`generated by default as identity${sequenceOptions ? ` (${sequenceOptions})` : ''}`), column.autoincrement);
500
530
  /* v8 ignore next 3: default value branch */
501
531
  const useDefault = changedProperties
502
532
  ? false
@@ -568,7 +598,7 @@ export class OracleSchemaHelper extends SchemaHelper {
568
598
  }
569
599
  createIndex(index, table, createPrimary = false) {
570
600
  if (index.primary) {
571
- return '';
601
+ return createPrimary ? super.createIndex(index, table, true) : '';
572
602
  }
573
603
  if (index.expression) {
574
604
  return index.expression;
@@ -624,6 +654,34 @@ export class OracleSchemaHelper extends SchemaHelper {
624
654
  }
625
655
  return `drop table if exists ${this.quote(schema, name)} cascade constraint`;
626
656
  }
657
+ /** Oracle supports multiple events and both row and statement level in one trigger, but `instead of` works only on views and there is no `truncate` DML event. */
658
+ createTrigger(table, trigger) {
659
+ if (trigger.expression) {
660
+ return trigger.expression;
661
+ }
662
+ if (trigger.timing === 'instead of') {
663
+ throw new Error(`Oracle supports INSTEAD OF triggers only on views. Use BEFORE or AFTER for trigger "${trigger.name}".`);
664
+ }
665
+ if (trigger.events.includes('truncate')) {
666
+ throw new Error(`Oracle does not support TRUNCATE triggers. Remove the TRUNCATE event from trigger "${trigger.name}".`);
667
+ }
668
+ if (trigger.when && trigger.forEach === 'statement') {
669
+ throw new Error(`Oracle supports WHEN conditions only on row-level triggers (trigger "${trigger.name}").`);
670
+ }
671
+ const timing = trigger.timing.toUpperCase();
672
+ const events = trigger.events.map(e => e.toUpperCase()).join(' OR ');
673
+ const forEach = trigger.forEach === 'statement' ? '' : ' for each row';
674
+ const when = trigger.when ? ` when (${trigger.when})` : '';
675
+ return `create or replace trigger ${this.getTriggerName(table, trigger)} ${timing} ${events} on ${table.getQuotedName()}${forEach}${when} begin ${this.normalizeTriggerBody(trigger.body)} end;`;
676
+ }
677
+ /** Uses `IF EXISTS` (Oracle 23c+), same as the other drop statements. */
678
+ dropTrigger(table, trigger) {
679
+ return `drop trigger if exists ${this.getTriggerName(table, trigger)}`;
680
+ }
681
+ getTriggerName(table, trigger) {
682
+ const schema = table.schema === this.platform.getDefaultSchemaName() ? undefined : table.schema;
683
+ return this.quote(schema, trigger.name);
684
+ }
627
685
  getAddColumnsSQL(table, columns) {
628
686
  const adds = columns
629
687
  .map(column => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/oracledb",
3
- "version": "7.3.0-dev.2",
3
+ "version": "7.3.0-dev.20",
4
4
  "description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL, SQLite, MSSQL and Oracle databases.",
5
5
  "keywords": [
6
6
  "data-mapper",
@@ -42,15 +42,15 @@
42
42
  "copy": "node ../../scripts/copy.mjs"
43
43
  },
44
44
  "dependencies": {
45
- "@mikro-orm/sql": "7.3.0-dev.2",
46
- "kysely": "0.29.6",
47
- "oracledb": "7.0.1"
45
+ "@mikro-orm/sql": "7.3.0-dev.20",
46
+ "kysely": "0.29.8",
47
+ "oracledb": "26.0.0"
48
48
  },
49
49
  "devDependencies": {
50
- "@mikro-orm/core": "^7.2.1"
50
+ "@mikro-orm/core": "^7.2.7"
51
51
  },
52
52
  "peerDependencies": {
53
- "@mikro-orm/core": "7.3.0-dev.2"
53
+ "@mikro-orm/core": "7.3.0-dev.20"
54
54
  },
55
55
  "engines": {
56
56
  "node": ">= 22.17.0"