@mikro-orm/knex 6.4.17-dev.6 → 6.4.17-dev.61

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({
@@ -333,6 +333,9 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
333
333
  if (meta && !core_1.Utils.isEmpty(populate)) {
334
334
  this.buildFields(meta, populate, joinedProps, qb, qb.alias, options, true);
335
335
  }
336
+ if (options.em) {
337
+ await qb.applyJoinedFilters(options.em, options.filters);
338
+ }
336
339
  return this.rethrow(qb.getCount());
337
340
  }
338
341
  async nativeInsert(entityName, data, options = {}) {
@@ -340,7 +343,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
340
343
  const meta = this.metadata.find(entityName);
341
344
  const collections = this.extractManyToMany(entityName, data);
342
345
  const pks = meta?.primaryKeys ?? [this.config.getNamingStrategy().referenceColumnName()];
343
- 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));
344
347
  const res = await this.rethrow(qb.insert(data).execute('run', false));
345
348
  res.row = res.row || {};
346
349
  let pk;
@@ -401,14 +404,14 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
401
404
  value = this.mapDataToFieldNames(value, false, prop.embeddedProps, options.convertCustomTypes);
402
405
  }
403
406
  }
404
- if (options.convertCustomTypes && prop.customType) {
405
- params.push(prop.customType.convertToDatabaseValue(value, this.platform, { key: prop.name, mode: 'query-data' }));
406
- return;
407
- }
408
407
  if (typeof value === 'undefined' && this.platform.usesDefaultKeyword()) {
409
408
  params.push((0, core_1.raw)('default'));
410
409
  return;
411
410
  }
411
+ if (options.convertCustomTypes && prop.customType) {
412
+ params.push(prop.customType.convertToDatabaseValue(value, this.platform, { key: prop.name, mode: 'query-data' }));
413
+ return;
414
+ }
412
415
  params.push(value);
413
416
  };
414
417
  if (fields.length > 0 || this.platform.usesDefaultKeyword()) {
@@ -467,7 +470,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
467
470
  if (transform) {
468
471
  sql = transform(sql);
469
472
  }
470
- const res = await this.execute(sql, params, 'run', options.ctx);
473
+ const res = await this.execute(sql, params, 'run', options.ctx, options.loggerContext);
471
474
  let pk;
472
475
  /* istanbul ignore next */
473
476
  if (pks.length > 1) { // owner has composite pk
@@ -495,7 +498,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
495
498
  where = { [meta?.primaryKeys[0] ?? pks[0]]: where };
496
499
  }
497
500
  if (core_1.Utils.hasObjectKeys(data)) {
498
- const qb = this.createQueryBuilder(entityName, options.ctx, 'write', options.convertCustomTypes)
501
+ const qb = this.createQueryBuilder(entityName, options.ctx, 'write', options.convertCustomTypes, options.loggerContext)
499
502
  .withSchema(this.getSchemaName(meta, options));
500
503
  if (options.upsert) {
501
504
  /* istanbul ignore next */
@@ -534,7 +537,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
534
537
  const meta = this.metadata.get(entityName);
535
538
  if (options.upsert) {
536
539
  const uniqueFields = options.onConflictFields ?? (core_1.Utils.isPlainObject(where[0]) ? Object.keys(where[0]).flatMap(key => core_1.Utils.splitPrimaryKeys(key)) : meta.primaryKeys);
537
- 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));
538
541
  const returning = (0, core_1.getOnConflictReturningFields)(meta, data[0], uniqueFields, options);
539
542
  qb.insert(data)
540
543
  .onConflict(uniqueFields)
@@ -647,7 +650,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
647
650
  /* istanbul ignore next */
648
651
  sql += returningFields.length > 0 ? ` returning ${returningFields.map(field => this.platform.quoteIdentifier(field)).join(', ')}` : '';
649
652
  }
650
- 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));
651
654
  for (let i = 0; i < collections.length; i++) {
652
655
  await this.processManyToMany(meta, where[i], collections[i], false, options);
653
656
  }
@@ -659,7 +662,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
659
662
  if (core_1.Utils.isPrimaryKey(where) && pks.length === 1) {
660
663
  where = { [pks[0]]: where };
661
664
  }
662
- 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));
663
666
  return this.rethrow(qb.execute('run', false));
664
667
  }
665
668
  /**
@@ -747,7 +750,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
747
750
  schema = this.config.get('schema');
748
751
  }
749
752
  const tableName = `${schema ?? '_'}.${pivotMeta.tableName}`;
750
- 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);
751
754
  persister.enqueueUpdate(coll.property, insertDiff, deleteDiff, pks);
752
755
  }
753
756
  for (const persister of core_1.Utils.values(groups)) {
@@ -1078,7 +1081,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
1078
1081
  for (const prop of meta.relations) {
1079
1082
  if (collections[prop.name]) {
1080
1083
  const pivotMeta = this.metadata.find(prop.pivotEntity);
1081
- 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);
1082
1085
  persister.enqueueUpdate(prop, collections[prop.name], clear, pks);
1083
1086
  await this.rethrow(persister.execute());
1084
1087
  }
@@ -1156,7 +1159,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
1156
1159
  if (!join && parentAlias === qb.alias) {
1157
1160
  continue;
1158
1161
  }
1159
- if (![core_1.ReferenceKind.SCALAR, core_1.ReferenceKind.EMBEDDED].includes(prop.kind) && typeof childOrder === 'object') {
1162
+ if (join && ![core_1.ReferenceKind.SCALAR, core_1.ReferenceKind.EMBEDDED].includes(prop.kind) && typeof childOrder === 'object') {
1160
1163
  const children = this.buildPopulateOrderBy(qb, meta2, core_1.Utils.asArray(childOrder), path, explicit, propAlias);
1161
1164
  orderBy.push(...children);
1162
1165
  continue;
@@ -1311,16 +1314,19 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
1311
1314
  ret.push('*');
1312
1315
  }
1313
1316
  if (ret.length > 0 && !hasExplicitFields && addFormulas) {
1314
- meta.props
1315
- .filter(prop => prop.formula && !lazyProps.includes(prop))
1316
- .forEach(prop => {
1317
- const a = this.platform.quoteIdentifier(alias);
1318
- const aliased = this.platform.quoteIdentifier(prop.fieldNames[0]);
1319
- ret.push((0, core_1.raw)(`${prop.formula(a)} as ${aliased}`));
1320
- });
1321
- meta.props
1322
- .filter(prop => !prop.object && (prop.hasConvertToDatabaseValueSQL || prop.hasConvertToJSValueSQL))
1323
- .forEach(prop => ret.push(prop.name));
1317
+ for (const prop of meta.props) {
1318
+ if (lazyProps.includes(prop)) {
1319
+ continue;
1320
+ }
1321
+ if (prop.formula) {
1322
+ const a = this.platform.quoteIdentifier(alias);
1323
+ const aliased = this.platform.quoteIdentifier(prop.fieldNames[0]);
1324
+ ret.push((0, core_1.raw)(`${prop.formula(a)} as ${aliased}`));
1325
+ }
1326
+ if (!prop.object && (prop.hasConvertToDatabaseValueSQL || prop.hasConvertToJSValueSQL)) {
1327
+ ret.push(prop.name);
1328
+ }
1329
+ }
1324
1330
  }
1325
1331
  // add joined relations after the root entity fields
1326
1332
  if (joinedProps.length > 0) {
@@ -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);
package/README.md CHANGED
@@ -141,7 +141,7 @@ There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit m
141
141
  - [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)
142
142
  - [Filters](https://mikro-orm.io/docs/filters)
143
143
  - [Using `QueryBuilder`](https://mikro-orm.io/docs/query-builder)
144
- - [Preloading Deeply Nested Structures via populate](https://mikro-orm.io/docs/nested-populate)
144
+ - [Populating relations](https://mikro-orm.io/docs/populating-relations)
145
145
  - [Property Validation](https://mikro-orm.io/docs/property-validation)
146
146
  - [Lifecycle Hooks](https://mikro-orm.io/docs/events#hooks)
147
147
  - [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)
@@ -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;
@@ -204,7 +204,14 @@ class MySqlSchemaHelper extends SchemaHelper_1.SchemaHelper {
204
204
  col.defaultTo(null);
205
205
  }
206
206
  else {
207
- col.defaultTo(knex.raw(column.default + (column.extra ? ' ' + column.extra : '')));
207
+ const columnType = column.type.toLowerCase();
208
+ // https://dev.mysql.com/doc/refman/9.0/en/data-type-defaults.html
209
+ const needsExpression = ['blob', 'text', 'json', 'point', 'linestring', 'polygon', 'multipoint', 'multilinestring', 'multipolygon', 'geometrycollection'].some(type => columnType.startsWith(type));
210
+ let defaultSql = needsExpression && !column.default.startsWith('(') ? `(${column.default})` : column.default;
211
+ if (column.extra) {
212
+ defaultSql += ' ' + column.extra;
213
+ }
214
+ col.defaultTo(knex.raw(defaultSql));
208
215
  }
209
216
  }
210
217
  return col;
@@ -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/index.mjs CHANGED
@@ -219,12 +219,14 @@ export const compareBuffers = mod.compareBuffers;
219
219
  export const compareObjects = mod.compareObjects;
220
220
  export const createSqlFunction = mod.createSqlFunction;
221
221
  export const defineConfig = mod.defineConfig;
222
+ export const defineEntity = mod.defineEntity;
222
223
  export const equals = mod.equals;
223
224
  export const getOnConflictFields = mod.getOnConflictFields;
224
225
  export const getOnConflictReturningFields = mod.getOnConflictReturningFields;
225
226
  export const helper = mod.helper;
226
227
  export const knex = mod.knex;
227
228
  export const parseJsonSafe = mod.parseJsonSafe;
229
+ export const quote = mod.quote;
228
230
  export const raw = mod.raw;
229
231
  export const ref = mod.ref;
230
232
  export const rel = mod.rel;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/knex",
3
- "version": "6.4.17-dev.6",
3
+ "version": "6.4.17-dev.61",
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.6",
69
+ "@mikro-orm/core": "6.4.17-dev.61",
70
70
  "better-sqlite3": "*",
71
71
  "libsql": "*",
72
72
  "mariadb": "*"
@@ -49,13 +49,14 @@ class CriteriaNodeFactory {
49
49
  static createObjectItemNode(metadata, entityName, node, payload, key, meta) {
50
50
  const prop = meta?.properties[key];
51
51
  const childEntity = prop && prop.kind !== core_1.ReferenceKind.SCALAR ? prop.type : entityName;
52
- if (prop?.customType instanceof core_1.JsonType) {
52
+ const isNotEmbedded = prop?.kind !== core_1.ReferenceKind.EMBEDDED;
53
+ if (isNotEmbedded && prop?.customType instanceof core_1.JsonType) {
53
54
  return this.createScalarNode(metadata, childEntity, payload[key], node, key);
54
55
  }
55
56
  if (prop?.kind === core_1.ReferenceKind.SCALAR && payload[key] != null && Object.keys(payload[key]).some(f => core_1.Utils.isGroupOperator(f))) {
56
57
  throw core_1.ValidationError.cannotUseGroupOperatorsInsideScalars(entityName, prop.name, payload);
57
58
  }
58
- if (prop?.kind !== core_1.ReferenceKind.EMBEDDED) {
59
+ if (isNotEmbedded) {
59
60
  return this.createNode(metadata, childEntity, payload[key], node, key);
60
61
  }
61
62
  if (payload[key] == null) {
@@ -72,11 +73,12 @@ class CriteriaNodeFactory {
72
73
  throw core_1.ValidationError.cannotUseOperatorsInsideEmbeddables(entityName, prop.name, payload);
73
74
  }
74
75
  const map = Object.keys(payload[key]).reduce((oo, k) => {
75
- if (!prop.embeddedProps[k] && !allowedOperators.includes(k)) {
76
+ const embeddedProp = prop.embeddedProps[k] ?? Object.values(prop.embeddedProps).find(p => p.name === k);
77
+ if (!embeddedProp && !allowedOperators.includes(k)) {
76
78
  throw core_1.ValidationError.invalidEmbeddableQuery(entityName, k, prop.type);
77
79
  }
78
- if (prop.embeddedProps[k]) {
79
- oo[prop.embeddedProps[k].name] = payload[key][k];
80
+ if (embeddedProp) {
81
+ oo[embeddedProp.name] = payload[key][k];
80
82
  }
81
83
  else if (typeof payload[key][k] === 'object') {
82
84
  oo[k] = JSON.stringify(payload[key][k]);
@@ -1,4 +1,4 @@
1
- import { type Configuration, type DeferMode, type Dictionary, type EntityMetadata, type EntityProperty, type NamingStrategy } from '@mikro-orm/core';
1
+ import { type Configuration, type DeferMode, type Dictionary, type EntityMetadata, type EntityProperty, type NamingStrategy, type IndexCallback } from '@mikro-orm/core';
2
2
  import type { SchemaHelper } from './SchemaHelper';
3
3
  import type { CheckDef, Column, ForeignKey, IndexDef } from '../typings';
4
4
  import type { AbstractSqlPlatform } from '../AbstractSqlPlatform';
@@ -53,12 +53,13 @@ export declare class DatabaseTable {
53
53
  private getPropertyTypeForForeignKey;
54
54
  private getPropertyTypeForColumn;
55
55
  private getPropertyDefaultValue;
56
+ private processIndexExpression;
56
57
  addIndex(meta: EntityMetadata, index: {
57
- properties: string | string[];
58
+ properties?: string | string[];
58
59
  name?: string;
59
60
  type?: string;
60
- expression?: string;
61
- deferMode?: DeferMode;
61
+ expression?: string | IndexCallback<any>;
62
+ deferMode?: DeferMode | `${DeferMode}`;
62
63
  options?: Dictionary;
63
64
  }, type: 'index' | 'unique' | 'primary'): void;
64
65
  addCheck(check: CheckDef): void;
@@ -700,6 +700,18 @@ class DatabaseTable {
700
700
  }
701
701
  return '' + val;
702
702
  }
703
+ processIndexExpression(expression, meta) {
704
+ if (expression instanceof Function) {
705
+ const exp = expression({ name: this.name, schema: this.schema, toString() {
706
+ if (this.schema) {
707
+ return `${this.schema}.${this.name}`;
708
+ }
709
+ return this.name;
710
+ } }, meta.createColumnMappingObject());
711
+ return exp instanceof core_1.RawQueryFragment ? this.platform.formatQuery(exp.sql, exp.params) : exp;
712
+ }
713
+ return expression;
714
+ }
703
715
  addIndex(meta, index, type) {
704
716
  const properties = core_1.Utils.unique(core_1.Utils.flatten(core_1.Utils.asArray(index.properties).map(prop => {
705
717
  const parts = prop.split('.');
@@ -741,7 +753,7 @@ class DatabaseTable {
741
753
  primary: type === 'primary',
742
754
  unique: type !== 'index',
743
755
  type: index.type,
744
- expression: index.expression,
756
+ expression: this.processIndexExpression(index.expression, meta),
745
757
  options: index.options,
746
758
  deferMode: index.deferMode,
747
759
  });
package/typings.d.ts CHANGED
@@ -75,7 +75,7 @@ export interface IndexDef {
75
75
  storageEngineIndexType?: 'hash' | 'btree';
76
76
  predicate?: Knex.QueryBuilder;
77
77
  }>;
78
- deferMode?: DeferMode;
78
+ deferMode?: DeferMode | `${DeferMode}`;
79
79
  }
80
80
  export interface CheckDef<T = unknown> {
81
81
  name: string;