@mikro-orm/postgresql 7.0.0-dev.9 → 7.0.0-dev.91

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,5 +1,5 @@
1
- import TypeOverrides from 'pg/lib/type-overrides.js';
2
- import { Pool } from 'pg';
1
+ import { Pool, TypeOverrides } from 'pg';
2
+ import Cursor from 'pg-cursor';
3
3
  import { PostgresDialect } from 'kysely';
4
4
  import array from 'postgres-array';
5
5
  import { AbstractSqlConnection, Utils } from '@mikro-orm/knex';
@@ -8,6 +8,7 @@ export class PostgreSqlConnection extends AbstractSqlConnection {
8
8
  const options = this.mapOptions(overrides);
9
9
  return new PostgresDialect({
10
10
  pool: new Pool(options),
11
+ cursor: Cursor,
11
12
  onCreateConnection: this.options.onCreateConnection ?? this.config.get('onCreateConnection'),
12
13
  });
13
14
  }
@@ -1,8 +1,8 @@
1
1
  import { ExceptionConverter, type Dictionary, type DriverException } from '@mikro-orm/core';
2
2
  export declare class PostgreSqlExceptionConverter extends ExceptionConverter {
3
3
  /**
4
- * @link http://www.postgresql.org/docs/9.4/static/errcodes-appendix.html
5
- * @link https://github.com/doctrine/dbal/blob/master/src/Driver/AbstractPostgreSQLDriver.php
4
+ * @see http://www.postgresql.org/docs/9.4/static/errcodes-appendix.html
5
+ * @see https://github.com/doctrine/dbal/blob/master/src/Driver/AbstractPostgreSQLDriver.php
6
6
  */
7
7
  convertException(exception: Error & Dictionary): DriverException;
8
8
  }
@@ -1,8 +1,8 @@
1
1
  import { DeadlockException, ExceptionConverter, ForeignKeyConstraintViolationException, InvalidFieldNameException, NonUniqueFieldNameException, NotNullConstraintViolationException, SyntaxErrorException, TableExistsException, TableNotFoundException, UniqueConstraintViolationException, CheckConstraintViolationException, } from '@mikro-orm/core';
2
2
  export class PostgreSqlExceptionConverter extends ExceptionConverter {
3
3
  /**
4
- * @link http://www.postgresql.org/docs/9.4/static/errcodes-appendix.html
5
- * @link https://github.com/doctrine/dbal/blob/master/src/Driver/AbstractPostgreSQLDriver.php
4
+ * @see http://www.postgresql.org/docs/9.4/static/errcodes-appendix.html
5
+ * @see https://github.com/doctrine/dbal/blob/master/src/Driver/AbstractPostgreSQLDriver.php
6
6
  */
7
7
  convertException(exception) {
8
8
  if (exception.detail?.toString().trim()) {
@@ -11,7 +11,7 @@ export class PostgreSqlExceptionConverter extends ExceptionConverter {
11
11
  if (exception.hint?.toString().trim()) {
12
12
  exception.message += '\n - hint: ' + exception.hint;
13
13
  }
14
- /* v8 ignore start */
14
+ /* v8 ignore next */
15
15
  switch (exception.code) {
16
16
  case '40001':
17
17
  case '40P01':
@@ -42,7 +42,6 @@ export class PostgreSqlExceptionConverter extends ExceptionConverter {
42
42
  case '42P07':
43
43
  return new TableExistsException(exception);
44
44
  }
45
- /* v8 ignore stop */
46
45
  return super.convertException(exception);
47
46
  }
48
47
  }
@@ -1,19 +1,18 @@
1
- import { MikroORM, type Options, type IDatabaseDriver, type EntityManager, type EntityManagerType } from '@mikro-orm/core';
2
- import { PostgreSqlDriver } from './PostgreSqlDriver.js';
1
+ import { type AnyEntity, type EntityClass, type EntitySchema, MikroORM, type Options, type IDatabaseDriver, type EntityManager, type EntityManagerType } from '@mikro-orm/core';
3
2
  import type { SqlEntityManager } from '@mikro-orm/knex';
3
+ import { PostgreSqlDriver } from './PostgreSqlDriver.js';
4
+ export type PostgreSqlOptions<EM extends SqlEntityManager<PostgreSqlDriver> = SqlEntityManager<PostgreSqlDriver>, Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]> = Options<PostgreSqlDriver, EM, Entities>;
5
+ export declare function definePostgreSqlConfig<EM extends SqlEntityManager<PostgreSqlDriver> = SqlEntityManager<PostgreSqlDriver>, Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]>(options: Options<PostgreSqlDriver, EM, Entities>): Options<PostgreSqlDriver, EM, Entities>;
4
6
  /**
5
7
  * @inheritDoc
6
8
  */
7
- export declare class PostgreSqlMikroORM<EM extends EntityManager = SqlEntityManager> extends MikroORM<PostgreSqlDriver, EM> {
8
- private static DRIVER;
9
+ export declare class PostgreSqlMikroORM<EM extends SqlEntityManager<PostgreSqlDriver> = SqlEntityManager<PostgreSqlDriver>, Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]> extends MikroORM<PostgreSqlDriver, EM, Entities> {
9
10
  /**
10
11
  * @inheritDoc
11
12
  */
12
- static init<D extends IDatabaseDriver = PostgreSqlDriver, EM extends EntityManager = D[typeof EntityManagerType] & EntityManager>(options?: Options<D, EM>): Promise<MikroORM<D, EM>>;
13
+ static init<D extends IDatabaseDriver = PostgreSqlDriver, EM extends EntityManager<D> = D[typeof EntityManagerType] & EntityManager<D>, Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]>(options: Options<D, EM, Entities>): Promise<MikroORM<D, EM, Entities>>;
13
14
  /**
14
15
  * @inheritDoc
15
16
  */
16
- static initSync<D extends IDatabaseDriver = PostgreSqlDriver, EM extends EntityManager = D[typeof EntityManagerType] & EntityManager>(options: Options<D, EM>): MikroORM<D, EM>;
17
+ constructor(options: Options<PostgreSqlDriver, EM, Entities>);
17
18
  }
18
- export type PostgreSqlOptions = Options<PostgreSqlDriver>;
19
- export declare function definePostgreSqlConfig(options: PostgreSqlOptions): Options<PostgreSqlDriver, SqlEntityManager<PostgreSqlDriver> & EntityManager<IDatabaseDriver<import("@mikro-orm/core").Connection>>>;
@@ -1,24 +1,22 @@
1
1
  import { defineConfig, MikroORM, } from '@mikro-orm/core';
2
2
  import { PostgreSqlDriver } from './PostgreSqlDriver.js';
3
+ export function definePostgreSqlConfig(options) {
4
+ return defineConfig({ driver: PostgreSqlDriver, ...options });
5
+ }
3
6
  /**
4
7
  * @inheritDoc
5
8
  */
6
9
  export class PostgreSqlMikroORM extends MikroORM {
7
- static DRIVER = PostgreSqlDriver;
8
10
  /**
9
11
  * @inheritDoc
10
12
  */
11
13
  static async init(options) {
12
- return super.init(options);
14
+ return super.init(definePostgreSqlConfig(options));
13
15
  }
14
16
  /**
15
17
  * @inheritDoc
16
18
  */
17
- static initSync(options) {
18
- return super.initSync(options);
19
+ constructor(options) {
20
+ super(definePostgreSqlConfig(options));
19
21
  }
20
22
  }
21
- /* v8 ignore next 3 */
22
- export function definePostgreSqlConfig(options) {
23
- return defineConfig({ driver: PostgreSqlDriver, ...options });
24
- }
@@ -1,5 +1,5 @@
1
1
  import { type IPostgresInterval } from 'postgres-interval';
2
- import { type IsolationLevel, type EntityProperty, Type, type SimpleColumnMeta, type Configuration } from '@mikro-orm/core';
2
+ import { type Configuration, type EntityProperty, type IsolationLevel, type SimpleColumnMeta, Type } from '@mikro-orm/core';
3
3
  import { AbstractSqlPlatform, type IndexDef, PostgreSqlNativeQueryBuilder } from '@mikro-orm/knex';
4
4
  import { PostgreSqlSchemaHelper } from './PostgreSqlSchemaHelper.js';
5
5
  import { PostgreSqlExceptionConverter } from './PostgreSqlExceptionConverter.js';
@@ -81,7 +81,9 @@ export declare class PostgreSqlPlatform extends AbstractSqlPlatform {
81
81
  getJsonDeclarationSQL(): string;
82
82
  getSearchJsonPropertyKey(path: string[], type: string | undefined | Type, aliased: boolean, value?: unknown): string;
83
83
  getJsonIndexDefinition(index: IndexDef): string[];
84
- quoteIdentifier(id: string, quote?: string): string;
84
+ quoteIdentifier(id: string | {
85
+ toString: () => string;
86
+ }, quote?: string): string;
85
87
  escape(value: any): string;
86
88
  private pad;
87
89
  /** @internal */
@@ -1,7 +1,7 @@
1
1
  import { Client } from 'pg';
2
2
  import parseDate from 'postgres-date';
3
3
  import PostgresInterval from 'postgres-interval';
4
- import { raw, ALIAS_REPLACEMENT, Utils, Type, RawQueryFragment, } from '@mikro-orm/core';
4
+ import { ALIAS_REPLACEMENT, ARRAY_OPERATORS, raw, RawQueryFragment, Type, Utils, } from '@mikro-orm/core';
5
5
  import { AbstractSqlPlatform, PostgreSqlNativeQueryBuilder } from '@mikro-orm/knex';
6
6
  import { PostgreSqlSchemaHelper } from './PostgreSqlSchemaHelper.js';
7
7
  import { PostgreSqlExceptionConverter } from './PostgreSqlExceptionConverter.js';
@@ -62,7 +62,7 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
62
62
  return 'int';
63
63
  }
64
64
  getBigIntTypeDeclarationSQL(column) {
65
- /* v8 ignore next 3 */
65
+ /* v8 ignore next */
66
66
  if (column.autoincrement) {
67
67
  return `bigserial`;
68
68
  }
@@ -78,7 +78,7 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
78
78
  if (prop.customType instanceof FullTextType) {
79
79
  return `:column: @@ plainto_tsquery('${prop.customType.regconfig}', :query)`;
80
80
  }
81
- /* v8 ignore next 3 */
81
+ /* v8 ignore next */
82
82
  if (prop.columnTypes[0] === 'tsvector') {
83
83
  return `:column: @@ plainto_tsquery('simple', :query)`;
84
84
  }
@@ -132,13 +132,13 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
132
132
  }
133
133
  }
134
134
  getRegExpOperator(val, flags) {
135
- /* v8 ignore next 3 */
135
+ /* v8 ignore next */
136
136
  if ((val instanceof RegExp && val.flags.includes('i')) || flags?.includes('i')) {
137
137
  return '~*';
138
138
  }
139
139
  return '~';
140
140
  }
141
- /* v8 ignore next 8 */
141
+ /* v8 ignore next */
142
142
  getRegExpValue(val) {
143
143
  if (val.flags.includes('i')) {
144
144
  return { $re: val.source, $flags: val.flags };
@@ -158,11 +158,11 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
158
158
  return 'double precision';
159
159
  }
160
160
  getEnumTypeDeclarationSQL(column) {
161
- /* v8 ignore next 3 */
161
+ /* v8 ignore next */
162
162
  if (column.nativeEnumName) {
163
163
  return column.nativeEnumName;
164
164
  }
165
- if (column.items?.every(item => Utils.isString(item))) {
165
+ if (column.items?.every(item => typeof item === 'string')) {
166
166
  return 'text';
167
167
  }
168
168
  return `smallint`;
@@ -231,7 +231,7 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
231
231
  const cast = (key) => raw(type in types ? `(${key})::${types[type]}` : key);
232
232
  let lastOperator = '->>';
233
233
  // force `->` for operator payloads with array values
234
- if (Utils.isPlainObject(value) && Object.keys(value).every(key => Utils.isArrayOperator(key) && Array.isArray(value[key]))) {
234
+ if (Utils.isPlainObject(value) && Object.keys(value).every(key => ARRAY_OPERATORS.includes(key) && Array.isArray(value[key]))) {
235
235
  lastOperator = '->';
236
236
  }
237
237
  if (path.length === 0) {
@@ -258,7 +258,7 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
258
258
  if (RawQueryFragment.isKnownFragment(id)) {
259
259
  return super.quoteIdentifier(id);
260
260
  }
261
- return `${quote}${id.replace('.', `${quote}.${quote}`)}${quote}`;
261
+ return `${quote}${id.toString().replace('.', `${quote}.${quote}`)}${quote}`;
262
262
  }
263
263
  escape(value) {
264
264
  if (typeof value === 'string') {
@@ -270,6 +270,9 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
270
270
  if (ArrayBuffer.isView(value)) {
271
271
  return `E'\\\\x${value.toString('hex')}'`;
272
272
  }
273
+ if (Array.isArray(value)) {
274
+ return value.map(v => this.escape(v)).join(', ');
275
+ }
273
276
  return super.escape(value);
274
277
  }
275
278
  pad(number, digits) {
@@ -283,14 +286,14 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
283
286
  let offset = -date.getTimezoneOffset();
284
287
  let year = date.getFullYear();
285
288
  const isBCYear = year < 1;
286
- /* v8 ignore next 3 */
289
+ /* v8 ignore next */
287
290
  if (isBCYear) {
288
291
  year = Math.abs(year) + 1;
289
292
  }
290
293
  const datePart = `${this.pad(year, 4)}-${this.pad(date.getMonth() + 1, 2)}-${this.pad(date.getDate(), 2)}`;
291
294
  const timePart = `${this.pad(date.getHours(), 2)}:${this.pad(date.getMinutes(), 2)}:${this.pad(date.getSeconds(), 2)}.${this.pad(date.getMilliseconds(), 3)}`;
292
295
  let ret = `${datePart}T${timePart}`;
293
- /* v8 ignore next 4 */
296
+ /* v8 ignore next */
294
297
  if (offset < 0) {
295
298
  ret += '-';
296
299
  offset *= -1;
@@ -299,7 +302,7 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
299
302
  ret += '+';
300
303
  }
301
304
  ret += this.pad(Math.floor(offset / 60), 2) + ':' + this.pad(offset % 60, 2);
302
- /* v8 ignore next 3 */
305
+ /* v8 ignore next */
303
306
  if (isBCYear) {
304
307
  ret += ' BC';
305
308
  }
@@ -377,13 +380,13 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
377
380
  if (typeof value === 'string' && value.charAt(10) === 'T') {
378
381
  return new Date(value);
379
382
  }
380
- /* v8 ignore next 3 */
383
+ /* v8 ignore next */
381
384
  if (typeof value === 'number') {
382
385
  return new Date(value);
383
386
  }
384
387
  // @ts-ignore fix wrong type resolution during build
385
388
  const parsed = parseDate(value);
386
- /* v8 ignore next 3 */
389
+ /* v8 ignore next */
387
390
  if (parsed === null) {
388
391
  return value;
389
392
  }
@@ -68,7 +68,9 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
68
68
  const table = schema.addTable(t.table_name, t.schema_name, t.table_comment);
69
69
  const pks = await this.getPrimaryKeys(connection, indexes[key], table.name, table.schema);
70
70
  const enums = this.getEnumDefinitions(checks[key] ?? []);
71
- 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
+ }
72
74
  }
73
75
  }
74
76
  async getAllIndexes(connection, tables) {
@@ -211,7 +213,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
211
213
  if (match) {
212
214
  return match[1];
213
215
  }
214
- /* v8 ignore next 8 */
216
+ /* v8 ignore next */
215
217
  switch (value) {
216
218
  case 'r': return 'RESTRICT';
217
219
  case 'c': return 'CASCADE';
@@ -303,7 +305,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
303
305
  if (item.columnName && m1 && m2) {
304
306
  const m3 = m2[1].match(/('[^']*'::text)/g);
305
307
  let items;
306
- /* v8 ignore next 5 */
308
+ /* v8 ignore next */
307
309
  if (m3) {
308
310
  items = m3.map((item) => item.trim().match(/^\(?'(.*)'/)?.[1]);
309
311
  }
@@ -321,7 +323,8 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
321
323
  }, {});
322
324
  }
323
325
  createTableColumn(column, table) {
324
- const compositePK = table.getPrimaryKey()?.composite;
326
+ const pk = table.getPrimaryKey();
327
+ const compositePK = pk?.composite;
325
328
  const primaryKey = !this.hasNonDefaultPrimaryKeyName(table);
326
329
  const col = [this.quote(column.name)];
327
330
  if (column.autoincrement && !column.generated && !compositePK) {
@@ -351,7 +354,7 @@ export class PostgreSqlSchemaHelper extends SchemaHelper {
351
354
  Utils.runIfNotEmpty(() => col.push('null'), column.nullable);
352
355
  Utils.runIfNotEmpty(() => col.push('not null'), !column.nullable);
353
356
  }
354
- if (column.autoincrement && !column.generated && !compositePK) {
357
+ if (column.autoincrement && !compositePK) {
355
358
  Utils.runIfNotEmpty(() => col.push('primary key'), primaryKey && column.primary);
356
359
  }
357
360
  const useDefault = column.default != null && column.default !== 'null' && !column.autoincrement;
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
@@ -5,4 +5,5 @@ export * from './PostgreSqlPlatform.js';
5
5
  export * from './PostgreSqlSchemaHelper.js';
6
6
  export * from './PostgreSqlExceptionConverter.js';
7
7
  export * from './types/index.js';
8
- export { PostgreSqlMikroORM as MikroORM, PostgreSqlOptions as Options, definePostgreSqlConfig as defineConfig, } from './PostgreSqlMikroORM.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
@@ -6,3 +6,4 @@ export * from './PostgreSqlSchemaHelper.js';
6
6
  export * from './PostgreSqlExceptionConverter.js';
7
7
  export * from './types/index.js';
8
8
  export { PostgreSqlMikroORM as MikroORM, definePostgreSqlConfig as defineConfig, } from './PostgreSqlMikroORM.js';
9
+ export { raw } from './raw.js';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mikro-orm/postgresql",
3
3
  "type": "module",
4
- "version": "7.0.0-dev.9",
4
+ "version": "7.0.0-dev.91",
5
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.",
6
6
  "exports": {
7
7
  "./package.json": "./package.json",
@@ -38,7 +38,7 @@
38
38
  },
39
39
  "homepage": "https://mikro-orm.io",
40
40
  "engines": {
41
- "node": ">= 22.11.0"
41
+ "node": ">= 22.17.0"
42
42
  },
43
43
  "scripts": {
44
44
  "build": "yarn clean && yarn compile && yarn copy",
@@ -50,18 +50,19 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@mikro-orm/knex": "7.0.0-dev.9",
54
- "pg": "8.14.1",
53
+ "@mikro-orm/knex": "7.0.0-dev.91",
54
+ "pg": "8.16.3",
55
+ "pg-cursor": "2.15.3",
55
56
  "postgres-array": "3.0.4",
56
57
  "postgres-date": "2.1.0",
57
58
  "postgres-interval": "4.0.2"
58
59
  },
59
60
  "devDependencies": {
60
- "@mikro-orm/core": "^6.4.13",
61
- "kysely": "0.28.0"
61
+ "@mikro-orm/core": "^6.6.2",
62
+ "kysely": "0.28.8"
62
63
  },
63
64
  "peerDependencies": {
64
- "@mikro-orm/core": "7.0.0-dev.9",
65
+ "@mikro-orm/core": "7.0.0-dev.91",
65
66
  "kysely": "*"
66
67
  }
67
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/knex';
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/knex';
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
+ }