@mikro-orm/knex 6.4.17-dev.60 → 6.4.17-dev.62

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.
@@ -1,5 +1,5 @@
1
1
  import { type Knex } from 'knex';
2
- import { Connection, type AnyEntity, type Configuration, type ConnectionOptions, type EntityData, type IsolationLevel, type QueryResult, type Transaction, type TransactionEventBroadcaster, type LoggingOptions } from '@mikro-orm/core';
2
+ import { Connection, type AnyEntity, type Configuration, type ConnectionOptions, type EntityData, type IsolationLevel, type QueryResult, type Transaction, type TransactionEventBroadcaster, type LogContext, type LoggingOptions } from '@mikro-orm/core';
3
3
  import type { AbstractSqlPlatform } from './AbstractSqlPlatform';
4
4
  export declare abstract class AbstractSqlConnection extends Connection {
5
5
  private static __patched;
@@ -33,15 +33,17 @@ export declare abstract class AbstractSqlConnection extends Connection {
33
33
  readOnly?: boolean;
34
34
  ctx?: Knex.Transaction;
35
35
  eventBroadcaster?: TransactionEventBroadcaster;
36
+ loggerContext?: LogContext;
36
37
  }): Promise<T>;
37
38
  begin(options?: {
38
39
  isolationLevel?: IsolationLevel;
39
40
  readOnly?: boolean;
40
41
  ctx?: Knex.Transaction;
41
42
  eventBroadcaster?: TransactionEventBroadcaster;
43
+ loggerContext?: LogContext;
42
44
  }): Promise<Knex.Transaction>;
43
- commit(ctx: Knex.Transaction, eventBroadcaster?: TransactionEventBroadcaster): Promise<void>;
44
- rollback(ctx: Knex.Transaction, eventBroadcaster?: TransactionEventBroadcaster): Promise<void>;
45
+ commit(ctx: Knex.Transaction, eventBroadcaster?: TransactionEventBroadcaster, loggerContext?: LogContext): Promise<void>;
46
+ rollback(ctx: Knex.Transaction, eventBroadcaster?: TransactionEventBroadcaster, loggerContext?: LogContext): Promise<void>;
45
47
  execute<T extends QueryResult | EntityData<AnyEntity> | EntityData<AnyEntity>[] = EntityData<AnyEntity>[]>(queryOrKnex: string | Knex.QueryBuilder | Knex.Raw, params?: unknown[], method?: 'all' | 'get' | 'run', ctx?: Transaction, loggerContext?: LoggingOptions): Promise<T>;
46
48
  /**
47
49
  * Execute raw SQL queries from file
@@ -56,11 +56,11 @@ class AbstractSqlConnection extends core_1.Connection {
56
56
  const trx = await this.begin(options);
57
57
  try {
58
58
  const ret = await cb(trx);
59
- await this.commit(trx, options.eventBroadcaster);
59
+ await this.commit(trx, options.eventBroadcaster, options.loggerContext);
60
60
  return ret;
61
61
  }
62
62
  catch (error) {
63
- await this.rollback(trx, options.eventBroadcaster);
63
+ await this.rollback(trx, options.eventBroadcaster, options.loggerContext);
64
64
  throw error;
65
65
  }
66
66
  }
@@ -72,6 +72,19 @@ class AbstractSqlConnection extends core_1.Connection {
72
72
  isolationLevel: options.isolationLevel,
73
73
  readOnly: options.readOnly,
74
74
  });
75
+ if (options.ctx) {
76
+ const ctx = options.ctx;
77
+ ctx.index ??= 0;
78
+ const savepointName = `trx${ctx.index + 1}`;
79
+ Reflect.defineProperty(trx, 'index', { value: ctx.index + 1 });
80
+ Reflect.defineProperty(trx, 'savepointName', { value: savepointName });
81
+ this.logQuery(this.platform.getSavepointSQL(savepointName), options.loggerContext);
82
+ }
83
+ else {
84
+ for (const query of this.platform.getBeginTransactionSQL(options)) {
85
+ this.logQuery(query, options.loggerContext);
86
+ }
87
+ }
75
88
  if (!options.ctx) {
76
89
  await options.eventBroadcaster?.dispatchEvent(core_1.EventType.afterTransactionStart, trx);
77
90
  }
@@ -80,23 +93,35 @@ class AbstractSqlConnection extends core_1.Connection {
80
93
  }
81
94
  return trx;
82
95
  }
83
- async commit(ctx, eventBroadcaster) {
96
+ async commit(ctx, eventBroadcaster, loggerContext) {
84
97
  const runTrxHooks = isRootTransaction(ctx);
85
98
  if (runTrxHooks) {
86
99
  await eventBroadcaster?.dispatchEvent(core_1.EventType.beforeTransactionCommit, ctx);
87
100
  }
88
101
  ctx.commit();
89
102
  await ctx.executionPromise; // https://github.com/knex/knex/issues/3847#issuecomment-626330453
103
+ if ('savepointName' in ctx) {
104
+ this.logQuery(this.platform.getReleaseSavepointSQL(ctx.savepointName), loggerContext);
105
+ }
106
+ else {
107
+ this.logQuery(this.platform.getCommitTransactionSQL(), loggerContext);
108
+ }
90
109
  if (runTrxHooks) {
91
110
  await eventBroadcaster?.dispatchEvent(core_1.EventType.afterTransactionCommit, ctx);
92
111
  }
93
112
  }
94
- async rollback(ctx, eventBroadcaster) {
113
+ async rollback(ctx, eventBroadcaster, loggerContext) {
95
114
  const runTrxHooks = isRootTransaction(ctx);
96
115
  if (runTrxHooks) {
97
116
  await eventBroadcaster?.dispatchEvent(core_1.EventType.beforeTransactionRollback, ctx);
98
117
  }
99
118
  await ctx.rollback();
119
+ if ('savepointName' in ctx) {
120
+ this.logQuery(this.platform.getRollbackToSavepointSQL(ctx.savepointName), loggerContext);
121
+ }
122
+ else {
123
+ this.logQuery(this.platform.getRollbackTransactionSQL(), loggerContext);
124
+ }
100
125
  if (runTrxHooks) {
101
126
  await eventBroadcaster?.dispatchEvent(core_1.EventType.afterTransactionRollback, ctx);
102
127
  }
@@ -107,7 +132,7 @@ class AbstractSqlConnection extends core_1.Connection {
107
132
  ctx ??= (queryOrKnex.client.transacting ? queryOrKnex : null);
108
133
  const q = queryOrKnex.toSQL();
109
134
  queryOrKnex = q.sql;
110
- params = q.bindings;
135
+ params = q.bindings ?? [];
111
136
  }
112
137
  queryOrKnex = this.config.get('onQuery')(queryOrKnex, params);
113
138
  const formatted = this.platform.formatQuery(queryOrKnex, params);
@@ -141,11 +166,7 @@ class AbstractSqlConnection extends core_1.Connection {
141
166
  return driverOptions;
142
167
  }
143
168
  return (0, knex_1.knex)(this.getKnexOptions(type))
144
- .on('query', data => {
145
- if (!data.__knexQueryUid) {
146
- this.logQuery(data.sql.toLowerCase().replace(/;$/, ''));
147
- }
148
- });
169
+ .on('query', data => data);
149
170
  }
150
171
  getKnexOptions(type) {
151
172
  const config = core_1.Utils.mergeConfig({
@@ -343,7 +343,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
343
343
  const meta = this.metadata.find(entityName);
344
344
  const collections = this.extractManyToMany(entityName, data);
345
345
  const pks = meta?.primaryKeys ?? [this.config.getNamingStrategy().referenceColumnName()];
346
- const qb = this.createQueryBuilder(entityName, options.ctx, 'write', options.convertCustomTypes).withSchema(this.getSchemaName(meta, options));
346
+ const qb = this.createQueryBuilder(entityName, options.ctx, 'write', options.convertCustomTypes, options.loggerContext).withSchema(this.getSchemaName(meta, options));
347
347
  const res = await this.rethrow(qb.insert(data).execute('run', false));
348
348
  res.row = res.row || {};
349
349
  let pk;
@@ -470,7 +470,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
470
470
  if (transform) {
471
471
  sql = transform(sql);
472
472
  }
473
- const res = await this.execute(sql, params, 'run', options.ctx);
473
+ const res = await this.execute(sql, params, 'run', options.ctx, options.loggerContext);
474
474
  let pk;
475
475
  /* istanbul ignore next */
476
476
  if (pks.length > 1) { // owner has composite pk
@@ -498,7 +498,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
498
498
  where = { [meta?.primaryKeys[0] ?? pks[0]]: where };
499
499
  }
500
500
  if (core_1.Utils.hasObjectKeys(data)) {
501
- const qb = this.createQueryBuilder(entityName, options.ctx, 'write', options.convertCustomTypes)
501
+ const qb = this.createQueryBuilder(entityName, options.ctx, 'write', options.convertCustomTypes, options.loggerContext)
502
502
  .withSchema(this.getSchemaName(meta, options));
503
503
  if (options.upsert) {
504
504
  /* istanbul ignore next */
@@ -537,7 +537,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
537
537
  const meta = this.metadata.get(entityName);
538
538
  if (options.upsert) {
539
539
  const uniqueFields = options.onConflictFields ?? (core_1.Utils.isPlainObject(where[0]) ? Object.keys(where[0]).flatMap(key => core_1.Utils.splitPrimaryKeys(key)) : meta.primaryKeys);
540
- const qb = this.createQueryBuilder(entityName, options.ctx, 'write', options.convertCustomTypes).withSchema(this.getSchemaName(meta, options));
540
+ const qb = this.createQueryBuilder(entityName, options.ctx, 'write', options.convertCustomTypes, options.loggerContext).withSchema(this.getSchemaName(meta, options));
541
541
  const returning = (0, core_1.getOnConflictReturningFields)(meta, data[0], uniqueFields, options);
542
542
  qb.insert(data)
543
543
  .onConflict(uniqueFields)
@@ -650,7 +650,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
650
650
  /* istanbul ignore next */
651
651
  sql += returningFields.length > 0 ? ` returning ${returningFields.map(field => this.platform.quoteIdentifier(field)).join(', ')}` : '';
652
652
  }
653
- const res = await this.rethrow(this.execute(sql, params, 'run', options.ctx));
653
+ const res = await this.rethrow(this.execute(sql, params, 'run', options.ctx, options.loggerContext));
654
654
  for (let i = 0; i < collections.length; i++) {
655
655
  await this.processManyToMany(meta, where[i], collections[i], false, options);
656
656
  }
@@ -662,7 +662,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
662
662
  if (core_1.Utils.isPrimaryKey(where) && pks.length === 1) {
663
663
  where = { [pks[0]]: where };
664
664
  }
665
- const qb = this.createQueryBuilder(entityName, options.ctx, 'write', false).delete(where).withSchema(this.getSchemaName(meta, options));
665
+ const qb = this.createQueryBuilder(entityName, options.ctx, 'write', false, options.loggerContext).delete(where).withSchema(this.getSchemaName(meta, options));
666
666
  return this.rethrow(qb.execute('run', false));
667
667
  }
668
668
  /**
@@ -750,7 +750,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
750
750
  schema = this.config.get('schema');
751
751
  }
752
752
  const tableName = `${schema ?? '_'}.${pivotMeta.tableName}`;
753
- const persister = groups[tableName] ??= new PivotCollectionPersister_1.PivotCollectionPersister(pivotMeta, this, options?.ctx, schema);
753
+ const persister = groups[tableName] ??= new PivotCollectionPersister_1.PivotCollectionPersister(pivotMeta, this, options?.ctx, schema, options?.loggerContext);
754
754
  persister.enqueueUpdate(coll.property, insertDiff, deleteDiff, pks);
755
755
  }
756
756
  for (const persister of core_1.Utils.values(groups)) {
@@ -1081,7 +1081,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
1081
1081
  for (const prop of meta.relations) {
1082
1082
  if (collections[prop.name]) {
1083
1083
  const pivotMeta = this.metadata.find(prop.pivotEntity);
1084
- const persister = new PivotCollectionPersister_1.PivotCollectionPersister(pivotMeta, this, options?.ctx, options?.schema);
1084
+ const persister = new PivotCollectionPersister_1.PivotCollectionPersister(pivotMeta, this, options?.ctx, options?.schema, options?.loggerContext);
1085
1085
  persister.enqueueUpdate(prop, collections[prop.name], clear, pks);
1086
1086
  await this.rethrow(persister.execute());
1087
1087
  }
@@ -1,4 +1,4 @@
1
- import { Platform, type Constructor, type EntityManager, type EntityRepository, type IDatabaseDriver, type MikroORM } from '@mikro-orm/core';
1
+ import { Platform, type Constructor, type EntityManager, type EntityRepository, type IDatabaseDriver, type MikroORM, type IsolationLevel } from '@mikro-orm/core';
2
2
  import { SqlSchemaGenerator, type SchemaHelper } from './schema';
3
3
  import type { IndexDef } from './typings';
4
4
  export declare abstract class AbstractSqlPlatform extends Platform {
@@ -10,6 +10,15 @@ export declare abstract class AbstractSqlPlatform extends Platform {
10
10
  /** @inheritDoc */
11
11
  lookupExtensions(orm: MikroORM): void;
12
12
  getSchemaGenerator(driver: IDatabaseDriver, em?: EntityManager): SqlSchemaGenerator;
13
+ getBeginTransactionSQL(options?: {
14
+ isolationLevel?: IsolationLevel;
15
+ readOnly?: boolean;
16
+ }): string[];
17
+ getCommitTransactionSQL(): string;
18
+ getRollbackTransactionSQL(): string;
19
+ getSavepointSQL(savepointName: string): string;
20
+ getRollbackToSavepointSQL(savepointName: string): string;
21
+ getReleaseSavepointSQL(savepointName: string): string;
13
22
  quoteValue(value: any): string;
14
23
  escape(value: any): string;
15
24
  getSearchJsonPropertySQL(path: string, type: string, aliased: boolean): string;
@@ -27,6 +27,27 @@ class AbstractSqlPlatform extends core_1.Platform {
27
27
  getSchemaGenerator(driver, em) {
28
28
  return new schema_1.SqlSchemaGenerator(em ?? driver);
29
29
  }
30
+ getBeginTransactionSQL(options) {
31
+ if (options?.isolationLevel) {
32
+ return [`set transaction isolation level ${options.isolationLevel}`, 'begin'];
33
+ }
34
+ return ['begin'];
35
+ }
36
+ getCommitTransactionSQL() {
37
+ return 'commit';
38
+ }
39
+ getRollbackTransactionSQL() {
40
+ return 'rollback';
41
+ }
42
+ getSavepointSQL(savepointName) {
43
+ return `savepoint ${this.quoteIdentifier(savepointName)}`;
44
+ }
45
+ getRollbackToSavepointSQL(savepointName) {
46
+ return `rollback to savepoint ${this.quoteIdentifier(savepointName)}`;
47
+ }
48
+ getReleaseSavepointSQL(savepointName) {
49
+ return `release savepoint ${this.quoteIdentifier(savepointName)}`;
50
+ }
30
51
  quoteValue(value) {
31
52
  if (core_1.Utils.isRawSql(value)) {
32
53
  return this.formatQuery(value.sql, value.params ?? []);
@@ -1,16 +1,17 @@
1
- import { type EntityMetadata, type EntityProperty, type Primary, type Transaction } from '@mikro-orm/core';
1
+ import { type Dictionary, type EntityMetadata, type EntityProperty, type Primary, type Transaction } from '@mikro-orm/core';
2
2
  import { type AbstractSqlDriver } from './AbstractSqlDriver';
3
3
  export declare class PivotCollectionPersister<Entity extends object> {
4
4
  private readonly meta;
5
5
  private readonly driver;
6
6
  private readonly ctx?;
7
7
  private readonly schema?;
8
+ private readonly loggerContext?;
8
9
  private readonly platform;
9
10
  private readonly inserts;
10
11
  private readonly deletes;
11
12
  private readonly batchSize;
12
13
  private order;
13
- constructor(meta: EntityMetadata<Entity>, driver: AbstractSqlDriver, ctx?: Transaction | undefined, schema?: string | undefined);
14
+ constructor(meta: EntityMetadata<Entity>, driver: AbstractSqlDriver, ctx?: Transaction | undefined, schema?: string | undefined, loggerContext?: Dictionary | undefined);
14
15
  enqueueUpdate(prop: EntityProperty<Entity>, insertDiff: Primary<Entity>[][], deleteDiff: Primary<Entity>[][] | boolean, pks: Primary<Entity>[]): void;
15
16
  private enqueueInsert;
16
17
  private enqueueDelete;
@@ -41,16 +41,18 @@ class PivotCollectionPersister {
41
41
  driver;
42
42
  ctx;
43
43
  schema;
44
+ loggerContext;
44
45
  platform;
45
46
  inserts = new Map();
46
47
  deletes = new Map();
47
48
  batchSize;
48
49
  order = 0;
49
- constructor(meta, driver, ctx, schema) {
50
+ constructor(meta, driver, ctx, schema, loggerContext) {
50
51
  this.meta = meta;
51
52
  this.driver = driver;
52
53
  this.ctx = ctx;
53
54
  this.schema = schema;
55
+ this.loggerContext = loggerContext;
54
56
  this.platform = this.driver.getPlatform();
55
57
  this.batchSize = this.driver.config.get('batchSize');
56
58
  }
@@ -102,6 +104,7 @@ class PivotCollectionPersister {
102
104
  await this.driver.nativeDelete(this.meta.className, cond, {
103
105
  ctx: this.ctx,
104
106
  schema: this.schema,
107
+ loggerContext: this.loggerContext,
105
108
  });
106
109
  }
107
110
  }
@@ -122,12 +125,13 @@ class PivotCollectionPersister {
122
125
  schema: this.schema,
123
126
  convertCustomTypes: false,
124
127
  processCollections: false,
128
+ loggerContext: this.loggerContext,
125
129
  });
126
130
  }
127
131
  }
128
132
  else {
129
133
  await core_1.Utils.runSerial(items, item => {
130
- return this.driver.createQueryBuilder(this.meta.className, this.ctx, 'write')
134
+ return this.driver.createQueryBuilder(this.meta.className, this.ctx, 'write', false, this.loggerContext)
131
135
  .withSchema(this.schema)
132
136
  .insert(item)
133
137
  .execute('run', false);
@@ -1,4 +1,4 @@
1
- import { type SimpleColumnMeta, type Type, type TransformContext } from '@mikro-orm/core';
1
+ import { type SimpleColumnMeta, type Type, type TransformContext, type IsolationLevel } from '@mikro-orm/core';
2
2
  import { MySqlSchemaHelper } from './MySqlSchemaHelper';
3
3
  import { MySqlExceptionConverter } from './MySqlExceptionConverter';
4
4
  import { AbstractSqlPlatform } from '../../AbstractSqlPlatform';
@@ -13,6 +13,10 @@ export declare class MySqlPlatform extends AbstractSqlPlatform {
13
13
  readonly "desc nulls last": "is null";
14
14
  };
15
15
  getDefaultCharset(): string;
16
+ getBeginTransactionSQL(options?: {
17
+ isolationLevel?: IsolationLevel;
18
+ readOnly?: boolean;
19
+ }): string[];
16
20
  convertJsonToDatabaseValue(value: unknown, context?: TransformContext): unknown;
17
21
  getJsonIndexDefinition(index: IndexDef): string[];
18
22
  getBooleanTypeDeclarationSQL(): string;
@@ -17,6 +17,20 @@ class MySqlPlatform extends AbstractSqlPlatform_1.AbstractSqlPlatform {
17
17
  getDefaultCharset() {
18
18
  return 'utf8mb4';
19
19
  }
20
+ getBeginTransactionSQL(options) {
21
+ if (options?.isolationLevel || options?.readOnly) {
22
+ const parts = [];
23
+ if (options.isolationLevel) {
24
+ parts.push(`isolation level ${options.isolationLevel}`);
25
+ }
26
+ if (options.readOnly) {
27
+ parts.push('read only');
28
+ }
29
+ const sql = `set transaction ${parts.join(', ')}`;
30
+ return [sql, 'begin'];
31
+ }
32
+ return ['begin'];
33
+ }
20
34
  convertJsonToDatabaseValue(value, context) {
21
35
  if (context?.mode === 'query') {
22
36
  return value;
@@ -1,4 +1,4 @@
1
- import { type EntityProperty } from '@mikro-orm/core';
1
+ import { type EntityProperty, type IsolationLevel } from '@mikro-orm/core';
2
2
  import { AbstractSqlPlatform } from '../../AbstractSqlPlatform';
3
3
  export declare abstract class BaseSqlitePlatform extends AbstractSqlPlatform {
4
4
  usesDefaultKeyword(): boolean;
@@ -7,6 +7,10 @@ export declare abstract class BaseSqlitePlatform extends AbstractSqlPlatform {
7
7
  getDateTimeTypeDeclarationSQL(column: {
8
8
  length: number;
9
9
  }): string;
10
+ getBeginTransactionSQL(options?: {
11
+ isolationLevel?: IsolationLevel;
12
+ readOnly?: boolean;
13
+ }): string[];
10
14
  getEnumTypeDeclarationSQL(column: {
11
15
  items?: unknown[];
12
16
  fieldNames: string[];
@@ -16,6 +16,9 @@ class BaseSqlitePlatform extends AbstractSqlPlatform_1.AbstractSqlPlatform {
16
16
  getDateTimeTypeDeclarationSQL(column) {
17
17
  return 'datetime';
18
18
  }
19
+ getBeginTransactionSQL(options) {
20
+ return ['begin'];
21
+ }
19
22
  getEnumTypeDeclarationSQL(column) {
20
23
  if (column.items?.every(item => core_1.Utils.isString(item))) {
21
24
  return 'text';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/knex",
3
- "version": "6.4.17-dev.60",
3
+ "version": "6.4.17-dev.62",
4
4
  "description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",
5
5
  "main": "index.js",
6
6
  "module": "index.mjs",
@@ -66,7 +66,7 @@
66
66
  "@mikro-orm/core": "^6.4.16"
67
67
  },
68
68
  "peerDependencies": {
69
- "@mikro-orm/core": "6.4.17-dev.60",
69
+ "@mikro-orm/core": "6.4.17-dev.62",
70
70
  "better-sqlite3": "*",
71
71
  "libsql": "*",
72
72
  "mariadb": "*"