@mikro-orm/sql 7.3.0-dev.21 → 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.
@@ -63,7 +66,11 @@ export declare abstract class AbstractSqlDriver<Connection extends AbstractSqlCo
63
66
  private nativeCloneTPT;
64
67
  private mapCloneOverrides;
65
68
  private buildCloneFields;
66
- private getCloneableProps;
69
+ /**
70
+ * Returns properties whose columns can be copied by an `INSERT … SELECT` (owning columns that are not PKs, generated or formulas).
71
+ * @internal
72
+ */
73
+ getCloneableProps<T extends object>(meta: EntityMetadata<T>, ownProps?: boolean): EntityProperty<T>[];
67
74
  nativeInsertMany<T extends object>(entityName: EntityName<T>, data: EntityDictionary<T>[], options?: NativeInsertUpdateManyOptions<T>, transform?: (sql: string) => string): Promise<QueryResult<T>>;
68
75
  /** 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
76
  protected resolveInsertedPrimaryKeys<T extends object>(meta: EntityMetadata<T>, data: EntityDictionary<T>[], res: QueryResult<T>): any[][];
@@ -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,6 +342,17 @@ 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
+ // copy without the consumed aliased columns, deleting them would leave the row in slow dictionary mode
346
+ if (populate.length > 0) {
347
+ const clean = {};
348
+ const consumed = map.consumedKeys;
349
+ for (const key in ret) {
350
+ if (!consumed?.has(key)) {
351
+ clean[key] = ret[key];
352
+ }
353
+ }
354
+ return clean;
355
+ }
345
356
  }
346
357
  return ret;
347
358
  }
@@ -413,7 +424,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
413
424
  const relationPojo = {};
414
425
  const tz = this.platform.getTimezone();
415
426
  for (const p of targetProps) {
416
- this.mapJoinedProp(relationPojo, p, relationAlias, root, tz, meta2);
427
+ this.mapJoinedProp(relationPojo, p, this.aliasedKeys(p, relationAlias), root, tz, meta2);
417
428
  }
418
429
  // For TPT base targets, map child-specific fields and resolve the
419
430
  // concrete class so the factory creates the correct subtype.
@@ -428,9 +439,10 @@ export class AbstractSqlDriver extends DatabaseDriver {
428
439
  this.mapJoinedProps(relationPojo, meta2, populateChildren, qb, root, map, targetPath);
429
440
  }
430
441
  // Clean up aliased columns for ALL targets (even non-matching ones)
442
+ const consumed = (map.consumedKeys ??= new Set());
431
443
  for (const p of targetProps) {
432
444
  for (const name of p.fieldNames) {
433
- delete root[`${relationAlias}__${name}`];
445
+ consumed.add(`${relationAlias}__${name}`);
434
446
  }
435
447
  }
436
448
  }
@@ -464,8 +476,9 @@ export class AbstractSqlDriver extends DatabaseDriver {
464
476
  const alias = `${relationAlias}__${prop.inverseJoinColumns[0]}`;
465
477
  item = root[alias];
466
478
  }
467
- prop.joinColumns.forEach(name => delete root[`${relationAlias}__${name}`]);
468
- 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}`));
469
482
  result[prop.name] ??= [];
470
483
  if (item) {
471
484
  result[prop.name].push(item);
@@ -475,17 +488,12 @@ export class AbstractSqlDriver extends DatabaseDriver {
475
488
  const mapToPk = !hint.dataOnly && !!(ref || prop.mapToPk);
476
489
  // all rows of a result share their columns, so resolve the mapped props once per join path
477
490
  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
- });
491
+ joinedTargets[path] ??= this.resolveJoinedTargets(meta2, hint, mapToPk, !!ref, relationAlias, root, map);
492
+ const targets = joinedTargets[path];
493
+ const { targetProps, targetKeys, pkKeys, virtualProps } = targets;
484
494
  // If the primary key value for the relation is null, we know we haven't joined to anything
485
495
  // and therefore we don't return any record (since all values would be null)
486
- const hasPK = meta2.getPrimaryProps().every(pk => pk.fieldNames.every(name => {
487
- return root[`${relationAlias}__${name}`] != null;
488
- }));
496
+ const hasPK = pkKeys.every(key => root[key] != null);
489
497
  if (!hasPK) {
490
498
  if ([ReferenceKind.MANY_TO_MANY, ReferenceKind.ONE_TO_MANY].includes(prop.kind)) {
491
499
  result[prop.name] = [];
@@ -493,10 +501,10 @@ export class AbstractSqlDriver extends DatabaseDriver {
493
501
  if ([ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind)) {
494
502
  result[prop.name] = null;
495
503
  }
496
- for (const prop of targetProps) {
497
- for (const name of prop.fieldNames) {
498
- delete root[`${relationAlias}__${name}`];
499
- }
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;
500
508
  }
501
509
  return;
502
510
  }
@@ -513,18 +521,11 @@ export class AbstractSqlDriver extends DatabaseDriver {
513
521
  }
514
522
  });
515
523
  const tz = this.platform.getTimezone();
516
- for (const prop of targetProps) {
517
- 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);
518
526
  }
519
527
  // Handle TPT polymorphic child fields - map fields from child table aliases
520
528
  this.mapTPTChildFields(relationPojo, meta2, relationAlias, qb, root);
521
- // properties can be mapped to multiple places, e.g. when sharing a column in multiple FKs,
522
- // so we need to delete them after everything is mapped from given level
523
- for (const prop of targetProps) {
524
- for (const name of prop.fieldNames) {
525
- delete root[`${relationAlias}__${name}`];
526
- }
527
- }
528
529
  if (mapToPk) {
529
530
  const tmp = Object.values(relationPojo);
530
531
  /* v8 ignore next */
@@ -539,14 +540,34 @@ export class AbstractSqlDriver extends DatabaseDriver {
539
540
  }
540
541
  const populateChildren = hint.children || [];
541
542
  this.mapJoinedProps(relationPojo, meta2, populateChildren, qb, root, map, path);
543
+ targets.childrenResolved = true;
542
544
  });
543
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
+ }
544
564
  /**
545
565
  * Maps a single property from a joined result row into the relation pojo.
546
566
  * Handles polymorphic FKs, composite keys, Date parsing, and embedded objects.
547
567
  */
548
- mapJoinedProp(relationPojo, prop, relationAlias, root, tz, meta, options) {
549
- 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')) {
550
571
  return;
551
572
  }
552
573
  // inline embeddables are mapped via their flattened child props; mapping the embedded root prop
@@ -555,10 +576,8 @@ export class AbstractSqlDriver extends DatabaseDriver {
555
576
  return;
556
577
  }
557
578
  if (prop.polymorphic && prop.kind !== ReferenceKind.EMBEDDED) {
558
- const discriminatorAlias = `${relationAlias}__${prop.fieldNames[0]}`;
559
- const discriminatorValue = root[discriminatorAlias];
560
- const pkFieldNames = prop.fieldNames.slice(1);
561
- const pkValues = pkFieldNames.map(name => root[`${relationAlias}__${name}`]);
579
+ const discriminatorValue = row[keys[0]];
580
+ const pkValues = keys.slice(1).map(key => row[key]);
562
581
  const pkValue = pkValues.length === 1 ? pkValues[0] : pkValues;
563
582
  if (discriminatorValue != null && pkValue != null) {
564
583
  relationPojo[prop.name] = new PolymorphicRef(discriminatorValue, pkValue);
@@ -569,7 +588,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
569
588
  }
570
589
  else if (prop.fieldNames.length > 1) {
571
590
  // composite keys
572
- const fk = prop.fieldNames.map(name => root[`${relationAlias}__${name}`]);
591
+ const fk = keys.map(key => row[key]);
573
592
  // `mapFlatCompositePrimaryKey` collapses to a scalar when the target PK is a single prop
574
593
  // (e.g. a relation referencing a composite unique key on a single-PK target).
575
594
  const pk = Utils.mapFlatCompositePrimaryKey(fk, prop);
@@ -577,8 +596,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
577
596
  relationPojo[prop.name] = valid ? pk : null;
578
597
  }
579
598
  else if (prop.runtimeType === 'Date') {
580
- const alias = `${relationAlias}__${prop.fieldNames[0]}`;
581
- const value = root[alias];
599
+ const value = row[keys[0]];
582
600
  if (tz &&
583
601
  tz !== 'local' &&
584
602
  typeof value === 'string' &&
@@ -594,9 +612,13 @@ export class AbstractSqlDriver extends DatabaseDriver {
594
612
  relationPojo[prop.name] = value;
595
613
  }
596
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
+ }
597
620
  else {
598
- const alias = `${relationAlias}__${prop.fieldNames[0]}`;
599
- relationPojo[prop.name] = root[alias];
621
+ relationPojo[prop.name] = row[keys[0]];
600
622
  if (prop.kind === ReferenceKind.EMBEDDED && (prop.object || meta.embeddable)) {
601
623
  const item = parseJsonSafe(relationPojo[prop.name]);
602
624
  if (Array.isArray(item)) {
@@ -609,8 +631,8 @@ export class AbstractSqlDriver extends DatabaseDriver {
609
631
  }
610
632
  }
611
633
  if (options?.deleteFromRoot) {
612
- for (const name of prop.fieldNames) {
613
- delete root[`${relationAlias}__${name}`];
634
+ for (const key of keys) {
635
+ delete row[key];
614
636
  }
615
637
  }
616
638
  }
@@ -763,25 +785,12 @@ export class AbstractSqlDriver extends DatabaseDriver {
763
785
  }
764
786
  return { selectFields, insertColumns };
765
787
  }
788
+ /**
789
+ * Returns properties whose columns can be copied by an `INSERT … SELECT` (owning columns that are not PKs, generated or formulas).
790
+ * @internal
791
+ */
766
792
  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
- });
793
+ return (ownProps ? (meta.ownProps ?? meta.props) : meta.props).filter(prop => !prop.primary && !prop.generated && this.platform.shouldHaveColumn(prop, true, undefined, false, false));
785
794
  }
786
795
  async nativeInsertMany(entityName, data, options = {}, transform) {
787
796
  options.processCollections ??= true;
@@ -1130,6 +1139,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
1130
1139
  }
1131
1140
  }
1132
1141
  }
1142
+ const scalarColumn = prop.fieldNames.length > 1 && !prop.polymorphic ? this.getScalarFieldName(prop) : undefined;
1133
1143
  prop.fieldNames.forEach((fieldName, fieldNameIdx) => {
1134
1144
  if (fields.has(fieldName) || (prop.ownColumns && !prop.ownColumns.includes(fieldName))) {
1135
1145
  return;
@@ -1151,7 +1161,15 @@ export class AbstractSqlDriver extends DatabaseDriver {
1151
1161
  sql += '?';
1152
1162
  }
1153
1163
  params.push(...pks);
1154
- addParams(prop, prop.fieldNames.length > 1 ? data[idx][key]?.[fieldNameIdx] : data[idx][key]);
1164
+ const value = data[idx][key];
1165
+ const scalar = Array.isArray(value) && value.length === 1 ? value[0] : value;
1166
+ // a composite FK given as a scalar holds only the target PK, written to the column that references it
1167
+ if (scalarColumn && !isRaw(scalar) && Utils.isPrimaryKey(scalar)) {
1168
+ addParams(prop, (fieldName === scalarColumn ? scalar : null));
1169
+ }
1170
+ else {
1171
+ addParams(prop, prop.fieldNames.length > 1 ? value?.[fieldNameIdx] : value);
1172
+ }
1155
1173
  }
1156
1174
  });
1157
1175
  sql += ` else ${this.platform.quoteIdentifier(fieldName)} end, `;
@@ -1692,9 +1710,10 @@ export class AbstractSqlDriver extends DatabaseDriver {
1692
1710
  if (!Utils.isEmpty(orderBy) || RawQueryFragment.hasObjectFragments(orderBy)) {
1693
1711
  return Utils.asArray(orderBy).map(o => ({ [pivotProp.name]: o }));
1694
1712
  }
1695
- if (prop.kind === ReferenceKind.MANY_TO_MANY && Utils.asArray(parentOrderBy).some(o => o[prop.name])) {
1713
+ if (prop.kind === ReferenceKind.MANY_TO_MANY &&
1714
+ Utils.asArray(parentOrderBy).some(o => !Utils.isEmpty(o[prop.name]))) {
1696
1715
  return Utils.asArray(parentOrderBy)
1697
- .filter(o => o[prop.name])
1716
+ .filter(o => !Utils.isEmpty(o[prop.name]))
1698
1717
  .map(o => ({ [pivotProp.name]: o[prop.name] }));
1699
1718
  }
1700
1719
  if (!Utils.isEmpty(prop.orderBy) || RawQueryFragment.hasObjectFragments(prop.orderBy)) {
@@ -2104,7 +2123,7 @@ export class AbstractSqlDriver extends DatabaseDriver {
2104
2123
  if (childAlias) {
2105
2124
  // Map fields using same filtering as joined loading, plus skip PKs
2106
2125
  for (const prop of currentMeta.ownProps.filter(p => !p.primary && this.platform.shouldHaveColumn(p, []))) {
2107
- this.mapJoinedProp(relationPojo, prop, childAlias, root, tz, currentMeta, {
2126
+ this.mapJoinedProp(relationPojo, prop, this.aliasedKeys(prop, childAlias), root, tz, currentMeta, {
2108
2127
  deleteFromRoot: true,
2109
2128
  });
2110
2129
  }
@@ -1,4 +1,4 @@
1
- import { isRaw, JsonProperty, Platform, raw, Utils, ValidationError, } from '@mikro-orm/core';
1
+ import { inspect, isRaw, JsonProperty, Platform, raw, Utils, ValidationError, } from '@mikro-orm/core';
2
2
  import { SqlEntityRepository } from './SqlEntityRepository.js';
3
3
  import { SqlSchemaGenerator } from './schema/SqlSchemaGenerator.js';
4
4
  import { NativeQueryBuilder } from './query/NativeQueryBuilder.js';
@@ -169,9 +169,12 @@ export class AbstractSqlPlatform extends Platform {
169
169
  * @internal
170
170
  */
171
171
  validateOrderByDirection(direction) {
172
- const dir = ('' + direction).toLowerCase().trim();
172
+ if (typeof direction !== 'string') {
173
+ throw new ValidationError(`Invalid order direction: ${inspect(direction)}`);
174
+ }
175
+ const dir = direction.toLowerCase().trim();
173
176
  if (!AbstractSqlPlatform.ORDER_BY_DIRECTIONS.has(dir)) {
174
- throw new Error(`Invalid order direction: '${direction}'`);
177
+ throw new ValidationError(`Invalid order direction: '${direction}'`);
175
178
  }
176
179
  return dir;
177
180
  }
@@ -68,6 +68,7 @@ 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
+ normalizeExpression(expr: string): string;
71
72
  /** Decodes the backslash escapes of an introspected string literal. */
72
73
  unescapeDefault(val: string): string;
73
74
  }
@@ -313,12 +313,14 @@ export class MySqlSchemaHelper extends SchemaHelper {
313
313
  const ret = {};
314
314
  for (const check of allChecks) {
315
315
  const key = this.getTableKey(check);
316
+ // string literals come back escaped twice, decoded one level the same as the defaults in `wrap()`
317
+ const expression = check.expression.replace(/\\(.)/gs, '$1');
316
318
  ret[key] ??= [];
317
319
  ret[key].push({
318
320
  name: check.name,
319
321
  columnName: check.column_name,
320
- definition: `check ${check.expression}`,
321
- expression: check.expression.replace(/^\((.*)\)$/, '$1'),
322
+ definition: `check ${expression}`,
323
+ expression: expression.replace(/^\((.*)\)$/, '$1'),
322
324
  });
323
325
  }
324
326
  return ret;
@@ -628,6 +630,10 @@ export class MySqlSchemaHelper extends SchemaHelper {
628
630
  const stringType = type instanceof StringType || type instanceof TextType || type instanceof EnumType;
629
631
  return stringType ? this.platform.quoteDefaultValue(val) : val;
630
632
  }
633
+ normalizeExpression(expr) {
634
+ // `\'` and `''` are the same quote inside a literal
635
+ return expr.replace(/\\(.)/gs, (escape, char) => (char === "'" ? "''" : escape));
636
+ }
631
637
  /** Decodes the backslash escapes of an introspected string literal. */
632
638
  unescapeDefault(val) {
633
639
  const sqlEscapes = { 0: '\0', b: '\b', n: '\n', r: '\r', t: '\t', Z: '\x1a' };
@@ -78,6 +78,7 @@ export declare class BasePostgreSqlPlatform extends AbstractSqlPlatform {
78
78
  /**
79
79
  * Ported from PostgreSQL 9.2.4 source code (`src/interfaces/libpq/fe-exec.c`),
80
80
  * matching `pg.Client.prototype.escapeLiteral` so we don't need a `pg` dep here.
81
+ * Avoids per-character concatenation (builds a rope, slow on large values) and regexps (fixed cost on tiny values).
81
82
  */
82
83
  private escapeLiteral;
83
84
  getVarcharTypeDeclarationSQL(column: {
@@ -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) {
@@ -273,28 +274,22 @@ export class BasePostgreSqlPlatform extends AbstractSqlPlatform {
273
274
  /**
274
275
  * Ported from PostgreSQL 9.2.4 source code (`src/interfaces/libpq/fe-exec.c`),
275
276
  * matching `pg.Client.prototype.escapeLiteral` so we don't need a `pg` dep here.
277
+ * Avoids per-character concatenation (builds a rope, slow on large values) and regexps (fixed cost on tiny values).
276
278
  */
277
279
  escapeLiteral(str) {
278
- let hasBackslash = false;
279
- let escaped = `'`;
280
- for (let i = 0; i < str.length; i++) {
281
- const c = str[i];
282
- if (c === `'`) {
283
- escaped += c + c;
284
- }
285
- else if (c === '\\') {
286
- escaped += c + c;
287
- hasBackslash = true;
288
- }
289
- else {
290
- escaped += c;
291
- }
280
+ const hasBackslash = str.includes('\\');
281
+ const hasQuote = str.includes(`'`);
282
+ if (!hasBackslash && !hasQuote) {
283
+ return `'${str}'`;
292
284
  }
293
- escaped += `'`;
285
+ let escaped = str;
294
286
  if (hasBackslash) {
295
- escaped = ` E${escaped}`;
287
+ escaped = escaped.replaceAll('\\', '\\\\');
288
+ }
289
+ if (hasQuote) {
290
+ escaped = escaped.replaceAll(`'`, `''`);
296
291
  }
297
- return escaped;
292
+ return hasBackslash ? ` E'${escaped}'` : `'${escaped}'`;
298
293
  }
299
294
  getVarcharTypeDeclarationSQL(column) {
300
295
  if (column.length === -1) {
@@ -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 */
@@ -255,7 +255,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
255
255
  const table = schema.addTable(t.table_name, t.schema_name, t.table_comment);
256
256
  table.collation = dbCollation;
257
257
  const pks = await this.getPrimaryKeys(connection, indexes[key], table.name, table.schema);
258
- const enums = this.getEnumDefinitions(checks[key] ?? []);
258
+ const enums = this.getEnumDefinitions(checks[key] ?? [], columns[key] ?? []);
259
259
  if (columns[key]) {
260
260
  table.init(columns[key], indexes[key], checks[key], pks, fks[key], enums);
261
261
  }
@@ -1072,7 +1072,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
1072
1072
  }
1073
1073
  return `alter type ${this.quote(name)} add value if not exists ${this.platform.quoteValue(value)}${suffix}`;
1074
1074
  }
1075
- getEnumDefinitions(checks) {
1075
+ getEnumDefinitions(checks, columns) {
1076
1076
  return checks.reduce((o, item) => {
1077
1077
  // check constraints are defined as one of:
1078
1078
  // `CHECK ((type = ANY (ARRAY['local'::text, 'global'::text])))`
@@ -1084,13 +1084,20 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
1084
1084
  // the single-value form must compare against a quoted literal (`= 'a'::text`); anything else
1085
1085
  // (e.g. a JSON `->>` extraction like `name = data->>'name'`) is not an enum constraint
1086
1086
  const m2 = item.definition?.match(/\(array\[(.*)]\)/i) || item.definition?.match(/ = ('(?:[^']|'')*'::[\w ]+)\)/i);
1087
- if (item.columnName && m1 && m2) {
1087
+ // enums with string items are emulated with a check, a check like `delta in (1, -1)` on a number is a plain one
1088
+ const column = columns.find(c => c.name === item.columnName);
1089
+ const numeric = column != null &&
1090
+ (this.platform.isNumericColumn(column.mappedType) ||
1091
+ [DecimalType, FloatType, DoubleType].some(t => column.mappedType instanceof t));
1092
+ if (item.columnName && m1 && m2 && !numeric) {
1088
1093
  /* v8 ignore next */
1089
1094
  const parts = m2[1].match(/('(?:[^']|'')*'::\w[\w ]*)/g) ?? m2[1].split(',');
1090
1095
  let items = parts.map((item) => /^\(?'((?:[^']|'')*)'/.exec(item.trim())?.[1]?.replace(/''/g, "'"));
1091
1096
  items = items.filter(item => item !== undefined);
1092
1097
  if (items.length > 0) {
1093
1098
  o[item.columnName] = items;
1099
+ // kept to compare with a plain check of the same values, e.g. `kind = 'manual'` is stored like a single item enum
1100
+ item.introspectedExpression = item.expression;
1094
1101
  item.expression = this.platform.getEnumCheckConstraintExpression(item.columnName, items);
1095
1102
  item.definition = `check (${item.expression})`;
1096
1103
  }
@@ -1324,18 +1331,20 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
1324
1331
  const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
1325
1332
  if (column.autoincrement) {
1326
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));
1327
1336
  const sequenceOptions = this.getSequenceOptionsSQL(column);
1328
1337
  const { incrementBy = 1, startWith = incrementBy < 0 ? -1 : 1 } = column.sequence ?? {};
1329
1338
  const lastValue = `(select ${incrementBy < 0 ? 'min' : 'max'}(${this.quote(column.name)}) from ${this.quote(name)})`;
1330
1339
  ret.push(`create sequence if not exists ${this.quote(seqName)}${sequenceOptions ? ` ${sequenceOptions}` : ''}`);
1331
1340
  if (sequenceOptions) {
1332
1341
  // continue after the existing values, but never before the declared start
1333
- 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)`);
1334
1343
  }
1335
1344
  else {
1336
- ret.push(`select setval('${seqName}', ${lastValue})`);
1345
+ ret.push(`select setval(${seq}, ${lastValue})`);
1337
1346
  }
1338
- 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})`);
1339
1348
  }
1340
1349
  return ret;
1341
1350
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/sql",
3
- "version": "7.3.0-dev.21",
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.8"
53
+ "@mikro-orm/core": "^7.2.10"
54
54
  },
55
55
  "peerDependencies": {
56
- "@mikro-orm/core": "7.3.0-dev.21"
56
+ "@mikro-orm/core": "7.3.0-dev.23"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">= 22.17.0"
@@ -1,4 +1,4 @@
1
- import { ALIAS_REPLACEMENT, GroupOperator, QueryFlag, QueryHelper, raw, RawQueryFragment, ReferenceKind, Utils, } from '@mikro-orm/core';
1
+ import { ALIAS_REPLACEMENT, GroupOperator, QueryFlag, QueryHelper, raw, RawQueryFragment, ReferenceKind, Utils, ValidationError, } from '@mikro-orm/core';
2
2
  import { CriteriaNode } from './CriteriaNode.js';
3
3
  import { JoinType, QueryType } from './enums.js';
4
4
  const COLLECTION_OPERATORS = ['$some', '$none', '$every', '$size', '$all'];
@@ -7,6 +7,9 @@ const COLLECTION_OPERATORS = ['$some', '$none', '$every', '$size', '$all'];
7
7
  */
8
8
  export class ObjectCriteriaNode extends CriteriaNode {
9
9
  process(qb, options) {
10
+ if (options?.type === 'orderBy' && this.prop?.kind === ReferenceKind.SCALAR) {
11
+ throw new ValidationError(`Invalid order direction for ${Utils.className(this.entityName)}.${this.prop.name}`);
12
+ }
10
13
  const targets = this.isPolymorphicBranch() ? QueryHelper.findTargetMetas(this.prop, this.key) : [];
11
14
  if (options?.type === 'orderBy' && targets.length > 1) {
12
15
  return this.processPolymorphicOrderBy(qb, targets, options);
@@ -980,8 +980,6 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
980
980
  * Tier 3: Derive from target entity metadata (all cloneable columns), auto-populate source select
981
981
  */
982
982
  private resolveInsertFromColumns;
983
- /** Returns properties that are safe to clone (persistable, non-PK, non-generated). */
984
- private getCloneableProps;
985
983
  private applyDiscriminatorCondition;
986
984
  /**
987
985
  * Ensures TPT joins are applied. Can be called early before finalize() to populate
@@ -1033,6 +1031,11 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
1033
1031
  */
1034
1032
  private processNestedJoins;
1035
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;
1036
1039
  /**
1037
1040
  * Resolves a `persist: false` virtual field referenced in `orderBy` (e.g. `qb.as('reviewCount')` or a
1038
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
  }
@@ -1262,7 +1262,6 @@ export class QueryBuilder {
1262
1262
  const entities = [];
1263
1263
  for (const row of res) {
1264
1264
  const entity = this.mapResult(row);
1265
- this.propagatePopulateHint(entity, this.#state.populate);
1266
1265
  entities.push(entity);
1267
1266
  if (limit != null && --limit === 0) {
1268
1267
  break;
@@ -1300,7 +1299,9 @@ export class QueryBuilder {
1300
1299
  * Executes the query, returning both array of results and total count query (without offset and limit).
1301
1300
  */
1302
1301
  async getResultAndCount() {
1303
- return [await this.clone().getResultList(), await this.clone().getCount()];
1302
+ // `getCount()` clones by itself, except when the type is not set yet
1303
+ const countQb = this.#state.type === undefined ? this.clone() : this;
1304
+ return [await this.clone().getResultList(), await countQb.getCount()];
1304
1305
  }
1305
1306
  as(aliasOrTargetEntity, alias) {
1306
1307
  const qb = this.getNativeQuery();
@@ -1884,7 +1885,7 @@ export class QueryBuilder {
1884
1885
  });
1885
1886
  }
1886
1887
  // Tier 3: derive from metadata — all cloneable columns
1887
- const cloneableProps = this.getCloneableProps(meta);
1888
+ const cloneableProps = this.driver.getCloneableProps(meta);
1888
1889
  const selectFields = [];
1889
1890
  const columns = [];
1890
1891
  for (const prop of cloneableProps) {
@@ -1899,27 +1900,6 @@ export class QueryBuilder {
1899
1900
  }
1900
1901
  return columns;
1901
1902
  }
1902
- /** Returns properties that are safe to clone (persistable, non-PK, non-generated). */
1903
- getCloneableProps(meta) {
1904
- return meta.props.filter(prop => {
1905
- if (prop.persist === false) {
1906
- return false;
1907
- }
1908
- if (prop.primary) {
1909
- return false;
1910
- }
1911
- if (!prop.fieldNames?.length) {
1912
- return false;
1913
- }
1914
- if ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
1915
- return false;
1916
- }
1917
- if (prop.kind === ReferenceKind.EMBEDDED && !prop.object) {
1918
- return false;
1919
- }
1920
- return true;
1921
- });
1922
- }
1923
1903
  applyDiscriminatorCondition() {
1924
1904
  const meta = this.mainAlias.meta;
1925
1905
  if (meta.root.inheritanceType !== 'sti' || !meta.discriminatorValue) {
@@ -2041,12 +2021,13 @@ export class QueryBuilder {
2041
2021
  if (meta && (this.#state.fields?.includes('*') || this.#state.fields?.includes(`${this.mainAlias.aliasName}.*`))) {
2042
2022
  const schema = this.getSchema(this.mainAlias);
2043
2023
  // Per-column entries are unquoted (meant for `quote`), while `toString()` yields the quoted alias for plain template literals
2044
- // For TPT, use helper to resolve correct alias per property (inherited props use parent alias)
2045
2024
  const quotedMainAlias = this.platform.quoteIdentifier(this.mainAlias.aliasName).toString();
2046
- const columns = meta.createColumnMappingObject(prop => this.helper.getTPTAliasForProperty(prop.name, this.mainAlias.aliasName), quotedMainAlias);
2025
+ let columns;
2047
2026
  meta.props
2048
2027
  .filter(prop => prop.formula && (!prop.lazy || this.#state.flags.has(QueryFlag.INCLUDE_LAZY_FORMULAS)))
2049
2028
  .map(prop => {
2029
+ // For TPT, use helper to resolve correct alias per property (inherited props use parent alias)
2030
+ columns ??= meta.createColumnMappingObject(p => this.helper.getTPTAliasForProperty(p.name, this.mainAlias.aliasName), quotedMainAlias);
2050
2031
  const aliased = this.platform.quoteIdentifier(prop.fieldNames[0]);
2051
2032
  const table = this.helper.createFormulaTable(quotedMainAlias, meta, schema);
2052
2033
  return `${this.driver.evaluateFormula(prop.formula, columns, table)} as ${aliased}`;
@@ -2293,6 +2274,17 @@ export class QueryBuilder {
2293
2274
  return [ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(join.prop.kind);
2294
2275
  });
2295
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
+ }
2296
2288
  /**
2297
2289
  * Resolves a `persist: false` virtual field referenced in `orderBy` (e.g. `qb.as('reviewCount')` or a
2298
2290
  * `raw()` fragment aliased in the select) to the alias and SQL expression it was selected under. The
@@ -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
@@ -763,33 +767,29 @@ export class QueryBuilderHelper {
763
767
  if (isRaw(colPart)) {
764
768
  colPart = this.#platform.formatQuery(colPart.sql, colPart.params);
765
769
  }
766
- if (Array.isArray(order)) {
767
- order.forEach(part => ret.push(...this.getQueryOrderFromObject(type, part, populate, collation)));
768
- }
769
- else {
770
- ret.push(...this.#platform.getOrderByExpression(colPart, order, collation));
771
- }
770
+ ret.push(...this.#platform.getOrderByExpression(colPart, order, collation));
772
771
  }
773
772
  }
774
773
  return ret;
775
774
  }
776
775
  splitField(field, greedyAlias = false) {
777
- const parts = field.split('.');
778
- const ref = parts[parts.length - 1].split(':')[1];
779
- if (ref) {
780
- parts[parts.length - 1] = parts[parts.length - 1].substring(0, parts[parts.length - 1].indexOf(':'));
781
- }
782
- if (parts.length === 1) {
783
- return [this.#alias, parts[0], ref];
784
- }
785
- if (greedyAlias) {
786
- const fromField = parts.pop();
787
- const fromAlias = parts.join('.');
788
- return [fromAlias, fromField, ref];
789
- }
790
- const fromAlias = parts.shift();
791
- const fromField = parts.join('.');
792
- return [fromAlias, fromField, ref];
776
+ const lastDot = field.lastIndexOf('.');
777
+ const colon = field.indexOf(':', lastDot + 1);
778
+ let end = field.length;
779
+ let ref;
780
+ // only the segment between the first and second colon of the last path part is the ref
781
+ if (colon !== -1) {
782
+ const nextColon = field.indexOf(':', colon + 1);
783
+ ref = field.substring(colon + 1, nextColon === -1 ? end : nextColon);
784
+ if (ref) {
785
+ end = colon;
786
+ }
787
+ }
788
+ if (lastDot === -1) {
789
+ return [this.#alias, field.substring(0, end), ref];
790
+ }
791
+ const aliasEnd = greedyAlias ? lastDot : field.indexOf('.');
792
+ return [field.substring(0, aliasEnd), field.substring(aliasEnd + 1, end), ref];
793
793
  }
794
794
  getLockSQL(qb, lockMode, lockTables = [], joinsMap) {
795
795
  const meta = this.#metadata.find(this.#entityName);
@@ -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`
@@ -151,7 +151,9 @@ export class DatabaseTable {
151
151
  precision: prop.precision,
152
152
  scale: prop.scale,
153
153
  default: prop.defaultRaw,
154
- enumItems: prop.nativeEnumName || prop.items?.every(i => typeof i === 'string') ? prop.items : undefined,
154
+ enumItems: prop.nativeEnumName || ((prop.enum || prop.array) && prop.items?.every(i => typeof i === 'string'))
155
+ ? prop.items
156
+ : undefined,
155
157
  comment: prop.comment,
156
158
  collation: prop.collation,
157
159
  extra: prop.extra,
@@ -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 &&
@@ -927,12 +933,13 @@ export class SchemaComparator {
927
933
  // Protect dots inside string literals before the quote strip below, or the alias-prefix normalization
928
934
  // would mangle literal contents — `current_setting('app.tenant')` and `current_setting('req.tenant')`
929
935
  // must not both collapse to `current_settingtenant`
930
- .replace(/'([^']*)'/g, (_, inner) => `'${inner.replaceAll('.', '\u0000')}'`)
936
+ // numbers are left alone, postgres quotes the negative ones (`'-1.5'::numeric`)
937
+ .replace(/'([^']*)'/g, (m, inner) => /^-?\d+(\.\d+)?$/.test(inner) ? m : `'${inner.replaceAll('.', '\u0000')}'`)
931
938
  // Remove quotes first so we can process identifiers
932
939
  .replace(/['"`]/g, '')
933
940
  // MySQL adds table/alias prefixes to columns (e.g., a.name or table_name.column vs just column)
934
941
  // Strip these prefixes - match word.word patterns and keep only the last part
935
- .replace(/\b\w+\.(\w+)/g, '$1')
942
+ .replace(/\b(?!\d)\w+\.(\w+)/g, '$1')
936
943
  // PostgreSQL rewrites `x [not] between a and b` to `x >= a and x <= b` (`x < a or x > b`), cast targets are skipped
937
944
  .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}`)
938
945
  // Normalize JOIN syntax: inner join -> join (equivalent in SQL)
package/typings.d.ts CHANGED
@@ -115,6 +115,8 @@ export interface CheckDef<T = unknown> {
115
115
  expression: string | CheckCallback<T>;
116
116
  definition?: string;
117
117
  columnName?: string;
118
+ /** @internal the expression as introspected, before it was normalized as the check of an enum */
119
+ introspectedExpression?: string;
118
120
  }
119
121
  /** Resolved row level security policy for schema operations (all callbacks resolved to strings). */
120
122
  export interface SqlPolicyDef {