@mikro-orm/knex 6.0.0-dev.60 → 6.0.0-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 type { AnyEntity, Configuration, ConnectionOptions, EntityData, IsolationLevel, QueryResult, Transaction, TransactionEventBroadcaster } from '@mikro-orm/core';
2
+ import type { AnyEntity, Configuration, ConnectionOptions, EntityData, IsolationLevel, LoggerContext, QueryResult, Transaction, TransactionEventBroadcaster } from '@mikro-orm/core';
3
3
  import { Connection } from '@mikro-orm/core';
4
4
  import type { AbstractSqlPlatform } from './AbstractSqlPlatform';
5
5
  export declare abstract class AbstractSqlConnection extends Connection {
@@ -25,7 +25,7 @@ export declare abstract class AbstractSqlConnection extends Connection {
25
25
  }): Promise<Knex.Transaction>;
26
26
  commit(ctx: Knex.Transaction, eventBroadcaster?: TransactionEventBroadcaster): Promise<void>;
27
27
  rollback(ctx: Knex.Transaction, eventBroadcaster?: TransactionEventBroadcaster): Promise<void>;
28
- execute<T extends QueryResult | EntityData<AnyEntity> | EntityData<AnyEntity>[] = EntityData<AnyEntity>[]>(queryOrKnex: string | Knex.QueryBuilder | Knex.Raw, params?: unknown[], method?: 'all' | 'get' | 'run', ctx?: Transaction): Promise<T>;
28
+ 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?: LoggerContext): Promise<T>;
29
29
  /**
30
30
  * Execute raw SQL queries from file
31
31
  */
@@ -83,7 +83,7 @@ class AbstractSqlConnection extends core_1.Connection {
83
83
  await eventBroadcaster?.dispatchEvent(core_1.EventType.afterTransactionRollback, ctx);
84
84
  }
85
85
  }
86
- async execute(queryOrKnex, params = [], method = 'all', ctx) {
86
+ async execute(queryOrKnex, params = [], method = 'all', ctx, loggerContext) {
87
87
  await this.ensureConnection();
88
88
  if (core_1.Utils.isObject(queryOrKnex)) {
89
89
  ctx ??= (queryOrKnex.client.transacting ? queryOrKnex : null);
@@ -99,7 +99,7 @@ class AbstractSqlConnection extends core_1.Connection {
99
99
  query.transacting(ctx);
100
100
  }
101
101
  return query;
102
- }, { query: queryOrKnex, params });
102
+ }, { query: queryOrKnex, params, ...loggerContext });
103
103
  return this.transformRawResult(res, method);
104
104
  }
105
105
  /**
@@ -1,5 +1,5 @@
1
1
  import type { Knex } from 'knex';
2
- import type { AnyEntity, Collection, ConnectionType, Configuration, Constructor, CountOptions, DeleteOptions, Dictionary, DriverMethodOptions, EntityData, EntityDictionary, EntityField, EntityMetadata, EntityName, EntityProperty, FilterQuery, FindOneOptions, FindOptions, IDatabaseDriver, LockOptions, NativeInsertUpdateManyOptions, NativeInsertUpdateOptions, PopulateOptions, Primary, QueryOrderMap, QueryResult, Transaction, OrderDefinition } from '@mikro-orm/core';
2
+ import type { AnyEntity, Collection, ConnectionType, Configuration, Constructor, CountOptions, DeleteOptions, Dictionary, DriverMethodOptions, EntityData, EntityDictionary, EntityField, EntityMetadata, EntityName, EntityProperty, FilterQuery, FindOneOptions, FindOptions, IDatabaseDriver, LockOptions, NativeInsertUpdateManyOptions, NativeInsertUpdateOptions, PopulateOptions, Primary, QueryOrderMap, QueryResult, Transaction, OrderDefinition, LoggerContext } from '@mikro-orm/core';
3
3
  import { DatabaseDriver, EntityManagerType } from '@mikro-orm/core';
4
4
  import type { AbstractSqlConnection } from './AbstractSqlConnection';
5
5
  import type { AbstractSqlPlatform } from './AbstractSqlPlatform';
@@ -48,7 +48,7 @@ export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlCo
48
48
  */
49
49
  mapPropToFieldNames<T extends object>(qb: QueryBuilder<T>, prop: EntityProperty<T>, tableAlias?: string): Field<T>[];
50
50
  /** @internal */
51
- createQueryBuilder<T extends object>(entityName: EntityName<T> | QueryBuilder<T>, ctx?: Transaction<Knex.Transaction>, preferredConnectionType?: ConnectionType, convertCustomTypes?: boolean): QueryBuilder<T>;
51
+ createQueryBuilder<T extends object>(entityName: EntityName<T> | QueryBuilder<T>, ctx?: Transaction<Knex.Transaction>, preferredConnectionType?: ConnectionType, convertCustomTypes?: boolean, loggerContext?: LoggerContext): QueryBuilder<T>;
52
52
  protected resolveConnectionType(args: {
53
53
  ctx?: Transaction<Knex.Transaction>;
54
54
  connectionType?: ConnectionType;
@@ -26,7 +26,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
26
26
  }
27
27
  const populate = this.autoJoinOneToOneOwner(meta, options.populate, options.fields);
28
28
  const joinedProps = this.joinedProps(meta, populate);
29
- const qb = this.createQueryBuilder(entityName, options.ctx, options.connectionType, false);
29
+ const qb = this.createQueryBuilder(entityName, options.ctx, options.connectionType, false, options.loggerContext);
30
30
  const fields = this.buildFields(meta, populate, joinedProps, qb, options.fields);
31
31
  const joinedPropsOrderBy = this.buildJoinedPropsOrderBy(entityName, qb, meta, joinedProps);
32
32
  const orderBy = [...core_1.Utils.asArray(options.orderBy), ...joinedPropsOrderBy];
@@ -650,9 +650,9 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
650
650
  return prop.fieldNames;
651
651
  }
652
652
  /** @internal */
653
- createQueryBuilder(entityName, ctx, preferredConnectionType, convertCustomTypes) {
653
+ createQueryBuilder(entityName, ctx, preferredConnectionType, convertCustomTypes, loggerContext) {
654
654
  const connectionType = this.resolveConnectionType({ ctx, connectionType: preferredConnectionType });
655
- const qb = new query_1.QueryBuilder(entityName, this.metadata, this, ctx, undefined, connectionType);
655
+ const qb = new query_1.QueryBuilder(entityName, this.metadata, this, ctx, undefined, connectionType, undefined, loggerContext);
656
656
  if (!convertCustomTypes) {
657
657
  qb.unsetFlag(core_1.QueryFlag.CONVERT_CUSTOM_TYPES);
658
658
  }
@@ -846,7 +846,7 @@ class AbstractSqlDriver extends core_1.DatabaseDriver {
846
846
  ret.push((0, core_1.raw)(`${prop.formula(alias)} as ${aliased}`));
847
847
  });
848
848
  meta.props
849
- .filter(prop => prop.customType?.convertToDatabaseValueSQL || prop.customType?.convertToJSValueSQL)
849
+ .filter(prop => prop.hasConvertToDatabaseValueSQL || prop.hasConvertToJSValueSQL)
850
850
  .forEach(prop => ret.push(prop.name));
851
851
  }
852
852
  return ret.length > 0 ? core_1.Utils.unique(ret) : ['*'];
@@ -14,6 +14,7 @@ export declare abstract class AbstractSqlPlatform extends Platform {
14
14
  quoteValue(value: any): string;
15
15
  formatQuery(sql: string, params: readonly any[]): string;
16
16
  getSearchJsonPropertySQL(path: string, type: string, aliased: boolean): string;
17
+ getSearchJsonPropertyKey(path: string[], type: string, aliased: boolean): string;
17
18
  isRaw(value: any): boolean;
18
19
  supportsSchemas(): boolean;
19
20
  /** @inheritDoc */
@@ -76,6 +76,14 @@ class AbstractSqlPlatform extends core_1.Platform {
76
76
  getSearchJsonPropertySQL(path, type, aliased) {
77
77
  return this.getSearchJsonPropertyKey(path.split('->'), type, aliased);
78
78
  }
79
+ getSearchJsonPropertyKey(path, type, aliased) {
80
+ const [a, ...b] = path;
81
+ const quoteKey = (key) => key.match(/^[a-z]\w*$/i) ? key : `"${key}"`;
82
+ if (aliased) {
83
+ return (0, core_1.raw)(alias => `json_extract(${this.quoteIdentifier(`${alias}.${a}`)}, '$.${b.map(quoteKey).join('.')}')`);
84
+ }
85
+ return (0, core_1.raw)(`json_extract(${this.quoteIdentifier(a)}, '$.${b.map(quoteKey).join('.')}')`);
86
+ }
79
87
  isRaw(value) {
80
88
  return super.isRaw(value) || (typeof value === 'object' && value !== null && value.client && ['Ref', 'Raw'].includes(value.constructor.name));
81
89
  }
@@ -18,5 +18,12 @@ export declare class SqlEntityRepository<T extends object> extends EntityReposit
18
18
  * Returns configured knex instance.
19
19
  */
20
20
  getKnex(type?: ConnectionType): Knex;
21
+ /**
22
+ * @inheritDoc
23
+ */
24
+ getEntityManager(): SqlEntityManager;
25
+ /**
26
+ * @inheritDoc
27
+ */
21
28
  protected get em(): SqlEntityManager;
22
29
  }
@@ -11,7 +11,7 @@ class SqlEntityRepository extends core_1.EntityRepository {
11
11
  * Creates a QueryBuilder instance
12
12
  */
13
13
  createQueryBuilder(alias) {
14
- return this.em.createQueryBuilder(this.entityName, alias);
14
+ return this.getEntityManager().createQueryBuilder(this.entityName, alias);
15
15
  }
16
16
  /**
17
17
  * Shortcut for `createQueryBuilder()`
@@ -23,10 +23,19 @@ class SqlEntityRepository extends core_1.EntityRepository {
23
23
  * Returns configured knex instance.
24
24
  */
25
25
  getKnex(type) {
26
- return this.em.getConnection(type).getKnex();
26
+ return this.getEntityManager().getConnection(type).getKnex();
27
27
  }
28
+ /**
29
+ * @inheritDoc
30
+ */
31
+ getEntityManager() {
32
+ return this._em;
33
+ }
34
+ /**
35
+ * @inheritDoc
36
+ */
28
37
  get em() {
29
- return this._em.getContext(false);
38
+ return this._em;
30
39
  }
31
40
  }
32
41
  exports.SqlEntityRepository = SqlEntityRepository;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/knex",
3
- "version": "6.0.0-dev.60",
3
+ "version": "6.0.0-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",
@@ -63,9 +63,9 @@
63
63
  "sqlstring": "2.3.3"
64
64
  },
65
65
  "devDependencies": {
66
- "@mikro-orm/core": "^5.6.16"
66
+ "@mikro-orm/core": "^5.7.2"
67
67
  },
68
68
  "peerDependencies": {
69
- "@mikro-orm/core": "~6.0.0-dev.60"
69
+ "@mikro-orm/core": "~6.0.0-dev.62"
70
70
  }
71
71
  }
@@ -97,7 +97,7 @@ class CriteriaNode {
97
97
  [util_1.inspect.custom]() {
98
98
  const o = {};
99
99
  ['entityName', 'key', 'index', 'payload']
100
- .filter(k => this[k] != null)
100
+ .filter(k => this[k] !== undefined)
101
101
  .forEach(k => o[k] = this[k]);
102
102
  return `${this.constructor.name} ${(0, util_1.inspect)(o)}`;
103
103
  }
@@ -37,9 +37,6 @@ class CriteriaNodeFactory {
37
37
  }
38
38
  static createObjectNode(metadata, entityName, payload, parent, key) {
39
39
  const meta = metadata.find(entityName);
40
- if (!parent && Object.keys(payload).every(k => meta?.properties[k]?.kind === core_1.ReferenceKind.SCALAR)) {
41
- return this.createScalarNode(metadata, entityName, payload, parent, key);
42
- }
43
40
  const node = new ObjectCriteriaNode_1.ObjectCriteriaNode(metadata, entityName, parent, key);
44
41
  node.payload = Object.keys(payload).reduce((o, item) => {
45
42
  o[item] = this.createObjectItemNode(metadata, entityName, node, payload, item, meta);
@@ -1,7 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  import { inspect } from 'util';
3
3
  import type { Knex } from 'knex';
4
- import type { AnyEntity, ConnectionType, Dictionary, EntityData, EntityName, EntityProperty, FlushMode, GroupOperator, MetadataStorage, ObjectQuery, PopulateOptions, QBFilterQuery, QBQueryOrderMap, QueryResult, RequiredEntityData } from '@mikro-orm/core';
4
+ import type { AnyEntity, ConnectionType, Dictionary, EntityData, EntityName, EntityProperty, FlushMode, GroupOperator, LoggerContext, MetadataStorage, ObjectQuery, PopulateOptions, QBFilterQuery, QBQueryOrderMap, QueryResult, RequiredEntityData } from '@mikro-orm/core';
5
5
  import { LockMode, PopulateHint, QueryFlag } from '@mikro-orm/core';
6
6
  import { QueryType } from './enums';
7
7
  import type { AbstractSqlDriver } from '../AbstractSqlDriver';
@@ -35,6 +35,7 @@ export declare class QueryBuilder<T extends object = AnyEntity> {
35
35
  private readonly context?;
36
36
  private connectionType?;
37
37
  private readonly em?;
38
+ private readonly loggerContext?;
38
39
  get mainAlias(): Alias;
39
40
  get alias(): string;
40
41
  get helper(): QueryBuilderHelper;
@@ -78,7 +79,7 @@ export declare class QueryBuilder<T extends object = AnyEntity> {
78
79
  /**
79
80
  * @internal
80
81
  */
81
- constructor(entityName: EntityName<T> | QueryBuilder<T>, metadata: MetadataStorage, driver: AbstractSqlDriver, context?: Knex.Transaction<any, any[]> | undefined, alias?: string, connectionType?: ConnectionType | undefined, em?: SqlEntityManager<AbstractSqlDriver<import("..").AbstractSqlConnection, import("..").AbstractSqlPlatform>> | undefined);
82
+ constructor(entityName: EntityName<T> | QueryBuilder<T>, metadata: MetadataStorage, driver: AbstractSqlDriver, context?: Knex.Transaction<any, any[]> | undefined, alias?: string, connectionType?: ConnectionType | undefined, em?: SqlEntityManager<AbstractSqlDriver<import("..").AbstractSqlConnection, import("..").AbstractSqlPlatform>> | undefined, loggerContext?: LoggerContext | undefined);
82
83
  select(fields: Field<T> | Field<T>[], distinct?: boolean): SelectQueryBuilder<T>;
83
84
  addSelect(fields: Field<T> | Field<T>[]): SelectQueryBuilder<T>;
84
85
  distinct(): SelectQueryBuilder<T>;
@@ -52,12 +52,13 @@ class QueryBuilder {
52
52
  /**
53
53
  * @internal
54
54
  */
55
- constructor(entityName, metadata, driver, context, alias, connectionType, em) {
55
+ constructor(entityName, metadata, driver, context, alias, connectionType, em, loggerContext) {
56
56
  this.metadata = metadata;
57
57
  this.driver = driver;
58
58
  this.context = context;
59
59
  this.connectionType = connectionType;
60
60
  this.em = em;
61
+ this.loggerContext = loggerContext;
61
62
  /** @internal */
62
63
  this._populate = [];
63
64
  /** @internal */
@@ -369,6 +370,7 @@ class QueryBuilder {
369
370
  getKnexQuery() {
370
371
  this.finalize();
371
372
  const qb = this.getQueryBase();
373
+ qb.__raw = true; // tag it as there is now way to check via `instanceof`
372
374
  core_1.Utils.runIfNotEmpty(() => this.helper.appendQueryCondition(this.type ?? enums_1.QueryType.SELECT, this._cond, qb), this._cond && !this._onConflict);
373
375
  core_1.Utils.runIfNotEmpty(() => qb.groupBy(this.prepareFields(this._groupBy, 'groupBy')), this._groupBy);
374
376
  core_1.Utils.runIfNotEmpty(() => this.helper.appendQueryCondition(this.type ?? enums_1.QueryType.SELECT, this._having, qb, undefined, 'having'), this._having);
@@ -457,7 +459,7 @@ class QueryBuilder {
457
459
  return cached.data;
458
460
  }
459
461
  const type = this.connectionType || (method === 'run' ? 'write' : 'read');
460
- const res = await this.driver.getConnection(type).execute(query.sql, query.bindings, method, this.context);
462
+ const res = await this.driver.getConnection(type).execute(query.sql, query.bindings, method, this.context, this.loggerContext);
461
463
  const meta = this.mainAlias.metadata;
462
464
  if (!mapResults || !meta) {
463
465
  await this.em?.storeCache(this._cache, cached, res);
@@ -708,7 +710,7 @@ class QueryBuilder {
708
710
  });
709
711
  const meta = this.mainAlias.metadata;
710
712
  /* istanbul ignore next */
711
- const requiresSQLConversion = meta?.props.filter(p => p.customType?.convertToJSValueSQL) ?? [];
713
+ const requiresSQLConversion = meta?.props.filter(p => p.hasConvertToJSValueSQL) ?? [];
712
714
  if (this.flags.has(core_1.QueryFlag.CONVERT_CUSTOM_TYPES) && (fields.includes('*') || fields.includes(`${this.mainAlias.aliasName}.*`)) && requiresSQLConversion.length > 0) {
713
715
  requiresSQLConversion.forEach(p => ret.push(this.helper.mapper(p.name, this.type)));
714
716
  }
@@ -939,6 +941,7 @@ class QueryBuilder {
939
941
  // multiple sub-queries are needed to get around mysql limitations with order by + limit + where in + group by (o.O)
940
942
  // https://stackoverflow.com/questions/17892762/mysql-this-version-of-mysql-doesnt-yet-support-limit-in-all-any-some-subqu
941
943
  const subSubQuery = this.getKnex().select(pks).from(knexQuery);
944
+ subSubQuery.__raw = true; // tag it as there is now way to check via `instanceof`
942
945
  this._limit = undefined;
943
946
  this._offset = undefined;
944
947
  this.select(this._fields).where({ [core_1.Utils.getPrimaryKeyHash(meta.primaryKeys)]: { $in: subSubQuery } });
@@ -73,7 +73,7 @@ class QueryBuilderHelper {
73
73
  const as = alias === null ? '' : ` as ${aliased}`;
74
74
  return this.knex.raw(`${prop.formula(alias2)}${as}`);
75
75
  }
76
- if (prop?.customType?.convertToJSValueSQL) {
76
+ if (prop?.hasConvertToJSValueSQL) {
77
77
  const prefixed = this.prefix(field, isTableNameAliasRequired, true);
78
78
  const valueSQL = prop.customType.convertToJSValueSQL(prefixed, this.platform);
79
79
  if (alias === null) {
@@ -301,7 +301,7 @@ class QueryBuilderHelper {
301
301
  }
302
302
  appendOnConflictClause(type, onConflict, qb) {
303
303
  onConflict.forEach(item => {
304
- const sub = qb.onConflict(item.fields);
304
+ const sub = item.fields.length > 0 ? qb.onConflict(item.fields) : qb.onConflict();
305
305
  core_1.Utils.runIfNotEmpty(() => sub.ignore(), item.ignore);
306
306
  core_1.Utils.runIfNotEmpty(() => {
307
307
  let mergeParam = item.merge;
@@ -618,9 +618,10 @@ class QueryBuilderHelper {
618
618
  if (prop.customType && convertCustomTypes && !this.platform.isRaw(data[k])) {
619
619
  data[k] = prop.customType.convertToDatabaseValue(data[k], this.platform, { fromQuery: true, key: k, mode: 'query-data' });
620
620
  }
621
- if (prop.customType && 'convertToDatabaseValueSQL' in prop.customType && !this.platform.isRaw(data[k])) {
621
+ if (prop.hasConvertToDatabaseValueSQL && !this.platform.isRaw(data[k])) {
622
622
  const quoted = this.platform.quoteValue(data[k]);
623
- data[k] = this.knex.raw(prop.customType.convertToDatabaseValueSQL(quoted, this.platform).replace(/\?/, '\\?'));
623
+ const sql = prop.customType.convertToDatabaseValueSQL(quoted, this.platform);
624
+ data[k] = this.knex.raw(sql.replace(/\?/, '\\?'));
624
625
  }
625
626
  if (!prop.customType && (Array.isArray(data[k]) || core_1.Utils.isPlainObject(data[k]))) {
626
627
  data[k] = JSON.stringify(data[k]);
@@ -439,6 +439,11 @@ class SchemaComparator {
439
439
  const defaultValueTo = !['0', 'false', 'f', 'n', 'no', 'off'].includes('' + to.default);
440
440
  return defaultValueFrom === defaultValueTo;
441
441
  }
442
+ if (to.mappedType instanceof core_1.JsonType) {
443
+ const defaultValueFrom = (0, core_1.parseJsonSafe)(from.default.replace(/^'(.*)'$/, '$1'));
444
+ const defaultValueTo = (0, core_1.parseJsonSafe)(to.default?.replace(/^'(.*)'$/, '$1'));
445
+ return core_1.Utils.equals(defaultValueFrom, defaultValueTo);
446
+ }
442
447
  if (to.mappedType instanceof core_1.DateTimeType && from.default && to.default) {
443
448
  // normalize now/current_timestamp defaults, also remove `()` from the end of default expression
444
449
  const defaultValueFrom = from.default.toLowerCase().replace('current_timestamp', 'now').replace(/\(\)$/, '');