@mikro-orm/sql 7.2.7-dev.7 → 7.2.7-dev.9

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.
@@ -137,6 +137,7 @@ export declare class PostgreSqlSchemaHelper extends SchemaHelper {
137
137
  private getAlterColumnAutoincrement;
138
138
  getChangeColumnCommentSQL(tableName: string, to: Column, schemaName?: string): string;
139
139
  alterTableComment(table: DatabaseTable, comment?: string): string;
140
+ normalizeExpression(expr: string): string;
140
141
  normalizeDefaultValue(defaultValue: string, length: number): string | number;
141
142
  appendComments(table: DatabaseTable): string[];
142
143
  getDatabaseExistsSQL(name: string): string;
@@ -7,6 +7,49 @@ const POSTGIS_VIEWS = ['geography_columns', 'geometry_columns'];
7
7
  const DOLLAR_QUOTE_TAG = /(\$(?:[A-Za-z_]\w*)?\$)/;
8
8
  /** pg-added `(<operand>)::type` cast in a check body, including multi word types like `double precision`. */
9
9
  const CHECK_CAST_RE = /\(([^()]*)\)::\w+(?: precision| varying| with(?:out)? time zone)?(?:\[\])?/g;
10
+ /**
11
+ * PostgreSQL prints `interval '1 minute'` back as `'00:01:00'`, so the literal is reformatted the same way.
12
+ * Only non-negative `<n> <unit>` lists are handled, anything else has to be written the way PostgreSQL prints it.
13
+ */
14
+ function normalizeIntervalLiteral(literal) {
15
+ // `[field, factor]` into the months, days and microseconds triple PostgreSQL stores an interval as
16
+ const units = {
17
+ year: [0, 12],
18
+ month: [0, 1],
19
+ mon: [0, 1],
20
+ week: [1, 7],
21
+ day: [1, 1],
22
+ hour: [2, 3_600_000_000],
23
+ minute: [2, 60_000_000],
24
+ second: [2, 1_000_000],
25
+ };
26
+ const parts = [0, 0, 0];
27
+ const rest = literal
28
+ .toLowerCase()
29
+ .replace(/(\d+(?:\.\d+)?) *(year|month|mon|week|day|hour|minute|second)s?\b/g, (_, qty, unit) => {
30
+ const [field, factor] = units[unit];
31
+ parts[field] += +qty * factor;
32
+ return '';
33
+ });
34
+ if (rest.trim() || !Number.isInteger(parts[0]) || !Number.isInteger(parts[1])) {
35
+ return undefined;
36
+ }
37
+ const [months, days] = parts;
38
+ const micros = Math.round(parts[2]);
39
+ const fields = [
40
+ [Math.trunc(months / 12), 'year'],
41
+ [months % 12, 'mon'],
42
+ [days, 'day'],
43
+ ]
44
+ .filter(([v]) => v > 0)
45
+ .map(([v, u]) => `${v} ${u}${v === 1 ? '' : 's'}`);
46
+ if (micros || !fields.length) {
47
+ const s = Math.floor(micros / 1_000_000);
48
+ const time = [s / 3600, (s / 60) % 60, s % 60].map(v => String(Math.floor(v)).padStart(2, '0')).join(':');
49
+ fields.push(time + String((micros % 1_000_000) / 1_000_000).slice(1));
50
+ }
51
+ return fields.join(' ');
52
+ }
10
53
  export class PostgreSqlSchemaHelper extends SchemaHelper {
11
54
  static DEFAULT_VALUES = {
12
55
  'now()': ['now()', 'current_timestamp'],
@@ -1227,6 +1270,12 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
1227
1270
  alterTableComment(table, comment) {
1228
1271
  return `comment on table ${table.getQuotedName()} is ${this.platform.quoteValue(comment ?? '')}`;
1229
1272
  }
1273
+ normalizeExpression(expr) {
1274
+ return expr.replace(/\binterval\s*'([^']*)'|'([^']*)'\s*::\s*interval\b/gi, (match, typed, cast) => {
1275
+ const literal = normalizeIntervalLiteral(typed ?? cast);
1276
+ return literal == null ? match : `'${literal}'::interval`;
1277
+ });
1278
+ }
1230
1279
  normalizeDefaultValue(defaultValue, length) {
1231
1280
  if (!defaultValue || typeof defaultValue !== 'string') {
1232
1281
  return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
@@ -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';
@@ -74,6 +74,7 @@ export declare class SqlitePlatform extends AbstractSqlPlatform {
74
74
  */
75
75
  supportsSchemas(): boolean;
76
76
  getDefaultSchemaName(): string | undefined;
77
+ validateMetadata(meta: EntityMetadata): void;
77
78
  getFullTextWhereClause(): string;
78
79
  escape(value: any): string;
79
80
  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';
@@ -110,6 +111,14 @@ export class SqlitePlatform extends AbstractSqlPlatform {
110
111
  // Return 'main' only when schema support is active (i.e., databases are attached)
111
112
  return this.supportsSchemas() ? 'main' : undefined;
112
113
  }
114
+ validateMetadata(meta) {
115
+ super.validateMetadata(meta);
116
+ // `main` always exists and `*` resolves at runtime; anything else fails later as `unknown database` unless attached
117
+ const attached = this.config.get('attachDatabases')?.some(db => db.name === meta.schema);
118
+ if (meta.schema && !['main', '*'].includes(meta.schema) && !attached) {
119
+ 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`);
120
+ }
121
+ }
113
122
  getFullTextWhereClause() {
114
123
  return `:column: match :query`;
115
124
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/sql",
3
- "version": "7.2.7-dev.7",
3
+ "version": "7.2.7-dev.9",
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",
@@ -53,7 +53,7 @@
53
53
  "@mikro-orm/core": "^7.2.6"
54
54
  },
55
55
  "peerDependencies": {
56
- "@mikro-orm/core": "7.2.7-dev.7"
56
+ "@mikro-orm/core": "7.2.7-dev.9"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">= 22.17.0"
@@ -821,6 +821,7 @@ export declare class QueryBuilder<Entity extends object = AnyEntity, RootAlias e
821
821
  * ```
822
822
  */
823
823
  stream(options?: QBStreamOptions): AsyncIterableIterator<Loaded<Entity, Hint, Fields>>;
824
+ private convertStreamExceptions;
824
825
  /**
825
826
  * Alias for `qb.getResultList()`
826
827
  */
@@ -1080,12 +1080,19 @@ export class QueryBuilder {
1080
1080
  const conn = this.getConnection();
1081
1081
  // outside a transaction, wrap in a short implicit one so RLS `set local` session context applies (no-op when unset)
1082
1082
  const sessionContext = this.context ? undefined : this.em?.getTransactionSessionContext();
1083
- const res = await (sessionContext
1084
- ? conn.transactional(trx => conn.execute(query.sql, query.params, method, trx, loggerContext), {
1085
- sessionContext,
1086
- loggerContext,
1087
- })
1088
- : conn.execute(query.sql, query.params, method, this.context, loggerContext));
1083
+ let res;
1084
+ // a QueryBuilder used directly must honour the same `convertException` contract as the driver methods
1085
+ try {
1086
+ res = await (sessionContext
1087
+ ? conn.transactional(trx => conn.execute(query.sql, query.params, method, trx, loggerContext), {
1088
+ sessionContext,
1089
+ loggerContext,
1090
+ })
1091
+ : conn.execute(query.sql, query.params, method, this.context, loggerContext));
1092
+ }
1093
+ catch (e) {
1094
+ throw this.driver.convertException(e);
1095
+ }
1089
1096
  const meta = this.mainAlias.meta;
1090
1097
  if (!options.mapResults || !meta) {
1091
1098
  await this.em?.storeCache(this.#state.cache, cached, res);
@@ -1146,7 +1153,7 @@ export class QueryBuilder {
1146
1153
  const chunkSize = options.chunkSize ?? 100;
1147
1154
  const query = this.toQuery();
1148
1155
  const loggerContext = { id: this.em?.id, ...this.loggerContext, ...this.#abortOptions };
1149
- const res = this.getConnection().stream(query.sql, query.params, this.context, loggerContext, chunkSize);
1156
+ const res = this.convertStreamExceptions(this.getConnection().stream(query.sql, query.params, this.context, loggerContext, chunkSize));
1150
1157
  const meta = this.mainAlias.meta;
1151
1158
  if (options.rawResults || !meta) {
1152
1159
  yield* res;
@@ -1180,6 +1187,14 @@ export class QueryBuilder {
1180
1187
  }
1181
1188
  }
1182
1189
  }
1190
+ async *convertStreamExceptions(res) {
1191
+ try {
1192
+ yield* res;
1193
+ }
1194
+ catch (e) {
1195
+ throw this.driver.convertException(e);
1196
+ }
1197
+ }
1183
1198
  /**
1184
1199
  * Alias for `qb.getResultList()`
1185
1200
  */
@@ -1,4 +1,4 @@
1
- import { DecimalType, EntitySchema, isRaw, ReferenceKind, t, Type, UnknownType, Utils, } from '@mikro-orm/core';
1
+ import { DecimalType, EntitySchema, isRaw, MetadataError, ReferenceKind, t, Type, UnknownType, Utils, } from '@mikro-orm/core';
2
2
  import { toEntityPartitionBy } from './partitioning.js';
3
3
  /**
4
4
  * @internal
@@ -975,19 +975,23 @@ export class DatabaseTable {
975
975
  if (columns?.length && properties.length > 0) {
976
976
  for (const col of columns) {
977
977
  if (!properties.includes(col.name)) {
978
- throw new Error(`Index '${name}' on entity '${meta.className}': column option references field '${col.name}' which is not in the index properties`);
978
+ throw new MetadataError(`Index '${name}' on entity '${meta.className}': column option references field '${col.name}' which is not in the index properties`);
979
979
  }
980
980
  }
981
981
  }
982
982
  // Validate fillFactor range
983
983
  if (index.fillFactor != null && (index.fillFactor < 0 || index.fillFactor > 100)) {
984
- throw new Error(`fillFactor must be between 0 and 100, got ${index.fillFactor} for index '${name}' on entity '${meta.className}'`);
984
+ throw new MetadataError(`fillFactor must be between 0 and 100, got ${index.fillFactor} for index '${name}' on entity '${meta.className}'`);
985
985
  }
986
986
  // The `expression` escape hatch takes the full index definition as raw SQL; combining it
987
987
  // with `where` is dialect-dependent (PG/Oracle/MySQL drop `where`, MSSQL appends it) so we
988
988
  // reject the combination up-front and ask users to inline the predicate into `expression`.
989
989
  if (index.expression && index.where != null) {
990
- throw new Error(`Index '${name}' on entity '${meta.className}': cannot combine \`expression\` with \`where\` — inline the WHERE clause into the \`expression\` escape hatch, or drop \`expression\` and use structured \`properties\` + \`where\`.`);
990
+ throw new MetadataError(`Index '${name}' on entity '${meta.className}': cannot combine \`expression\` with \`where\` — inline the WHERE clause into the \`expression\` escape hatch, or drop \`expression\` and use structured \`properties\` + \`where\`.`);
991
+ }
992
+ // `where` forces the `create unique index` form, and no dialect accepts `deferrable` on an index.
993
+ if (index.where != null && index.deferMode) {
994
+ throw new MetadataError(`Index '${name}' on entity '${meta.className}': cannot combine \`deferMode\` with \`where\` — partial unique indexes cannot be deferrable. On PostgreSQL, declare an exclusion constraint instead, e.g. \`exclude using btree (col with =) where (...) deferrable initially ${index.deferMode}\`.`);
991
995
  }
992
996
  const where = this.processIndexWhere(index.where, meta);
993
997
  const expression = this.processIndexExpression(name, index.expression, meta);
@@ -906,9 +906,13 @@ export class SchemaComparator {
906
906
  // expressions like check constraints might be normalized by the driver,
907
907
  // e.g. quotes might be added (https://github.com/mikro-orm/mikro-orm/issues/3827)
908
908
  const simplify = (str) => {
909
- return (str
909
+ if (str == null) {
910
+ return str;
911
+ }
912
+ return (this.#helper
913
+ .normalizeExpression(str)
910
914
  // lookbehind: only strip a real charset introducer, never an underscore inside a literal like 'a_b'
911
- ?.replace(/(?<![\w'])_\w+'(.*?)'/g, '$1')
915
+ .replace(/(?<![\w'])_\w+'(.*?)'/g, '$1')
912
916
  .replace(/!=/g, '<>')
913
917
  // `\b` keeps this from firing inside identifiers like `min(...)`
914
918
  .replace(/\bnot\s+in\s*\((.*?)\)/gi, '<> all (array[$1])')
@@ -163,6 +163,11 @@ export declare abstract class SchemaHelper {
163
163
  getNamespaces(connection: AbstractSqlConnection, ctx?: Transaction): Promise<string[]>;
164
164
  protected mapIndexes(indexes: IndexDef[]): Promise<IndexDef[]>;
165
165
  mapForeignKeys(fks: any[], tableName: string, schemaName?: string): Dictionary;
166
+ /**
167
+ * Rewrites the parts of a user-provided expression the database stores in a different form, so that
168
+ * `SchemaComparator.diffExpression()` compares it to the introspected definition on equal footing.
169
+ */
170
+ normalizeExpression(expr: string): string;
166
171
  /** Decodes the content of an introspected string literal, the inverse of `Platform.quoteDefaultValue()`. */
167
172
  unescapeDefault(val: string): string;
168
173
  normalizeDefaultValue(defaultValue: string | RawQueryFragment, length?: number, defaultValues?: Dictionary<string[]>): string | number;
@@ -718,6 +718,13 @@ export class SchemaHelper {
718
718
  return ret;
719
719
  }, {});
720
720
  }
721
+ /**
722
+ * Rewrites the parts of a user-provided expression the database stores in a different form, so that
723
+ * `SchemaComparator.diffExpression()` compares it to the introspected definition on equal footing.
724
+ */
725
+ normalizeExpression(expr) {
726
+ return expr;
727
+ }
721
728
  /** Decodes the content of an introspected string literal, the inverse of `Platform.quoteDefaultValue()`. */
722
729
  unescapeDefault(val) {
723
730
  return val.replaceAll("''", "'");