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

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 (46) 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/mssql/MsSqlNativeQueryBuilder.js +4 -3
  7. package/dialects/mysql/BaseMySqlPlatform.d.ts +11 -0
  8. package/dialects/mysql/BaseMySqlPlatform.js +20 -1
  9. package/dialects/mysql/MySqlNativeQueryBuilder.js +4 -3
  10. package/dialects/mysql/MySqlSchemaHelper.d.ts +8 -0
  11. package/dialects/mysql/MySqlSchemaHelper.js +35 -6
  12. package/dialects/oracledb/OracleNativeQueryBuilder.js +4 -3
  13. package/dialects/postgresql/BasePostgreSqlPlatform.d.ts +1 -0
  14. package/dialects/postgresql/BasePostgreSqlPlatform.js +3 -0
  15. package/dialects/postgresql/PostgreSqlExceptionConverter.js +1 -0
  16. package/dialects/postgresql/PostgreSqlSchemaHelper.d.ts +7 -0
  17. package/dialects/postgresql/PostgreSqlSchemaHelper.js +159 -18
  18. package/dialects/sqlite/SqlitePlatform.d.ts +3 -1
  19. package/dialects/sqlite/SqlitePlatform.js +12 -0
  20. package/dialects/sqlite/SqliteSchemaHelper.d.ts +2 -0
  21. package/dialects/sqlite/SqliteSchemaHelper.js +32 -9
  22. package/index.d.ts +2 -0
  23. package/index.js +2 -0
  24. package/package.json +4 -4
  25. package/plugin/transformer.d.ts +2 -1
  26. package/plugin/transformer.js +39 -13
  27. package/query/CriteriaNode.d.ts +1 -0
  28. package/query/CriteriaNode.js +12 -3
  29. package/query/CriteriaNodeFactory.js +1 -1
  30. package/query/NativeQueryBuilder.d.ts +8 -0
  31. package/query/NativeQueryBuilder.js +40 -6
  32. package/query/ObjectCriteriaNode.d.ts +2 -0
  33. package/query/ObjectCriteriaNode.js +46 -20
  34. package/query/QueryBuilder.d.ts +13 -3
  35. package/query/QueryBuilder.js +110 -44
  36. package/query/QueryBuilderHelper.d.ts +2 -0
  37. package/query/QueryBuilderHelper.js +75 -24
  38. package/schema/DatabaseTable.js +36 -8
  39. package/schema/SchemaComparator.d.ts +2 -1
  40. package/schema/SchemaComparator.js +48 -23
  41. package/schema/SchemaHelper.d.ts +25 -1
  42. package/schema/SchemaHelper.js +68 -5
  43. package/schema/SqlSchemaGenerator.d.ts +7 -4
  44. package/schema/SqlSchemaGenerator.js +29 -10
  45. package/schema/partitioning.js +6 -6
  46. package/typings.d.ts +3 -1
@@ -1,4 +1,4 @@
1
- import { EnumType, StringType, TextType } from '@mikro-orm/core';
1
+ import { EnumType, JsonType, StringType, TextType, } from '@mikro-orm/core';
2
2
  import { SchemaHelper } from '../../schema/SchemaHelper.js';
3
3
  export class MySqlSchemaHelper extends SchemaHelper {
4
4
  #cache = {};
@@ -24,6 +24,11 @@ export class MySqlSchemaHelper extends SchemaHelper {
24
24
  getResetSchemaSQL(defaultSchema) {
25
25
  return `use ${this.quote(defaultSchema)}`;
26
26
  }
27
+ getMigrationLockSQL() {
28
+ // `get_lock` names are server-wide and limited to 64 characters
29
+ const name = `left(concat(database(), '.', ?), 64)`;
30
+ return { acquire: `select get_lock(${name}, 0) as locked`, release: `select release_lock(${name})` };
31
+ }
27
32
  supportsMigrationSchema() {
28
33
  return true;
29
34
  }
@@ -42,12 +47,25 @@ export class MySqlSchemaHelper extends SchemaHelper {
42
47
  enableForeignKeysSQL() {
43
48
  return 'set foreign_key_checks = 1;';
44
49
  }
50
+ getResetSequenceSQL(tableName, schemaName, columnName, startWith) {
51
+ return `alter table ${this.quote(this.getTableName(tableName, schemaName))} auto_increment = ${startWith}`;
52
+ }
53
+ getAddColumnsSQL(table, columns) {
54
+ const [sql, ...rest] = super.getAddColumnsSQL(table, columns);
55
+ const startWith = columns.find(column => column.autoincrement)?.sequence?.startWith;
56
+ // the table option numbers the existing rows of the added column from the declared start too
57
+ return [startWith != null ? `${sql}, auto_increment = ${startWith}` : sql, ...rest];
58
+ }
45
59
  finalizeTable(table, charset, collate) {
46
60
  let sql = ` default character set ${charset}`;
47
61
  if (collate) {
48
62
  sql += ` collate ${collate}`;
49
63
  }
50
64
  sql += ' engine = InnoDB';
65
+ const startWith = table.getColumns().find(column => column.autoincrement)?.sequence?.startWith;
66
+ if (startWith != null) {
67
+ sql += ` auto_increment = ${startWith}`;
68
+ }
51
69
  if (table.comment) {
52
70
  sql += ` comment = ${this.platform.quoteValue(table.comment)}`;
53
71
  }
@@ -572,10 +590,8 @@ export class MySqlSchemaHelper extends SchemaHelper {
572
590
  const enums = await connection.execute(sql, [], 'all', ctx);
573
591
  return enums.reduce((o, item) => {
574
592
  o[item.table_name] ??= {};
575
- o[item.table_name][item.column_name] = item.column_type
576
- .match(/enum\((.*)\)/)[1]
577
- .split(',')
578
- .map((item) => /'(.*)'/.exec(item)[1]);
593
+ // items can hold commas, doubled quotes and backslash escapes
594
+ o[item.table_name][item.column_name] = [...item.column_type.matchAll(/'((?:''|\\.|[^'\\])*)'/g)].map(([, value]) => this.unescapeDefault(value.replaceAll("''", "'")));
579
595
  return o;
580
596
  }, {});
581
597
  }
@@ -601,7 +617,20 @@ export class MySqlSchemaHelper extends SchemaHelper {
601
617
  return super.normalizeDefaultValue(defaultValue, length, MySqlSchemaHelper.DEFAULT_VALUES);
602
618
  }
603
619
  wrap(val, type) {
620
+ if (typeof val !== 'string' || val.length === 0) {
621
+ return val;
622
+ }
623
+ // text/blob literal defaults come back escaped twice with a charset introducer, e.g. `_utf8mb4\'it\\\'s\'` (JSON is parsed by the comparator)
624
+ const expression = type instanceof JsonType ? null : /^_\w+\\'(.*)\\'$/s.exec(val);
625
+ if (expression) {
626
+ return this.platform.quoteDefaultValue(this.unescapeDefault(expression[1].replace(/\\(.)/gs, '$1')));
627
+ }
604
628
  const stringType = type instanceof StringType || type instanceof TextType || type instanceof EnumType;
605
- return typeof val === 'string' && val.length > 0 && stringType ? this.platform.quoteValue(val) : val;
629
+ return stringType ? this.platform.quoteDefaultValue(val) : val;
630
+ }
631
+ /** Decodes the backslash escapes of an introspected string literal. */
632
+ unescapeDefault(val) {
633
+ const sqlEscapes = { 0: '\0', b: '\b', n: '\n', r: '\r', t: '\t', Z: '\x1a' };
634
+ return val.replace(/\\(.)/gs, (_, char) => sqlEscapes[char] ?? char);
606
635
  }
607
636
  }
@@ -181,7 +181,8 @@ export class OracleNativeQueryBuilder extends NativeQueryBuilder {
181
181
  if (!clause.ignore) {
182
182
  /* v8 ignore next: merge type branch */
183
183
  if (!clause.merge || Array.isArray(clause.merge)) {
184
- const mergeParts = (clause.merge || keys)
184
+ const merge = clause.merge?.length ? clause.merge : keys;
185
+ const mergeParts = merge
185
186
  .filter(field => !Array.isArray(clause.fields) || !clause.fields.includes(field))
186
187
  .filter((field) => keys.includes(field)) // only reference columns present in the source data
187
188
  .map((column) => `${this.quote(column)} = tsource.${this.quote(column)}`);
@@ -193,7 +194,7 @@ export class OracleNativeQueryBuilder extends NativeQueryBuilder {
193
194
  this.params.push(...clause.where.params);
194
195
  }
195
196
  this.parts.push('then update set');
196
- this.parts.push(mergeParts.join(', '));
197
+ this.parts.push(this.joinVersionMerge(clause, mergeParts, merge));
197
198
  }
198
199
  } /* v8 ignore start: object-form merge branch */
199
200
  else if (typeof clause.merge === 'object') {
@@ -207,7 +208,7 @@ export class OracleNativeQueryBuilder extends NativeQueryBuilder {
207
208
  this.params.push(value);
208
209
  return `${this.getTableName()}.${this.quote(key)} = ?`;
209
210
  });
210
- this.parts.push(parts.join(', '));
211
+ this.parts.push(this.joinVersionMerge(clause, parts, Object.keys(clause.merge)));
211
212
  }
212
213
  /* v8 ignore stop */
213
214
  }
@@ -59,6 +59,7 @@ export declare class BasePostgreSqlPlatform extends AbstractSqlPlatform {
59
59
  };
60
60
  isBigIntProperty(prop: EntityProperty): boolean;
61
61
  getArrayDeclarationSQL(): string;
62
+ supportsArrayOverlap(): boolean;
62
63
  getFloatDeclarationSQL(): string;
63
64
  getDoubleDeclarationSQL(): string;
64
65
  getEnumTypeDeclarationSQL(column: {
@@ -199,6 +199,9 @@ export class BasePostgreSqlPlatform extends AbstractSqlPlatform {
199
199
  getArrayDeclarationSQL() {
200
200
  return 'text[]';
201
201
  }
202
+ supportsArrayOverlap() {
203
+ return true;
204
+ }
202
205
  getFloatDeclarationSQL() {
203
206
  return 'real';
204
207
  }
@@ -25,6 +25,7 @@ export class PostgreSqlExceptionConverter extends ExceptionConverter {
25
25
  break;
26
26
  case '23502':
27
27
  return new NotNullConstraintViolationException(exception);
28
+ case '23001':
28
29
  case '23503':
29
30
  return new ForeignKeyConstraintViolationException(exception);
30
31
  case '23505':
@@ -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/index.d.ts CHANGED
@@ -3,6 +3,8 @@
3
3
  * @module sql
4
4
  */
5
5
  export { Kysely } from 'kysely';
6
+ /** @hidden */
7
+ export * as kysely from 'kysely';
6
8
  export * from '@mikro-orm/core';
7
9
  export * from './AbstractSqlConnection.js';
8
10
  export * from './AbstractSqlDriver.js';
package/index.js CHANGED
@@ -3,6 +3,8 @@
3
3
  * @module sql
4
4
  */
5
5
  export { Kysely } from 'kysely';
6
+ /** @hidden */
7
+ export * as kysely from 'kysely';
6
8
  export * from '@mikro-orm/core';
7
9
  export * from './AbstractSqlConnection.js';
8
10
  export * from './AbstractSqlDriver.js';