@mikro-orm/sql 7.3.0-dev.16 → 7.3.0-dev.18

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.
@@ -130,6 +130,10 @@ export class AbstractSqlConnection extends Connection {
130
130
  }
131
131
  catch (rollbackError) {
132
132
  this.logger.warn('query', `Failed to roll back transaction: ${rollbackError.message}`);
133
+ // the inner writes are still part of the outer transaction, so it must not commit them
134
+ if (options.ctx) {
135
+ options.ctx.failedSavepointRollback ??= new Error(`Cannot commit the transaction, rolling back to savepoint "${trx.savepointName}" failed: ${rollbackError.message}`, { cause: rollbackError });
136
+ }
133
137
  }
134
138
  throw error;
135
139
  }
@@ -203,6 +207,9 @@ export class AbstractSqlConnection extends Connection {
203
207
  if (ctx.isRolledBack) {
204
208
  return;
205
209
  }
210
+ if ('failedSavepointRollback' in ctx) {
211
+ throw ctx.failedSavepointRollback;
212
+ }
206
213
  await eventBroadcaster?.dispatchEvent(EventType.beforeTransactionCommit, ctx);
207
214
  if ('savepointName' in ctx) {
208
215
  await ctx.releaseSavepoint(ctx.savepointName).execute();
@@ -216,6 +223,10 @@ export class AbstractSqlConnection extends Connection {
216
223
  }
217
224
  /** Rolls back the transaction or rolls back to the savepoint. */
218
225
  async rollback(ctx, eventBroadcaster, loggerContext) {
226
+ // kysely rolls back on its own when the database answers a commit with a rollback
227
+ if (ctx.isRolledBack) {
228
+ return;
229
+ }
219
230
  await eventBroadcaster?.dispatchEvent(EventType.beforeTransactionRollback, ctx);
220
231
  await this.waitForIdleTransaction(ctx);
221
232
  if ('savepointName' in ctx) {
@@ -18,6 +18,8 @@ export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlCo
18
18
  evaluateFormula(formula: (...args: any[]) => string | Raw, columns: any, table: FormulaTable): string;
19
19
  /** For TPT entities, returns ownProps (columns in this table); otherwise returns all props. */
20
20
  protected getTableProps<T extends object>(meta: EntityMetadata<T>): EntityProperty<T>[];
21
+ /** Columns reloaded by INSERT: generated/default columns any row leaves to the database, and explicit `returning` hints. */
22
+ protected getInsertReturningProperties<T extends object>(meta: EntityMetadata<T>, data: EntityDictionary<T>[]): EntityProperty<T>[];
21
23
  /** Columns reloaded by UPDATE: raw values, PKs, generated/version columns and explicit `returning` hints. */
22
24
  protected getUpdateReturningProperties<T extends object>(meta: EntityMetadata<T>, data: EntityDictionary<T>[]): EntityProperty<T>[];
23
25
  /** Column expression for the `returning` clause of batch updates, applying `convertToJSValueSQL` of custom types. */
@@ -63,6 +65,8 @@ export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlCo
63
65
  private buildCloneFields;
64
66
  private getCloneableProps;
65
67
  nativeInsertMany<T extends object>(entityName: EntityName<T>, data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>, transform?: (sql: string) => string): Promise<QueryResult<T>>;
68
+ /** 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
+ protected resolveInsertedPrimaryKeys<T extends object>(meta: EntityMetadata<T>, data: EntityDictionary<T>[], res: QueryResult<T>): any[][];
66
70
  nativeUpdate<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>, data: EntityDictionary<T>, options?: NativeInsertUpdateOptions<T> & UpsertOptions<T>): Promise<QueryResult<T>>;
67
71
  nativeUpdateMany<T extends object>(entityName: EntityName<T>, where: FilterQuery<T>[], data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T> & UpsertManyOptions<T>, transform?: (sql: string, params: any[]) => string): Promise<QueryResult<T>>;
68
72
  nativeDelete<T extends object>(entityName: EntityName<T>, where: FilterQuery<T> | string | any, options?: DeleteOptions<T>): Promise<QueryResult<T>>;
@@ -127,6 +131,12 @@ export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlCo
127
131
  * @internal
128
132
  */
129
133
  protected addTPTPolymorphicJoinsForRelation<T extends object>(qb: AnyQueryBuilder<T>, meta: EntityMetadata<T>, baseAlias: string, fields: InternalField<T>[]): void;
134
+ /**
135
+ * Registers the ancestor table aliases of each polymorphically joined TPT descendant,
136
+ * so formulas on descendants resolve inherited columns to the table that owns them.
137
+ * @internal
138
+ */
139
+ registerTPTAncestorAliases(qb: AnyQueryBuilder<any>, meta: EntityMetadata, baseAlias: string, childAliases: Dictionary<string>): void;
130
140
  /**
131
141
  * Find the alias for a TPT child table in the query builder.
132
142
  * @internal
@@ -49,6 +49,12 @@ export class AbstractSqlDriver extends DatabaseDriver {
49
49
  getTableProps(meta) {
50
50
  return meta.inheritanceType === 'tpt' && meta.ownProps ? meta.ownProps : meta.props;
51
51
  }
52
+ /** Columns reloaded by INSERT: generated/default columns any row leaves to the database, and explicit `returning` hints. */
53
+ getInsertReturningProperties(meta, data) {
54
+ return this.getTableProps(meta).filter(prop => prop.returning ||
55
+ (((prop.persist !== false && prop.defaultRaw) || prop.autoincrement || prop.generated) &&
56
+ data.some(d => !(prop.name in d) || isRaw(d[prop.name]))));
57
+ }
52
58
  /** Columns reloaded by UPDATE: raw values, PKs, generated/version columns and explicit `returning` hints. */
53
59
  getUpdateReturningProperties(meta, data) {
54
60
  const returning = new Set();
@@ -467,9 +473,14 @@ export class AbstractSqlDriver extends DatabaseDriver {
467
473
  return;
468
474
  }
469
475
  const mapToPk = !hint.dataOnly && !!(ref || prop.mapToPk);
470
- const targetProps = mapToPk
471
- ? meta2.getPrimaryProps()
472
- : meta2.props.filter(prop => this.platform.shouldHaveColumn(prop, hint.children || []));
476
+ // all rows of a result share their columns, so resolve the mapped props once per join path
477
+ const joinedTargets = (map.joinedTargets ??= {});
478
+ const { targetProps, virtualProps } = (joinedTargets[path] ??= {
479
+ targetProps: (mapToPk
480
+ ? meta2.getPrimaryProps()
481
+ : meta2.props.filter(prop => this.platform.shouldHaveColumn(prop, hint.children || []))).filter(prop => prop.fieldNames.some(name => typeof root[`${relationAlias}__${name}`] !== 'undefined')),
482
+ virtualProps: meta2.props.filter(prop => !ref && prop.persist === false && prop.fieldNames),
483
+ });
473
484
  // If the primary key value for the relation is null, we know we haven't joined to anything
474
485
  // and therefore we don't return any record (since all values would be null)
475
486
  const hasPK = meta2.getPrimaryProps().every(pk => pk.fieldNames.every(name => {
@@ -490,9 +501,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
490
501
  return;
491
502
  }
492
503
  let relationPojo = {};
493
- meta2.props
494
- .filter(prop => !ref && prop.persist === false && prop.fieldNames)
495
- .forEach(prop => {
504
+ virtualProps.forEach(prop => {
496
505
  /* v8 ignore next */
497
506
  if (prop.fieldNames.length > 1) {
498
507
  // composite keys
@@ -798,10 +807,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
798
807
  ? '(' + fields.map(k => this.platform.quoteIdentifier(k)).join(', ') + ')'
799
808
  : `(${this.platform.quoteIdentifier(pks[0])})`;
800
809
  if (this.platform.usesOutputStatement()) {
801
- const returningProps = this.getTableProps(meta).filter(prop => prop.returning ||
802
- (((prop.persist !== false && prop.defaultRaw) || prop.autoincrement || prop.generated) &&
803
- (!(prop.name in data[0]) || isRaw(data[0][prop.name]))));
804
- const returningFields = Utils.flatten(returningProps.map(prop => prop.fieldNames));
810
+ const returningFields = Utils.flatten(this.getInsertReturningProperties(meta, data).map(prop => prop.fieldNames));
805
811
  sql +=
806
812
  returningFields.length > 0
807
813
  ? ` output ${returningFields.map(field => 'inserted.' + this.platform.quoteIdentifier(field)).join(', ')}`
@@ -825,11 +831,11 @@ export class AbstractSqlDriver extends DatabaseDriver {
825
831
  value = this.platform.cloneEmbeddable(value);
826
832
  for (let i = 0; i < value.length; i++) {
827
833
  const item = value[i];
828
- value[i] = this.mapDataToFieldNames(item, false, prop.embeddedProps, options.convertCustomTypes);
834
+ value[i] = this.mapDataToFieldNames(item, false, this.variantProps(prop, item), options.convertCustomTypes);
829
835
  }
830
836
  }
831
837
  else {
832
- value = this.mapDataToFieldNames(value, false, prop.embeddedProps, options.convertCustomTypes);
838
+ value = this.mapDataToFieldNames(value, false, this.variantProps(prop, value), options.convertCustomTypes);
833
839
  }
834
840
  }
835
841
  if (typeof value === 'undefined' && this.platform.usesDefaultKeyword()) {
@@ -853,10 +859,16 @@ export class AbstractSqlDriver extends DatabaseDriver {
853
859
  // the map misses subtypes whose props were not initialized yet during discovery (root column owner, grandchildren)
854
860
  const discriminator = row[meta.discriminatorColumn];
855
861
  const childClass = meta.discriminatorMap?.[discriminator];
856
- const activeField = prop.stiFieldNameMap[discriminator] ??
857
- (childClass && this.metadata.find(childClass)?.properties[prop.name]?.fieldNames[0]);
862
+ const childProp = childClass && this.metadata.find(childClass)?.properties[prop.name];
863
+ const activeField = prop.stiFieldNameMap[discriminator] ?? childProp?.fieldNames[0];
858
864
  for (const field of prop.stiFieldNames) {
859
- params.push(field === activeField ? (row[prop.name] ?? null) : null);
865
+ // the subtype's own property, as siblings can declare it with a different type or embeddable
866
+ if (field === activeField) {
867
+ addParams(childProp ?? prop, row);
868
+ }
869
+ else {
870
+ params.push(null);
871
+ }
860
872
  keys.push('?');
861
873
  }
862
874
  return;
@@ -922,10 +934,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
922
934
  .join(', ');
923
935
  }
924
936
  if (meta && this.platform.usesReturningStatement()) {
925
- const returningProps = this.getTableProps(meta).filter(prop => prop.returning ||
926
- (((prop.persist !== false && prop.defaultRaw) || prop.autoincrement || prop.generated) &&
927
- (!(prop.name in data[0]) || isRaw(data[0][prop.name]))));
928
- const returningFields = Utils.flatten(returningProps.map(prop => prop.fieldNames));
937
+ const returningFields = Utils.flatten(this.getInsertReturningProperties(meta, data).map(prop => prop.fieldNames));
929
938
  /* v8 ignore next */
930
939
  sql +=
931
940
  returningFields.length > 0
@@ -936,22 +945,35 @@ export class AbstractSqlDriver extends DatabaseDriver {
936
945
  sql = transform(sql);
937
946
  }
938
947
  const res = await this.execute(sql, params, 'run', options.ctx, withAbortContext(options.loggerContext, options));
939
- let pk;
940
- if (pks.length > 1) {
941
- // owner has composite pk
942
- pk = data.map(d => Utils.getOrderedPrimaryKeys(d, meta));
943
- }
944
- else {
945
- res.row ??= {};
946
- res.rows ??= [];
947
- pk = data.map((d, i) => d[pks[0]] ?? res.rows[i]?.[pks[0]]).map(d => [d]);
948
- res.insertId = res.insertId || res.row[pks[0]];
949
- }
948
+ const pk = this.resolveInsertedPrimaryKeys(meta, data, res);
950
949
  for (let i = 0; i < collections.length; i++) {
951
950
  await this.processManyToMany(meta, pk[i], collections[i], false, options);
952
951
  }
953
952
  return res;
954
953
  }
954
+ /** 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. */
955
+ resolveInsertedPrimaryKeys(meta, data, res) {
956
+ const pks = this.getPrimaryKeyFields(meta);
957
+ if (pks.length > 1) {
958
+ // owner has composite pk
959
+ const pk = data.map(d => Utils.getOrderedPrimaryKeys(d, meta));
960
+ res.insertedIds = pk;
961
+ return pk;
962
+ }
963
+ res.row ??= {};
964
+ res.rows ??= [];
965
+ const ids = data.map((d, i) => {
966
+ // a raw pk expression is resolved by the database, its value only exists in the returned row
967
+ const supplied = d[meta.primaryKeys[0]] ?? d[pks[0]];
968
+ return supplied == null || isRaw(supplied) ? res.rows[i]?.[pks[0]] : supplied;
969
+ });
970
+ res.insertId = res.insertId || res.row[pks[0]];
971
+ // drivers without `returning` leave the ids unknown here, keep the `insertId` fallback for them
972
+ if (ids.every(id => id != null)) {
973
+ res.insertedIds = ids;
974
+ }
975
+ return ids.map(id => [id]);
976
+ }
955
977
  async nativeUpdate(entityName, where, data, options = {}) {
956
978
  options.convertCustomTypes ??= true;
957
979
  const meta = this.metadata.get(entityName);
@@ -1011,16 +1033,23 @@ export class AbstractSqlDriver extends DatabaseDriver {
1011
1033
  const meta = this.metadata.get(entityName);
1012
1034
  if (options.upsert) {
1013
1035
  if (meta.tptParent) {
1036
+ // the parent table reports a single insertId per batch, the EM sends such rows one by one
1037
+ if (where.filter(cond => Utils.isEmpty(cond)).length > 1) {
1038
+ throw new Error(`Cannot upsert more than one ${meta.className} row without a unique value in one batch`);
1039
+ }
1014
1040
  // TPT parent tables go first, the PK they provide is the conflict target of this table
1015
- await this.nativeUpdateMany(meta.tptParent.class, where, data, options);
1041
+ const res = await this.nativeUpdateMany(meta.tptParent.class, where, data, options);
1016
1042
  for (const [i, row] of data.entries()) {
1017
1043
  if (meta.primaryKeys.some(pk => row[pk] == null)) {
1018
- const found = await this.findOne(meta.tptParent.class, where[i], {
1019
- fields: meta.primaryKeys,
1020
- ctx: options.ctx,
1021
- connectionType: 'write',
1022
- schema: options.schema,
1023
- });
1044
+ // a row without a condition cannot conflict, only the insert knows its PK
1045
+ const found = Utils.isEmpty(where[i])
1046
+ ? { [meta.primaryKeys[0]]: res.insertId }
1047
+ : await this.findOne(meta.tptParent.class, where[i], {
1048
+ fields: meta.primaryKeys,
1049
+ ctx: options.ctx,
1050
+ connectionType: 'write',
1051
+ schema: options.schema,
1052
+ });
1024
1053
  meta.primaryKeys.forEach(pk => (row[pk] = found?.[pk]));
1025
1054
  }
1026
1055
  }
@@ -1040,7 +1069,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
1040
1069
  data = data.map(row => Object.fromEntries(Object.entries(row).filter(([key]) => own(key))));
1041
1070
  options.onConflictMergeFields = options.onConflictMergeFields?.filter(f => own(f));
1042
1071
  options.onConflictExcludeFields = options.onConflictExcludeFields?.filter(f => own(f));
1043
- returning = [];
1072
+ returning = this.getPrimaryKeyFields(meta);
1044
1073
  }
1045
1074
  qb.insert(data)
1046
1075
  .onConflict(uniqueFields)
@@ -1056,7 +1085,12 @@ export class AbstractSqlDriver extends DatabaseDriver {
1056
1085
  qb.where(options.onConflictWhere);
1057
1086
  }
1058
1087
  const res = await this.rethrow(qb.execute('run', false));
1059
- return meta.inheritanceType === 'tpt' ? { ...res, row: undefined, rows: [] } : res;
1088
+ if (meta.inheritanceType === 'tpt') {
1089
+ // child tables do not generate the PK, so every table of the hierarchy reports the one of its first row
1090
+ const insertId = data[0][meta.primaryKeys[0]] ?? res.insertId ?? res.row?.[returning[0]];
1091
+ return { ...res, insertId, row: undefined, rows: [] };
1092
+ }
1093
+ return res;
1060
1094
  }
1061
1095
  const collections = options.processCollections ? data.map(d => this.extractManyToMany(meta, d)) : [];
1062
1096
  const keys = new Set();
@@ -1077,11 +1111,11 @@ export class AbstractSqlDriver extends DatabaseDriver {
1077
1111
  if (prop.array && value) {
1078
1112
  for (let i = 0; i < value.length; i++) {
1079
1113
  const item = value[i];
1080
- value[i] = this.mapDataToFieldNames(item, false, prop.embeddedProps, options.convertCustomTypes);
1114
+ value[i] = this.mapDataToFieldNames(item, false, this.variantProps(prop, item), options.convertCustomTypes);
1081
1115
  }
1082
1116
  }
1083
1117
  else {
1084
- value = this.mapDataToFieldNames(value, false, prop.embeddedProps, options.convertCustomTypes);
1118
+ value = this.mapDataToFieldNames(value, false, this.variantProps(prop, value), options.convertCustomTypes);
1085
1119
  }
1086
1120
  }
1087
1121
  params.push(value ?? null);
@@ -1143,26 +1177,32 @@ export class AbstractSqlDriver extends DatabaseDriver {
1143
1177
  }
1144
1178
  sql += ' where ';
1145
1179
  const pkProps = meta.primaryKeys.concat(...meta.getOwnConcurrencyCheckKeys());
1180
+ // an optimistically locked batch carries the version in every condition
1181
+ if (meta.versionProperty &&
1182
+ where.every(cond => Utils.isPlainObject(cond) && meta.versionProperty in cond)) {
1183
+ pkProps.push(meta.versionProperty);
1184
+ }
1146
1185
  const pks = Utils.flatten(pkProps.map(pk => meta.properties[pk].fieldNames));
1147
1186
  const useTupleIn = pks.length <= 1 || this.platform.allowsComparingTuples();
1148
1187
  const condTemplate = useTupleIn
1149
1188
  ? `(${pks.map(() => '?').join(', ')})`
1150
1189
  : `(${pks.map(pk => `${this.platform.quoteIdentifier(pk)} = ?`).join(' and ')})`;
1151
- const conds = where.map(cond => {
1190
+ const conds = where.flatMap(cond => {
1152
1191
  // with multiple PK columns the condition is looked up by property name, so it needs to stay an object
1153
1192
  if (pks.length === 1 && Utils.isPlainObject(cond) && Utils.getObjectKeysSize(cond) === 1) {
1154
1193
  cond = Object.values(cond)[0];
1155
1194
  }
1156
1195
  if (pks.length > 1) {
1157
- pkProps.forEach(pk => {
1158
- if (Array.isArray(cond[pk])) {
1159
- params.push(...Utils.flatten(cond[pk]));
1160
- }
1161
- else {
1162
- params.push(cond[pk]);
1163
- }
1196
+ // a date version in sqlite matches either of its storage formats (see `convertVersionValue()`)
1197
+ const version = cond[meta.versionProperty];
1198
+ const versions = version?.$in ?? [version];
1199
+ return versions.map(v => {
1200
+ pkProps.forEach(pk => {
1201
+ const value = pk === meta.versionProperty ? v : cond[pk];
1202
+ params.push(...(Array.isArray(value) ? Utils.flatten(value) : [value]));
1203
+ });
1204
+ return condTemplate;
1164
1205
  });
1165
- return condTemplate;
1166
1206
  }
1167
1207
  params.push(cond);
1168
1208
  return '?';
@@ -1971,6 +2011,10 @@ export class AbstractSqlDriver extends DatabaseDriver {
1971
2011
  qb.createAlias(childMeta.class, childAlias);
1972
2012
  childAliases[childMeta.className] = childAlias;
1973
2013
  qb.addPropertyJoin(childMeta.tptInverseProp, baseAlias, childAlias, JoinType.leftJoin, `[tpt]${meta.className}`);
2014
+ }
2015
+ this.registerTPTAncestorAliases(qb, meta, baseAlias, childAliases);
2016
+ for (const childMeta of descendants) {
2017
+ const childAlias = childAliases[childMeta.className];
1974
2018
  // Add fields from this child (only ownProps, skip PKs)
1975
2019
  const schema = childMeta.schema === '*' ? '*' : this.getSchemaName(childMeta);
1976
2020
  childMeta
@@ -1982,6 +2026,21 @@ export class AbstractSqlDriver extends DatabaseDriver {
1982
2026
  fields.push(this.buildTPTDiscriminatorExpression(meta, descendants, childAliases, baseAlias));
1983
2027
  }
1984
2028
  }
2029
+ /**
2030
+ * Registers the ancestor table aliases of each polymorphically joined TPT descendant,
2031
+ * so formulas on descendants resolve inherited columns to the table that owns them.
2032
+ * @internal
2033
+ */
2034
+ registerTPTAncestorAliases(qb, meta, baseAlias, childAliases) {
2035
+ const tptAlias = qb.state.tptAlias;
2036
+ for (const childMeta of meta.allTPTDescendants) {
2037
+ for (let parent = childMeta.tptParent; parent; parent = parent.tptParent) {
2038
+ tptAlias[`${childAliases[childMeta.className]}:${parent.className}`] =
2039
+ childAliases[parent.className] ??
2040
+ (parent === meta ? baseAlias : tptAlias[`${baseAlias}:${parent.className}`]);
2041
+ }
2042
+ }
2043
+ }
1985
2044
  /**
1986
2045
  * Find the alias for a TPT child table in the query builder.
1987
2046
  * @internal
@@ -2069,6 +2128,12 @@ export class AbstractSqlDriver extends DatabaseDriver {
2069
2128
  }
2070
2129
  const aliased = this.platform.quoteIdentifier(`${tableAlias}__${prop.fieldNames[0]}`);
2071
2130
  const sourceAlias = qb.helper.getTPTAliasForProperty(prop.name, tableAlias);
2131
+ if (prop.formula) {
2132
+ const quotedAlias = this.platform.quoteIdentifier(tableAlias).toString();
2133
+ const table = this.createFormulaTable(quotedAlias, meta, schema);
2134
+ const columns = meta.createColumnMappingObject(p => qb.helper.getTPTAliasForProperty(p.name, tableAlias), quotedAlias);
2135
+ return [raw(`${this.evaluateFormula(prop.formula, columns, table)} as ${aliased}`)];
2136
+ }
2072
2137
  if (prop.customTypes?.some(type => !!type?.convertToJSValueSQL)) {
2073
2138
  return prop.fieldNames.map((col, idx) => {
2074
2139
  if (!prop.customTypes[idx]?.convertToJSValueSQL) {
@@ -2083,12 +2148,6 @@ export class AbstractSqlDriver extends DatabaseDriver {
2083
2148
  const prefixed = this.platform.quoteIdentifier(`${sourceAlias}.${prop.fieldNames[0]}`);
2084
2149
  return [raw(`${prop.customType.convertToJSValueSQL(prefixed, this.platform)} as ${aliased}`)];
2085
2150
  }
2086
- if (prop.formula) {
2087
- const quotedAlias = this.platform.quoteIdentifier(tableAlias).toString();
2088
- const table = this.createFormulaTable(quotedAlias, meta, schema);
2089
- const columns = meta.createColumnMappingObject(tableAlias);
2090
- return [raw(`${this.evaluateFormula(prop.formula, columns, table)} as ${aliased}`)];
2091
- }
2092
2151
  return prop.fieldNames.map(fieldName => {
2093
2152
  return raw('?? as ??', [`${sourceAlias}.${fieldName}`, `${tableAlias}__${fieldName}`]);
2094
2153
  });
@@ -2496,9 +2555,11 @@ export class AbstractSqlDriver extends DatabaseDriver {
2496
2555
  ret.push('*');
2497
2556
  }
2498
2557
  if (ret.length > 0 && !hasExplicitFields && addFormulas) {
2499
- // Create formula column mapping with unquoted aliases - quoting should be handled by the user via `quote` helper
2558
+ // `toString()` must yield the quoted alias like `QueryBuilder.finalize()`, which dedupes formulas by rendered SQL
2500
2559
  const quotedAlias = this.platform.quoteIdentifier(alias);
2501
- const columns = meta.createColumnMappingObject(alias);
2560
+ // TPT parent aliases are only known once the parent joins exist
2561
+ qb.ensureTPTJoins();
2562
+ const columns = meta.createColumnMappingObject(p => qb.helper.getTPTAliasForProperty(p.name, alias), quotedAlias.toString());
2502
2563
  const effectiveSchema = schema ?? (meta.schema !== '*' ? meta.schema : undefined);
2503
2564
  for (const prop of meta.props) {
2504
2565
  if (lazyProps.includes(prop)) {
@@ -2509,7 +2570,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
2509
2570
  const table = this.createFormulaTable(quotedAlias.toString(), meta, effectiveSchema);
2510
2571
  ret.push(raw(`${this.evaluateFormula(prop.formula, columns, table)} as ${aliased}`));
2511
2572
  }
2512
- if (!prop.object && (prop.hasConvertToDatabaseValueSQL || prop.hasConvertToJSValueSQL)) {
2573
+ if (!prop.object && !prop.formula && (prop.hasConvertToDatabaseValueSQL || prop.hasConvertToJSValueSQL)) {
2513
2574
  ret.push(prop.name);
2514
2575
  }
2515
2576
  }
@@ -96,7 +96,7 @@ export class AbstractSqlPlatform extends Platform {
96
96
  return this.formatQuery(value.sql, value.params);
97
97
  }
98
98
  if (Utils.isPlainObject(value) || value?.[JsonProperty]) {
99
- return this.escape(JSON.stringify(value));
99
+ return this.escape(this.convertJsonToDatabaseValue(value));
100
100
  }
101
101
  return this.escape(value);
102
102
  }
@@ -16,6 +16,8 @@ export declare class BaseMySqlPlatform extends AbstractSqlPlatform {
16
16
  };
17
17
  /** mysql and mariadb treat null as the lowest value when no placement is requested. */
18
18
  sortsNullsLowest(): boolean;
19
+ /** mysql reads backslashes in string literals as escapes, so defaults need the same escaping as values (minus the needless `\"`). */
20
+ quoteDefaultValue(value: string): string;
19
21
  supportsMultiColumnCountDistinct(): boolean;
20
22
  /** @internal */
21
23
  createNativeQueryBuilder(): MySqlNativeQueryBuilder;
@@ -22,6 +22,10 @@ export class BaseMySqlPlatform extends AbstractSqlPlatform {
22
22
  sortsNullsLowest() {
23
23
  return true;
24
24
  }
25
+ /** mysql reads backslashes in string literals as escapes, so defaults need the same escaping as values (minus the needless `\"`). */
26
+ quoteDefaultValue(value) {
27
+ return this.quoteValue(value).replaceAll('\\"', '"');
28
+ }
25
29
  supportsMultiColumnCountDistinct() {
26
30
  return true;
27
31
  }
@@ -68,4 +68,6 @@ export declare class MySqlSchemaHelper extends SchemaHelper {
68
68
  protected getChecksSQL(tables: Table[]): string;
69
69
  normalizeDefaultValue(defaultValue: string, length: number): string | number;
70
70
  protected wrap(val: string | null | undefined, type: Type<unknown>): string | null | undefined;
71
+ /** Decodes the backslash escapes of an introspected string literal. */
72
+ unescapeDefault(val: string): string;
71
73
  }
@@ -1,4 +1,4 @@
1
- import { EnumType, StringType, TextType } from '@mikro-orm/core';
1
+ import { EnumType, JsonType, StringType, TextType, } from '@mikro-orm/core';
2
2
  import { SchemaHelper } from '../../schema/SchemaHelper.js';
3
3
  export class MySqlSchemaHelper extends SchemaHelper {
4
4
  #cache = {};
@@ -619,7 +619,20 @@ export class MySqlSchemaHelper extends SchemaHelper {
619
619
  return super.normalizeDefaultValue(defaultValue, length, MySqlSchemaHelper.DEFAULT_VALUES);
620
620
  }
621
621
  wrap(val, type) {
622
+ if (typeof val !== 'string' || val.length === 0) {
623
+ return val;
624
+ }
625
+ // text/blob literal defaults come back escaped twice with a charset introducer, e.g. `_utf8mb4\'it\\\'s\'` (JSON is parsed by the comparator)
626
+ const expression = type instanceof JsonType ? null : /^_\w+\\'(.*)\\'$/s.exec(val);
627
+ if (expression) {
628
+ return this.platform.quoteDefaultValue(this.unescapeDefault(expression[1].replace(/\\(.)/gs, '$1')));
629
+ }
622
630
  const stringType = type instanceof StringType || type instanceof TextType || type instanceof EnumType;
623
- return typeof val === 'string' && val.length > 0 && stringType ? this.platform.quoteValue(val) : val;
631
+ return stringType ? this.platform.quoteDefaultValue(val) : val;
632
+ }
633
+ /** Decodes the backslash escapes of an introspected string literal. */
634
+ unescapeDefault(val) {
635
+ const sqlEscapes = { 0: '\0', b: '\b', n: '\n', r: '\r', t: '\t', Z: '\x1a' };
636
+ return val.replace(/\\(.)/gs, (_, char) => sqlEscapes[char] ?? char);
624
637
  }
625
638
  }
@@ -59,6 +59,7 @@ export declare class BasePostgreSqlPlatform extends AbstractSqlPlatform {
59
59
  };
60
60
  isBigIntProperty(prop: EntityProperty): boolean;
61
61
  getArrayDeclarationSQL(): string;
62
+ supportsArrayOverlap(): boolean;
62
63
  getFloatDeclarationSQL(): string;
63
64
  getDoubleDeclarationSQL(): string;
64
65
  getEnumTypeDeclarationSQL(column: {
@@ -199,6 +199,9 @@ export class BasePostgreSqlPlatform extends AbstractSqlPlatform {
199
199
  getArrayDeclarationSQL() {
200
200
  return 'text[]';
201
201
  }
202
+ supportsArrayOverlap() {
203
+ return true;
204
+ }
202
205
  getFloatDeclarationSQL() {
203
206
  return 'real';
204
207
  }
@@ -25,6 +25,7 @@ export class PostgreSqlExceptionConverter extends ExceptionConverter {
25
25
  break;
26
26
  case '23502':
27
27
  return new NotNullConstraintViolationException(exception);
28
+ case '23001':
28
29
  case '23503':
29
30
  return new ForeignKeyConstraintViolationException(exception);
30
31
  case '23505':
@@ -143,6 +143,7 @@ export declare class PostgreSqlSchemaHelper extends SchemaHelper {
143
143
  private getAlterColumnAutoincrement;
144
144
  getChangeColumnCommentSQL(tableName: string, to: Column, schemaName?: string): string;
145
145
  alterTableComment(table: DatabaseTable, comment?: string): string;
146
+ normalizeExpression(expr: string): string;
146
147
  normalizeDefaultValue(defaultValue: string, length: number): string | number;
147
148
  appendComments(table: DatabaseTable): string[];
148
149
  getDatabaseExistsSQL(name: string): string;
@@ -7,6 +7,65 @@ const POSTGIS_VIEWS = ['geography_columns', 'geometry_columns'];
7
7
  const DOLLAR_QUOTE_TAG = /(\$(?:[A-Za-z_]\w*)?\$)/;
8
8
  /** pg-added `(<operand>)::type` cast in a check body, including multi word types like `double precision`. */
9
9
  const CHECK_CAST_RE = /\(([^()]*)\)::\w+(?: precision| varying| with(?:out)? time zone)?(?:\[\])?/g;
10
+ /**
11
+ * PostgreSQL prints `interval '1 minute'` back as `'00:01:00'`, so the literal is reformatted the same way.
12
+ * Only non-negative `<n> <unit>` lists are handled, anything else has to be written the way PostgreSQL prints it.
13
+ */
14
+ function normalizeIntervalLiteral(literal) {
15
+ // `[field, factor]` into the months, days and microseconds triple PostgreSQL stores an interval as
16
+ const units = {
17
+ year: [0, 12],
18
+ yr: [0, 12],
19
+ y: [0, 12],
20
+ month: [0, 1],
21
+ mon: [0, 1],
22
+ week: [1, 7],
23
+ w: [1, 7],
24
+ day: [1, 1],
25
+ d: [1, 1],
26
+ hour: [2, 3_600_000_000],
27
+ hr: [2, 3_600_000_000],
28
+ h: [2, 3_600_000_000],
29
+ minute: [2, 60_000_000],
30
+ min: [2, 60_000_000],
31
+ m: [2, 60_000_000],
32
+ second: [2, 1_000_000],
33
+ sec: [2, 1_000_000],
34
+ s: [2, 1_000_000],
35
+ millisecond: [2, 1_000],
36
+ msec: [2, 1_000],
37
+ ms: [2, 1_000],
38
+ microsecond: [2, 1],
39
+ usec: [2, 1],
40
+ us: [2, 1],
41
+ };
42
+ const parts = [0, 0, 0];
43
+ // longer spellings first, so `ms`/`msec` are not read as `m` + plural `s`
44
+ const unitRe = /(\d+(?:\.\d+)?) *(milliseconds?|microseconds?|msecs?|usecs?|years?|months?|mons?|weeks?|days?|hours?|minutes?|seconds?|yrs?|hrs?|mins?|secs?|ms|us|[ywdhms])\b/g;
45
+ const rest = literal.toLowerCase().replace(unitRe, (_, qty, unit) => {
46
+ const [field, factor] = units[unit] ?? units[unit.slice(0, -1)];
47
+ parts[field] += +qty * factor;
48
+ return '';
49
+ });
50
+ if (rest.trim() || !Number.isInteger(parts[0]) || !Number.isInteger(parts[1])) {
51
+ return undefined;
52
+ }
53
+ const [months, days] = parts;
54
+ const micros = Math.round(parts[2]);
55
+ const fields = [
56
+ [Math.trunc(months / 12), 'year'],
57
+ [months % 12, 'mon'],
58
+ [days, 'day'],
59
+ ]
60
+ .filter(([v]) => v > 0)
61
+ .map(([v, u]) => `${v} ${u}${v === 1 ? '' : 's'}`);
62
+ if (micros || !fields.length) {
63
+ const s = Math.floor(micros / 1_000_000);
64
+ const time = [s / 3600, (s / 60) % 60, s % 60].map(v => String(Math.floor(v)).padStart(2, '0')).join(':');
65
+ fields.push(time + String((micros % 1_000_000) / 1_000_000).slice(1));
66
+ }
67
+ return fields.join(' ');
68
+ }
10
69
  export class PostgreSqlSchemaHelper extends SchemaHelper {
11
70
  static DEFAULT_VALUES = {
12
71
  'now()': ['now()', 'current_timestamp'],
@@ -355,10 +414,9 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
355
414
  return columnDefs.map(colDef => {
356
415
  const name = unquote(colDef);
357
416
  const result = { name };
358
- // Find this column in the expression and extract modifiers
359
- // Create a pattern that matches the column name (quoted or unquoted) followed by modifiers
417
+ // Match the column (quoted or unquoted) as a whole list item, so `id` never matches inside `author_id`
360
418
  const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
361
- const colPattern = new RegExp(`"?${escapedName}"?\\s*([^,)]*?)(?:,|$)`, 'i');
419
+ const colPattern = new RegExp(`(?:^|,)\\s*"?${escapedName}"?(?=\\s|,|$)\\s*([^,)]*?)(?:,|$)`, 'i');
362
420
  const colMatch = columnsStr.match(colPattern);
363
421
  if (colMatch) {
364
422
  const modifiers = colMatch[1];
@@ -436,14 +494,19 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
436
494
  const key = this.getTableKey(col);
437
495
  ret[key] ??= [];
438
496
  let type = col.data_type.toLowerCase() === 'array' ? col.udt_name.replace(/^_(.*)$/, '$1[]') : col.udt_name;
497
+ // `udt_name` drops array element typmods (`_numeric` for `numeric(12,2)[]`), recover them from `format_type`
498
+ const arrayModifier = type.endsWith('[]')
499
+ ? /^[^(]*(\([^)]*\))[^(]*\[\]$/.exec(col.format_type ?? '')?.[1]
500
+ : undefined;
501
+ if (arrayModifier) {
502
+ type = `${type.slice(0, -2)}${arrayModifier}[]`;
503
+ }
439
504
  if (col.data_type === 'USER-DEFINED' &&
440
505
  col.udt_schema &&
441
506
  col.udt_schema !== this.platform.getDefaultSchemaName()) {
442
507
  type = `${col.udt_schema}.${type}`;
443
508
  }
444
- if (type === 'bpchar') {
445
- type = 'char';
446
- }
509
+ type = type.replace(/^bpchar\b/, 'char');
447
510
  // postgis stores the geometry/geography typmod (`geometry(point,4326)`) in atttypmod, which
448
511
  // information_schema does not expose — recover the full type via format_type so it round-trips
449
512
  if ((col.udt_name === 'geometry' || col.udt_name === 'geography') && col.format_type) {
@@ -1284,11 +1347,18 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
1284
1347
  alterTableComment(table, comment) {
1285
1348
  return `comment on table ${table.getQuotedName()} is ${this.platform.quoteValue(comment ?? '')}`;
1286
1349
  }
1350
+ normalizeExpression(expr) {
1351
+ return expr.replace(/\binterval\s*'([^']*)'|'([^']*)'\s*::\s*interval\b/gi, (_, typed, cast) => {
1352
+ // `interval 'x'` and `'x'::interval` are the same literal and PostgreSQL always prints the cast form
1353
+ const literal = typed ?? cast;
1354
+ return `'${normalizeIntervalLiteral(literal) ?? literal}'::interval`;
1355
+ });
1356
+ }
1287
1357
  normalizeDefaultValue(defaultValue, length) {
1288
1358
  if (!defaultValue || typeof defaultValue !== 'string') {
1289
1359
  return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
1290
1360
  }
1291
- const match = /^'(.*)'::(.*)$/.exec(defaultValue);
1361
+ const match = /^'(.*)'::(.*)$/s.exec(defaultValue);
1292
1362
  if (match) {
1293
1363
  if (match[2] === 'integer') {
1294
1364
  return +match[1];
@@ -1,4 +1,4 @@
1
- import { type EntityProperty, type IsolationLevel } from '@mikro-orm/core';
1
+ import { type EntityMetadata, type EntityProperty, type IsolationLevel } from '@mikro-orm/core';
2
2
  import { AbstractSqlPlatform } from '../../AbstractSqlPlatform.js';
3
3
  import { SqliteNativeQueryBuilder } from './SqliteNativeQueryBuilder.js';
4
4
  import { SqliteSchemaHelper } from './SqliteSchemaHelper.js';
@@ -75,6 +75,7 @@ export declare class SqlitePlatform extends AbstractSqlPlatform {
75
75
  */
76
76
  supportsSchemas(): boolean;
77
77
  getDefaultSchemaName(): string | undefined;
78
+ validateMetadata(meta: EntityMetadata): void;
78
79
  getFullTextWhereClause(): string;
79
80
  escape(value: any): string;
80
81
  convertVersionValue(value: Date | number, prop: EntityProperty): number | {