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

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,7 +1,7 @@
1
- import { AbstractSqlConnection, type Knex } from '@mikro-orm/knex';
1
+ import { type PoolConfig } from 'pg';
2
+ import { PostgresDialect } from 'kysely';
3
+ import { AbstractSqlConnection } from '@mikro-orm/knex';
2
4
  export declare class PostgreSqlConnection extends AbstractSqlConnection {
3
- createKnex(): void;
4
- getDefaultClientUrl(): string;
5
- getConnectionOptions(): Knex.PgConnectionConfig;
6
- protected transformRawResult<T>(res: any, method: 'all' | 'get' | 'run'): T;
5
+ createKyselyDialect(overrides: PoolConfig): PostgresDialect;
6
+ mapOptions(overrides: PoolConfig): PoolConfig;
7
7
  }
@@ -5,19 +5,24 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.PostgreSqlConnection = void 0;
7
7
  const type_overrides_1 = __importDefault(require("pg/lib/type-overrides"));
8
+ const pg_1 = require("pg");
9
+ const kysely_1 = require("kysely");
8
10
  const postgres_array_1 = __importDefault(require("postgres-array"));
9
11
  const knex_1 = require("@mikro-orm/knex");
10
12
  class PostgreSqlConnection extends knex_1.AbstractSqlConnection {
11
- createKnex() {
12
- this.client = this.createKnexClient(knex_1.PostgreSqlKnexDialect);
13
- this.client.client.ormConfig = this.config;
14
- this.connected = true;
13
+ createKyselyDialect(overrides) {
14
+ const options = this.mapOptions(overrides);
15
+ return new kysely_1.PostgresDialect({
16
+ pool: new pg_1.Pool(options),
17
+ onCreateConnection: this.options.onCreateConnection ?? this.config.get('onCreateConnection'),
18
+ });
15
19
  }
16
- getDefaultClientUrl() {
17
- return 'postgresql://postgres@127.0.0.1:5432';
18
- }
19
- getConnectionOptions() {
20
- const ret = super.getConnectionOptions();
20
+ mapOptions(overrides) {
21
+ const ret = { ...this.getConnectionOptions() };
22
+ const pool = this.config.get('pool');
23
+ knex_1.Utils.defaultValue(ret, 'min', pool?.min);
24
+ knex_1.Utils.defaultValue(ret, 'max', pool?.max);
25
+ knex_1.Utils.defaultValue(ret, 'idleTimeoutMillis', pool?.idleTimeoutMillis);
21
26
  // use `select typname, oid, typarray from pg_type order by oid` to get the list of OIDs
22
27
  const types = new type_overrides_1.default();
23
28
  [
@@ -33,24 +38,7 @@ class PostgreSqlConnection extends knex_1.AbstractSqlConnection {
33
38
  1187, // interval[]
34
39
  ].forEach(oid => types.setTypeParser(oid, str => postgres_array_1.default.parse(str)));
35
40
  ret.types = types;
36
- return ret;
37
- }
38
- transformRawResult(res, method) {
39
- if (Array.isArray(res)) {
40
- return res.map(row => this.transformRawResult(row, method));
41
- }
42
- if (method === 'get') {
43
- return res.rows[0];
44
- }
45
- if (method === 'all') {
46
- return res.rows;
47
- }
48
- return {
49
- affectedRows: res.rowCount,
50
- insertId: res.rows[0] ? res.rows[0].id : 0,
51
- row: res.rows[0],
52
- rows: res.rows,
53
- };
41
+ return knex_1.Utils.mergeConfig(ret, overrides);
54
42
  }
55
43
  }
56
44
  exports.PostgreSqlConnection = PostgreSqlConnection;
@@ -6,7 +6,7 @@ const PostgreSqlConnection_1 = require("./PostgreSqlConnection");
6
6
  const PostgreSqlPlatform_1 = require("./PostgreSqlPlatform");
7
7
  class PostgreSqlDriver extends knex_1.AbstractSqlDriver {
8
8
  constructor(config) {
9
- super(config, new PostgreSqlPlatform_1.PostgreSqlPlatform(), PostgreSqlConnection_1.PostgreSqlConnection, ['knex', 'pg']);
9
+ super(config, new PostgreSqlPlatform_1.PostgreSqlPlatform(), PostgreSqlConnection_1.PostgreSqlConnection, ['kysely', 'pg']);
10
10
  }
11
11
  }
12
12
  exports.PostgreSqlDriver = PostgreSqlDriver;
@@ -1,15 +1,17 @@
1
1
  import { type IPostgresInterval } from 'postgres-interval';
2
- import { type EntityProperty, Type, type SimpleColumnMeta, type Configuration } from '@mikro-orm/core';
3
- import { AbstractSqlPlatform, type IndexDef } from '@mikro-orm/knex';
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';
4
4
  import { PostgreSqlSchemaHelper } from './PostgreSqlSchemaHelper';
5
5
  import { PostgreSqlExceptionConverter } from './PostgreSqlExceptionConverter';
6
6
  export declare class PostgreSqlPlatform extends AbstractSqlPlatform {
7
7
  protected readonly schemaHelper: PostgreSqlSchemaHelper;
8
8
  protected readonly exceptionConverter: PostgreSqlExceptionConverter;
9
9
  setConfig(config: Configuration): void;
10
+ createNativeQueryBuilder(): PostgreSqlNativeQueryBuilder;
10
11
  usesReturningStatement(): boolean;
11
12
  usesCascadeStatement(): boolean;
12
13
  supportsNativeEnums(): boolean;
14
+ usesEnumCheckConstraints(): boolean;
13
15
  supportsCustomPrimaryKeyNames(): boolean;
14
16
  getCurrentTimestampSQL(length: number): string;
15
17
  getDateTimeTypeDeclarationSQL(column: {
@@ -38,7 +40,7 @@ export declare class PostgreSqlPlatform extends AbstractSqlPlatform {
38
40
  getFullTextWhereClause(prop: EntityProperty): string;
39
41
  supportsCreatingFullTextIndex(): boolean;
40
42
  getFullTextIndexExpression(indexName: string, schemaName: string | undefined, tableName: string, columns: SimpleColumnMeta[]): string;
41
- normalizeColumnType(type: string, options?: {
43
+ normalizeColumnType(type: string, options: {
42
44
  length?: number;
43
45
  precision?: number;
44
46
  scale?: number;
@@ -60,6 +62,10 @@ export declare class PostgreSqlPlatform extends AbstractSqlPlatform {
60
62
  nativeEnumName?: string;
61
63
  }): string;
62
64
  supportsMultipleStatements(): boolean;
65
+ getBeginTransactionSQL(options?: {
66
+ isolationLevel?: IsolationLevel;
67
+ readOnly?: boolean;
68
+ }): string[];
63
69
  marshallArray(values: string[]): string;
64
70
  unmarshallArray(value: string): string[];
65
71
  getVarcharTypeDeclarationSQL(column: {
@@ -100,4 +106,5 @@ export declare class PostgreSqlPlatform extends AbstractSqlPlatform {
100
106
  * @inheritDoc
101
107
  */
102
108
  parseDate(value: string | number): Date;
109
+ getDefaultClientUrl(): string;
103
110
  }
@@ -21,6 +21,9 @@ class PostgreSqlPlatform extends knex_1.AbstractSqlPlatform {
21
21
  }
22
22
  super.setConfig(config);
23
23
  }
24
+ createNativeQueryBuilder() {
25
+ return new knex_1.PostgreSqlNativeQueryBuilder(this);
26
+ }
24
27
  usesReturningStatement() {
25
28
  return true;
26
29
  }
@@ -30,6 +33,9 @@ class PostgreSqlPlatform extends knex_1.AbstractSqlPlatform {
30
33
  supportsNativeEnums() {
31
34
  return true;
32
35
  }
36
+ usesEnumCheckConstraints() {
37
+ return true;
38
+ }
33
39
  supportsCustomPrimaryKeyNames() {
34
40
  return true;
35
41
  }
@@ -97,7 +103,7 @@ class PostgreSqlPlatform extends knex_1.AbstractSqlPlatform {
97
103
  }
98
104
  return `create index ${quotedIndexName} on ${quotedTableName} using gin(to_tsvector('simple', ${quotedColumnNames.join(` || ' ' || `)}))`;
99
105
  }
100
- normalizeColumnType(type, options = {}) {
106
+ normalizeColumnType(type, options) {
101
107
  const simpleType = this.extractSimpleType(type);
102
108
  if (['int', 'int4', 'integer'].includes(simpleType)) {
103
109
  return this.getIntegerTypeDeclarationSQL({});
@@ -171,6 +177,15 @@ class PostgreSqlPlatform extends knex_1.AbstractSqlPlatform {
171
177
  supportsMultipleStatements() {
172
178
  return true;
173
179
  }
180
+ getBeginTransactionSQL(options) {
181
+ if (options?.isolationLevel || options?.readOnly) {
182
+ let sql = 'start transaction';
183
+ sql += options.isolationLevel ? ` isolation level ${options.isolationLevel}` : '';
184
+ sql += options.readOnly ? ` read only` : '';
185
+ return [sql];
186
+ }
187
+ return ['begin'];
188
+ }
174
189
  marshallArray(values) {
175
190
  const quote = (v) => v === '' || v.match(/["{},\\]/) ? JSON.stringify(v) : v;
176
191
  return `{${values.map(v => quote('' + v)).join(',')}}`;
@@ -247,6 +262,9 @@ class PostgreSqlPlatform extends knex_1.AbstractSqlPlatform {
247
262
  });
248
263
  }
249
264
  quoteIdentifier(id, quote = '"') {
265
+ if (core_1.RawQueryFragment.isKnownFragment(id)) {
266
+ return super.quoteIdentifier(id);
267
+ }
250
268
  return `${quote}${id.replace('.', `${quote}.${quote}`)}${quote}`;
251
269
  }
252
270
  escape(value) {
@@ -336,14 +354,15 @@ class PostgreSqlPlatform extends knex_1.AbstractSqlPlatform {
336
354
  getIndexName(tableName, columns, type) {
337
355
  const indexName = super.getIndexName(tableName, columns, type);
338
356
  if (indexName.length > 63) {
339
- return `${indexName.substring(0, 55 - type.length)}_${core_1.Utils.hash(indexName, 5)}_${type}`;
357
+ const suffix = type === 'primary' ? 'pkey' : type;
358
+ return `${indexName.substring(0, 55 - type.length)}_${core_1.Utils.hash(indexName, 5)}_${suffix}`;
340
359
  }
341
360
  return indexName;
342
361
  }
343
362
  getDefaultPrimaryName(tableName, columns) {
344
363
  const indexName = `${tableName}_pkey`;
345
364
  if (indexName.length > 63) {
346
- return `${indexName.substring(0, 55 - 'primary'.length)}_${core_1.Utils.hash(indexName, 5)}_primary`;
365
+ return `${indexName.substring(0, 55 - 'pkey'.length)}_${core_1.Utils.hash(indexName, 5)}_pkey`;
347
366
  }
348
367
  return indexName;
349
368
  }
@@ -376,5 +395,8 @@ class PostgreSqlPlatform extends knex_1.AbstractSqlPlatform {
376
395
  }
377
396
  return parsed;
378
397
  }
398
+ getDefaultClientUrl() {
399
+ return 'postgresql://postgres@127.0.0.1:5432';
400
+ }
379
401
  }
380
402
  exports.PostgreSqlPlatform = PostgreSqlPlatform;
@@ -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 Knex, 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/knex';
3
3
  export declare class PostgreSqlSchemaHelper extends SchemaHelper {
4
4
  static readonly DEFAULT_VALUES: {
5
5
  'now()': string[];
@@ -32,24 +32,25 @@ export declare class PostgreSqlSchemaHelper extends SchemaHelper {
32
32
  getCreateNativeEnumSQL(name: string, values: unknown[], schema?: string): string;
33
33
  getDropNativeEnumSQL(name: string, schema?: string): string;
34
34
  getAlterNativeEnumSQL(name: string, schema?: string, value?: string, items?: string[], oldItems?: string[]): string;
35
- getEnumDefinitions(connection: AbstractSqlConnection, checks: CheckDef[], tableName?: string, schemaName?: string): Promise<Dictionary<string[]>>;
36
- createTableColumn(table: Knex.TableBuilder, column: Column, fromTable: DatabaseTable, changedProperties?: Set<string>, alter?: boolean): Knex.ColumnBuilder | undefined;
37
- configureColumn(column: Column, col: Knex.ColumnBuilder, knex: Knex, changedProperties?: Set<string>): Knex.ColumnBuilder;
38
- getPreAlterTable(tableDiff: TableDifference, safe: boolean): string;
39
- getPostAlterTable(tableDiff: TableDifference, safe: boolean): string;
40
- getAlterColumnAutoincrement(tableName: string, column: Column, schemaName?: string): string;
35
+ private getEnumDefinitions;
36
+ createTableColumn(column: Column, table: DatabaseTable): string | undefined;
37
+ getPreAlterTable(tableDiff: TableDifference, safe: boolean): string[];
38
+ castColumn(name: string, type: string): string;
39
+ dropForeignKey(tableName: string, constraintName: string): string;
40
+ getPostAlterTable(tableDiff: TableDifference, safe: boolean): string[];
41
+ private getAlterColumnAutoincrement;
41
42
  getChangeColumnCommentSQL(tableName: string, to: Column, schemaName?: string): string;
43
+ alterTableComment(table: DatabaseTable, comment?: string): string;
42
44
  normalizeDefaultValue(defaultValue: string, length: number): string | number;
45
+ appendComments(table: DatabaseTable): string[];
43
46
  getDatabaseExistsSQL(name: string): string;
44
47
  getDatabaseNotExistsError(dbName: string): string;
45
48
  getManagementDbName(): string;
46
49
  disableForeignKeysSQL(): string;
47
50
  enableForeignKeysSQL(): string;
48
- getRenameIndexSQL(tableName: string, index: IndexDef, oldIndexName: string): string;
51
+ getRenameIndexSQL(tableName: string, index: IndexDef, oldIndexName: string): string[];
52
+ dropIndex(table: string, index: IndexDef, oldIndexName?: string): string;
49
53
  private getIndexesSQL;
50
54
  private getChecksSQL;
51
- getChecks(connection: AbstractSqlConnection, tableName: string, schemaName: string, columns?: Column[]): Promise<CheckDef[]>;
52
- getColumns(connection: AbstractSqlConnection, tableName: string, schemaName?: string): Promise<Column[]>;
53
- getIndexes(connection: AbstractSqlConnection, tableName: string, schemaName?: string): Promise<IndexDef[]>;
54
55
  inferLengthFromColumnType(type: string): number | undefined;
55
56
  }
@@ -55,7 +55,7 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
55
55
  return `${ignoredPrefixes} and "${column}" not in (${ignored})`;
56
56
  }
57
57
  async loadInformationSchema(schema, connection, tables, schemas) {
58
- schemas ??= tables.length === 0 ? [schema.name] : tables.map(t => t.schema_name ?? schema.name);
58
+ schemas ??= tables.length === 0 ? [schema.name] : tables.map(t => t.schema_name);
59
59
  const nativeEnums = await this.getNativeEnumDefinitions(connection, schemas);
60
60
  schema.setNativeEnums(nativeEnums);
61
61
  if (tables.length === 0) {
@@ -70,7 +70,7 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
70
70
  const key = this.getTableKey(t);
71
71
  const table = schema.addTable(t.table_name, t.schema_name, t.table_comment);
72
72
  const pks = await this.getPrimaryKeys(connection, indexes[key], table.name, table.schema);
73
- const enums = await this.getEnumDefinitions(connection, checks[key] ?? []);
73
+ const enums = this.getEnumDefinitions(checks[key] ?? []);
74
74
  table.init(columns[key], indexes[key], checks[key], pks, fks[key], enums);
75
75
  }
76
76
  }
@@ -265,13 +265,13 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
265
265
  if (schema && schema !== this.platform.getDefaultSchemaName()) {
266
266
  name = schema + '.' + name;
267
267
  }
268
- return `create type ${this.platform.quoteIdentifier(name)} as enum (${values.map(value => this.platform.quoteValue(value)).join(', ')})`;
268
+ return `create type ${this.quote(name)} as enum (${values.map(value => this.platform.quoteValue(value)).join(', ')})`;
269
269
  }
270
270
  getDropNativeEnumSQL(name, schema) {
271
271
  if (schema && schema !== this.platform.getDefaultSchemaName()) {
272
272
  name = schema + '.' + name;
273
273
  }
274
- return `drop type ${this.platform.quoteIdentifier(name)}`;
274
+ return `drop type ${this.quote(name)}`;
275
275
  }
276
276
  getAlterNativeEnumSQL(name, schema, value, items, oldItems) {
277
277
  if (schema && schema !== this.platform.getDefaultSchemaName()) {
@@ -287,11 +287,10 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
287
287
  suffix = ` before ${this.platform.quoteValue(oldItems[0])}`;
288
288
  }
289
289
  }
290
- return `alter type ${this.platform.quoteIdentifier(name)} add value if not exists ${this.platform.quoteValue(value)}${suffix}`;
290
+ return `alter type ${this.quote(name)} add value if not exists ${this.platform.quoteValue(value)}${suffix}`;
291
291
  }
292
- async getEnumDefinitions(connection, checks, tableName, schemaName) {
293
- const found = [];
294
- const enums = checks.reduce((o, item, index) => {
292
+ getEnumDefinitions(checks) {
293
+ return checks.reduce((o, item) => {
295
294
  // check constraints are defined as one of:
296
295
  // `CHECK ((type = ANY (ARRAY['local'::text, 'global'::text])))`
297
296
  // `CHECK (("columnName" = ANY (ARRAY['local'::text, 'global'::text])))`
@@ -313,72 +312,50 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
313
312
  items = items.filter(item => item !== undefined);
314
313
  if (items.length > 0) {
315
314
  o[item.columnName] = items;
316
- found.push(index);
315
+ item.expression = `${this.quote(item.columnName)} in ('${items.join("', '")}')`;
316
+ item.definition = `check (${item.expression})`;
317
317
  }
318
318
  }
319
319
  return o;
320
320
  }, {});
321
- found.reverse().forEach(index => checks.splice(index, 1));
322
- return enums;
323
- }
324
- createTableColumn(table, column, fromTable, changedProperties, alter) {
325
- const pk = fromTable.getPrimaryKey();
326
- const primaryKey = column.primary && !changedProperties && !this.hasNonDefaultPrimaryKeyName(fromTable);
327
- if (column.autoincrement && !column.generated && !pk?.composite && !changedProperties) {
328
- if (column.mappedType instanceof core_1.BigIntType) {
329
- return table.bigIncrements(column.name, { primaryKey });
330
- }
331
- return table.increments(column.name, { primaryKey });
321
+ }
322
+ createTableColumn(column, table) {
323
+ const compositePK = table.getPrimaryKey()?.composite;
324
+ const primaryKey = !this.hasNonDefaultPrimaryKeyName(table);
325
+ const col = [this.quote(column.name)];
326
+ if (column.autoincrement && !column.generated && !compositePK) {
327
+ col.push(column.mappedType.getColumnType({ autoincrement: true }, this.platform));
332
328
  }
333
- if (column.nativeEnumName && column.enumItems) {
334
- let schemaPrefix = fromTable.schema && fromTable.schema !== this.platform.getDefaultSchemaName() ? `${fromTable.schema}.` : '';
335
- let enumName = column.nativeEnumName;
336
- if (enumName.includes('.')) {
337
- const [schemaName, ...parts] = enumName.split('.');
338
- enumName = parts.join('.');
339
- schemaPrefix = schemaName + '.';
340
- }
341
- const type = this.platform.quoteIdentifier(schemaPrefix + enumName);
342
- if (column.type.endsWith('[]')) {
343
- return table.specificType(column.name, type + '[]');
329
+ else {
330
+ let columnType = column.type;
331
+ if (column.nativeEnumName) {
332
+ const parts = column.type.split('.');
333
+ if (parts.length === 2 && parts[0] === '*') {
334
+ columnType = `${table.schema}.${parts[1]}`;
335
+ }
336
+ if (columnType.endsWith('[]')) {
337
+ columnType = this.quote(columnType.substring(0, columnType.length - 2)) + '[]';
338
+ }
339
+ else {
340
+ columnType = this.quote(columnType);
341
+ }
344
342
  }
345
- return table.specificType(column.name, type);
346
- }
347
- if (changedProperties && column.mappedType instanceof core_1.EnumType && column.enumItems?.every(item => core_1.Utils.isString(item))) {
348
- const checkName = this.platform.getConfig().getNamingStrategy().indexName(fromTable.name, [column.name], 'check');
349
- if (changedProperties.has('enumItems') || (!column.nativeEnumName && fromTable.getColumn(column.name)?.nativeEnumName)) {
350
- table.check(`${this.platform.quoteIdentifier(column.name)} in ('${(column.enumItems.join("', '"))}')`, {}, this.platform.quoteIdentifier(checkName));
343
+ if (column.generated === 'by default as identity') {
344
+ columnType += ` generated ${column.generated}`;
351
345
  }
352
- if (changedProperties.has('type')) {
353
- return table.specificType(column.name, column.type);
346
+ else if (column.generated) {
347
+ columnType += ` generated always as ${column.generated}`;
354
348
  }
355
- return undefined;
356
- }
357
- if (column.mappedType instanceof core_1.EnumType && column.enumItems?.every(item => core_1.Utils.isString(item))) {
358
- return table.enum(column.name, column.enumItems);
349
+ col.push(columnType);
350
+ core_1.Utils.runIfNotEmpty(() => col.push('null'), column.nullable);
351
+ core_1.Utils.runIfNotEmpty(() => col.push('not null'), !column.nullable);
359
352
  }
360
- // serial is just a pseudo type, it cannot be used for altering
361
- /* istanbul ignore next */
362
- if (changedProperties && column.type.includes('serial')) {
363
- column.type = column.type.replace('serial', 'int');
364
- }
365
- let columnType = column.type;
366
- if (column.generated === 'by default as identity') {
367
- columnType += ` generated ${column.generated}`;
368
- }
369
- else if (column.generated) {
370
- columnType += ` generated always as ${column.generated}`;
353
+ if (column.autoincrement && !column.generated && !compositePK) {
354
+ core_1.Utils.runIfNotEmpty(() => col.push('primary key'), primaryKey && column.primary);
371
355
  }
372
- return table.specificType(column.name, columnType);
373
- }
374
- configureColumn(column, col, knex, changedProperties) {
375
- const guard = (key) => !changedProperties || changedProperties.has(key);
376
- core_1.Utils.runIfNotEmpty(() => col.nullable(), column.nullable && guard('nullable'));
377
- core_1.Utils.runIfNotEmpty(() => col.notNullable(), !column.nullable && guard('nullable'));
378
- core_1.Utils.runIfNotEmpty(() => col.unsigned(), column.unsigned && guard('unsigned'));
379
- core_1.Utils.runIfNotEmpty(() => col.comment(column.comment), column.comment && !changedProperties);
380
- this.configureColumnDefault(column, col, knex, changedProperties);
381
- return col;
356
+ const useDefault = column.default != null && column.default !== 'null' && !column.autoincrement;
357
+ core_1.Utils.runIfNotEmpty(() => col.push(`default ${column.default}`), useDefault);
358
+ return col.join(' ');
382
359
  }
383
360
  getPreAlterTable(tableDiff, safe) {
384
361
  const ret = [];
@@ -387,7 +364,7 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
387
364
  const schemaName = parts.pop();
388
365
  /* istanbul ignore next */
389
366
  const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
390
- const quotedName = this.platform.quoteIdentifier(name);
367
+ const quotedName = this.quote(name);
391
368
  // detect that the column was an enum before and remove the check constraint in such case here
392
369
  const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof core_1.EnumType);
393
370
  for (const col of changedEnums) {
@@ -397,19 +374,27 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
397
374
  if (col.fromColumn.nativeEnumName && !col.column.nativeEnumName && col.fromColumn.default) {
398
375
  ret.push(`alter table ${quotedName} alter column "${col.column.name}" drop default`);
399
376
  }
400
- if (!col.fromColumn.nativeEnumName) {
401
- if (col.changedProperties.has('enumItems') || col.column.nativeEnumName) {
402
- const constraintName = `${tableName}_${col.column.name}_check`;
403
- ret.push(`alter table ${quotedName} drop constraint if exists "${constraintName}"`);
404
- }
405
- }
406
377
  }
407
378
  // changing uuid column type requires to cast it to text first
408
379
  const uuids = Object.values(tableDiff.changedColumns).filter(col => col.changedProperties.has('type') && col.fromColumn.type === 'uuid');
409
380
  for (const col of uuids) {
410
381
  ret.push(`alter table ${quotedName} alter column "${col.column.name}" type text using ("${col.column.name}"::text)`);
411
382
  }
412
- return ret.join(';\n');
383
+ for (const { column } of Object.values(tableDiff.changedColumns).filter(diff => diff.changedProperties.has('autoincrement'))) {
384
+ if (!column.autoincrement && column.default == null) {
385
+ ret.push(`alter table ${quotedName} alter column ${this.quote(column.name)} drop default`);
386
+ }
387
+ }
388
+ return ret;
389
+ }
390
+ castColumn(name, type) {
391
+ if (type === 'uuid') {
392
+ type = 'text::uuid';
393
+ }
394
+ return ` using (${this.quote(name)}::${type})`;
395
+ }
396
+ dropForeignKey(tableName, constraintName) {
397
+ return `alter table ${this.quote(tableName)} drop constraint ${this.quote(constraintName)}`;
413
398
  }
414
399
  getPostAlterTable(tableDiff, safe) {
415
400
  const ret = [];
@@ -418,8 +403,8 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
418
403
  const schemaName = parts.pop();
419
404
  /* istanbul ignore next */
420
405
  const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
421
- const quotedName = this.platform.quoteIdentifier(name);
422
- // detect that the column was an enum before and remove the check constraint in such case here
406
+ const quotedName = this.quote(name);
407
+ // detect that the column was an enum before and remove the check constraint in such a case here
423
408
  const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof core_1.EnumType);
424
409
  for (const col of changedEnums) {
425
410
  if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.column.default) {
@@ -429,30 +414,32 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
429
414
  ret.push(`alter table ${quotedName} alter column "${col.column.name}" set default ${col.column.default}`);
430
415
  }
431
416
  }
432
- return ret.join(';\n');
417
+ for (const { column } of Object.values(tableDiff.changedColumns).filter(diff => diff.changedProperties.has('autoincrement'))) {
418
+ ret.push(...this.getAlterColumnAutoincrement(tableName, column, schemaName));
419
+ }
420
+ return ret;
433
421
  }
434
422
  getAlterColumnAutoincrement(tableName, column, schemaName) {
435
423
  const ret = [];
436
- const quoted = (val) => this.platform.quoteIdentifier(val);
437
424
  /* istanbul ignore next */
438
425
  const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
439
426
  /* istanbul ignore else */
440
427
  if (column.autoincrement) {
441
428
  const seqName = this.platform.getIndexName(tableName, [column.name], 'sequence');
442
- ret.push(`create sequence if not exists ${quoted(seqName)}`);
443
- ret.push(`select setval('${seqName}', (select max(${quoted(column.name)}) from ${quoted(name)}))`);
444
- ret.push(`alter table ${quoted(name)} alter column ${quoted(column.name)} set default nextval('${seqName}')`);
445
- }
446
- else if (column.default == null) {
447
- ret.push(`alter table ${quoted(name)} alter column ${quoted(column.name)} drop default`);
429
+ ret.push(`create sequence if not exists ${this.quote(seqName)}`);
430
+ ret.push(`select setval('${seqName}', (select max(${this.quote(column.name)}) from ${this.quote(name)}))`);
431
+ ret.push(`alter table ${this.quote(name)} alter column ${this.quote(column.name)} set default nextval('${seqName}')`);
448
432
  }
449
- return ret.join(';\n');
433
+ return ret;
450
434
  }
451
435
  getChangeColumnCommentSQL(tableName, to, schemaName) {
452
- const name = this.platform.quoteIdentifier((schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName);
436
+ const name = this.quote((schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName);
453
437
  const value = to.comment ? this.platform.quoteValue(to.comment) : 'null';
454
438
  return `comment on column ${name}."${to.name}" is ${value}`;
455
439
  }
440
+ alterTableComment(table, comment) {
441
+ return `comment on table ${table.getQuotedName()} is ${this.platform.quoteValue(comment ?? '')}`;
442
+ }
456
443
  normalizeDefaultValue(defaultValue, length) {
457
444
  if (!defaultValue || typeof defaultValue !== 'string') {
458
445
  return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
@@ -466,6 +453,20 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
466
453
  }
467
454
  return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
468
455
  }
456
+ appendComments(table) {
457
+ const sql = [];
458
+ if (table.comment) {
459
+ const comment = this.platform.quoteValue(table.comment).replace(/^'|'$/g, '');
460
+ sql.push(`comment on table ${table.getQuotedName()} is ${this.platform.quoteValue(this.processComment(comment))}`);
461
+ }
462
+ for (const column of table.getColumns()) {
463
+ if (column.comment) {
464
+ const comment = this.platform.quoteValue(this.processComment(column.comment));
465
+ sql.push(`comment on column ${table.getQuotedName()}.${this.quote(column.name)} is ${comment}`);
466
+ }
467
+ }
468
+ return sql;
469
+ }
469
470
  getDatabaseExistsSQL(name) {
470
471
  return `select 1 from pg_database where datname = '${name}'`;
471
472
  }
@@ -482,9 +483,15 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
482
483
  return `set session_replication_role = 'origin';`;
483
484
  }
484
485
  getRenameIndexSQL(tableName, index, oldIndexName) {
485
- oldIndexName = this.platform.quoteIdentifier(oldIndexName);
486
- const keyName = this.platform.quoteIdentifier(index.keyName);
487
- return `alter index ${oldIndexName} rename to ${keyName}`;
486
+ oldIndexName = this.quote(oldIndexName);
487
+ const keyName = this.quote(index.keyName);
488
+ return [`alter index ${oldIndexName} rename to ${keyName}`];
489
+ }
490
+ dropIndex(table, index, oldIndexName = index.keyName) {
491
+ if (index.primary || (index.unique && index.constraint)) {
492
+ return `alter table ${this.quote(table)} drop constraint ${this.quote(oldIndexName)}`;
493
+ }
494
+ return `drop index ${this.quote(oldIndexName)}`;
488
495
  }
489
496
  getIndexesSQL(tables) {
490
497
  return `select indrelid::regclass as table_name, ns.nspname as schema_name, relname as constraint_name, idx.indisunique as unique, idx.indisprimary as primary, contype, condeferrable, condeferred,
@@ -500,7 +507,7 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
500
507
  join pg_class as i on i.oid = idx.indexrelid
501
508
  join pg_namespace as ns on i.relnamespace = ns.oid
502
509
  left join pg_constraint as c on c.conname = i.relname
503
- where indrelid in (${tables.map(t => `${this.platform.quoteValue(`${this.platform.quoteIdentifier(t.schema_name ?? this.platform.getDefaultSchemaName() ?? '')}.${this.platform.quoteIdentifier(t.table_name)}`)}::regclass`).join(', ')})
510
+ where indrelid in (${tables.map(t => `${this.platform.quoteValue(`${this.quote(t.schema_name)}.${this.quote(t.table_name)}`)}::regclass`).join(', ')})
504
511
  order by relname`;
505
512
  }
506
513
  getChecksSQL(tablesBySchemas) {
@@ -509,24 +516,9 @@ class PostgreSqlSchemaHelper extends knex_1.SchemaHelper {
509
516
  join pg_namespace nsp on nsp.oid = pgc.connamespace
510
517
  join pg_class cls on pgc.conrelid = cls.oid
511
518
  join information_schema.constraint_column_usage ccu on pgc.conname = ccu.constraint_name and nsp.nspname = ccu.constraint_schema
512
- where contype = 'c' and (${[...tablesBySchemas.entries()].map(([schema, tables]) => `ccu.table_name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(',')}) and ccu.table_schema = ${this.platform.quoteValue(schema ?? this.platform.getDefaultSchemaName() ?? '')}`).join(' or ')})
519
+ where contype = 'c' and (${[...tablesBySchemas.entries()].map(([schema, tables]) => `ccu.table_name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(',')}) and ccu.table_schema = ${this.platform.quoteValue(schema)}`).join(' or ')})
513
520
  order by pgc.conname`;
514
521
  }
515
- /* istanbul ignore next */
516
- async getChecks(connection, tableName, schemaName, columns) {
517
- const res = await this.getAllChecks(connection, new Map([[schemaName, [{ table_name: tableName, schema_name: schemaName }]]]));
518
- return res[tableName];
519
- }
520
- /* istanbul ignore next */
521
- async getColumns(connection, tableName, schemaName) {
522
- const res = await this.getAllColumns(connection, new Map([[schemaName, [{ table_name: tableName, schema_name: schemaName }]]]));
523
- return res[tableName];
524
- }
525
- /* istanbul ignore next */
526
- async getIndexes(connection, tableName, schemaName) {
527
- const res = await this.getAllIndexes(connection, [{ table_name: tableName, schema_name: schemaName }]);
528
- return res[tableName];
529
- }
530
522
  inferLengthFromColumnType(type) {
531
523
  const match = type.match(/^(\w+(?:\s+\w+)*)\s*(?:\(\s*(\d+)\s*\)|$)/);
532
524
  if (!match) {
package/README.md CHANGED
@@ -183,7 +183,6 @@ yarn add @mikro-orm/core @mikro-orm/mariadb # for mysql/mariadb
183
183
  yarn add @mikro-orm/core @mikro-orm/postgresql # for postgresql
184
184
  yarn add @mikro-orm/core @mikro-orm/mssql # for mssql
185
185
  yarn add @mikro-orm/core @mikro-orm/sqlite # for sqlite
186
- yarn add @mikro-orm/core @mikro-orm/better-sqlite # for better-sqlite
187
186
  yarn add @mikro-orm/core @mikro-orm/libsql # for libsql
188
187
  ```
189
188
 
@@ -196,7 +195,6 @@ npm i -s @mikro-orm/core @mikro-orm/mariadb # for mysql/mariadb
196
195
  npm i -s @mikro-orm/core @mikro-orm/postgresql # for postgresql
197
196
  npm i -s @mikro-orm/core @mikro-orm/mssql # for mssql
198
197
  npm i -s @mikro-orm/core @mikro-orm/sqlite # for sqlite
199
- npm i -s @mikro-orm/core @mikro-orm/better-sqlite # for better-sqlite
200
198
  npm i -s @mikro-orm/core @mikro-orm/libsql # for libsql
201
199
  ```
202
200
 
package/index.mjs CHANGED
@@ -19,12 +19,10 @@ export const ArrayType = mod.ArrayType;
19
19
  export const BaseEntity = mod.BaseEntity;
20
20
  export const BaseSqliteConnection = mod.BaseSqliteConnection;
21
21
  export const BaseSqlitePlatform = mod.BaseSqlitePlatform;
22
- export const BaseSqliteSchemaHelper = mod.BaseSqliteSchemaHelper;
23
22
  export const BeforeCreate = mod.BeforeCreate;
24
23
  export const BeforeDelete = mod.BeforeDelete;
25
24
  export const BeforeUpdate = mod.BeforeUpdate;
26
25
  export const BeforeUpsert = mod.BeforeUpsert;
27
- export const BetterSqliteKnexDialect = mod.BetterSqliteKnexDialect;
28
26
  export const BigIntType = mod.BigIntType;
29
27
  export const BlobType = mod.BlobType;
30
28
  export const BooleanType = mod.BooleanType;
@@ -113,14 +111,12 @@ export const JSON_KEY_OPERATORS = mod.JSON_KEY_OPERATORS;
113
111
  export const JoinType = mod.JoinType;
114
112
  export const JsonProperty = mod.JsonProperty;
115
113
  export const JsonType = mod.JsonType;
116
- export const Knex = mod.Knex;
117
- export const LibSqlKnexDialect = mod.LibSqlKnexDialect;
114
+ export const Kysely = mod.Kysely;
118
115
  export const LoadStrategy = mod.LoadStrategy;
119
116
  export const LockMode = mod.LockMode;
120
117
  export const LockWaitTimeoutException = mod.LockWaitTimeoutException;
121
118
  export const ManyToMany = mod.ManyToMany;
122
119
  export const ManyToOne = mod.ManyToOne;
123
- export const MariaDbKnexDialect = mod.MariaDbKnexDialect;
124
120
  export const MediumIntType = mod.MediumIntType;
125
121
  export const MemoryCacheAdapter = mod.MemoryCacheAdapter;
126
122
  export const MetadataDiscovery = mod.MetadataDiscovery;
@@ -130,13 +126,12 @@ export const MetadataStorage = mod.MetadataStorage;
130
126
  export const MetadataValidator = mod.MetadataValidator;
131
127
  export const MikroORM = mod.MikroORM;
132
128
  export const MongoNamingStrategy = mod.MongoNamingStrategy;
133
- export const MonkeyPatchable = mod.MonkeyPatchable;
134
- export const MsSqlKnexDialect = mod.MsSqlKnexDialect;
135
- export const MySqlConnection = mod.MySqlConnection;
129
+ export const MsSqlNativeQueryBuilder = mod.MsSqlNativeQueryBuilder;
136
130
  export const MySqlExceptionConverter = mod.MySqlExceptionConverter;
137
- export const MySqlKnexDialect = mod.MySqlKnexDialect;
131
+ export const MySqlNativeQueryBuilder = mod.MySqlNativeQueryBuilder;
138
132
  export const MySqlPlatform = mod.MySqlPlatform;
139
133
  export const MySqlSchemaHelper = mod.MySqlSchemaHelper;
134
+ export const NativeQueryBuilder = mod.NativeQueryBuilder;
140
135
  export const NodeState = mod.NodeState;
141
136
  export const NonUniqueFieldNameException = mod.NonUniqueFieldNameException;
142
137
  export const NotFoundError = mod.NotFoundError;
@@ -159,7 +154,7 @@ export const PopulatePath = mod.PopulatePath;
159
154
  export const PostgreSqlConnection = mod.PostgreSqlConnection;
160
155
  export const PostgreSqlDriver = mod.PostgreSqlDriver;
161
156
  export const PostgreSqlExceptionConverter = mod.PostgreSqlExceptionConverter;
162
- export const PostgreSqlKnexDialect = mod.PostgreSqlKnexDialect;
157
+ export const PostgreSqlNativeQueryBuilder = mod.PostgreSqlNativeQueryBuilder;
163
158
  export const PostgreSqlPlatform = mod.PostgreSqlPlatform;
164
159
  export const PostgreSqlSchemaHelper = mod.PostgreSqlSchemaHelper;
165
160
  export const PrimaryKey = mod.PrimaryKey;
@@ -173,6 +168,7 @@ export const QueryOperator = mod.QueryOperator;
173
168
  export const QueryOrder = mod.QueryOrder;
174
169
  export const QueryOrderNumeric = mod.QueryOrderNumeric;
175
170
  export const QueryType = mod.QueryType;
171
+ export const Raw = mod.Raw;
176
172
  export const RawQueryFragment = mod.RawQueryFragment;
177
173
  export const ReadOnlyException = mod.ReadOnlyException;
178
174
  export const Ref = mod.Ref;
@@ -194,8 +190,9 @@ export const SmallIntType = mod.SmallIntType;
194
190
  export const SqlEntityManager = mod.SqlEntityManager;
195
191
  export const SqlEntityRepository = mod.SqlEntityRepository;
196
192
  export const SqlSchemaGenerator = mod.SqlSchemaGenerator;
197
- export const SqliteKnexDialect = mod.SqliteKnexDialect;
198
- export const SqliteTableCompiler = mod.SqliteTableCompiler;
193
+ export const SqliteExceptionConverter = mod.SqliteExceptionConverter;
194
+ export const SqliteNativeQueryBuilder = mod.SqliteNativeQueryBuilder;
195
+ export const SqliteSchemaHelper = mod.SqliteSchemaHelper;
199
196
  export const StringType = mod.StringType;
200
197
  export const SyntaxErrorException = mod.SyntaxErrorException;
201
198
  export const TableExistsException = mod.TableExistsException;
@@ -229,7 +226,7 @@ export const equals = mod.equals;
229
226
  export const getOnConflictFields = mod.getOnConflictFields;
230
227
  export const getOnConflictReturningFields = mod.getOnConflictReturningFields;
231
228
  export const helper = mod.helper;
232
- export const knex = mod.knex;
229
+ export const isRaw = mod.isRaw;
233
230
  export const parseJsonSafe = mod.parseJsonSafe;
234
231
  export const raw = mod.raw;
235
232
  export const ref = mod.ref;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/postgresql",
3
- "version": "6.4.7-dev.1",
3
+ "version": "7.0.0-dev.1",
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
  "main": "index.js",
6
6
  "module": "index.mjs",
@@ -46,7 +46,7 @@
46
46
  },
47
47
  "homepage": "https://mikro-orm.io",
48
48
  "engines": {
49
- "node": ">= 18.12.0"
49
+ "node": ">= 22.11.0"
50
50
  },
51
51
  "scripts": {
52
52
  "build": "yarn clean && yarn compile && yarn copy && yarn run -T gen-esm-wrapper index.js index.mjs",
@@ -58,16 +58,18 @@
58
58
  "access": "public"
59
59
  },
60
60
  "dependencies": {
61
- "@mikro-orm/knex": "6.4.7-dev.1",
62
- "pg": "8.13.3",
61
+ "@mikro-orm/knex": "7.0.0-dev.1",
62
+ "pg": "8.13.1",
63
63
  "postgres-array": "3.0.2",
64
64
  "postgres-date": "2.1.0",
65
65
  "postgres-interval": "4.0.2"
66
66
  },
67
67
  "devDependencies": {
68
- "@mikro-orm/core": "^6.4.6"
68
+ "@mikro-orm/core": "^6.4.5",
69
+ "kysely": "https://pkg.pr.new/kysely-org/kysely/kysely@2b7007e"
69
70
  },
70
71
  "peerDependencies": {
71
- "@mikro-orm/core": "6.4.7-dev.1"
72
+ "@mikro-orm/core": "7.0.0-dev.1",
73
+ "kysely": "*"
72
74
  }
73
75
  }