@mikro-orm/postgresql 7.0.0-dev.10 → 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,6 +1,6 @@
1
1
  import { type PoolConfig } from 'pg';
2
2
  import { PostgresDialect } from 'kysely';
3
- import { AbstractSqlConnection } from '@mikro-orm/knex';
3
+ import { AbstractSqlConnection } from '@mikro-orm/sql';
4
4
  export declare class PostgreSqlConnection extends AbstractSqlConnection {
5
5
  createKyselyDialect(overrides: PoolConfig): PostgresDialect;
6
6
  mapOptions(overrides: PoolConfig): PoolConfig;
@@ -1,13 +1,14 @@
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
- import { AbstractSqlConnection, Utils } from '@mikro-orm/knex';
5
+ import { AbstractSqlConnection, Utils } from '@mikro-orm/sql';
6
6
  export class PostgreSqlConnection extends AbstractSqlConnection {
7
7
  createKyselyDialect(overrides) {
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,6 +1,9 @@
1
- import type { Configuration } from '@mikro-orm/core';
2
- import { AbstractSqlDriver } from '@mikro-orm/knex';
1
+ import type { Configuration, Constructor } from '@mikro-orm/core';
2
+ import { AbstractSqlDriver } from '@mikro-orm/sql';
3
3
  import { PostgreSqlConnection } from './PostgreSqlConnection.js';
4
+ import { PostgreSqlMikroORM } from './PostgreSqlMikroORM.js';
4
5
  export declare class PostgreSqlDriver extends AbstractSqlDriver<PostgreSqlConnection> {
5
6
  constructor(config: Configuration);
7
+ /** @inheritDoc */
8
+ getORMClass(): Constructor<PostgreSqlMikroORM>;
6
9
  }
@@ -1,8 +1,13 @@
1
- import { AbstractSqlDriver } from '@mikro-orm/knex';
1
+ import { AbstractSqlDriver } from '@mikro-orm/sql';
2
2
  import { PostgreSqlConnection } from './PostgreSqlConnection.js';
3
3
  import { PostgreSqlPlatform } from './PostgreSqlPlatform.js';
4
+ import { PostgreSqlMikroORM } from './PostgreSqlMikroORM.js';
4
5
  export class PostgreSqlDriver extends AbstractSqlDriver {
5
6
  constructor(config) {
6
7
  super(config, new PostgreSqlPlatform(), PostgreSqlConnection, ['kysely', 'pg']);
7
8
  }
9
+ /** @inheritDoc */
10
+ getORMClass() {
11
+ return PostgreSqlMikroORM;
12
+ }
8
13
  }
@@ -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';
1
+ import { type AnyEntity, type EntityClass, type EntitySchema, MikroORM, type Options, type IDatabaseDriver, type EntityManager, type EntityManagerType } from '@mikro-orm/core';
2
+ import type { SqlEntityManager } from '@mikro-orm/sql';
2
3
  import { PostgreSqlDriver } from './PostgreSqlDriver.js';
3
- import type { SqlEntityManager } from '@mikro-orm/knex';
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,6 +1,6 @@
1
1
  import { type IPostgresInterval } from 'postgres-interval';
2
- import { type IsolationLevel, type EntityProperty, Type, type SimpleColumnMeta, type Configuration } from '@mikro-orm/core';
3
- import { AbstractSqlPlatform, type IndexDef, PostgreSqlNativeQueryBuilder } from '@mikro-orm/knex';
2
+ import { type Configuration, type EntityProperty, type IsolationLevel, type SimpleColumnMeta, Type } from '@mikro-orm/core';
3
+ import { AbstractSqlPlatform, type IndexDef, PostgreSqlNativeQueryBuilder } from '@mikro-orm/sql';
4
4
  import { PostgreSqlSchemaHelper } from './PostgreSqlSchemaHelper.js';
5
5
  import { PostgreSqlExceptionConverter } from './PostgreSqlExceptionConverter.js';
6
6
  export declare class PostgreSqlPlatform extends AbstractSqlPlatform {
@@ -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,8 +1,8 @@
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';
5
- import { AbstractSqlPlatform, PostgreSqlNativeQueryBuilder } from '@mikro-orm/knex';
4
+ import { ALIAS_REPLACEMENT, ARRAY_OPERATORS, raw, RawQueryFragment, Type, Utils, } from '@mikro-orm/core';
5
+ import { AbstractSqlPlatform, PostgreSqlNativeQueryBuilder } from '@mikro-orm/sql';
6
6
  import { PostgreSqlSchemaHelper } from './PostgreSqlSchemaHelper.js';
7
7
  import { PostgreSqlExceptionConverter } from './PostgreSqlExceptionConverter.js';
8
8
  import { FullTextType } from './types/FullTextType.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,9 +258,12 @@ 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
+ if (typeof value === 'bigint') {
265
+ value = value.toString();
266
+ }
264
267
  if (typeof value === 'string') {
265
268
  return Client.prototype.escapeLiteral(value);
266
269
  }
@@ -270,7 +273,10 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
270
273
  if (ArrayBuffer.isView(value)) {
271
274
  return `E'\\\\x${value.toString('hex')}'`;
272
275
  }
273
- return super.escape(value);
276
+ if (Array.isArray(value)) {
277
+ return value.map(v => this.escape(v)).join(', ');
278
+ }
279
+ return value;
274
280
  }
275
281
  pad(number, digits) {
276
282
  return String(number).padStart(digits, '0');
@@ -283,14 +289,14 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
283
289
  let offset = -date.getTimezoneOffset();
284
290
  let year = date.getFullYear();
285
291
  const isBCYear = year < 1;
286
- /* v8 ignore next 3 */
292
+ /* v8 ignore next */
287
293
  if (isBCYear) {
288
294
  year = Math.abs(year) + 1;
289
295
  }
290
296
  const datePart = `${this.pad(year, 4)}-${this.pad(date.getMonth() + 1, 2)}-${this.pad(date.getDate(), 2)}`;
291
297
  const timePart = `${this.pad(date.getHours(), 2)}:${this.pad(date.getMinutes(), 2)}:${this.pad(date.getSeconds(), 2)}.${this.pad(date.getMilliseconds(), 3)}`;
292
298
  let ret = `${datePart}T${timePart}`;
293
- /* v8 ignore next 4 */
299
+ /* v8 ignore next */
294
300
  if (offset < 0) {
295
301
  ret += '-';
296
302
  offset *= -1;
@@ -299,7 +305,7 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
299
305
  ret += '+';
300
306
  }
301
307
  ret += this.pad(Math.floor(offset / 60), 2) + ':' + this.pad(offset % 60, 2);
302
- /* v8 ignore next 3 */
308
+ /* v8 ignore next */
303
309
  if (isBCYear) {
304
310
  ret += ' BC';
305
311
  }
@@ -377,13 +383,13 @@ export class PostgreSqlPlatform extends AbstractSqlPlatform {
377
383
  if (typeof value === 'string' && value.charAt(10) === 'T') {
378
384
  return new Date(value);
379
385
  }
380
- /* v8 ignore next 3 */
386
+ /* v8 ignore next */
381
387
  if (typeof value === 'number') {
382
388
  return new Date(value);
383
389
  }
384
390
  // @ts-ignore fix wrong type resolution during build
385
391
  const parsed = parseDate(value);
386
- /* v8 ignore next 3 */
392
+ /* v8 ignore next */
387
393
  if (parsed === null) {
388
394
  return value;
389
395
  }
@@ -1,5 +1,5 @@
1
1
  import { type Dictionary } from '@mikro-orm/core';
2
- import { SchemaHelper, type AbstractSqlConnection, type CheckDef, type Column, type DatabaseSchema, type DatabaseTable, type ForeignKey, type IndexDef, type Table, type TableDifference } from '@mikro-orm/knex';
2
+ import { SchemaHelper, type AbstractSqlConnection, type CheckDef, type Column, type DatabaseSchema, type DatabaseTable, type ForeignKey, type IndexDef, type Table, type TableDifference } from '@mikro-orm/sql';
3
3
  export declare class PostgreSqlSchemaHelper extends SchemaHelper {
4
4
  static readonly DEFAULT_VALUES: {
5
5
  'now()': string[];
@@ -1,5 +1,5 @@
1
1
  import { EnumType, Type, Utils, DeferMode } from '@mikro-orm/core';
2
- import { SchemaHelper, } from '@mikro-orm/knex';
2
+ import { SchemaHelper, } from '@mikro-orm/sql';
3
3
  export class PostgreSqlSchemaHelper extends SchemaHelper {
4
4
  static DEFAULT_VALUES = {
5
5
  'now()': ['now()', 'current_timestamp'],
@@ -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
@@ -1,8 +1,9 @@
1
- export * from '@mikro-orm/knex';
1
+ export * from '@mikro-orm/sql';
2
2
  export * from './PostgreSqlConnection.js';
3
3
  export * from './PostgreSqlDriver.js';
4
4
  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
@@ -1,4 +1,4 @@
1
- export * from '@mikro-orm/knex';
1
+ export * from '@mikro-orm/sql';
2
2
  export * from './PostgreSqlConnection.js';
3
3
  export * from './PostgreSqlDriver.js';
4
4
  export * from './PostgreSqlPlatform.js';
@@ -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.10",
4
+ "version": "7.0.0-dev.100",
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.10",
54
- "pg": "8.14.1",
53
+ "@mikro-orm/sql": "7.0.0-dev.100",
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.9"
62
63
  },
63
64
  "peerDependencies": {
64
- "@mikro-orm/core": "7.0.0-dev.10",
65
+ "@mikro-orm/core": "7.0.0-dev.100",
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/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
+ }