@mikro-orm/sql 7.3.0-dev.22 → 7.3.0-dev.23

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.
@@ -51,6 +51,9 @@ export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlCo
51
51
  */
52
52
  private mapTPTColumns;
53
53
  private mapJoinedProps;
54
+ /** Keys are marked consumed, not deleted per row: deletes are slow and shared FK columns must stay readable. */
55
+ private resolveJoinedTargets;
56
+ private aliasedKeys;
54
57
  /**
55
58
  * Maps a single property from a joined result row into the relation pojo.
56
59
  * Handles polymorphic FKs, composite keys, Date parsing, and embedded objects.
@@ -1,4 +1,4 @@
1
- import { ALIAS_REPLACEMENT_RE, DatabaseDriver, EntityManagerType, getLoadingStrategy, getOnConflictFields, getOnConflictReturningFields, helper, isRaw, LoadStrategy, parseJsonSafe, PolymorphicRef, QueryFlag, QueryHelper, QueryOrder, raw, RawQueryFragment, ReferenceKind, Utils, } from '@mikro-orm/core';
1
+ import { ALIAS_REPLACEMENT_RE, DatabaseDriver, DateType, EntityManagerType, getLoadingStrategy, getOnConflictFields, getOnConflictReturningFields, helper, isRaw, LoadStrategy, parseJsonSafe, PolymorphicRef, QueryFlag, QueryHelper, QueryOrder, raw, RawQueryFragment, ReferenceKind, Utils, } from '@mikro-orm/core';
2
2
  import { QueryBuilder } from './query/QueryBuilder.js';
3
3
  import { JoinType, QueryType } from './query/enums.js';
4
4
  import { SqlEntityManager } from './SqlEntityManager.js';
@@ -342,11 +342,14 @@ export class AbstractSqlDriver extends DatabaseDriver {
342
342
  if (qb) {
343
343
  // here we map the aliased results (cartesian product) to an object graph
344
344
  this.mapJoinedProps(ret, meta, populate, qb, ret, map);
345
- // the aliased columns were deleted, which left the row in slow dictionary mode
345
+ // copy without the consumed aliased columns, deleting them would leave the row in slow dictionary mode
346
346
  if (populate.length > 0) {
347
347
  const clean = {};
348
+ const consumed = map.consumedKeys;
348
349
  for (const key in ret) {
349
- clean[key] = ret[key];
350
+ if (!consumed?.has(key)) {
351
+ clean[key] = ret[key];
352
+ }
350
353
  }
351
354
  return clean;
352
355
  }
@@ -421,7 +424,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
421
424
  const relationPojo = {};
422
425
  const tz = this.platform.getTimezone();
423
426
  for (const p of targetProps) {
424
- this.mapJoinedProp(relationPojo, p, relationAlias, root, tz, meta2);
427
+ this.mapJoinedProp(relationPojo, p, this.aliasedKeys(p, relationAlias), root, tz, meta2);
425
428
  }
426
429
  // For TPT base targets, map child-specific fields and resolve the
427
430
  // concrete class so the factory creates the correct subtype.
@@ -436,9 +439,10 @@ export class AbstractSqlDriver extends DatabaseDriver {
436
439
  this.mapJoinedProps(relationPojo, meta2, populateChildren, qb, root, map, targetPath);
437
440
  }
438
441
  // Clean up aliased columns for ALL targets (even non-matching ones)
442
+ const consumed = (map.consumedKeys ??= new Set());
439
443
  for (const p of targetProps) {
440
444
  for (const name of p.fieldNames) {
441
- delete root[`${relationAlias}__${name}`];
445
+ consumed.add(`${relationAlias}__${name}`);
442
446
  }
443
447
  }
444
448
  }
@@ -472,8 +476,9 @@ export class AbstractSqlDriver extends DatabaseDriver {
472
476
  const alias = `${relationAlias}__${prop.inverseJoinColumns[0]}`;
473
477
  item = root[alias];
474
478
  }
475
- prop.joinColumns.forEach(name => delete root[`${relationAlias}__${name}`]);
476
- prop.inverseJoinColumns.forEach(name => delete root[`${relationAlias}__${name}`]);
479
+ const consumed = (map.consumedKeys ??= new Set());
480
+ prop.joinColumns.forEach(name => consumed.add(`${relationAlias}__${name}`));
481
+ prop.inverseJoinColumns.forEach(name => consumed.add(`${relationAlias}__${name}`));
477
482
  result[prop.name] ??= [];
478
483
  if (item) {
479
484
  result[prop.name].push(item);
@@ -483,17 +488,12 @@ export class AbstractSqlDriver extends DatabaseDriver {
483
488
  const mapToPk = !hint.dataOnly && !!(ref || prop.mapToPk);
484
489
  // all rows of a result share their columns, so resolve the mapped props once per join path
485
490
  const joinedTargets = (map.joinedTargets ??= {});
486
- const { targetProps, virtualProps } = (joinedTargets[path] ??= {
487
- targetProps: (mapToPk
488
- ? meta2.getPrimaryProps()
489
- : meta2.props.filter(prop => this.platform.shouldHaveColumn(prop, hint.children || []))).filter(prop => prop.fieldNames.some(name => typeof root[`${relationAlias}__${name}`] !== 'undefined')),
490
- virtualProps: meta2.props.filter(prop => !ref && prop.persist === false && prop.fieldNames),
491
- });
491
+ joinedTargets[path] ??= this.resolveJoinedTargets(meta2, hint, mapToPk, !!ref, relationAlias, root, map);
492
+ const targets = joinedTargets[path];
493
+ const { targetProps, targetKeys, pkKeys, virtualProps } = targets;
492
494
  // If the primary key value for the relation is null, we know we haven't joined to anything
493
495
  // and therefore we don't return any record (since all values would be null)
494
- const hasPK = meta2.getPrimaryProps().every(pk => pk.fieldNames.every(name => {
495
- return root[`${relationAlias}__${name}`] != null;
496
- }));
496
+ const hasPK = pkKeys.every(key => root[key] != null);
497
497
  if (!hasPK) {
498
498
  if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {
499
499
  result[prop.name] = [];
@@ -501,10 +501,10 @@ export class AbstractSqlDriver extends DatabaseDriver {
501
501
  if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
502
502
  result[prop.name] = null;
503
503
  }
504
- for (const prop of targetProps) {
505
- for (const name of prop.fieldNames) {
506
- delete root[`${relationAlias}__${name}`];
507
- }
504
+ // resolve nested join paths once, so their columns are dropped even when no row has this relation
505
+ if (hint.children?.length && !targets.childrenResolved) {
506
+ this.mapJoinedProps({}, meta2, hint.children, qb, root, map, path);
507
+ targets.childrenResolved = true;
508
508
  }
509
509
  return;
510
510
  }
@@ -521,18 +521,11 @@ export class AbstractSqlDriver extends DatabaseDriver {
521
521
  }
522
522
  });
523
523
  const tz = this.platform.getTimezone();
524
- for (const prop of targetProps) {
525
- this.mapJoinedProp(relationPojo, prop, relationAlias, root, tz, meta2);
524
+ for (let i = 0; i < targetProps.length; i++) {
525
+ this.mapJoinedProp(relationPojo, targetProps[i], targetKeys[i], root, tz, meta2);
526
526
  }
527
527
  // Handle TPT polymorphic child fields - map fields from child table aliases
528
528
  this.mapTPTChildFields(relationPojo, meta2, relationAlias, qb, root);
529
- // properties can be mapped to multiple places, e.g. when sharing a column in multiple FKs,
530
- // so we need to delete them after everything is mapped from given level
531
- for (const prop of targetProps) {
532
- for (const name of prop.fieldNames) {
533
- delete root[`${relationAlias}__${name}`];
534
- }
535
- }
536
529
  if (mapToPk) {
537
530
  const tmp = Object.values(relationPojo);
538
531
  /* v8 ignore next */
@@ -547,14 +540,34 @@ export class AbstractSqlDriver extends DatabaseDriver {
547
540
  }
548
541
  const populateChildren = hint.children || [];
549
542
  this.mapJoinedProps(relationPojo, meta2, populateChildren, qb, root, map, path);
543
+ targets.childrenResolved = true;
550
544
  });
551
545
  }
546
+ /** Keys are marked consumed, not deleted per row: deletes are slow and shared FK columns must stay readable. */
547
+ resolveJoinedTargets(meta, hint, mapToPk, ref, relationAlias, root, map) {
548
+ const targetProps = (mapToPk
549
+ ? meta.getPrimaryProps()
550
+ : meta.props.filter(prop => this.platform.shouldHaveColumn(prop, hint.children || []))).filter(prop => prop.fieldNames.some(name => typeof root[`${relationAlias}__${name}`] !== 'undefined'));
551
+ const targetKeys = targetProps.map(prop => this.aliasedKeys(prop, relationAlias));
552
+ const consumed = (map.consumedKeys ??= new Set());
553
+ targetKeys.forEach(keys => keys.forEach(key => consumed.add(key)));
554
+ return {
555
+ targetProps,
556
+ targetKeys,
557
+ pkKeys: meta.getPrimaryProps().flatMap(pk => this.aliasedKeys(pk, relationAlias)),
558
+ virtualProps: meta.props.filter(prop => !ref && prop.persist === false && prop.fieldNames),
559
+ };
560
+ }
561
+ aliasedKeys(prop, relationAlias) {
562
+ return prop.fieldNames.map(name => `${relationAlias}__${name}`);
563
+ }
552
564
  /**
553
565
  * Maps a single property from a joined result row into the relation pojo.
554
566
  * Handles polymorphic FKs, composite keys, Date parsing, and embedded objects.
555
567
  */
556
- mapJoinedProp(relationPojo, prop, relationAlias, root, tz, meta, options) {
557
- if (prop.fieldNames.every(name => typeof root[`${relationAlias}__${name}`] === 'undefined')) {
568
+ mapJoinedProp(relationPojo, prop, keys, root, tz, meta, options) {
569
+ const row = root;
570
+ if (keys.every(key => typeof row[key] === 'undefined')) {
558
571
  return;
559
572
  }
560
573
  // inline embeddables are mapped via their flattened child props; mapping the embedded root prop
@@ -563,10 +576,8 @@ export class AbstractSqlDriver extends DatabaseDriver {
563
576
  return;
564
577
  }
565
578
  if (prop.polymorphic && prop.kind !== ReferenceKind.EMBEDDED) {
566
- const discriminatorAlias = `${relationAlias}__${prop.fieldNames[0]}`;
567
- const discriminatorValue = root[discriminatorAlias];
568
- const pkFieldNames = prop.fieldNames.slice(1);
569
- const pkValues = pkFieldNames.map(name => root[`${relationAlias}__${name}`]);
579
+ const discriminatorValue = row[keys[0]];
580
+ const pkValues = keys.slice(1).map(key => row[key]);
570
581
  const pkValue = pkValues.length === 1 ? pkValues[0] : pkValues;
571
582
  if (discriminatorValue != null && pkValue != null) {
572
583
  relationPojo[prop.name] = new PolymorphicRef(discriminatorValue, pkValue);
@@ -577,7 +588,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
577
588
  }
578
589
  else if (prop.fieldNames.length > 1) {
579
590
  // composite keys
580
- const fk = prop.fieldNames.map(name => root[`${relationAlias}__${name}`]);
591
+ const fk = keys.map(key => row[key]);
581
592
  // `mapFlatCompositePrimaryKey` collapses to a scalar when the target PK is a single prop
582
593
  // (e.g. a relation referencing a composite unique key on a single-PK target).
583
594
  const pk = Utils.mapFlatCompositePrimaryKey(fk, prop);
@@ -585,8 +596,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
585
596
  relationPojo[prop.name] = valid ? pk : null;
586
597
  }
587
598
  else if (prop.runtimeType === 'Date') {
588
- const alias = `${relationAlias}__${prop.fieldNames[0]}`;
589
- const value = root[alias];
599
+ const value = row[keys[0]];
590
600
  if (tz &&
591
601
  tz !== 'local' &&
592
602
  typeof value === 'string' &&
@@ -602,9 +612,13 @@ export class AbstractSqlDriver extends DatabaseDriver {
602
612
  relationPojo[prop.name] = value;
603
613
  }
604
614
  }
615
+ else if (prop.customType instanceof DateType) {
616
+ // tedious returns DATE columns as `Date`, map them to the string the entity holds, so the snapshot matches it
617
+ const value = row[keys[0]];
618
+ relationPojo[prop.name] = (value instanceof Date ? this.platform.convertDateToJSValue(value) : value);
619
+ }
605
620
  else {
606
- const alias = `${relationAlias}__${prop.fieldNames[0]}`;
607
- relationPojo[prop.name] = root[alias];
621
+ relationPojo[prop.name] = row[keys[0]];
608
622
  if (prop.kind === ReferenceKind.EMBEDDED && (prop.object || meta.embeddable)) {
609
623
  const item = parseJsonSafe(relationPojo[prop.name]);
610
624
  if (Array.isArray(item)) {
@@ -617,8 +631,8 @@ export class AbstractSqlDriver extends DatabaseDriver {
617
631
  }
618
632
  }
619
633
  if (options?.deleteFromRoot) {
620
- for (const name of prop.fieldNames) {
621
- delete root[`${relationAlias}__${name}`];
634
+ for (const key of keys) {
635
+ delete row[key];
622
636
  }
623
637
  }
624
638
  }
@@ -2109,7 +2123,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
2109
2123
  if (childAlias) {
2110
2124
  // Map fields using same filtering as joined loading, plus skip PKs
2111
2125
  for (const prop of currentMeta.ownProps.filter(p => !p.primary && this.platform.shouldHaveColumn(p, []))) {
2112
- this.mapJoinedProp(relationPojo, prop, childAlias, root, tz, currentMeta, {
2126
+ this.mapJoinedProp(relationPojo, prop, this.aliasedKeys(prop, childAlias), root, tz, currentMeta, {
2113
2127
  deleteFromRoot: true,
2114
2128
  });
2115
2129
  }
@@ -231,8 +231,9 @@ export class BasePostgreSqlPlatform extends AbstractSqlPlatform {
231
231
  return ['begin'];
232
232
  }
233
233
  marshallArray(values) {
234
- const quote = (v) => (v === '' || /["{},\\]/.exec(v) ? JSON.stringify(v) : v);
235
- return `{${values.map(v => quote('' + v)).join(',')}}`;
234
+ // Quote what Postgres would read differently unquoted: empty, `NULL`, delimiters and surrounding whitespace.
235
+ const quote = (v) => v === '' || /^null$/i.test(v) || /["{},\\]|^\s|\s$/.test(v) ? `"${v.replace(/["\\]/g, '\\$&')}"` : v;
236
+ return `{${values.map(v => (v === null ? 'NULL' : quote('' + v))).join(',')}}`;
236
237
  }
237
238
  /* v8 ignore next */
238
239
  unmarshallArray(value) {
@@ -1331,18 +1331,20 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
1331
1331
  const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
1332
1332
  if (column.autoincrement) {
1333
1333
  const seqName = this.platform.getIndexName(tableName, [column.name], 'sequence');
1334
+ // the regclass text needs the quoted name too, otherwise postgres folds a mixed case name to lower case
1335
+ const seq = this.platform.quoteValue(this.quote(seqName));
1334
1336
  const sequenceOptions = this.getSequenceOptionsSQL(column);
1335
1337
  const { incrementBy = 1, startWith = incrementBy < 0 ? -1 : 1 } = column.sequence ?? {};
1336
1338
  const lastValue = `(select ${incrementBy < 0 ? 'min' : 'max'}(${this.quote(column.name)}) from ${this.quote(name)})`;
1337
1339
  ret.push(`create sequence if not exists ${this.quote(seqName)}${sequenceOptions ? ` ${sequenceOptions}` : ''}`);
1338
1340
  if (sequenceOptions) {
1339
1341
  // continue after the existing values, but never before the declared start
1340
- ret.push(`select setval('${seqName}', ${incrementBy < 0 ? 'least' : 'greatest'}(${lastValue} + ${incrementBy}, ${startWith}), false)`);
1342
+ ret.push(`select setval(${seq}, ${incrementBy < 0 ? 'least' : 'greatest'}(${lastValue} + ${incrementBy}, ${startWith}), false)`);
1341
1343
  }
1342
1344
  else {
1343
- ret.push(`select setval('${seqName}', ${lastValue})`);
1345
+ ret.push(`select setval(${seq}, ${lastValue})`);
1344
1346
  }
1345
- ret.push(`alter table ${this.quote(name)} alter column ${this.quote(column.name)} set default nextval('${seqName}')`);
1347
+ ret.push(`alter table ${this.quote(name)} alter column ${this.quote(column.name)} set default nextval(${seq})`);
1346
1348
  }
1347
1349
  return ret;
1348
1350
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/sql",
3
- "version": "7.3.0-dev.22",
3
+ "version": "7.3.0-dev.23",
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",
@@ -47,13 +47,13 @@
47
47
  "copy": "node ../../scripts/copy.mjs"
48
48
  },
49
49
  "dependencies": {
50
- "kysely": "0.29.8"
50
+ "kysely": "0.29.9"
51
51
  },
52
52
  "devDependencies": {
53
- "@mikro-orm/core": "^7.2.9"
53
+ "@mikro-orm/core": "^7.2.10"
54
54
  },
55
55
  "peerDependencies": {
56
- "@mikro-orm/core": "7.3.0-dev.22"
56
+ "@mikro-orm/core": "7.3.0-dev.23"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">= 22.17.0"
@@ -1031,6 +1031,11 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
1031
1031
  */
1032
1032
  private processNestedJoins;
1033
1033
  private hasToManyJoins;
1034
+ /**
1035
+ * Whether a join can match more than one row per root row. Only owning to-one joins target a unique key; inverse 1:1
1036
+ * relies on an unenforced unique FK, and sub-query or table reference joins match arbitrary rows.
1037
+ */
1038
+ private canRepeatRootRows;
1034
1039
  /**
1035
1040
  * Resolves a `persist: false` virtual field referenced in `orderBy` (e.g. `qb.as('reviewCount')` or a
1036
1041
  * `raw()` fragment aliased in the select) to the alias and SQL expression it was selected under. The
@@ -1,5 +1,5 @@
1
1
  var _a;
2
- import { EntityMetadata, helper, inspect, isRaw, LoadStrategy, LockMode, PopulateHint, QueryFlag, QueryHelper, raw, RawQueryFragment, Reference, ReferenceKind, serialize, SUBQUERY_BRAND, Utils, ValidationError, } from '@mikro-orm/core';
2
+ import { EntityMetadata, helper, inspect, isRaw, LoadStrategy, LockMode, PopulateHint, QueryFlag, QueryHelper, raw, RawQueryFragment, Reference, ReferenceKind, serialize, SUBQUERY_BRAND, Utils, validatePaginationValue, ValidationError, } from '@mikro-orm/core';
3
3
  import { JoinType, QueryType } from './enums.js';
4
4
  import { QueryBuilderHelper } from './QueryBuilderHelper.js';
5
5
  import { CriteriaNodeFactory } from './CriteriaNodeFactory.js';
@@ -737,7 +737,7 @@ export class QueryBuilder {
737
737
  */
738
738
  limit(limit, offset = 0) {
739
739
  this.ensureNotFinalized();
740
- this.#state.limit = limit;
740
+ this.#state.limit = validatePaginationValue(limit, 'limit');
741
741
  if (offset) {
742
742
  this.offset(offset);
743
743
  }
@@ -753,7 +753,7 @@ export class QueryBuilder {
753
753
  */
754
754
  offset(offset) {
755
755
  this.ensureNotFinalized();
756
- this.#state.offset = offset;
756
+ this.#state.offset = validatePaginationValue(offset, 'offset');
757
757
  return this;
758
758
  }
759
759
  withSchema(schema) {
@@ -1117,7 +1117,7 @@ export class QueryBuilder {
1117
1117
  if (Array.isArray(res)) {
1118
1118
  const map = {};
1119
1119
  mapped = res.map(r => this.driver.mapResult(r, meta, this.#state.populate, this, map));
1120
- if (options.mergeResults && joinedProps.length > 0) {
1120
+ if (options.mergeResults && joinedProps.length > 0 && this.canRepeatRootRows()) {
1121
1121
  mapped = this.driver.mergeJoinedResult(mapped, this.mainAlias.meta, joinedProps);
1122
1122
  }
1123
1123
  }
@@ -2274,6 +2274,17 @@ export class QueryBuilder {
2274
2274
  return [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(join.prop.kind);
2275
2275
  });
2276
2276
  }
2277
+ /**
2278
+ * Whether a join can match more than one row per root row. Only owning to-one joins target a unique key; inverse 1:1
2279
+ * relies on an unenforced unique FK, and sub-query or table reference joins match arbitrary rows.
2280
+ */
2281
+ canRepeatRootRows() {
2282
+ return Object.values(this.#state.joins).some(join => {
2283
+ const { kind, owner, name } = join.prop;
2284
+ const uniqueTarget = kind === ReferenceKind.MANY_TO_ONE || (kind === ReferenceKind.ONE_TO_ONE && owner);
2285
+ return !uniqueTarget || join.subquery != null || name === '__subquery__';
2286
+ });
2287
+ }
2277
2288
  /**
2278
2289
  * Resolves a `persist: false` virtual field referenced in `orderBy` (e.g. `qb.as('reviewCount')` or a
2279
2290
  * `raw()` fragment aliased in the select) to the alias and SQL expression it was selected under. The
@@ -9,7 +9,10 @@ export class ScalarCriteriaNode extends CriteriaNode {
9
9
  process(qb, options) {
10
10
  const matchPopulateJoins = options?.matchPopulateJoins ||
11
11
  (this.prop && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(this.prop.kind));
12
- const nestedAlias = qb.getAliasForJoinPath(this.getPath(options), { ...options, matchPopulateJoins });
12
+ // nodes without a property (e.g. `$in` items) never join, so the alias lookup is not needed
13
+ const nestedAlias = this.prop
14
+ ? qb.getAliasForJoinPath(this.getPath(options), { ...options, matchPopulateJoins })
15
+ : undefined;
13
16
  if (this.shouldJoin(qb, nestedAlias)) {
14
17
  const path = this.getPath();
15
18
  const parentPath = this.parent.getPath(); // the parent is always there, otherwise `shouldJoin` would return `false`