@mikro-orm/knex 6.0.8-dev.9 → 6.1.1-dev.0

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 { type AnyEntity, type Collection, type Configuration, type ConnectionType, type Constructor, type CountOptions, DatabaseDriver, type DeleteOptions, type Dictionary, type DriverMethodOptions, type EntityData, type EntityDictionary, type EntityField, EntityManagerType, type EntityMetadata, type EntityName, type EntityProperty, type FilterQuery, type FindOneOptions, type FindOptions, type IDatabaseDriver, type LockOptions, type LoggingOptions, type NativeInsertUpdateManyOptions, type NativeInsertUpdateOptions, type Options, type OrderDefinition, type PopulateOptions, type Primary, type QueryOrderMap, type QueryResult, type Transaction, type UpsertManyOptions, type UpsertOptions } from '@mikro-orm/core';
2
+ import { type AnyEntity, type Collection, type Configuration, type ConnectionType, type Constructor, type CountOptions, DatabaseDriver, type DeleteOptions, type Dictionary, type DriverMethodOptions, type EntityData, type EntityDictionary, type EntityField, EntityManagerType, type EntityMetadata, type EntityName, type EntityProperty, type FilterQuery, type FindOneOptions, type FindOptions, type IDatabaseDriver, type LockOptions, type LoggingOptions, type NativeInsertUpdateManyOptions, type NativeInsertUpdateOptions, type ObjectQuery, type Options, type OrderDefinition, type PopulateOptions, type Primary, type QueryOrderMap, type QueryResult, type Transaction, type UpsertManyOptions, type UpsertOptions } from '@mikro-orm/core';
3
3
  import type { AbstractSqlConnection } from './AbstractSqlConnection';
4
4
  import type { AbstractSqlPlatform } from './AbstractSqlPlatform';
5
5
  import { QueryBuilder, QueryType } from './query';
@@ -31,7 +31,7 @@ export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlCo
31
31
  syncCollections<T extends object, O extends object>(collections: Iterable<Collection<T, O>>, options?: DriverMethodOptions): Promise<void>;
32
32
  loadFromPivotTable<T extends object, O extends object>(prop: EntityProperty, owners: Primary<O>[][], where?: FilterQuery<any>, orderBy?: OrderDefinition<T>, ctx?: Transaction, options?: FindOptions<T, any, any, any>, pivotJoin?: boolean): Promise<Dictionary<T[]>>;
33
33
  private getPivotOrderBy;
34
- execute<T extends QueryResult | EntityData<AnyEntity> | EntityData<AnyEntity>[] = EntityData<AnyEntity>[]>(queryOrKnex: string | Knex.QueryBuilder | Knex.Raw, params?: any[], method?: 'all' | 'get' | 'run', ctx?: Transaction): Promise<T>;
34
+ execute<T extends QueryResult | EntityData<AnyEntity> | EntityData<AnyEntity>[] = EntityData<AnyEntity>[]>(queryOrKnex: string | Knex.QueryBuilder | Knex.Raw, params?: any[], method?: 'all' | 'get' | 'run', ctx?: Transaction, loggerContext?: LoggingOptions): Promise<T>;
35
35
  /**
36
36
  * 1:1 owner side needs to be marked for population so QB auto-joins the owner id
37
37
  */
@@ -63,6 +63,7 @@ export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlCo
63
63
  protected extractManyToMany<T>(entityName: string, data: EntityDictionary<T>): EntityData<T>;
64
64
  protected processManyToMany<T extends object>(meta: EntityMetadata<T> | undefined, pks: Primary<T>[], collections: EntityData<T>, clear: boolean, options?: DriverMethodOptions): Promise<void>;
65
65
  lockPessimistic<T extends object>(entity: T, options: LockOptions): Promise<void>;
66
+ protected buildPopulateWhere<T extends object>(meta: EntityMetadata<T>, joinedProps: PopulateOptions<T>[], options: Pick<FindOptions<any>, 'populateWhere'>): ObjectQuery<T>;
66
67
  protected buildOrderBy<T extends object>(qb: QueryBuilder<T>, meta: EntityMetadata<T>, populate: PopulateOptions<T>[], options: Pick<FindOptions<any>, 'strategy' | 'orderBy' | 'populateOrderBy'>): QueryOrderMap<T>[];
67
68
  protected buildPopulateOrderBy<T extends object>(qb: QueryBuilder<T>, meta: EntityMetadata<T>, populateOrderBy: QueryOrderMap<T>[], parentPath: string, explicit: boolean, parentAlias?: string): QueryOrderMap<T>[];
68
69
  protected buildJoinedPropsOrderBy<T extends object>(qb: QueryBuilder<T>, meta: EntityMetadata<T>, populate: PopulateOptions<T>[], options?: Pick<FindOptions<any>, 'strategy' | 'orderBy' | 'populateOrderBy'>, parentPath?: string): QueryOrderMap<T>[];
@@ -34,6 +34,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
34
34
  const qb = this.createQueryBuilder(entityName, options.ctx, options.connectionType, false, options.logging);
35
35
  const fields = this.buildFields(meta, populate, joinedProps, qb, qb.alias, options);
36
36
  const orderBy = this.buildOrderBy(qb, meta, populate, options);
37
+ const populateWhere = this.buildPopulateWhere(meta, joinedProps, options);
37
38
  core_1.Utils.asArray(options.flags).forEach(flag => qb.setFlag(flag));
38
39
  if (core_1.Utils.isPrimaryKey(where, meta.compositePK)) {
39
40
  where = { [core_1.Utils.getPrimaryKeyHash(meta.primaryKeys)]: where };
@@ -43,7 +44,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
43
44
  qb.__populateWhere = options._populateWhere;
44
45
  qb.select(fields)
45
46
  // only add populateWhere if we are populate-joining, as this will be used to add `on` conditions
46
- .populate(populate, joinedProps.length > 0 ? options.populateWhere : undefined)
47
+ .populate(populate, joinedProps.length > 0 ? populateWhere : undefined)
47
48
  .where(where)
48
49
  .groupBy(options.groupBy)
49
50
  .having(options.having)
@@ -761,8 +762,8 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
761
762
  }
762
763
  return [];
763
764
  }
764
- async execute(queryOrKnex, params = [], method = 'all', ctx) {
765
- return this.rethrow(this.connection.execute(queryOrKnex, params, method, ctx));
765
+ async execute(queryOrKnex, params = [], method = 'all', ctx, loggerContext) {
766
+ return this.rethrow(this.connection.execute(queryOrKnex, params, method, ctx, loggerContext));
766
767
  }
767
768
  /**
768
769
  * 1:1 owner side needs to be marked for population so QB auto-joins the owner id
@@ -981,6 +982,31 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
981
982
  qb.select((0, core_1.raw)('1')).where(cond).setLockMode(options.lockMode, options.lockTableAliases);
982
983
  await this.rethrow(qb.execute());
983
984
  }
985
+ buildPopulateWhere(meta, joinedProps, options) {
986
+ const where = {};
987
+ for (const hint of joinedProps) {
988
+ const [propName] = hint.field.split(':', 2);
989
+ const prop = meta.properties[propName];
990
+ if (!core_1.Utils.isEmpty(prop.where)) {
991
+ where[prop.name] = core_1.Utils.copy(prop.where);
992
+ }
993
+ if (hint.children) {
994
+ const inner = this.buildPopulateWhere(prop.targetMeta, hint.children, {});
995
+ if (!core_1.Utils.isEmpty(inner)) {
996
+ where[prop.name] ??= {};
997
+ Object.assign(where[prop.name], inner);
998
+ }
999
+ }
1000
+ }
1001
+ if (core_1.Utils.isEmpty(options.populateWhere)) {
1002
+ return where;
1003
+ }
1004
+ if (core_1.Utils.isEmpty(where)) {
1005
+ return options.populateWhere;
1006
+ }
1007
+ /* istanbul ignore next */
1008
+ return { $and: [options.populateWhere, where] };
1009
+ }
984
1010
  buildOrderBy(qb, meta, populate, options) {
985
1011
  const joinedProps = this.joinedProps(meta, populate, options);
986
1012
  // `options._populateWhere` is a copy of the value provided by user with a fallback to the global config option
@@ -19,7 +19,7 @@ export declare class SqlEntityManager<Driver extends AbstractSqlDriver = Abstrac
19
19
  * Returns configured knex instance.
20
20
  */
21
21
  getKnex(type?: ConnectionType): Knex<any, any[]>;
22
- execute<T extends QueryResult | EntityData<AnyEntity> | EntityData<AnyEntity>[] = EntityData<AnyEntity>[]>(queryOrKnex: string | Knex.QueryBuilder | Knex.Raw, params?: any[], method?: 'all' | 'get' | 'run'): Promise<T>;
22
+ execute<T extends QueryResult | EntityData<AnyEntity> | EntityData<AnyEntity>[] = EntityData<AnyEntity>[]>(queryOrKnex: string | Knex.QueryBuilder | Knex.Raw, params?: any[], method?: 'all' | 'get' | 'run', loggerContext?: LoggingOptions): Promise<T>;
23
23
  getRepository<T extends object, U extends EntityRepository<T> = SqlEntityRepository<T>>(entityName: EntityName<T>): GetRepository<T, U>;
24
24
  protected applyDiscriminatorCondition<Entity extends object>(entityName: string, where: FilterQuery<Entity>): FilterQuery<Entity>;
25
25
  }
@@ -26,8 +26,8 @@ class SqlEntityManager extends core_1.EntityManager {
26
26
  getKnex(type) {
27
27
  return this.getConnection(type).getKnex();
28
28
  }
29
- async execute(queryOrKnex, params = [], method = 'all') {
30
- return this.getDriver().execute(queryOrKnex, params, method, this.getContext(false).getTransactionContext());
29
+ async execute(queryOrKnex, params = [], method = 'all', loggerContext) {
30
+ return this.getDriver().execute(queryOrKnex, params, method, this.getContext(false).getTransactionContext(), loggerContext);
31
31
  }
32
32
  getRepository(entityName) {
33
33
  return super.getRepository(entityName);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/knex",
3
- "version": "6.0.8-dev.9",
3
+ "version": "6.1.1-dev.0",
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",
@@ -63,9 +63,9 @@
63
63
  "sqlstring": "2.3.3"
64
64
  },
65
65
  "devDependencies": {
66
- "@mikro-orm/core": "^6.0.7"
66
+ "@mikro-orm/core": "^6.1.0"
67
67
  },
68
68
  "peerDependencies": {
69
- "@mikro-orm/core": "6.0.8-dev.9"
69
+ "@mikro-orm/core": "6.1.1-dev.0"
70
70
  }
71
71
  }
@@ -205,7 +205,11 @@ class QueryBuilderHelper {
205
205
  for (const key of Object.keys(join.cond)) {
206
206
  const hasPrefix = key.includes('.') || core_1.Utils.isOperator(key) || core_1.RawQueryFragment.isKnownFragment(key);
207
207
  const newKey = hasPrefix ? key : `${join.alias}.${key}`;
208
- conditions.push(this.processJoinClause(newKey, join.cond[key], join.alias, params));
208
+ const clause = this.processJoinClause(newKey, join.cond[key], join.alias, params);
209
+ /* istanbul ignore else */
210
+ if (clause !== '()') {
211
+ conditions.push(clause);
212
+ }
209
213
  }
210
214
  let sql = method + ' ';
211
215
  if (join.subquery) {
@@ -27,10 +27,11 @@ export declare abstract class SchemaHelper {
27
27
  getDropIndexSQL(tableName: string, index: IndexDef): string;
28
28
  getRenameIndexSQL(tableName: string, index: IndexDef, oldIndexName: string): string;
29
29
  hasNonDefaultPrimaryKeyName(table: DatabaseTable): boolean;
30
- createTableColumn(table: Knex.TableBuilder, column: Column, fromTable: DatabaseTable, changedProperties?: Set<string>): Knex.ColumnBuilder;
30
+ createTableColumn(table: Knex.TableBuilder, column: Column, fromTable: DatabaseTable, changedProperties?: Set<string>, alter?: boolean): Knex.ColumnBuilder;
31
31
  configureColumn(column: Column, col: Knex.ColumnBuilder, knex: Knex, changedProperties?: Set<string>): Knex.ColumnBuilder;
32
32
  configureColumnDefault(column: Column, col: Knex.ColumnBuilder, knex: Knex, changedProperties?: Set<string>): Knex.ColumnBuilder;
33
33
  getPreAlterTable(tableDiff: TableDifference, safe: boolean): string;
34
+ getPostAlterTable(tableDiff: TableDifference, safe: boolean): string;
34
35
  getAlterColumnAutoincrement(tableName: string, column: Column, schemaName?: string): string;
35
36
  getChangeColumnCommentSQL(tableName: string, to: Column, schemaName?: string): string;
36
37
  getNamespaces(connection: AbstractSqlConnection): Promise<string[]>;
@@ -104,7 +104,7 @@ class SchemaHelper {
104
104
  const defaultName = this.platform.getDefaultPrimaryName(table.name, pkIndex.columnNames);
105
105
  return pkIndex?.keyName !== defaultName;
106
106
  }
107
- createTableColumn(table, column, fromTable, changedProperties) {
107
+ createTableColumn(table, column, fromTable, changedProperties, alter) {
108
108
  const compositePK = fromTable.getPrimaryKey()?.composite;
109
109
  if (column.autoincrement && !column.generated && !compositePK && (!changedProperties || changedProperties.has('autoincrement') || changedProperties.has('type'))) {
110
110
  const primaryKey = !changedProperties && !this.hasNonDefaultPrimaryKeyName(fromTable);
@@ -144,6 +144,9 @@ class SchemaHelper {
144
144
  getPreAlterTable(tableDiff, safe) {
145
145
  return '';
146
146
  }
147
+ getPostAlterTable(tableDiff, safe) {
148
+ return '';
149
+ }
147
150
  getAlterColumnAutoincrement(tableName, column, schemaName) {
148
151
  return '';
149
152
  }
@@ -37,6 +37,7 @@ export declare class SqlSchemaGenerator extends AbstractSchemaGenerator<Abstract
37
37
  * We need to drop foreign keys first for all tables to allow dropping PK constraints.
38
38
  */
39
39
  private preAlterTable;
40
+ private postAlterTable;
40
41
  private splitTableName;
41
42
  private alterTable;
42
43
  /**
@@ -188,7 +188,7 @@ class SqlSchemaGenerator extends core_1.AbstractSchemaGenerator {
188
188
  }
189
189
  }
190
190
  for (const newTable of Object.values(schemaDiff.newTables)) {
191
- ret += await this.dump(this.createTable(newTable));
191
+ ret += await this.dump(this.createTable(newTable, true));
192
192
  }
193
193
  for (const newTable of Object.values(schemaDiff.newTables)) {
194
194
  ret += await this.dump(this.createSchemaBuilder(newTable.schema).alterTable(newTable.name, table => {
@@ -210,6 +210,11 @@ class SqlSchemaGenerator extends core_1.AbstractSchemaGenerator {
210
210
  ret += await this.dump(builder);
211
211
  }
212
212
  }
213
+ for (const changedTable of Object.values(schemaDiff.changedTables)) {
214
+ for (const builder of this.postAlterTable(changedTable, options.safe)) {
215
+ ret += await this.dump(builder);
216
+ }
217
+ }
213
218
  if (options.dropTables && !options.safe) {
214
219
  for (const removedNamespace of schemaDiff.removedNamespaces) {
215
220
  ret += await this.dump(this.knex.schema.dropSchema(removedNamespace));
@@ -263,6 +268,12 @@ class SqlSchemaGenerator extends core_1.AbstractSchemaGenerator {
263
268
  }));
264
269
  return ret;
265
270
  }
271
+ postAlterTable(diff, safe) {
272
+ const ret = [];
273
+ const push = (sql) => sql ? ret.push(this.knex.schema.raw(sql)) : undefined;
274
+ push(this.helper.getPostAlterTable(diff, safe));
275
+ return ret;
276
+ }
266
277
  splitTableName(name) {
267
278
  const parts = name.split('.');
268
279
  const tableName = parts.pop();
@@ -272,11 +283,19 @@ class SqlSchemaGenerator extends core_1.AbstractSchemaGenerator {
272
283
  alterTable(diff, safe) {
273
284
  const ret = [];
274
285
  const [schemaName, tableName] = this.splitTableName(diff.name);
275
- const changedNativeEnums = [];
276
- for (const { column, changedProperties } of Object.values(diff.changedColumns)) {
277
- if (column.nativeEnumName && changedProperties.has('enumItems') && column.nativeEnumName in diff.fromTable.nativeEnums) {
278
- changedNativeEnums.push([column.nativeEnumName, column.enumItems, diff.fromTable.getColumn(column.name).enumItems]);
286
+ if (this.platform.supportsNativeEnums()) {
287
+ const changedNativeEnums = [];
288
+ for (const { column, changedProperties } of Object.values(diff.changedColumns)) {
289
+ if (column.nativeEnumName && changedProperties.has('enumItems') && column.nativeEnumName in diff.fromTable.nativeEnums) {
290
+ changedNativeEnums.push([column.nativeEnumName, column.enumItems, diff.fromTable.getColumn(column.name).enumItems]);
291
+ }
279
292
  }
293
+ core_1.Utils.removeDuplicates(changedNativeEnums).forEach(([enumName, itemsNew, itemsOld]) => {
294
+ // postgres allows only adding new items, the values are case insensitive
295
+ itemsOld = itemsOld.map(v => v.toLowerCase());
296
+ const newItems = itemsNew.filter(val => !itemsOld.includes(val.toLowerCase()));
297
+ ret.push(...newItems.map(val => this.knex.schema.raw(this.helper.getAlterNativeEnumSQL(enumName, schemaName, val))));
298
+ });
280
299
  }
281
300
  ret.push(this.createSchemaBuilder(schemaName).alterTable(tableName, table => {
282
301
  for (const index of Object.values(diff.removedIndexes)) {
@@ -300,7 +319,7 @@ class SqlSchemaGenerator extends core_1.AbstractSchemaGenerator {
300
319
  }));
301
320
  ret.push(this.createSchemaBuilder(schemaName).alterTable(tableName, table => {
302
321
  for (const column of Object.values(diff.addedColumns)) {
303
- const col = this.helper.createTableColumn(table, column, diff.fromTable);
322
+ const col = this.helper.createTableColumn(table, column, diff.fromTable, undefined, true);
304
323
  this.helper.configureColumn(column, col, this.knex);
305
324
  const foreignKey = Object.values(diff.addedForeignKeys).find(fk => fk.columnNames.length === 1 && fk.columnNames[0] === column.name);
306
325
  if (foreignKey && this.options.createForeignKeyConstraints) {
@@ -319,7 +338,7 @@ class SqlSchemaGenerator extends core_1.AbstractSchemaGenerator {
319
338
  if (changedProperties.size === 1 && changedProperties.has('enumItems') && column.nativeEnumName) {
320
339
  continue;
321
340
  }
322
- const col = this.helper.createTableColumn(table, column, diff.fromTable, changedProperties).alter();
341
+ const col = this.helper.createTableColumn(table, column, diff.fromTable, changedProperties, true).alter();
323
342
  this.helper.configureColumn(column, col, this.knex, changedProperties);
324
343
  }
325
344
  for (const { column } of Object.values(diff.changedColumns).filter(diff => diff.changedProperties.has('autoincrement'))) {
@@ -366,13 +385,6 @@ class SqlSchemaGenerator extends core_1.AbstractSchemaGenerator {
366
385
  table.comment(comment);
367
386
  }
368
387
  }));
369
- if (this.platform.supportsNativeEnums()) {
370
- changedNativeEnums.forEach(([enumName, itemsNew, itemsOld]) => {
371
- // postgres allows only adding new items
372
- const newItems = itemsNew.filter(val => !itemsOld.includes(val));
373
- ret.push(...newItems.map(val => this.knex.schema.raw(this.helper.getAlterNativeEnumSQL(enumName, schemaName, val))));
374
- });
375
- }
376
388
  return ret;
377
389
  }
378
390
  /**
@@ -422,10 +434,10 @@ class SqlSchemaGenerator extends core_1.AbstractSchemaGenerator {
422
434
  }
423
435
  return builder;
424
436
  }
425
- createTable(tableDef) {
437
+ createTable(tableDef, alter) {
426
438
  return this.createSchemaBuilder(tableDef.schema).createTable(tableDef.name, table => {
427
439
  tableDef.getColumns().forEach(column => {
428
- const col = this.helper.createTableColumn(table, column, tableDef);
440
+ const col = this.helper.createTableColumn(table, column, tableDef, undefined, alter);
429
441
  this.helper.configureColumn(column, col, this.knex);
430
442
  });
431
443
  for (const index of tableDef.getIndexes()) {