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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/AbstractSqlConnection.js +11 -0
  2. package/AbstractSqlDriver.d.ts +10 -0
  3. package/AbstractSqlDriver.js +133 -64
  4. package/AbstractSqlPlatform.js +1 -1
  5. package/SqlEntityManager.js +2 -1
  6. package/dialects/mysql/BaseMySqlPlatform.d.ts +3 -0
  7. package/dialects/mysql/BaseMySqlPlatform.js +7 -0
  8. package/dialects/mysql/MySqlSchemaHelper.d.ts +8 -0
  9. package/dialects/mysql/MySqlSchemaHelper.js +33 -2
  10. package/dialects/postgresql/BasePostgreSqlPlatform.d.ts +1 -0
  11. package/dialects/postgresql/BasePostgreSqlPlatform.js +3 -0
  12. package/dialects/postgresql/PostgreSqlExceptionConverter.js +1 -0
  13. package/dialects/postgresql/PostgreSqlSchemaHelper.d.ts +7 -0
  14. package/dialects/postgresql/PostgreSqlSchemaHelper.js +159 -18
  15. package/dialects/sqlite/SqlitePlatform.d.ts +3 -1
  16. package/dialects/sqlite/SqlitePlatform.js +12 -0
  17. package/dialects/sqlite/SqliteSchemaHelper.d.ts +2 -0
  18. package/dialects/sqlite/SqliteSchemaHelper.js +32 -9
  19. package/package.json +4 -4
  20. package/plugin/transformer.d.ts +2 -1
  21. package/plugin/transformer.js +39 -13
  22. package/query/CriteriaNode.d.ts +1 -0
  23. package/query/CriteriaNode.js +12 -3
  24. package/query/CriteriaNodeFactory.js +1 -1
  25. package/query/NativeQueryBuilder.d.ts +2 -0
  26. package/query/NativeQueryBuilder.js +18 -3
  27. package/query/ObjectCriteriaNode.d.ts +2 -0
  28. package/query/ObjectCriteriaNode.js +46 -20
  29. package/query/QueryBuilder.d.ts +8 -3
  30. package/query/QueryBuilder.js +78 -40
  31. package/query/QueryBuilderHelper.d.ts +2 -0
  32. package/query/QueryBuilderHelper.js +58 -21
  33. package/schema/DatabaseTable.js +34 -8
  34. package/schema/SchemaComparator.d.ts +1 -1
  35. package/schema/SchemaComparator.js +35 -22
  36. package/schema/SchemaHelper.d.ts +25 -1
  37. package/schema/SchemaHelper.js +68 -5
  38. package/schema/SqlSchemaGenerator.d.ts +7 -4
  39. package/schema/SqlSchemaGenerator.js +29 -10
  40. package/schema/partitioning.js +6 -6
  41. package/typings.d.ts +3 -1
@@ -19,6 +19,10 @@ export declare class PostgreSqlSchemaHelper extends SchemaHelper {
19
19
  getSchemaBeginning(charset: string, disableForeignKeys?: boolean): string;
20
20
  getSetSchemaSQL(schema: string): string;
21
21
  getResetSchemaSQL(_defaultSchema: string): string;
22
+ getMigrationLockSQL(): {
23
+ acquire: string;
24
+ release: string;
25
+ } | undefined;
22
26
  supportsMigrationSchema(): boolean;
23
27
  getCreateDatabaseSQL(name: string): string;
24
28
  getListTablesSQL(): string;
@@ -29,6 +33,7 @@ export declare class PostgreSqlSchemaHelper extends SchemaHelper {
29
33
  loadMaterializedViews(schema: DatabaseSchema, connection: AbstractSqlConnection, schemaName?: string, ctx?: Transaction): Promise<void>;
30
34
  createMaterializedView(name: string, schema: string | undefined, definition: string, withData?: boolean): string;
31
35
  createTable(table: DatabaseTable, alter?: boolean): string[];
36
+ getResetSequenceSQL(tableName: string, schemaName: string | undefined, columnName: string, startWith: number): string;
32
37
  dropMaterializedViewIfExists(name: string, schema?: string): string;
33
38
  refreshMaterializedView(name: string, schema?: string, concurrently?: boolean): string;
34
39
  getNamespaces(connection: AbstractSqlConnection, ctx?: Transaction): Promise<string[]>;
@@ -134,9 +139,11 @@ export declare class PostgreSqlSchemaHelper extends SchemaHelper {
134
139
  castColumn(name: string, type: string): string;
135
140
  dropForeignKey(tableName: string, constraintName: string): string;
136
141
  getPostAlterTable(tableDiff: TableDifference, safe: boolean): string[];
142
+ getAddColumnsSQL(table: DatabaseTable, columns: Column[]): string[];
137
143
  private getAlterColumnAutoincrement;
138
144
  getChangeColumnCommentSQL(tableName: string, to: Column, schemaName?: string): string;
139
145
  alterTableComment(table: DatabaseTable, comment?: string): string;
146
+ normalizeExpression(expr: string): string;
140
147
  normalizeDefaultValue(defaultValue: string, length: number): string | number;
141
148
  appendComments(table: DatabaseTable): string[];
142
149
  getDatabaseExistsSQL(name: string): string;
@@ -5,6 +5,67 @@ import { normalizePartitionBound, normalizePartitionDefinition } from '../../sch
5
5
  const POSTGIS_VIEWS = ['geography_columns', 'geometry_columns'];
6
6
  /** Dollar-quote delimiter, e.g. `$$` or `$body$`, captured so `split` keeps it. */
7
7
  const DOLLAR_QUOTE_TAG = /(\$(?:[A-Za-z_]\w*)?\$)/;
8
+ /** pg-added `(<operand>)::type` cast in a check body, including multi word types like `double precision`. */
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
+ }
8
69
  export class PostgreSqlSchemaHelper extends SchemaHelper {
9
70
  static DEFAULT_VALUES = {
10
71
  'now()': ['now()', 'current_timestamp'],
@@ -31,6 +92,13 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
31
92
  getResetSchemaSQL(_defaultSchema) {
32
93
  return 'reset search_path';
33
94
  }
95
+ getMigrationLockSQL() {
96
+ // advisory locks are scoped to the current database
97
+ return {
98
+ acquire: 'select pg_try_advisory_lock(hashtext(?)) as locked',
99
+ release: 'select pg_advisory_unlock(hashtext(?))',
100
+ };
101
+ }
34
102
  supportsMigrationSchema() {
35
103
  return true;
36
104
  }
@@ -106,10 +174,23 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
106
174
  }
107
175
  createTable(table, alter) {
108
176
  const partitioning = table.getPartitioning();
177
+ const [createTable, ...rest] = super.createTable(table, alter);
178
+ // `serial` columns can't declare sequence options inline, so alter the implicit sequence right after creating the table
179
+ const sequences = table
180
+ .getColumns()
181
+ .filter(column => column.autoincrement && !column.generated && this.getSequenceOptionsSQL(column))
182
+ .map(column => {
183
+ const sequence = `pg_get_serial_sequence(${this.platform.quoteValue(table.getQuotedName())}, ${this.platform.quoteValue(column.name)})`;
184
+ const { startWith = -1, incrementBy = 1 } = column.sequence;
185
+ // `alter sequence` keeps the ascending bounds of the serial, so a descending one gets the bounds and start of a fresh sequence
186
+ const options = incrementBy < 0
187
+ ? `no minvalue maxvalue ${Math.max(startWith, -1)} start with ${startWith} increment by ${incrementBy}`
188
+ : this.getSequenceOptionsSQL(column);
189
+ return `do $$ begin execute format('alter sequence %s ${options} restart', ${sequence}); end $$`;
190
+ });
109
191
  if (!partitioning) {
110
- return super.createTable(table, alter);
192
+ return [createTable, ...sequences, ...rest];
111
193
  }
112
- const [createTable, ...rest] = super.createTable(table, alter);
113
194
  const partitions = partitioning.partitions.map(partition => {
114
195
  const partitionName = this.quote(this.getTableName(partition.name, partition.schema ?? table.schema));
115
196
  return `create table ${partitionName} partition of ${table.getQuotedName()} ${partition.bound}`;
@@ -119,7 +200,12 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
119
200
  // regex replacement tokens like `$$`, `$&`, or `$1` inside user-supplied expressions (e.g., a
120
201
  // callback that returns a dollar-quoted literal) are not interpreted as back-references.
121
202
  const spliced = `${createTable.slice(0, -1)} partition by ${partitioning.definition};`;
122
- return [spliced, ...rest, ...partitions];
203
+ return [spliced, ...sequences, ...rest, ...partitions];
204
+ }
205
+ getResetSequenceSQL(tableName, schemaName, columnName, startWith) {
206
+ const table = this.platform.quoteValue(this.quote(this.getTableName(tableName, schemaName)));
207
+ // `truncate … restart identity` goes back to the start the sequence was created with, which the metadata may not match
208
+ return `select setval(pg_get_serial_sequence(${table}, ${this.platform.quoteValue(columnName)}), ${startWith}, false)`;
123
209
  }
124
210
  dropMaterializedViewIfExists(name, schema) {
125
211
  return `drop materialized view if exists ${this.quote(this.getTableName(name, schema))} cascade`;
@@ -328,10 +414,9 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
328
414
  return columnDefs.map(colDef => {
329
415
  const name = unquote(colDef);
330
416
  const result = { name };
331
- // Find this column in the expression and extract modifiers
332
- // 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`
333
418
  const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
334
- const colPattern = new RegExp(`"?${escapedName}"?\\s*([^,)]*?)(?:,|$)`, 'i');
419
+ const colPattern = new RegExp(`(?:^|,)\\s*"?${escapedName}"?(?=\\s|,|$)\\s*([^,)]*?)(?:,|$)`, 'i');
335
420
  const colMatch = columnsStr.match(colPattern);
336
421
  if (colMatch) {
337
422
  const modifiers = colMatch[1];
@@ -389,11 +474,14 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
389
474
  identity_generation,
390
475
  generation_expression,
391
476
  pg_catalog.col_description(pgc.oid, cols.ordinal_position::int) column_comment,
392
- coll.collname as collation_name
477
+ coll.collname as collation_name,
478
+ seq.seqstart as sequence_start,
479
+ seq.seqincrement as sequence_increment
393
480
  from information_schema.columns cols
394
481
  join pg_class pgc on cols.table_name = pgc.relname
395
482
  join pg_attribute pga on pgc.oid = pga.attrelid and cols.column_name = pga.attname
396
483
  left join pg_collation coll on pga.attcollation = coll.oid and coll.collname <> 'default'
484
+ left join pg_sequence seq on seq.seqrelid = pg_get_serial_sequence(quote_ident(cols.table_schema) || '.' || quote_ident(cols.table_name), cols.column_name)::regclass
397
485
  where (${[...tablesBySchemas.entries()].map(([schema, tables]) => `(table_schema = ${this.platform.quoteValue(schema)} and table_name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(',')}))`).join(' or ')})
398
486
  order by ordinal_position`;
399
487
  const allColumns = await connection.execute(sql, [], 'all', ctx);
@@ -406,14 +494,19 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
406
494
  const key = this.getTableKey(col);
407
495
  ret[key] ??= [];
408
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
+ }
409
504
  if (col.data_type === 'USER-DEFINED' &&
410
505
  col.udt_schema &&
411
506
  col.udt_schema !== this.platform.getDefaultSchemaName()) {
412
507
  type = `${col.udt_schema}.${type}`;
413
508
  }
414
- if (type === 'bpchar') {
415
- type = 'char';
416
- }
509
+ type = type.replace(/^bpchar\b/, 'char');
417
510
  // postgis stores the geometry/geography typmod (`geometry(point,4326)`) in atttypmod, which
418
511
  // information_schema does not expose — recover the full type via format_type so it round-trips
419
512
  if ((col.udt_name === 'geometry' || col.udt_name === 'geography') && col.format_type) {
@@ -444,6 +537,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
444
537
  default: str(this.normalizeDefaultValue(col.column_default, col.length)),
445
538
  unsigned: increments,
446
539
  autoincrement: increments,
540
+ sequence: increments ? this.getIntrospectedSequence(col.sequence_start, col.sequence_increment) : undefined,
447
541
  generated: col.is_identity === 'YES'
448
542
  ? col.identity_generation === 'BY DEFAULT'
449
543
  ? 'by default as identity'
@@ -505,7 +599,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
505
599
  // SchemaHelper.createCheck).
506
600
  const m = /^check \(\((.*)\)\)$/is.exec(check.expression);
507
601
  const single = m ? null : /^check \((.*)\)$/is.exec(check.expression);
508
- const def = m ? m[1].replace(/\(([^()]*)\)::\w+(?:\[\])?/g, '$1') : single ? single[1] : check.expression;
602
+ const def = m ? m[1].replace(CHECK_CAST_RE, '$1') : single ? single[1] : check.expression;
509
603
  ret[key].push({
510
604
  name: check.name,
511
605
  columnName: check.column_name,
@@ -1032,11 +1126,15 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
1032
1126
  columnType = this.quote(columnType);
1033
1127
  }
1034
1128
  }
1035
- if (column.generated === 'by default as identity') {
1036
- columnType += ` generated ${column.generated}`;
1129
+ const sequenceOptions = this.getSequenceOptionsSQL(column);
1130
+ const generated = sequenceOptions && /^(by default as )?identity$/.test(column.generated ?? '')
1131
+ ? `${column.generated} (${sequenceOptions})`
1132
+ : column.generated;
1133
+ if (generated?.startsWith('by default as identity')) {
1134
+ columnType += ` generated ${generated}`;
1037
1135
  }
1038
- else if (column.generated) {
1039
- columnType += ` generated always as ${column.generated}`;
1136
+ else if (generated) {
1137
+ columnType += ` generated always as ${generated}`;
1040
1138
  }
1041
1139
  col.push(columnType);
1042
1140
  Utils.runIfNotEmpty(() => col.push(this.getCollateSQL(column.collation)), column.collation);
@@ -1193,14 +1291,50 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
1193
1291
  }
1194
1292
  return ret;
1195
1293
  }
1294
+ getAddColumnsSQL(table, columns) {
1295
+ const compositePK = table.getPrimaryKey()?.composite;
1296
+ const before = [];
1297
+ const after = [];
1298
+ const adds = columns.map(column => {
1299
+ const sequenceOptions = this.getSequenceOptionsSQL(column);
1300
+ if (!sequenceOptions || !column.autoincrement || column.generated) {
1301
+ return column;
1302
+ }
1303
+ // a `serial` column numbers the existing rows right away, so expand it to a sequence created with the options upfront
1304
+ const seqName = this.quote(this.getTableName(this.platform.getIndexName(table.name, [column.name], 'sequence'), table.schema));
1305
+ before.push(`create sequence ${seqName} ${sequenceOptions}`);
1306
+ after.push(`alter sequence ${seqName} owned by ${table.getQuotedName()}.${this.quote(column.name)}`);
1307
+ // the expanded column has no inline `primary key`, which `alterTable` expects from an added autoincrement PK
1308
+ if (column.primary && !compositePK && !this.hasNonDefaultPrimaryKeyName(table)) {
1309
+ after.push(`alter table ${table.getQuotedName()} add primary key (${this.quote(column.name)})`);
1310
+ }
1311
+ return {
1312
+ ...column,
1313
+ type: column.mappedType.getColumnType({ autoincrement: false }, this.platform),
1314
+ autoincrement: false,
1315
+ nullable: false,
1316
+ default: `nextval('${seqName}')`,
1317
+ };
1318
+ });
1319
+ return [...before, ...super.getAddColumnsSQL(table, adds), ...after];
1320
+ }
1196
1321
  getAlterColumnAutoincrement(tableName, column, schemaName) {
1197
1322
  const ret = [];
1198
1323
  /* v8 ignore next */
1199
1324
  const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
1200
1325
  if (column.autoincrement) {
1201
1326
  const seqName = this.platform.getIndexName(tableName, [column.name], 'sequence');
1202
- ret.push(`create sequence if not exists ${this.quote(seqName)}`);
1203
- ret.push(`select setval('${seqName}', (select max(${this.quote(column.name)}) from ${this.quote(name)}))`);
1327
+ const sequenceOptions = this.getSequenceOptionsSQL(column);
1328
+ const { incrementBy = 1, startWith = incrementBy < 0 ? -1 : 1 } = column.sequence ?? {};
1329
+ const lastValue = `(select ${incrementBy < 0 ? 'min' : 'max'}(${this.quote(column.name)}) from ${this.quote(name)})`;
1330
+ ret.push(`create sequence if not exists ${this.quote(seqName)}${sequenceOptions ? ` ${sequenceOptions}` : ''}`);
1331
+ if (sequenceOptions) {
1332
+ // 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)`);
1334
+ }
1335
+ else {
1336
+ ret.push(`select setval('${seqName}', ${lastValue})`);
1337
+ }
1204
1338
  ret.push(`alter table ${this.quote(name)} alter column ${this.quote(column.name)} set default nextval('${seqName}')`);
1205
1339
  }
1206
1340
  return ret;
@@ -1213,11 +1347,18 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
1213
1347
  alterTableComment(table, comment) {
1214
1348
  return `comment on table ${table.getQuotedName()} is ${this.platform.quoteValue(comment ?? '')}`;
1215
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
+ }
1216
1357
  normalizeDefaultValue(defaultValue, length) {
1217
1358
  if (!defaultValue || typeof defaultValue !== 'string') {
1218
1359
  return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
1219
1360
  }
1220
- const match = /^'(.*)'::(.*)$/.exec(defaultValue);
1361
+ const match = /^'(.*)'::(.*)$/s.exec(defaultValue);
1221
1362
  if (match) {
1222
1363
  if (match[2] === 'integer') {
1223
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';
@@ -14,6 +14,7 @@ export declare class SqlitePlatform extends AbstractSqlPlatform {
14
14
  usesReturningStatement(): boolean;
15
15
  usesEnumCheckConstraints(): boolean;
16
16
  supportsComments(): boolean;
17
+ supportsAutoincrementIncrement(): boolean;
17
18
  getCurrentTimestampSQL(length: number): string;
18
19
  getDateTimeTypeDeclarationSQL(column: {
19
20
  length: number;
@@ -74,6 +75,7 @@ export declare class SqlitePlatform extends AbstractSqlPlatform {
74
75
  */
75
76
  supportsSchemas(): boolean;
76
77
  getDefaultSchemaName(): string | undefined;
78
+ validateMetadata(meta: EntityMetadata): void;
77
79
  getFullTextWhereClause(): string;
78
80
  escape(value: any): string;
79
81
  convertVersionValue(value: Date | number, prop: EntityProperty): number | {
@@ -1,3 +1,4 @@
1
+ import { MetadataError } from '@mikro-orm/core';
1
2
  import { AbstractSqlPlatform } from '../../AbstractSqlPlatform.js';
2
3
  import { SqliteNativeQueryBuilder } from './SqliteNativeQueryBuilder.js';
3
4
  import { SqliteSchemaHelper } from './SqliteSchemaHelper.js';
@@ -26,6 +27,9 @@ export class SqlitePlatform extends AbstractSqlPlatform {
26
27
  supportsComments() {
27
28
  return false;
28
29
  }
30
+ supportsAutoincrementIncrement() {
31
+ return false;
32
+ }
29
33
  getCurrentTimestampSQL(length) {
30
34
  return `(strftime('%s', 'now') * 1000)`;
31
35
  }
@@ -110,6 +114,14 @@ export class SqlitePlatform extends AbstractSqlPlatform {
110
114
  // Return 'main' only when schema support is active (i.e., databases are attached)
111
115
  return this.supportsSchemas() ? 'main' : undefined;
112
116
  }
117
+ validateMetadata(meta) {
118
+ super.validateMetadata(meta);
119
+ // `main` always exists and `*` resolves at runtime; anything else fails later as `unknown database` unless attached
120
+ const attached = this.config.get('attachDatabases')?.some(db => db.name === meta.schema);
121
+ if (meta.schema && !['main', '*'].includes(meta.schema) && !attached) {
122
+ throw new MetadataError(`Entity ${meta.className} declares schema '${meta.schema}', but SQLite cannot address it: attach it via \`attachDatabases\` or remove the schema in \`discovery.onMetadata\` when sharing entities between drivers`);
123
+ }
124
+ }
113
125
  getFullTextWhereClause() {
114
126
  return `:column: match :query`;
115
127
  }
@@ -8,6 +8,7 @@ export declare class SqliteSchemaHelper extends SchemaHelper {
8
8
  private static readonly PARTIAL_WHERE_RE;
9
9
  disableForeignKeysSQL(): string;
10
10
  enableForeignKeysSQL(): string;
11
+ getForeignKeyCheckSQL(): string;
11
12
  supportsSchemaConstraints(): boolean;
12
13
  getCreateNamespaceSQL(name: string): string;
13
14
  getDropNamespaceSQL(name: string): string;
@@ -21,6 +22,7 @@ export declare class SqliteSchemaHelper extends SchemaHelper {
21
22
  getDropDatabaseSQL(name: string): string;
22
23
  loadInformationSchema(schema: DatabaseSchema, connection: AbstractSqlConnection, tables: Table[], schemas?: string[], ctx?: Transaction): Promise<void>;
23
24
  createTable(table: DatabaseTable, alter?: boolean): string[];
25
+ getResetSequenceSQL(tableName: string, schemaName: string | undefined, columnName: string, startWith: number): string;
24
26
  createTableColumn(column: Column, table: DatabaseTable, _changedProperties?: Set<string>): string | undefined;
25
27
  getAddColumnsSQL(table: DatabaseTable, columns: Column[], diff?: TableDifference): string[];
26
28
  dropForeignKey(tableName: string, constraintName: string): string;
@@ -22,6 +22,9 @@ export class SqliteSchemaHelper extends SchemaHelper {
22
22
  enableForeignKeysSQL() {
23
23
  return 'pragma foreign_keys = on;';
24
24
  }
25
+ getForeignKeyCheckSQL() {
26
+ return 'pragma foreign_key_check';
27
+ }
25
28
  supportsSchemaConstraints() {
26
29
  return false;
27
30
  }
@@ -128,8 +131,10 @@ export class SqliteSchemaHelper extends SchemaHelper {
128
131
  sql += `, primary key (${primaryKey.columnNames.map(c => this.quote(c)).join(', ')})`;
129
132
  }
130
133
  const parts = [];
131
- for (const fk of Object.values(table.getForeignKeys())) {
132
- parts.push(this.createForeignKey(table, fk, false));
134
+ if (this.options.createForeignKeyConstraints) {
135
+ for (const fk of Object.values(table.getForeignKeys())) {
136
+ parts.push(this.createForeignKey(table, fk, false));
137
+ }
133
138
  }
134
139
  for (const check of table.getChecks()) {
135
140
  const sql = `constraint ${this.quote(check.name)} check (${check.expression})`;
@@ -144,6 +149,13 @@ export class SqliteSchemaHelper extends SchemaHelper {
144
149
  }
145
150
  const ret = [];
146
151
  this.append(ret, sql);
152
+ const startWith = columns.find(column => column.autoincrement)?.sequence?.startWith;
153
+ if (startWith != null) {
154
+ // a table rebuild renames the counter row of the temp table over, so only seed it when missing
155
+ const sequenceTable = this.quote(this.getTableName('sqlite_sequence', table.schema));
156
+ const name = this.platform.quoteValue(table.name);
157
+ this.append(ret, `insert into ${sequenceTable} (name, seq) select ${name}, ${startWith - 1} where not exists (select 1 from ${sequenceTable} where name = ${name})`);
158
+ }
147
159
  for (const index of table.getIndexes()) {
148
160
  this.append(ret, this.createIndex(index, table));
149
161
  }
@@ -152,6 +164,12 @@ export class SqliteSchemaHelper extends SchemaHelper {
152
164
  }
153
165
  return ret;
154
166
  }
167
+ getResetSequenceSQL(tableName, schemaName, columnName, startWith) {
168
+ const sequenceTable = this.quote(this.getTableName('sqlite_sequence', schemaName));
169
+ const name = this.platform.quoteValue(tableName);
170
+ // the counter row does not exist before the first insert when the table was created without `sequence`
171
+ return `delete from ${sequenceTable} where name = ${name};\ninsert into ${sequenceTable} (name, seq) values (${name}, ${startWith - 1})`;
172
+ }
155
173
  createTableColumn(column, table, _changedProperties) {
156
174
  const col = [this.quote(column.name)];
157
175
  const checks = table.getChecks();
@@ -240,7 +258,8 @@ export class SqliteSchemaHelper extends SchemaHelper {
240
258
  }
241
259
  for (let i = cols.length - 1; i >= 0; i--) {
242
260
  const col = cols[i];
243
- const re = ` *, *[\`"']?${col.name}[\`"']? (.*)`;
261
+ // the first column is not preceded by a comma
262
+ const re = ` *(?:^|,) *[\`"']?${col.name}[\`"']? (.*)`;
244
263
  const columnDef = new RegExp(re, 'i').exec(columnsDef);
245
264
  if (columnDef) {
246
265
  columns[col.name] = { name: col.name, definition: columnDef[1] };
@@ -498,8 +517,10 @@ export class SqliteSchemaHelper extends SchemaHelper {
498
517
  const [schemaName, tableName] = this.splitTableName(diff.name);
499
518
  if (Utils.hasObjectKeys(diff.removedChecks) ||
500
519
  Utils.hasObjectKeys(diff.changedChecks) ||
501
- Utils.hasObjectKeys(diff.changedForeignKeys) ||
502
- Utils.hasObjectKeys(diff.changedColumns)) {
520
+ (this.options.createForeignKeyConstraints && Utils.hasObjectKeys(diff.changedForeignKeys)) ||
521
+ Utils.hasObjectKeys(diff.changedColumns) ||
522
+ // sqlite can only add or change a primary key by rebuilding the table
523
+ [...Object.values(diff.addedIndexes), ...Object.values(diff.changedIndexes)].some(index => index.primary)) {
503
524
  return this.getAlterTempTableSQL(diff);
504
525
  }
505
526
  for (const index of Object.values(diff.removedIndexes)) {
@@ -515,7 +536,8 @@ export class SqliteSchemaHelper extends SchemaHelper {
515
536
  if (Object.values(diff.addedColumns).length > 0) {
516
537
  this.append(ret, this.getAddColumnsSQL(diff.toTable, Object.values(diff.addedColumns), diff));
517
538
  }
518
- if (Utils.hasObjectKeys(diff.addedForeignKeys) || Utils.hasObjectKeys(diff.addedChecks)) {
539
+ if ((this.options.createForeignKeyConstraints && Utils.hasObjectKeys(diff.addedForeignKeys)) ||
540
+ Utils.hasObjectKeys(diff.addedChecks)) {
519
541
  return this.getAlterTempTableSQL(diff);
520
542
  }
521
543
  for (const [oldColumnName, column] of Object.entries(diff.renamedColumns)) {
@@ -644,10 +666,11 @@ export class SqliteSchemaHelper extends SchemaHelper {
644
666
  first.replace(`create table ${quotedName}`, `create table ${quotedTempName}`),
645
667
  ];
646
668
  const columns = [];
669
+ const renamedFrom = Object.fromEntries(Object.entries(changedTable.renamedColumns).map(([oldName, column]) => [column.name, oldName]));
647
670
  for (const column of changedTable.toTable.getColumns()) {
648
- const fromColumn = changedTable.fromTable.getColumn(column.name);
649
- if (fromColumn) {
650
- columns.push(this.quote(column.name));
671
+ const fromName = renamedFrom[column.name] ?? column.name;
672
+ if (changedTable.fromTable.getColumn(fromName)) {
673
+ columns.push(this.quote(fromName));
651
674
  }
652
675
  else {
653
676
  columns.push(`null as ${this.quote(column.name)}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/sql",
3
- "version": "7.3.0-dev.2",
3
+ "version": "7.3.0-dev.20",
4
4
  "description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",
5
5
  "keywords": [
6
6
  "data-mapper",
@@ -47,13 +47,13 @@
47
47
  "copy": "node ../../scripts/copy.mjs"
48
48
  },
49
49
  "dependencies": {
50
- "kysely": "0.29.6"
50
+ "kysely": "0.29.8"
51
51
  },
52
52
  "devDependencies": {
53
- "@mikro-orm/core": "^7.2.1"
53
+ "@mikro-orm/core": "^7.2.7"
54
54
  },
55
55
  "peerDependencies": {
56
- "@mikro-orm/core": "7.3.0-dev.2"
56
+ "@mikro-orm/core": "7.3.0-dev.20"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">= 22.17.0"
@@ -92,6 +92,7 @@ export declare class MikroTransformer extends OperationNodeTransformer {
92
92
  * This is called for SELECT queries when columnNamingStrategy is 'property'
93
93
  */
94
94
  transformResult(rows: Record<string, any>[] | undefined, entityMap: Map<string, EntityMetadata>): Record<string, any>[] | undefined;
95
+ private getResultMaps;
95
96
  buildGlobalFieldMap(entityMap: Map<string, EntityMetadata>): Record<string, EntityProperty>;
96
97
  buildGlobalRelationFieldMap(entityMap: Map<string, EntityMetadata>): Record<string, string>;
97
98
  /**
@@ -108,6 +109,6 @@ export declare class MikroTransformer extends OperationNodeTransformer {
108
109
  /**
109
110
  * Transform a single row by mapping column names to property names
110
111
  */
111
- transformRow(row: Record<string, any>, fieldToPropertyMap: Record<string, EntityProperty>, relationFieldMap: Record<string, string>): Record<string, any>;
112
+ transformRow(row: Record<string, any>, fieldEntries: [string, EntityProperty][], relationEntries: [string, string][]): Record<string, any>;
112
113
  prepareOutputValue(prop: EntityProperty | undefined, value: unknown): unknown;
113
114
  }
@@ -1,5 +1,12 @@
1
1
  import { ReferenceKind, isRaw, } from '@mikro-orm/core';
2
2
  import { AliasNode, ColumnNode, ColumnUpdateNode, IdentifierNode, OperationNodeTransformer, PrimitiveValueListNode, RawNode, ReferenceNode, SchemableIdentifierNode, SelectAllNode, SelectionNode, TableNode, ValueListNode, ValueNode, ValuesNode, } from 'kysely';
3
+ /** Past this many query shapes the cache of one metadata storage starts over, so generated aliases cannot grow it. */
4
+ const RESULT_MAPS_LIMIT = 1000;
5
+ /**
6
+ * Result maps per query shape (the aliases and entities of its entity map). They are derived from metadata alone, so
7
+ * they are built once and shared by every transformer, as `getKysely()` creates a new one per call.
8
+ */
9
+ const resultMapsCache = new WeakMap();
3
10
  const EXPANDABLE_KINDS = new Set([
4
11
  ReferenceKind.SCALAR,
5
12
  ReferenceKind.EMBEDDED,
@@ -884,12 +891,7 @@ export class MikroTransformer extends OperationNodeTransformer {
884
891
  if (byEntity) {
885
892
  return byEntity;
886
893
  }
887
- const allMetadata = Array.from(this.#metadata);
888
- const byTable = allMetadata.find(m => m.tableName === name);
889
- if (byTable) {
890
- return byTable;
891
- }
892
- return undefined;
894
+ return this.#metadata.getByTableName(name);
893
895
  }
894
896
  /**
895
897
  * Transform result rows by mapping database column names to property names
@@ -906,11 +908,35 @@ export class MikroTransformer extends OperationNodeTransformer {
906
908
  if (entityMap.size === 0) {
907
909
  return rows;
908
910
  }
909
- // Build a global mapping from database field names to property objects
910
- const fieldToPropertyMap = this.buildGlobalFieldMap(entityMap);
911
- const relationFieldMap = this.buildGlobalRelationFieldMap(entityMap);
911
+ // The global mapping from database field names to property objects, built once per query shape
912
+ const { fields, relations } = this.getResultMaps(entityMap);
912
913
  // Transform each row
913
- return rows.map(row => this.transformRow(row, fieldToPropertyMap, relationFieldMap));
914
+ return rows.map(row => this.transformRow(row, fields, relations));
915
+ }
916
+ getResultMaps(entityMap) {
917
+ let byShape = resultMapsCache.get(this.#metadata);
918
+ if (!byShape) {
919
+ byShape = new Map();
920
+ resultMapsCache.set(this.#metadata, byShape);
921
+ }
922
+ let shape = '';
923
+ for (const [alias, meta] of entityMap) {
924
+ shape += `${alias}\0${meta._id}\0`;
925
+ }
926
+ const cached = byShape.get(shape);
927
+ if (cached && Array.from(entityMap.values()).every((meta, i) => meta.props === cached.props[i])) {
928
+ return cached;
929
+ }
930
+ if (byShape.size >= RESULT_MAPS_LIMIT) {
931
+ byShape.clear();
932
+ }
933
+ const maps = {
934
+ props: Array.from(entityMap.values(), meta => meta.props),
935
+ fields: Object.entries(this.buildGlobalFieldMap(entityMap)),
936
+ relations: Object.entries(this.buildGlobalRelationFieldMap(entityMap)),
937
+ };
938
+ byShape.set(shape, maps);
939
+ return maps;
914
940
  }
915
941
  buildGlobalFieldMap(entityMap) {
916
942
  const map = {};
@@ -986,10 +1012,10 @@ export class MikroTransformer extends OperationNodeTransformer {
986
1012
  /**
987
1013
  * Transform a single row by mapping column names to property names
988
1014
  */
989
- transformRow(row, fieldToPropertyMap, relationFieldMap) {
1015
+ transformRow(row, fieldEntries, relationEntries) {
990
1016
  const transformed = { ...row };
991
1017
  // First pass: map regular fields from fieldName to propertyName and convert values
992
- for (const [fieldName, prop] of Object.entries(fieldToPropertyMap)) {
1018
+ for (const [fieldName, prop] of fieldEntries) {
993
1019
  if (!(fieldName in transformed)) {
994
1020
  continue;
995
1021
  }
@@ -1011,7 +1037,7 @@ export class MikroTransformer extends OperationNodeTransformer {
1011
1037
  // Second pass: handle relation fields
1012
1038
  // Only run if columnNamingStrategy is 'property', as we don't want to rename FKs otherwise
1013
1039
  if (this.#options.columnNamingStrategy === 'property') {
1014
- for (const [fieldName, relationPropertyName] of Object.entries(relationFieldMap)) {
1040
+ for (const [fieldName, relationPropertyName] of relationEntries) {
1015
1041
  if (fieldName in transformed && !(relationPropertyName in transformed)) {
1016
1042
  // Move the foreign key value to the relation property name
1017
1043
  transformed[relationPropertyName] = transformed[fieldName];
@@ -29,6 +29,7 @@ export declare class CriteriaNode<T extends object> implements ICriteriaNode<T>
29
29
  parentPath?: string;
30
30
  }): string;
31
31
  private isPivotJoin;
32
+ protected isOperatorPayload(payload: any): boolean;
32
33
  getPivotPath(path: string): string;
33
34
  aliased(field: string, alias?: string): string;
34
35
  isStrict(): boolean;
@@ -29,7 +29,7 @@ export class CriteriaNode {
29
29
  }
30
30
  for (const k of pks) {
31
31
  const [name, target] = QueryHelper.splitPolymorphicKey(k);
32
- this.prop = meta.props.find(prop => (prop.name === name && (!target || !!prop.polymorphTargets?.some(t => t.className === target))) ||
32
+ this.prop = meta.props.find(prop => (prop.name === name && (!target || QueryHelper.findTargetMetas(prop, k).length > 0)) ||
33
33
  (prop.fieldNames?.length === 1 && prop.fieldNames[0] === k && prop.persist !== false));
34
34
  const isProp = this.prop || meta.props.find(prop => (prop.fieldNames || []).includes(k));
35
35
  // do not validate if the key is prefixed or type casted (e.g. `k::text`)
@@ -131,8 +131,17 @@ export class CriteriaNode {
131
131
  this.payload instanceof RegExp ||
132
132
  this.payload instanceof Date ||
133
133
  rawField;
134
- const operator = Utils.isObject(this.payload) && Utils.getObjectQueryKeys(this.payload).every(k => Utils.isOperator(k, false));
135
- return this.prop.kind === ReferenceKind.MANY_TO_MANY && (scalar || operator);
134
+ return this.prop.kind === ReferenceKind.MANY_TO_MANY && (scalar || this.isOperatorPayload(this.payload));
135
+ }
136
+ isOperatorPayload(payload) {
137
+ return (Utils.isObject(payload) &&
138
+ Utils.getObjectQueryKeys(payload).every(k => {
139
+ if (k === '$not' && payload[k] instanceof CriteriaNode && Utils.isPlainObject(payload[k].payload)) {
140
+ // `$not` wrapping entity conditions is a condition on the target entity, not on the relation itself
141
+ return Utils.getObjectQueryKeys(payload[k].payload).every(ik => Utils.isOperator(ik, false));
142
+ }
143
+ return Utils.isOperator(k, false);
144
+ }));
136
145
  }
137
146
  getPivotPath(path) {
138
147
  return `${path}[pivot]`;