@mikro-orm/core 6.4.17-dev.29 → 6.4.17-dev.30

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,4 +1,4 @@
1
- import type { EntityClass, Dictionary, AutoPath } from '../typings';
1
+ import type { EntityClass, Dictionary, AutoPath, IndexCallback } from '../typings';
2
2
  import type { DeferMode } from '../enums';
3
3
  export declare function Index<T extends object, H extends string>(options?: IndexOptions<T, H>): (target: T, propertyName?: (T extends EntityClass<unknown> ? undefined : keyof T) | undefined) => any;
4
4
  export declare function Unique<T extends object, H extends string>(options?: UniqueOptions<T, H>): (target: T, propertyName?: (T extends EntityClass<unknown> ? undefined : keyof T) | undefined) => any;
@@ -8,7 +8,7 @@ interface BaseOptions<T, H extends string> {
8
8
  name?: string;
9
9
  properties?: (T extends EntityClass<infer P> ? Properties<P, H> : Properties<T, H>);
10
10
  options?: Dictionary;
11
- expression?: string;
11
+ expression?: string | (T extends EntityClass<infer P> ? IndexCallback<P> : IndexCallback<T>);
12
12
  }
13
13
  export interface UniqueOptions<T, H extends string = string> extends BaseOptions<T, H> {
14
14
  deferMode?: DeferMode | `${DeferMode}`;
package/index.d.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * @packageDocumentation
3
3
  * @module core
4
4
  */
5
- export { Constructor, ConnectionType, Dictionary, PrimaryKeyProp, Primary, IPrimaryKey, ObjectQuery, FilterQuery, IWrappedEntity, EntityName, EntityData, Highlighter, MaybePromise, AnyEntity, EntityClass, EntityProperty, EntityMetadata, QBFilterQuery, PopulateOptions, Populate, Loaded, New, LoadedReference, LoadedCollection, IMigrator, IMigrationGenerator, MigratorEvent, GetRepository, EntityRepositoryType, MigrationObject, DeepPartial, PrimaryProperty, Cast, IsUnknown, EntityDictionary, EntityDTO, MigrationDiff, GenerateOptions, FilterObject, IEntityGenerator, ISeedManager, EntityClassGroup, OptionalProps, EagerProps, HiddenProps, RequiredEntityData, CheckCallback, SimpleColumnMeta, Rel, Ref, ScalarRef, EntityRef, ISchemaGenerator, UmzugMigration, MigrateOptions, MigrationResult, MigrationRow, EntityKey, EntityValue, EntityDataValue, FilterKey, Opt, EntityType, FromEntityType, Selected, IsSubset, NoInfer, EntityProps, ExpandProperty, ExpandScalar, FilterItemValue, ExpandQuery, Scalar, ExpandHint, Hidden, FilterValue, MergeLoaded, MergeSelected, Config, DefineConfig, TypeConfig, ClearDatabaseOptions, CreateSchemaOptions, EnsureDatabaseOptions, UpdateSchemaOptions, DropSchemaOptions, RefreshDatabaseOptions, AutoPath, UnboxArray, MetadataProcessor, ImportsResolver, } from './typings';
5
+ export { Constructor, ConnectionType, Dictionary, PrimaryKeyProp, Primary, IPrimaryKey, ObjectQuery, FilterQuery, IWrappedEntity, EntityName, EntityData, Highlighter, MaybePromise, AnyEntity, EntityClass, EntityProperty, EntityMetadata, QBFilterQuery, PopulateOptions, Populate, Loaded, New, LoadedReference, LoadedCollection, IMigrator, IMigrationGenerator, MigratorEvent, GetRepository, EntityRepositoryType, MigrationObject, DeepPartial, PrimaryProperty, Cast, IsUnknown, EntityDictionary, EntityDTO, MigrationDiff, GenerateOptions, FilterObject, IEntityGenerator, ISeedManager, EntityClassGroup, OptionalProps, EagerProps, HiddenProps, RequiredEntityData, CheckCallback, IndexCallback, SimpleColumnMeta, Rel, Ref, ScalarRef, EntityRef, ISchemaGenerator, UmzugMigration, MigrateOptions, MigrationResult, MigrationRow, EntityKey, EntityValue, EntityDataValue, FilterKey, Opt, EntityType, FromEntityType, Selected, IsSubset, NoInfer, EntityProps, ExpandProperty, ExpandScalar, FilterItemValue, ExpandQuery, Scalar, ExpandHint, Hidden, FilterValue, MergeLoaded, MergeSelected, Config, DefineConfig, TypeConfig, ClearDatabaseOptions, CreateSchemaOptions, EnsureDatabaseOptions, UpdateSchemaOptions, DropSchemaOptions, RefreshDatabaseOptions, AutoPath, UnboxArray, MetadataProcessor, ImportsResolver, } from './typings';
6
6
  export * from './enums';
7
7
  export * from './errors';
8
8
  export * from './exceptions';
package/index.mjs CHANGED
@@ -188,6 +188,7 @@ export const getOnConflictFields = mod.getOnConflictFields;
188
188
  export const getOnConflictReturningFields = mod.getOnConflictReturningFields;
189
189
  export const helper = mod.helper;
190
190
  export const parseJsonSafe = mod.parseJsonSafe;
191
+ export const quote = mod.quote;
191
192
  export const raw = mod.raw;
192
193
  export const ref = mod.ref;
193
194
  export const rel = mod.rel;
@@ -54,7 +54,6 @@ export declare class MetadataDiscovery {
54
54
  private initAutoincrement;
55
55
  private initCheckConstraints;
56
56
  private initGeneratedColumn;
57
- private createColumnMappingObject;
58
57
  private getDefaultVersionValue;
59
58
  private inferDefaultValue;
60
59
  private initDefaultValue;
@@ -969,7 +969,7 @@ class MetadataDiscovery {
969
969
  }
970
970
  }
971
971
  initCheckConstraints(meta) {
972
- const map = this.createColumnMappingObject(meta);
972
+ const map = meta.createColumnMappingObject();
973
973
  for (const check of meta.checks) {
974
974
  const columns = check.property ? meta.properties[check.property].fieldNames : [];
975
975
  check.name ??= this.namingStrategy.indexName(meta.tableName, columns, 'check');
@@ -992,19 +992,11 @@ class MetadataDiscovery {
992
992
  }
993
993
  return;
994
994
  }
995
- const map = this.createColumnMappingObject(meta);
995
+ const map = meta.createColumnMappingObject();
996
996
  if (prop.generated instanceof Function) {
997
997
  prop.generated = prop.generated(map);
998
998
  }
999
999
  }
1000
- createColumnMappingObject(meta) {
1001
- return Object.values(meta.properties).reduce((o, prop) => {
1002
- if (prop.fieldNames) {
1003
- o[prop.name] = prop.fieldNames[0];
1004
- }
1005
- return o;
1006
- }, {});
1007
- }
1008
1000
  getDefaultVersionValue(meta, prop) {
1009
1001
  if (typeof prop.defaultRaw !== 'undefined') {
1010
1002
  return prop.defaultRaw;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
- "version": "6.4.17-dev.29",
3
+ "version": "6.4.17-dev.30",
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",
@@ -64,7 +64,7 @@
64
64
  "esprima": "4.0.1",
65
65
  "fs-extra": "11.3.0",
66
66
  "globby": "11.1.0",
67
- "mikro-orm": "6.4.17-dev.29",
67
+ "mikro-orm": "6.4.17-dev.30",
68
68
  "reflect-metadata": "0.2.2"
69
69
  }
70
70
  }
@@ -173,7 +173,9 @@ export declare abstract class Platform {
173
173
  getExtension<T>(extensionName: string, extensionKey: string, moduleName: string, em: EntityManager): T;
174
174
  getSchemaGenerator(driver: IDatabaseDriver, em?: EntityManager): ISchemaGenerator;
175
175
  processDateProperty(value: unknown): string | number | Date;
176
- quoteIdentifier(id: string, quote?: string): string;
176
+ quoteIdentifier(id: string | {
177
+ toString: () => string;
178
+ }, quote?: string): string;
177
179
  quoteValue(value: any): string;
178
180
  escape(value: any): string;
179
181
  formatQuery(sql: string, params: readonly any[]): string;
package/typings.d.ts CHANGED
@@ -6,7 +6,7 @@ import type { SerializationContext, SerializeOptions } from './serialization';
6
6
  import type { EntitySchema, MetadataStorage } from './metadata';
7
7
  import type { Type, types } from './types';
8
8
  import type { Platform } from './platforms';
9
- import type { Configuration } from './utils';
9
+ import type { Configuration, RawQueryFragment } from './utils';
10
10
  import type { EntityManager } from './EntityManager';
11
11
  import type { EmbeddedPrefixMode } from './decorators/Embedded';
12
12
  import type { EventSubscriber } from './events';
@@ -287,8 +287,14 @@ export type EntityDTO<T, C extends TypeConfig = never> = {
287
287
  } & {
288
288
  [K in keyof T as DTOOptionalKeys<T, K>]?: EntityDTOProp<T, T[K], C> | AddOptional<T[K]>;
289
289
  };
290
- type CheckKey<T> = IsUnknown<T> extends false ? keyof T : string;
291
- export type CheckCallback<T> = (columns: Record<CheckKey<T>, string>) => string;
290
+ type PropertyName<T> = IsUnknown<T> extends false ? keyof T : string;
291
+ type TableName = {
292
+ name: string;
293
+ schema?: string;
294
+ toString: () => string;
295
+ };
296
+ export type IndexCallback<T> = (table: TableName, columns: Record<PropertyName<T>, string>) => string | RawQueryFragment;
297
+ export type CheckCallback<T> = (columns: Record<PropertyName<T>, string>) => string;
292
298
  export type GeneratedColumnCallback<T> = (columns: Record<keyof T, string>) => string;
293
299
  export interface CheckConstraint<T = any> {
294
300
  name?: string;
@@ -396,6 +402,7 @@ export declare class EntityMetadata<T = any> {
396
402
  removeProperty(name: string, sync?: boolean): void;
397
403
  getPrimaryProps(): EntityProperty<T>[];
398
404
  getPrimaryProp(): EntityProperty<T>;
405
+ createColumnMappingObject(): Dictionary<any>;
399
406
  get tableName(): string;
400
407
  set tableName(name: string);
401
408
  sync(initIndexes?: boolean): void;
@@ -447,18 +454,18 @@ export interface EntityMetadata<T = any> {
447
454
  uniqueProps: EntityProperty<T>[];
448
455
  getterProps: EntityProperty<T>[];
449
456
  indexes: {
450
- properties: EntityKey<T> | EntityKey<T>[];
457
+ properties?: EntityKey<T> | EntityKey<T>[];
451
458
  name?: string;
452
459
  type?: string;
453
460
  options?: Dictionary;
454
- expression?: string;
461
+ expression?: string | IndexCallback<T>;
455
462
  }[];
456
463
  uniques: {
457
- properties: EntityKey<T> | EntityKey<T>[];
464
+ properties?: EntityKey<T> | EntityKey<T>[];
458
465
  name?: string;
459
466
  options?: Dictionary;
460
- expression?: string;
461
- deferMode?: DeferMode;
467
+ expression?: string | IndexCallback<T>;
468
+ deferMode?: DeferMode | `${DeferMode}`;
462
469
  }[];
463
470
  checks: CheckConstraint<T>[];
464
471
  repositoryClass?: string;
package/typings.js CHANGED
@@ -53,6 +53,14 @@ class EntityMetadata {
53
53
  getPrimaryProp() {
54
54
  return this.properties[this.primaryKeys[0]];
55
55
  }
56
+ createColumnMappingObject() {
57
+ return Object.values(this.properties).reduce((o, prop) => {
58
+ if (prop.fieldNames) {
59
+ o[prop.name] = prop.fieldNames[0];
60
+ }
61
+ return o;
62
+ }, {});
63
+ }
56
64
  get tableName() {
57
65
  return this.collection;
58
66
  }
@@ -70,6 +70,24 @@ export declare const ALIAS_REPLACEMENT_RE = "\\[::alias::\\]";
70
70
  * ```ts
71
71
  * @Filter({ name: 'long', cond: () => ({ [raw('length(perex)')]: { $gt: 10000 } }) })
72
72
  * ```
73
+ *
74
+ * The `raw` helper can be used within indexes and uniques to write database-agnostic SQL expressions. In that case, you can use `'??'` to tag your database identifiers (table name, column names, index name, ...) inside your expression, and pass those identifiers as a second parameter to the `raw` helper. Internally, those will automatically be quoted according to the database in use:
75
+ *
76
+ * ```ts
77
+ * // On postgres, will produce: create index "index custom_idx_on_name" on "library.author" ("country")
78
+ * // On mysql, will produce: create index `index custom_idx_on_name` on `library.author` (`country`)
79
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => raw(`create index ?? on ?? (??)`, ['custom_idx_on_name', table, columns.name]) })
80
+ * @Entity({ schema: 'library' })
81
+ * export class Author { ... }
82
+ * ```
83
+ *
84
+ * You can also use the `quote` tag function to write database-agnostic SQL expressions. The end-result is the same as using the `raw` function regarding database identifiers quoting, only to have a more elegant expression syntax:
85
+ *
86
+ * ```ts
87
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => quote`create index ${'custom_idx_on_name'} on ${table} (${columns.name})` })
88
+ * @Entity({ schema: 'library' })
89
+ * export class Author { ... }
90
+ * ```
73
91
  */
74
92
  export declare function raw<T extends object = any, R = any>(sql: EntityKey<T> | EntityKey<T>[] | AnyString | ((alias: string) => string) | RawQueryFragment, params?: readonly unknown[] | Dictionary<unknown>): R;
75
93
  /**
@@ -94,3 +112,19 @@ export declare namespace sql {
94
112
  var upper: <T extends object>(key: string | ((alias: string) => string)) => string;
95
113
  }
96
114
  export declare function createSqlFunction<T extends object, R = string>(func: string, key: string | ((alias: string) => string)): R;
115
+ /**
116
+ * Tag function providing quoting of db identifiers (table name, columns names, index names, ...).
117
+ *
118
+ * Within the template literal on which the tag function is applied, all placeholders are considered to be database identifiers, and will thus be quoted as so according to the database in use.
119
+ *
120
+ * ```ts
121
+ * // On postgres, will produce: create index "index custom_idx_on_name" on "library.author" ("name")
122
+ * // On mysql, will produce: create index `index custom_idx_on_name` on `library.author` (`name`)
123
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => quote`create index ${'custom_idx_on_name'} on ${table} (${columns.name})` })
124
+ * @Entity({ schema: 'library' })
125
+ * export class Author { ... }
126
+ * ```
127
+ */
128
+ export declare function quote(expParts: readonly string[], ...values: (string | {
129
+ toString(): string;
130
+ })[]): any;
@@ -4,6 +4,7 @@ exports.ALIAS_REPLACEMENT_RE = exports.ALIAS_REPLACEMENT = exports.RawQueryFragm
4
4
  exports.raw = raw;
5
5
  exports.sql = sql;
6
6
  exports.createSqlFunction = createSqlFunction;
7
+ exports.quote = quote;
7
8
  const node_async_hooks_1 = require("node:async_hooks");
8
9
  const node_util_1 = require("node:util");
9
10
  const Utils_1 = require("./Utils");
@@ -150,6 +151,24 @@ exports.ALIAS_REPLACEMENT_RE = '\\[::alias::\\]';
150
151
  * ```ts
151
152
  * @Filter({ name: 'long', cond: () => ({ [raw('length(perex)')]: { $gt: 10000 } }) })
152
153
  * ```
154
+ *
155
+ * The `raw` helper can be used within indexes and uniques to write database-agnostic SQL expressions. In that case, you can use `'??'` to tag your database identifiers (table name, column names, index name, ...) inside your expression, and pass those identifiers as a second parameter to the `raw` helper. Internally, those will automatically be quoted according to the database in use:
156
+ *
157
+ * ```ts
158
+ * // On postgres, will produce: create index "index custom_idx_on_name" on "library.author" ("country")
159
+ * // On mysql, will produce: create index `index custom_idx_on_name` on `library.author` (`country`)
160
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => raw(`create index ?? on ?? (??)`, ['custom_idx_on_name', table, columns.name]) })
161
+ * @Entity({ schema: 'library' })
162
+ * export class Author { ... }
163
+ * ```
164
+ *
165
+ * You can also use the `quote` tag function to write database-agnostic SQL expressions. The end-result is the same as using the `raw` function regarding database identifiers quoting, only to have a more elegant expression syntax:
166
+ *
167
+ * ```ts
168
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => quote`create index ${'custom_idx_on_name'} on ${table} (${columns.name})` })
169
+ * @Entity({ schema: 'library' })
170
+ * export class Author { ... }
171
+ * ```
153
172
  */
154
173
  function raw(sql, params) {
155
174
  if (sql instanceof RawQueryFragment) {
@@ -207,3 +226,19 @@ sql.ref = (...keys) => raw('??', [keys.join('.')]);
207
226
  sql.now = (length) => raw('current_timestamp' + (length == null ? '' : `(${length})`));
208
227
  sql.lower = (key) => createSqlFunction('lower', key);
209
228
  sql.upper = (key) => createSqlFunction('upper', key);
229
+ /**
230
+ * Tag function providing quoting of db identifiers (table name, columns names, index names, ...).
231
+ *
232
+ * Within the template literal on which the tag function is applied, all placeholders are considered to be database identifiers, and will thus be quoted as so according to the database in use.
233
+ *
234
+ * ```ts
235
+ * // On postgres, will produce: create index "index custom_idx_on_name" on "library.author" ("name")
236
+ * // On mysql, will produce: create index `index custom_idx_on_name` on `library.author` (`name`)
237
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => quote`create index ${'custom_idx_on_name'} on ${table} (${columns.name})` })
238
+ * @Entity({ schema: 'library' })
239
+ * export class Author { ... }
240
+ * ```
241
+ */
242
+ function quote(expParts, ...values) {
243
+ return raw(expParts.join('??'), values);
244
+ }