@mikro-orm/postgresql 7.0.0-dev.1 → 7.0.0-dev.100

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.
@@ -1,9 +1,6 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PostgreSqlSchemaHelper = void 0;
4
- const core_1 = require("@mikro-orm/core");
5
- const knex_1 = require("@mikro-orm/knex");
6
- class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
1
+ import { EnumType, Type, Utils, DeferMode } from '@mikro-orm/core';
2
+ import { SchemaHelper, } from '@mikro-orm/sql';
3
+ export class PostgreSqlSchemaHelper extends SchemaHelper {
7
4
  static DEFAULT_VALUES = {
8
5
  'now()': ['now()', 'current_timestamp'],
9
6
  'current_timestamp(?)': ['current_timestamp(?)'],
@@ -40,11 +37,11 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
40
37
  return res.map(row => row.schema_name);
41
38
  }
42
39
  getIgnoredNamespacesConditionSQL(column = 'schema_name') {
43
- /* istanbul ignore next */
44
40
  const ignored = [
45
41
  'information_schema',
46
42
  'tiger',
47
43
  'topology',
44
+ /* v8 ignore next */
48
45
  ...this.platform.getConfig().get('schemaGenerator').ignoreSchema ?? [],
49
46
  ].map(s => this.platform.quoteValue(s)).join(', ');
50
47
  const ignoredPrefixes = [
@@ -71,7 +68,9 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
71
68
  const table = schema.addTable(t.table_name, t.schema_name, t.table_comment);
72
69
  const pks = await this.getPrimaryKeys(connection, indexes[key], table.name, table.schema);
73
70
  const enums = this.getEnumDefinitions(checks[key] ?? []);
74
- table.init(columns[key], indexes[key], checks[key], pks, fks[key], enums);
71
+ if (columns[key]) {
72
+ table.init(columns[key], indexes[key], checks[key], pks, fks[key], enums);
73
+ }
75
74
  }
76
75
  }
77
76
  async getAllIndexes(connection, tables) {
@@ -91,13 +90,13 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
91
90
  primary: index.primary,
92
91
  };
93
92
  if (index.condeferrable) {
94
- indexDef.deferMode = index.condeferred ? core_1.DeferMode.INITIALLY_DEFERRED : core_1.DeferMode.INITIALLY_IMMEDIATE;
93
+ indexDef.deferMode = index.condeferred ? DeferMode.INITIALLY_DEFERRED : DeferMode.INITIALLY_IMMEDIATE;
95
94
  }
96
95
  if (index.index_def.some((col) => col.match(/[(): ,"'`]/)) || index.expression?.match(/ where /i)) {
97
96
  indexDef.expression = index.expression;
98
97
  }
99
98
  if (index.deferrable) {
100
- indexDef.deferMode = index.initially_deferred ? core_1.DeferMode.INITIALLY_DEFERRED : core_1.DeferMode.INITIALLY_IMMEDIATE;
99
+ indexDef.deferMode = index.initially_deferred ? DeferMode.INITIALLY_DEFERRED : DeferMode.INITIALLY_IMMEDIATE;
101
100
  }
102
101
  ret[key] ??= [];
103
102
  ret[key].push(indexDef);
@@ -166,7 +165,7 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
166
165
  comment: col.column_comment,
167
166
  };
168
167
  if (nativeEnums?.[column.type]) {
169
- column.mappedType = core_1.Type.getType(core_1.EnumType);
168
+ column.mappedType = Type.getType(EnumType);
170
169
  column.nativeEnumName = column.type;
171
170
  column.enumItems = nativeEnums[column.type]?.items;
172
171
  }
@@ -214,7 +213,7 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
214
213
  if (match) {
215
214
  return match[1];
216
215
  }
217
- /* istanbul ignore next */
216
+ /* v8 ignore next */
218
217
  switch (value) {
219
218
  case 'r': return 'RESTRICT';
220
219
  case 'c': return 'CASCADE';
@@ -228,7 +227,7 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
228
227
  fk.update_rule = mapReferentialIntegrity(fk.update_rule, fk.constraint_def);
229
228
  fk.delete_rule = mapReferentialIntegrity(fk.delete_rule, fk.constraint_def);
230
229
  if (fk.condeferrable) {
231
- fk.defer_mode = fk.condeferred ? core_1.DeferMode.INITIALLY_DEFERRED : core_1.DeferMode.INITIALLY_IMMEDIATE;
230
+ fk.defer_mode = fk.condeferred ? DeferMode.INITIALLY_DEFERRED : DeferMode.INITIALLY_IMMEDIATE;
232
231
  }
233
232
  const key = this.getTableKey(fk);
234
233
  ret[key] ??= [];
@@ -241,7 +240,7 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
241
240
  return ret;
242
241
  }
243
242
  async getNativeEnumDefinitions(connection, schemas) {
244
- const uniqueSchemas = core_1.Utils.unique(schemas);
243
+ const uniqueSchemas = Utils.unique(schemas);
245
244
  const res = await connection.execute(`select t.typname as enum_name, n.nspname as schema_name, array_agg(e.enumlabel order by e.enumsortorder) as enum_value
246
245
  from pg_type t
247
246
  join pg_enum e on t.oid = e.enumtypid
@@ -253,10 +252,14 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
253
252
  if (row.schema_name && row.schema_name !== this.platform.getDefaultSchemaName()) {
254
253
  name = row.schema_name + '.' + name;
255
254
  }
255
+ let items = row.enum_value;
256
+ if (!Array.isArray(items)) {
257
+ items = this.platform.unmarshallArray(row.enum_value);
258
+ }
256
259
  o[name] = {
257
260
  name: row.enum_name,
258
261
  schema: row.schema_name,
259
- items: this.platform.unmarshallArray(row.enum_value),
262
+ items,
260
263
  };
261
264
  return o;
262
265
  }, {});
@@ -302,7 +305,7 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
302
305
  if (item.columnName && m1 && m2) {
303
306
  const m3 = m2[1].match(/('[^']*'::text)/g);
304
307
  let items;
305
- /* istanbul ignore else */
308
+ /* v8 ignore next */
306
309
  if (m3) {
307
310
  items = m3.map((item) => item.trim().match(/^\(?'(.*)'/)?.[1]);
308
311
  }
@@ -320,7 +323,8 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
320
323
  }, {});
321
324
  }
322
325
  createTableColumn(column, table) {
323
- const compositePK = table.getPrimaryKey()?.composite;
326
+ const pk = table.getPrimaryKey();
327
+ const compositePK = pk?.composite;
324
328
  const primaryKey = !this.hasNonDefaultPrimaryKeyName(table);
325
329
  const col = [this.quote(column.name)];
326
330
  if (column.autoincrement && !column.generated && !compositePK) {
@@ -347,14 +351,14 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
347
351
  columnType += ` generated always as ${column.generated}`;
348
352
  }
349
353
  col.push(columnType);
350
- core_1.Utils.runIfNotEmpty(() => col.push('null'), column.nullable);
351
- core_1.Utils.runIfNotEmpty(() => col.push('not null'), !column.nullable);
354
+ Utils.runIfNotEmpty(() => col.push('null'), column.nullable);
355
+ Utils.runIfNotEmpty(() => col.push('not null'), !column.nullable);
352
356
  }
353
- if (column.autoincrement && !column.generated && !compositePK) {
354
- core_1.Utils.runIfNotEmpty(() => col.push('primary key'), primaryKey && column.primary);
357
+ if (column.autoincrement && !compositePK) {
358
+ Utils.runIfNotEmpty(() => col.push('primary key'), primaryKey && column.primary);
355
359
  }
356
360
  const useDefault = column.default != null && column.default !== 'null' && !column.autoincrement;
357
- core_1.Utils.runIfNotEmpty(() => col.push(`default ${column.default}`), useDefault);
361
+ Utils.runIfNotEmpty(() => col.push(`default ${column.default}`), useDefault);
358
362
  return col.join(' ');
359
363
  }
360
364
  getPreAlterTable(tableDiff, safe) {
@@ -362,11 +366,11 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
362
366
  const parts = tableDiff.name.split('.');
363
367
  const tableName = parts.pop();
364
368
  const schemaName = parts.pop();
365
- /* istanbul ignore next */
369
+ /* v8 ignore next */
366
370
  const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
367
371
  const quotedName = this.quote(name);
368
372
  // detect that the column was an enum before and remove the check constraint in such case here
369
- const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof core_1.EnumType);
373
+ const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof EnumType);
370
374
  for (const col of changedEnums) {
371
375
  if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.fromColumn.default) {
372
376
  ret.push(`alter table ${quotedName} alter column "${col.column.name}" drop default`);
@@ -401,11 +405,11 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
401
405
  const parts = tableDiff.name.split('.');
402
406
  const tableName = parts.pop();
403
407
  const schemaName = parts.pop();
404
- /* istanbul ignore next */
408
+ /* v8 ignore next */
405
409
  const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
406
410
  const quotedName = this.quote(name);
407
411
  // detect that the column was an enum before and remove the check constraint in such a case here
408
- const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof core_1.EnumType);
412
+ const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof EnumType);
409
413
  for (const col of changedEnums) {
410
414
  if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.column.default) {
411
415
  ret.push(`alter table ${quotedName} alter column "${col.column.name}" set default ${col.column.default}`);
@@ -421,9 +425,8 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
421
425
  }
422
426
  getAlterColumnAutoincrement(tableName, column, schemaName) {
423
427
  const ret = [];
424
- /* istanbul ignore next */
428
+ /* v8 ignore next */
425
429
  const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
426
- /* istanbul ignore else */
427
430
  if (column.autoincrement) {
428
431
  const seqName = this.platform.getIndexName(tableName, [column.name], 'sequence');
429
432
  ret.push(`create sequence if not exists ${this.quote(seqName)}`);
@@ -543,4 +546,3 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
543
546
  return +match[2];
544
547
  }
545
548
  }
546
- exports.PostgreSqlSchemaHelper = PostgreSqlSchemaHelper;
package/README.md CHANGED
@@ -11,7 +11,6 @@ TypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-or
11
11
  [![Chat on discord](https://img.shields.io/discord/1214904142443839538?label=discord&color=blue)](https://discord.gg/w8bjxFHS7X)
12
12
  [![Downloads](https://img.shields.io/npm/dm/@mikro-orm/core.svg)](https://www.npmjs.com/package/@mikro-orm/core)
13
13
  [![Coverage Status](https://img.shields.io/coveralls/mikro-orm/mikro-orm.svg)](https://coveralls.io/r/mikro-orm/mikro-orm?branch=master)
14
- [![Maintainability](https://api.codeclimate.com/v1/badges/27999651d3adc47cfa40/maintainability)](https://codeclimate.com/github/mikro-orm/mikro-orm/maintainability)
15
14
  [![Build Status](https://github.com/mikro-orm/mikro-orm/workflows/tests/badge.svg?branch=master)](https://github.com/mikro-orm/mikro-orm/actions?workflow=tests)
16
15
 
17
16
  ## 🤔 Unit of What?
@@ -141,7 +140,7 @@ There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit m
141
140
  - [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)
142
141
  - [Filters](https://mikro-orm.io/docs/filters)
143
142
  - [Using `QueryBuilder`](https://mikro-orm.io/docs/query-builder)
144
- - [Preloading Deeply Nested Structures via populate](https://mikro-orm.io/docs/nested-populate)
143
+ - [Populating relations](https://mikro-orm.io/docs/populating-relations)
145
144
  - [Property Validation](https://mikro-orm.io/docs/property-validation)
146
145
  - [Lifecycle Hooks](https://mikro-orm.io/docs/events#hooks)
147
146
  - [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)
@@ -382,6 +381,8 @@ See also the list of contributors who [participated](https://github.com/mikro-or
382
381
 
383
382
  Please ⭐️ this repository if this project helped you!
384
383
 
384
+ > If you'd like to support my open-source work, consider sponsoring me directly at [github.com/sponsors/b4nan](https://github.com/sponsors/b4nan).
385
+
385
386
  ## 📝 License
386
387
 
387
388
  Copyright © 2018 [Martin Adámek](https://github.com/b4nan).
package/index.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- export * from '@mikro-orm/knex';
2
- export * from './PostgreSqlConnection';
3
- export * from './PostgreSqlDriver';
4
- export * from './PostgreSqlPlatform';
5
- export * from './PostgreSqlSchemaHelper';
6
- export * from './PostgreSqlExceptionConverter';
7
- export * from './types';
8
- export { PostgreSqlMikroORM as MikroORM, PostgreSqlOptions as Options, definePostgreSqlConfig as defineConfig, } from './PostgreSqlMikroORM';
1
+ export * from '@mikro-orm/sql';
2
+ export * from './PostgreSqlConnection.js';
3
+ export * from './PostgreSqlDriver.js';
4
+ export * from './PostgreSqlPlatform.js';
5
+ export * from './PostgreSqlSchemaHelper.js';
6
+ export * from './PostgreSqlExceptionConverter.js';
7
+ export * from './types/index.js';
8
+ export { PostgreSqlMikroORM as MikroORM, type PostgreSqlOptions as Options, definePostgreSqlConfig as defineConfig, } from './PostgreSqlMikroORM.js';
9
+ export { raw } from './raw.js';
package/index.js CHANGED
@@ -1,28 +1,9 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.defineConfig = exports.MikroORM = void 0;
18
- /* istanbul ignore file */
19
- __exportStar(require("@mikro-orm/knex"), exports);
20
- __exportStar(require("./PostgreSqlConnection"), exports);
21
- __exportStar(require("./PostgreSqlDriver"), exports);
22
- __exportStar(require("./PostgreSqlPlatform"), exports);
23
- __exportStar(require("./PostgreSqlSchemaHelper"), exports);
24
- __exportStar(require("./PostgreSqlExceptionConverter"), exports);
25
- __exportStar(require("./types"), exports);
26
- var PostgreSqlMikroORM_1 = require("./PostgreSqlMikroORM");
27
- Object.defineProperty(exports, "MikroORM", { enumerable: true, get: function () { return PostgreSqlMikroORM_1.PostgreSqlMikroORM; } });
28
- Object.defineProperty(exports, "defineConfig", { enumerable: true, get: function () { return PostgreSqlMikroORM_1.definePostgreSqlConfig; } });
1
+ export * from '@mikro-orm/sql';
2
+ export * from './PostgreSqlConnection.js';
3
+ export * from './PostgreSqlDriver.js';
4
+ export * from './PostgreSqlPlatform.js';
5
+ export * from './PostgreSqlSchemaHelper.js';
6
+ export * from './PostgreSqlExceptionConverter.js';
7
+ export * from './types/index.js';
8
+ export { PostgreSqlMikroORM as MikroORM, definePostgreSqlConfig as defineConfig, } from './PostgreSqlMikroORM.js';
9
+ export { raw } from './raw.js';
package/package.json CHANGED
@@ -1,19 +1,11 @@
1
1
  {
2
2
  "name": "@mikro-orm/postgresql",
3
- "version": "7.0.0-dev.1",
3
+ "type": "module",
4
+ "version": "7.0.0-dev.100",
4
5
  "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
- "main": "index.js",
6
- "module": "index.mjs",
7
- "typings": "index.d.ts",
8
6
  "exports": {
9
7
  "./package.json": "./package.json",
10
- ".": {
11
- "import": {
12
- "types": "./index.d.ts",
13
- "default": "./index.mjs"
14
- },
15
- "require": "./index.js"
16
- }
8
+ ".": "./index.js"
17
9
  },
18
10
  "repository": {
19
11
  "type": "git",
@@ -46,10 +38,10 @@
46
38
  },
47
39
  "homepage": "https://mikro-orm.io",
48
40
  "engines": {
49
- "node": ">= 22.11.0"
41
+ "node": ">= 22.17.0"
50
42
  },
51
43
  "scripts": {
52
- "build": "yarn clean && yarn compile && yarn copy && yarn run -T gen-esm-wrapper index.js index.mjs",
44
+ "build": "yarn clean && yarn compile && yarn copy",
53
45
  "clean": "yarn run -T rimraf ./dist",
54
46
  "compile": "yarn run -T tsc -p tsconfig.build.json",
55
47
  "copy": "node ../../scripts/copy.mjs"
@@ -58,18 +50,19 @@
58
50
  "access": "public"
59
51
  },
60
52
  "dependencies": {
61
- "@mikro-orm/knex": "7.0.0-dev.1",
62
- "pg": "8.13.1",
63
- "postgres-array": "3.0.2",
53
+ "@mikro-orm/sql": "7.0.0-dev.100",
54
+ "pg": "8.16.3",
55
+ "pg-cursor": "2.15.3",
56
+ "postgres-array": "3.0.4",
64
57
  "postgres-date": "2.1.0",
65
58
  "postgres-interval": "4.0.2"
66
59
  },
67
60
  "devDependencies": {
68
- "@mikro-orm/core": "^6.4.5",
69
- "kysely": "https://pkg.pr.new/kysely-org/kysely/kysely@2b7007e"
61
+ "@mikro-orm/core": "^6.6.2",
62
+ "kysely": "0.28.9"
70
63
  },
71
64
  "peerDependencies": {
72
- "@mikro-orm/core": "7.0.0-dev.1",
65
+ "@mikro-orm/core": "7.0.0-dev.100",
73
66
  "kysely": "*"
74
67
  }
75
68
  }
package/raw.d.ts ADDED
@@ -0,0 +1,58 @@
1
+ import { type AnyString, type Dictionary, type EntityKey, type RawQueryFragment, type QueryBuilder } from '@mikro-orm/sql';
2
+ import type { SelectQueryBuilder } from 'kysely';
3
+ /**
4
+ * Creates raw SQL query fragment that can be assigned to a property or part of a filter. This fragment is represented
5
+ * by `RawQueryFragment` class instance that can be serialized to a string, so it can be used both as an object value
6
+ * and key. When serialized, the fragment key gets cached and only such cached key will be recognized by the ORM.
7
+ * This adds a runtime safety to the raw query fragments.
8
+ *
9
+ * > **`raw()` helper is required since v6 to use a raw fragment in your query, both through EntityManager and QueryBuilder.**
10
+ *
11
+ * ```ts
12
+ * // as a value
13
+ * await em.find(User, { time: raw('now()') });
14
+ *
15
+ * // as a key
16
+ * await em.find(User, { [raw('lower(name)')]: name.toLowerCase() });
17
+ *
18
+ * // value can be empty array
19
+ * await em.find(User, { [raw('(select 1 = 1)')]: [] });
20
+ * ```
21
+ *
22
+ * The `raw` helper supports several signatures, you can pass in a callback that receives the current property alias:
23
+ *
24
+ * ```ts
25
+ * await em.find(User, { [raw(alias => `lower(${alias}.name)`)]: name.toLowerCase() });
26
+ * ```
27
+ *
28
+ * You can also use the `sql` tagged template function, which works the same, but supports only the simple string signature:
29
+ *
30
+ * ```ts
31
+ * await em.find(User, { [sql`lower(name)`]: name.toLowerCase() });
32
+ * ```
33
+ *
34
+ * When using inside filters, you might have to use a callback signature to create new raw instance for every filter usage.
35
+ *
36
+ * ```ts
37
+ * @Filter({ name: 'long', cond: () => ({ [raw('length(perex)')]: { $gt: 10000 } }) })
38
+ * ```
39
+ *
40
+ * The `raw` helper can be used within indexes and uniques to write database-agnostic SQL expressions. In that case, you can use `'??'` to tag your database identifiers (table name, column names, index name, ...) inside your expression, and pass those identifiers as a second parameter to the `raw` helper. Internally, those will automatically be quoted according to the database in use:
41
+ *
42
+ * ```ts
43
+ * // On postgres, will produce: create index "index custom_idx_on_name" on "library.author" ("country")
44
+ * // On mysql, will produce: create index `index custom_idx_on_name` on `library.author` (`country`)
45
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => raw(`create index ?? on ?? (??)`, ['custom_idx_on_name', table, columns.name]) })
46
+ * @Entity({ schema: 'library' })
47
+ * export class Author { ... }
48
+ * ```
49
+ *
50
+ * You can also use the `quote` tag function to write database-agnostic SQL expressions. The end-result is the same as using the `raw` function regarding database identifiers quoting, only to have a more elegant expression syntax:
51
+ *
52
+ * ```ts
53
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => quote`create index ${'custom_idx_on_name'} on ${table} (${columns.name})` })
54
+ * @Entity({ schema: 'library' })
55
+ * export class Author { ... }
56
+ * ```
57
+ */
58
+ export declare function raw<T extends object = any, R = any>(sql: SelectQueryBuilder<any, any, any> | QueryBuilder<T> | EntityKey<T> | EntityKey<T>[] | AnyString | ((alias: string) => string) | RawQueryFragment, params?: readonly unknown[] | Dictionary<unknown>): NoInfer<R>;
package/raw.js ADDED
@@ -0,0 +1,64 @@
1
+ import { raw as raw_, Utils } from '@mikro-orm/sql';
2
+ /**
3
+ * Creates raw SQL query fragment that can be assigned to a property or part of a filter. This fragment is represented
4
+ * by `RawQueryFragment` class instance that can be serialized to a string, so it can be used both as an object value
5
+ * and key. When serialized, the fragment key gets cached and only such cached key will be recognized by the ORM.
6
+ * This adds a runtime safety to the raw query fragments.
7
+ *
8
+ * > **`raw()` helper is required since v6 to use a raw fragment in your query, both through EntityManager and QueryBuilder.**
9
+ *
10
+ * ```ts
11
+ * // as a value
12
+ * await em.find(User, { time: raw('now()') });
13
+ *
14
+ * // as a key
15
+ * await em.find(User, { [raw('lower(name)')]: name.toLowerCase() });
16
+ *
17
+ * // value can be empty array
18
+ * await em.find(User, { [raw('(select 1 = 1)')]: [] });
19
+ * ```
20
+ *
21
+ * The `raw` helper supports several signatures, you can pass in a callback that receives the current property alias:
22
+ *
23
+ * ```ts
24
+ * await em.find(User, { [raw(alias => `lower(${alias}.name)`)]: name.toLowerCase() });
25
+ * ```
26
+ *
27
+ * You can also use the `sql` tagged template function, which works the same, but supports only the simple string signature:
28
+ *
29
+ * ```ts
30
+ * await em.find(User, { [sql`lower(name)`]: name.toLowerCase() });
31
+ * ```
32
+ *
33
+ * When using inside filters, you might have to use a callback signature to create new raw instance for every filter usage.
34
+ *
35
+ * ```ts
36
+ * @Filter({ name: 'long', cond: () => ({ [raw('length(perex)')]: { $gt: 10000 } }) })
37
+ * ```
38
+ *
39
+ * The `raw` helper can be used within indexes and uniques to write database-agnostic SQL expressions. In that case, you can use `'??'` to tag your database identifiers (table name, column names, index name, ...) inside your expression, and pass those identifiers as a second parameter to the `raw` helper. Internally, those will automatically be quoted according to the database in use:
40
+ *
41
+ * ```ts
42
+ * // On postgres, will produce: create index "index custom_idx_on_name" on "library.author" ("country")
43
+ * // On mysql, will produce: create index `index custom_idx_on_name` on `library.author` (`country`)
44
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => raw(`create index ?? on ?? (??)`, ['custom_idx_on_name', table, columns.name]) })
45
+ * @Entity({ schema: 'library' })
46
+ * export class Author { ... }
47
+ * ```
48
+ *
49
+ * You can also use the `quote` tag function to write database-agnostic SQL expressions. The end-result is the same as using the `raw` function regarding database identifiers quoting, only to have a more elegant expression syntax:
50
+ *
51
+ * ```ts
52
+ * @Index({ name: 'custom_idx_on_name', expression: (table, columns) => quote`create index ${'custom_idx_on_name'} on ${table} (${columns.name})` })
53
+ * @Entity({ schema: 'library' })
54
+ * export class Author { ... }
55
+ * ```
56
+ */
57
+ export function raw(sql, params) {
58
+ if (Utils.isObject(sql) && 'compile' in sql) {
59
+ const query = sql.compile();
60
+ const processed = query.sql.replaceAll(/\$\d+/g, '?');
61
+ return raw_(processed, query.parameters);
62
+ }
63
+ return raw_(sql, params);
64
+ }
@@ -1,5 +1,5 @@
1
1
  import { Type, type TransformContext, type RawQueryFragment } from '@mikro-orm/core';
2
- import type { PostgreSqlPlatform } from '../PostgreSqlPlatform';
2
+ import type { PostgreSqlPlatform } from '../PostgreSqlPlatform.js';
3
3
  type FullTextWeight = 'A' | 'B' | 'C' | 'D';
4
4
  export type WeightedFullTextValue = {
5
5
  [K in FullTextWeight]?: string | null;
@@ -1,8 +1,5 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FullTextType = void 0;
4
- const core_1 = require("@mikro-orm/core");
5
- class FullTextType extends core_1.Type {
1
+ import { raw, Type } from '@mikro-orm/core';
2
+ export class FullTextType extends Type {
6
3
  regconfig;
7
4
  constructor(regconfig = 'simple') {
8
5
  super();
@@ -54,10 +51,9 @@ class FullTextType extends core_1.Type {
54
51
  return null;
55
52
  }
56
53
  // Join all the `setweight` parts using the PostgreSQL tsvector `||` concatenation operator
57
- return (0, core_1.raw)(sqlParts.join(' || '), bindings);
54
+ return raw(sqlParts.join(' || '), bindings);
58
55
  }
59
56
  // if it's not an object, it is expected to be string which does not have to be wrapped in setweight.
60
- return (0, core_1.raw)('to_tsvector(?, ?)', [this.regconfig, value]);
57
+ return raw('to_tsvector(?, ?)', [this.regconfig, value]);
61
58
  }
62
59
  }
63
- exports.FullTextType = FullTextType;
package/types/index.d.ts CHANGED
@@ -1 +1 @@
1
- export * from './FullTextType';
1
+ export * from './FullTextType.js';
package/types/index.js CHANGED
@@ -1,17 +1 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./FullTextType"), exports);
1
+ export * from './FullTextType.js';