@mikro-orm/sql 7.2.9-dev.2 → 7.2.9-dev.20

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.
@@ -63,7 +63,11 @@ export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlCo
63
63
  private nativeCloneTPT;
64
64
  private mapCloneOverrides;
65
65
  private buildCloneFields;
66
- private getCloneableProps;
66
+ /**
67
+ * Returns properties whose columns can be copied by an `INSERT … SELECT` (owning columns that are not PKs, generated or formulas).
68
+ * @internal
69
+ */
70
+ getCloneableProps<T extends object>(meta: EntityMetadata<T>, ownProps?: boolean): EntityProperty<T>[];
67
71
  nativeInsertMany<T extends object>(entityName: EntityName<T>, data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>, transform?: (sql: string) => string): Promise<QueryResult<T>>;
68
72
  /** Resolves the primary key of every inserted row from the supplied data or the returned rows, and reports them via `insertedIds` when all are known. */
69
73
  protected resolveInsertedPrimaryKeys<T extends object>(meta: EntityMetadata<T>, data: EntityDictionary<T>[], res: QueryResult<T>): any[][];
@@ -763,25 +763,12 @@ export class AbstractSqlDriver extends DatabaseDriver {
763
763
  }
764
764
  return { selectFields, insertColumns };
765
765
  }
766
+ /**
767
+ * Returns properties whose columns can be copied by an `INSERT … SELECT` (owning columns that are not PKs, generated or formulas).
768
+ * @internal
769
+ */
766
770
  getCloneableProps(meta, ownProps) {
767
- return (ownProps ? (meta.ownProps ?? meta.props) : meta.props).filter(prop => {
768
- if (prop.persist === false) {
769
- return false;
770
- }
771
- if (prop.primary) {
772
- return false;
773
- }
774
- if (!prop.fieldNames?.length) {
775
- return false;
776
- }
777
- if ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
778
- return false;
779
- }
780
- if (prop.kind === ReferenceKind.EMBEDDED && !prop.object) {
781
- return false;
782
- }
783
- return true;
784
- });
771
+ return (ownProps ? (meta.ownProps ?? meta.props) : meta.props).filter(prop => !prop.primary && !prop.generated && this.platform.shouldHaveColumn(prop, true, undefined, false, false));
785
772
  }
786
773
  async nativeInsertMany(entityName, data, options = {}, transform) {
787
774
  options.processCollections ??= true;
@@ -1130,6 +1117,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
1130
1117
  }
1131
1118
  }
1132
1119
  }
1120
+ const scalarColumn = prop.fieldNames.length > 1 && !prop.polymorphic ? this.getScalarFieldName(prop) : undefined;
1133
1121
  prop.fieldNames.forEach((fieldName, fieldNameIdx) => {
1134
1122
  if (fields.has(fieldName) || (prop.ownColumns && !prop.ownColumns.includes(fieldName))) {
1135
1123
  return;
@@ -1151,7 +1139,15 @@ export class AbstractSqlDriver extends DatabaseDriver {
1151
1139
  sql += '?';
1152
1140
  }
1153
1141
  params.push(...pks);
1154
- addParams(prop, prop.fieldNames.length > 1 ? data[idx][key]?.[fieldNameIdx] : data[idx][key]);
1142
+ const value = data[idx][key];
1143
+ const scalar = Array.isArray(value) && value.length === 1 ? value[0] : value;
1144
+ // a composite FK given as a scalar holds only the target PK, written to the column that references it
1145
+ if (scalarColumn && !isRaw(scalar) && Utils.isPrimaryKey(scalar)) {
1146
+ addParams(prop, (fieldName === scalarColumn ? scalar : null));
1147
+ }
1148
+ else {
1149
+ addParams(prop, prop.fieldNames.length > 1 ? value?.[fieldNameIdx] : value);
1150
+ }
1155
1151
  }
1156
1152
  });
1157
1153
  sql += ` else ${this.platform.quoteIdentifier(fieldName)} end, `;
@@ -62,6 +62,7 @@ export declare class MySqlSchemaHelper extends SchemaHelper {
62
62
  protected getChecksSQL(tables: Table[]): string;
63
63
  normalizeDefaultValue(defaultValue: string, length: number): string | number;
64
64
  protected wrap(val: string | null | undefined, type: Type<unknown>): string | null | undefined;
65
+ normalizeExpression(expr: string): string;
65
66
  /** Decodes the backslash escapes of an introspected string literal. */
66
67
  unescapeDefault(val: string): string;
67
68
  }
@@ -295,12 +295,14 @@ export class MySqlSchemaHelper extends SchemaHelper {
295
295
  const ret = {};
296
296
  for (const check of allChecks) {
297
297
  const key = this.getTableKey(check);
298
+ // string literals come back escaped twice, decoded one level the same as the defaults in `wrap()`
299
+ const expression = check.expression.replace(/\\(.)/gs, '$1');
298
300
  ret[key] ??= [];
299
301
  ret[key].push({
300
302
  name: check.name,
301
303
  columnName: check.column_name,
302
- definition: `check ${check.expression}`,
303
- expression: check.expression.replace(/^\((.*)\)$/, '$1'),
304
+ definition: `check ${expression}`,
305
+ expression: expression.replace(/^\((.*)\)$/, '$1'),
304
306
  });
305
307
  }
306
308
  return ret;
@@ -610,6 +612,10 @@ export class MySqlSchemaHelper extends SchemaHelper {
610
612
  const stringType = type instanceof StringType || type instanceof TextType || type instanceof EnumType;
611
613
  return stringType ? this.platform.quoteDefaultValue(val) : val;
612
614
  }
615
+ normalizeExpression(expr) {
616
+ // `\'` and `''` are the same quote inside a literal
617
+ return expr.replace(/\\(.)/gs, (escape, char) => (char === "'" ? "''" : escape));
618
+ }
613
619
  /** Decodes the backslash escapes of an introspected string literal. */
614
620
  unescapeDefault(val) {
615
621
  const sqlEscapes = { 0: '\0', b: '\b', n: '\n', r: '\r', t: '\t', Z: '\x1a' };
@@ -1,4 +1,4 @@
1
- import { DeferMode, EnumType, Type, Utils, } from '@mikro-orm/core';
1
+ import { DecimalType, DeferMode, DoubleType, EnumType, FloatType, Type, Utils, } from '@mikro-orm/core';
2
2
  import { SchemaHelper, stripStatementNewlines } from '../../schema/SchemaHelper.js';
3
3
  import { normalizePartitionBound, normalizePartitionDefinition } from '../../schema/partitioning.js';
4
4
  /** PostGIS system views that should be automatically ignored */
@@ -230,7 +230,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
230
230
  const table = schema.addTable(t.table_name, t.schema_name, t.table_comment);
231
231
  table.collation = dbCollation;
232
232
  const pks = await this.getPrimaryKeys(connection, indexes[key], table.name, table.schema);
233
- const enums = this.getEnumDefinitions(checks[key] ?? []);
233
+ const enums = this.getEnumDefinitions(checks[key] ?? [], columns[key] ?? []);
234
234
  if (columns[key]) {
235
235
  table.init(columns[key], indexes[key], checks[key], pks, fks[key], enums);
236
236
  }
@@ -1051,7 +1051,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
1051
1051
  }
1052
1052
  return `alter type ${this.quote(name)} add value if not exists ${this.platform.quoteValue(value)}${suffix}`;
1053
1053
  }
1054
- getEnumDefinitions(checks) {
1054
+ getEnumDefinitions(checks, columns) {
1055
1055
  return checks.reduce((o, item) => {
1056
1056
  // check constraints are defined as one of:
1057
1057
  // `CHECK ((type = ANY (ARRAY['local'::text, 'global'::text])))`
@@ -1063,13 +1063,20 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
1063
1063
  // the single-value form must compare against a quoted literal (`= 'a'::text`); anything else
1064
1064
  // (e.g. a JSON `->>` extraction like `name = data->>'name'`) is not an enum constraint
1065
1065
  const m2 = item.definition?.match(/\(array\[(.*)]\)/i) || item.definition?.match(/ = ('(?:[^']|'')*'::[\w ]+)\)/i);
1066
- if (item.columnName && m1 && m2) {
1066
+ // enums with string items are emulated with a check, a check like `delta in (1, -1)` on a number is a plain one
1067
+ const column = columns.find(c => c.name === item.columnName);
1068
+ const numeric = column != null &&
1069
+ (this.platform.isNumericColumn(column.mappedType) ||
1070
+ [DecimalType, FloatType, DoubleType].some(t => column.mappedType instanceof t));
1071
+ if (item.columnName && m1 && m2 && !numeric) {
1067
1072
  /* v8 ignore next */
1068
1073
  const parts = m2[1].match(/('(?:[^']|'')*'::\w[\w ]*)/g) ?? m2[1].split(',');
1069
1074
  let items = parts.map((item) => /^\(?'((?:[^']|'')*)'/.exec(item.trim())?.[1]?.replace(/''/g, "'"));
1070
1075
  items = items.filter(item => item !== undefined);
1071
1076
  if (items.length > 0) {
1072
1077
  o[item.columnName] = items;
1078
+ // kept to compare with a plain check of the same values, e.g. `kind = 'manual'` is stored like a single item enum
1079
+ item.introspectedExpression = item.expression;
1073
1080
  item.expression = this.platform.getEnumCheckConstraintExpression(item.columnName, items);
1074
1081
  item.definition = `check (${item.expression})`;
1075
1082
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/sql",
3
- "version": "7.2.9-dev.2",
3
+ "version": "7.2.9-dev.20",
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
  "keywords": [
6
6
  "data-mapper",
@@ -53,7 +53,7 @@
53
53
  "@mikro-orm/core": "^7.2.8"
54
54
  },
55
55
  "peerDependencies": {
56
- "@mikro-orm/core": "7.2.9-dev.2"
56
+ "@mikro-orm/core": "7.2.9-dev.20"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">= 22.17.0"
@@ -803,6 +803,11 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
803
803
  * Use `method` to specify what kind of result you want to get (array/single/meta).
804
804
  */
805
805
  execute<U = any>(method?: 'all' | 'get' | 'run', options?: ExecuteOptions | boolean): Promise<U>;
806
+ /**
807
+ * An update or delete with auto-joined conditions stays a select until `finalize()` wraps it,
808
+ * so read the same flags `wrapModifySubQuery()` uses.
809
+ */
810
+ private getExecuteType;
806
811
  private getConnection;
807
812
  /**
808
813
  * Executes the query and returns an async iterable (async generator) that yields results one by one.
@@ -975,8 +980,6 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
975
980
  * Tier 3: Derive from target entity metadata (all cloneable columns), auto-populate source select
976
981
  */
977
982
  private resolveInsertFromColumns;
978
- /** Returns properties that are safe to clone (persistable, non-PK, non-generated). */
979
- private getCloneableProps;
980
983
  private applyDiscriminatorCondition;
981
984
  /**
982
985
  * Ensures TPT joins are applied. Can be called early before finalize() to populate
@@ -1067,12 +1067,13 @@ export class QueryBuilder {
1067
1067
  options = typeof options === 'boolean' ? { mapResults: options } : (options ?? {});
1068
1068
  options.mergeResults ??= true;
1069
1069
  options.mapResults ??= true;
1070
- const isRunType = [QueryType.INSERT, QueryType.UPDATE, QueryType.DELETE, QueryType.TRUNCATE].includes(this.type);
1070
+ const type = this.getExecuteType();
1071
+ const isRunType = [QueryType.INSERT, QueryType.UPDATE, QueryType.DELETE, QueryType.TRUNCATE].includes(type);
1071
1072
  method ??= isRunType ? 'run' : 'all';
1072
1073
  if (!this.connectionType && (isRunType || this.context)) {
1073
1074
  this.connectionType = 'write';
1074
1075
  }
1075
- if (!this.#state.finalized && method === 'get' && this.type === QueryType.SELECT) {
1076
+ if (!this.#state.finalized && method === 'get' && type === QueryType.SELECT) {
1076
1077
  this.limit(1);
1077
1078
  }
1078
1079
  const query = this.toQuery();
@@ -1130,6 +1131,19 @@ export class QueryBuilder {
1130
1131
  await this.em?.storeCache(this.#state.cache, cached, mapped);
1131
1132
  return mapped;
1132
1133
  }
1134
+ /**
1135
+ * An update or delete with auto-joined conditions stays a select until `finalize()` wraps it,
1136
+ * so read the same flags `wrapModifySubQuery()` uses.
1137
+ */
1138
+ getExecuteType() {
1139
+ if (this.#state.flags.has(QueryFlag.UPDATE_SUB_QUERY)) {
1140
+ return QueryType.UPDATE;
1141
+ }
1142
+ if (this.#state.flags.has(QueryFlag.DELETE_SUB_QUERY)) {
1143
+ return QueryType.DELETE;
1144
+ }
1145
+ return this.type;
1146
+ }
1133
1147
  getConnection() {
1134
1148
  const write = !this.platform.getConfig().get('preferReadReplicas');
1135
1149
  const type = this.connectionType || (write ? 'write' : 'read');
@@ -1870,7 +1884,7 @@ export class QueryBuilder {
1870
1884
  });
1871
1885
  }
1872
1886
  // Tier 3: derive from metadata — all cloneable columns
1873
- const cloneableProps = this.getCloneableProps(meta);
1887
+ const cloneableProps = this.driver.getCloneableProps(meta);
1874
1888
  const selectFields = [];
1875
1889
  const columns = [];
1876
1890
  for (const prop of cloneableProps) {
@@ -1885,27 +1899,6 @@ export class QueryBuilder {
1885
1899
  }
1886
1900
  return columns;
1887
1901
  }
1888
- /** Returns properties that are safe to clone (persistable, non-PK, non-generated). */
1889
- getCloneableProps(meta) {
1890
- return meta.props.filter(prop => {
1891
- if (prop.persist === false) {
1892
- return false;
1893
- }
1894
- if (prop.primary) {
1895
- return false;
1896
- }
1897
- if (!prop.fieldNames?.length) {
1898
- return false;
1899
- }
1900
- if ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
1901
- return false;
1902
- }
1903
- if (prop.kind === ReferenceKind.EMBEDDED && !prop.object) {
1904
- return false;
1905
- }
1906
- return true;
1907
- });
1908
- }
1909
1902
  applyDiscriminatorCondition() {
1910
1903
  const meta = this.mainAlias.meta;
1911
1904
  if (meta.root.inheritanceType !== 'sti' || !meta.discriminatorValue) {
@@ -415,14 +415,18 @@ export class QueryBuilderHelper {
415
415
  Utils.runIfNotEmpty(() => {
416
416
  let mergeParam = item.merge;
417
417
  if (Utils.isObject(item.merge)) {
418
- mergeParam = {};
419
- Utils.keys(item.merge).forEach(key => {
420
- const k = this.mapper(key, type);
421
- mergeParam[k] = item.merge[key];
422
- });
418
+ // same mapping as the insert data, so composite FK and polymorphic values are split across their columns
419
+ mergeParam = this.processData(item.merge, false);
423
420
  }
424
421
  if (Array.isArray(item.merge)) {
425
- mergeParam = item.merge.map(key => this.mapper(key, type));
422
+ mergeParam = item.merge.flatMap(key => {
423
+ const [a, f] = typeof key === 'string' ? this.splitField(key) : [];
424
+ const prop = f ? this.getProperty(f, a) : undefined;
425
+ // a property name merges all columns of a composite FK, a column name merges just that column
426
+ return prop?.targetMeta && prop.fieldNames.length > 1 && !prop.fieldNames.includes(f)
427
+ ? (prop.ownColumns ?? prop.fieldNames)
428
+ : [this.mapper(key, type)];
429
+ });
426
430
  }
427
431
  sub.merge = mergeParam ?? [];
428
432
  // a merged row is updated, so its version is bumped as `updateVersionProperty()` does
@@ -92,6 +92,7 @@ export declare class SchemaComparator {
92
92
  private diffPolicy;
93
93
  parseJsonDefault(defaultValue?: string | null): Dictionary | string | null;
94
94
  private parseDecimalDefault;
95
+ private parseBigIntDefault;
95
96
  hasSameDefaultValue(from: Column, to: Column): boolean;
96
97
  private mapColumnToProperty;
97
98
  private log;
@@ -1,4 +1,4 @@
1
- import { ArrayType, BooleanType, DateTimeType, DecimalType, inspect, JsonType, parseJsonSafe, Utils, } from '@mikro-orm/core';
1
+ import { ArrayType, BigIntType, BooleanType, DateTimeType, DecimalType, inspect, JsonType, parseJsonSafe, Utils, } from '@mikro-orm/core';
2
2
  import { DatabaseTable } from './DatabaseTable.js';
3
3
  import { diffPartitioning } from './partitioning.js';
4
4
  /**
@@ -483,6 +483,12 @@ export class SchemaComparator {
483
483
  if (!this.diffExpression(check.expression, toTableCheck.expression)) {
484
484
  continue;
485
485
  }
486
+ // a check read as the one of an enum can be a plain check of the same values, e.g. `kind = 'manual'`
487
+ const introspected = check.introspectedExpression ?? toTableCheck.introspectedExpression;
488
+ const declared = check.introspectedExpression ? toTableCheck.expression : check.expression;
489
+ if (introspected && !this.diffExpression(introspected, declared)) {
490
+ continue;
491
+ }
486
492
  // only auto-generated enum checks, a user check tagged with an enum column must be diffed by expression
487
493
  if (fromColumn?.enumItems &&
488
494
  toColumn?.enumItems &&
@@ -925,12 +931,13 @@ export class SchemaComparator {
925
931
  // Protect dots inside string literals before the quote strip below, or the alias-prefix normalization
926
932
  // would mangle literal contents — `current_setting('app.tenant')` and `current_setting('req.tenant')`
927
933
  // must not both collapse to `current_settingtenant`
928
- .replace(/'([^']*)'/g, (_, inner) => `'${inner.replaceAll('.', '\u0000')}'`)
934
+ // numbers are left alone, postgres quotes the negative ones (`'-1.5'::numeric`)
935
+ .replace(/'([^']*)'/g, (m, inner) => /^-?\d+(\.\d+)?$/.test(inner) ? m : `'${inner.replaceAll('.', '\u0000')}'`)
929
936
  // Remove quotes first so we can process identifiers
930
937
  .replace(/['"`]/g, '')
931
938
  // MySQL adds table/alias prefixes to columns (e.g., a.name or table_name.column vs just column)
932
939
  // Strip these prefixes - match word.word patterns and keep only the last part
933
- .replace(/\b\w+\.(\w+)/g, '$1')
940
+ .replace(/\b(?!\d)\w+\.(\w+)/g, '$1')
934
941
  // PostgreSQL rewrites `x [not] between a and b` to `x >= a and x <= b` (`x < a or x > b`), cast targets are skipped
935
942
  .replace(/(?<!::\s*)\b(?!not\b)(\w+)\s+(not\s+)?between\s+(\S+)\s+and\s+(\S+)/gi, (_, x, not, a, b) => not ? `${x} < ${a} or ${x} > ${b}` : `${x} >= ${a} and ${x} <= ${b}`)
936
943
  // Normalize JOIN syntax: inner join -> join (equivalent in SQL)
@@ -1098,6 +1105,10 @@ export class SchemaComparator {
1098
1105
  const value = +('' + defaultValue).replace(/^'(.+)'$/, '$1');
1099
1106
  return Number.isFinite(value) ? value : null;
1100
1107
  }
1108
+ parseBigIntDefault(defaultValue) {
1109
+ const value = ('' + defaultValue).replace(/^'(.+)'$/, '$1');
1110
+ return /^-?\d+$/.test(value) ? BigInt(value) : null;
1111
+ }
1101
1112
  hasSameDefaultValue(from, to) {
1102
1113
  if (from.default == null ||
1103
1114
  from.default.toString().toLowerCase() === 'null' ||
@@ -1133,6 +1144,14 @@ export class SchemaComparator {
1133
1144
  this.#platform.formatDecimal(defaultValueTo, to.scale));
1134
1145
  }
1135
1146
  }
1147
+ // metadata quotes bigint defaults (`'0'`) while mysql reports them bare
1148
+ if (to.mappedType instanceof BigIntType) {
1149
+ const defaultValueFrom = this.parseBigIntDefault(from.default);
1150
+ const defaultValueTo = this.parseBigIntDefault(to.default);
1151
+ if (defaultValueFrom != null && defaultValueTo != null) {
1152
+ return defaultValueFrom === defaultValueTo;
1153
+ }
1154
+ }
1136
1155
  if (from.default && to.default) {
1137
1156
  return from.default.toString().toLowerCase() === to.default.toString().toLowerCase();
1138
1157
  }
package/typings.d.ts CHANGED
@@ -113,6 +113,8 @@ export interface CheckDef<T = unknown> {
113
113
  expression: string | CheckCallback<T>;
114
114
  definition?: string;
115
115
  columnName?: string;
116
+ /** @internal the expression as introspected, before it was normalized as the check of an enum */
117
+ introspectedExpression?: string;
116
118
  }
117
119
  /** Resolved row level security policy for schema operations (all callbacks resolved to strings). */
118
120
  export interface SqlPolicyDef {