@mikro-orm/postgresql 7.0.0-dev.17 → 7.0.0-dev.170

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,48 +0,0 @@
1
- import { DeadlockException, ExceptionConverter, ForeignKeyConstraintViolationException, InvalidFieldNameException, NonUniqueFieldNameException, NotNullConstraintViolationException, SyntaxErrorException, TableExistsException, TableNotFoundException, UniqueConstraintViolationException, CheckConstraintViolationException, } from '@mikro-orm/core';
2
- export class PostgreSqlExceptionConverter extends ExceptionConverter {
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
6
- */
7
- convertException(exception) {
8
- if (exception.detail?.toString().trim()) {
9
- exception.message += '\n - detail: ' + exception.detail;
10
- }
11
- if (exception.hint?.toString().trim()) {
12
- exception.message += '\n - hint: ' + exception.hint;
13
- }
14
- /* v8 ignore start */
15
- switch (exception.code) {
16
- case '40001':
17
- case '40P01':
18
- return new DeadlockException(exception);
19
- case '0A000':
20
- // Foreign key constraint violations during a TRUNCATE operation
21
- // are considered "feature not supported" in PostgreSQL.
22
- if (exception.message.includes('truncate')) {
23
- return new ForeignKeyConstraintViolationException(exception);
24
- }
25
- break;
26
- case '23502':
27
- return new NotNullConstraintViolationException(exception);
28
- case '23503':
29
- return new ForeignKeyConstraintViolationException(exception);
30
- case '23505':
31
- return new UniqueConstraintViolationException(exception);
32
- case '23514':
33
- return new CheckConstraintViolationException(exception);
34
- case '42601':
35
- return new SyntaxErrorException(exception);
36
- case '42702':
37
- return new NonUniqueFieldNameException(exception);
38
- case '42703':
39
- return new InvalidFieldNameException(exception);
40
- case '42P01':
41
- return new TableNotFoundException(exception);
42
- case '42P07':
43
- return new TableExistsException(exception);
44
- }
45
- /* v8 ignore stop */
46
- return super.convertException(exception);
47
- }
48
- }
@@ -1,56 +0,0 @@
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';
3
- export declare class PostgreSqlSchemaHelper extends SchemaHelper {
4
- static readonly DEFAULT_VALUES: {
5
- 'now()': string[];
6
- 'current_timestamp(?)': string[];
7
- "('now'::text)::timestamp(?) with time zone": string[];
8
- "('now'::text)::timestamp(?) without time zone": string[];
9
- 'null::character varying': string[];
10
- 'null::timestamp with time zone': string[];
11
- 'null::timestamp without time zone': string[];
12
- };
13
- getSchemaBeginning(charset: string, disableForeignKeys?: boolean): string;
14
- getCreateDatabaseSQL(name: string): string;
15
- getListTablesSQL(): string;
16
- getNamespaces(connection: AbstractSqlConnection): Promise<string[]>;
17
- private getIgnoredNamespacesConditionSQL;
18
- loadInformationSchema(schema: DatabaseSchema, connection: AbstractSqlConnection, tables: Table[], schemas?: string[]): Promise<void>;
19
- getAllIndexes(connection: AbstractSqlConnection, tables: Table[]): Promise<Dictionary<IndexDef[]>>;
20
- getAllColumns(connection: AbstractSqlConnection, tablesBySchemas: Map<string | undefined, Table[]>, nativeEnums?: Dictionary<{
21
- name: string;
22
- schema?: string;
23
- items: string[];
24
- }>): Promise<Dictionary<Column[]>>;
25
- getAllChecks(connection: AbstractSqlConnection, tablesBySchemas: Map<string | undefined, Table[]>): Promise<Dictionary<CheckDef[]>>;
26
- getAllForeignKeys(connection: AbstractSqlConnection, tablesBySchemas: Map<string | undefined, Table[]>): Promise<Dictionary<Dictionary<ForeignKey>>>;
27
- getNativeEnumDefinitions(connection: AbstractSqlConnection, schemas: string[]): Promise<Dictionary<{
28
- name: string;
29
- schema?: string;
30
- items: string[];
31
- }>>;
32
- getCreateNativeEnumSQL(name: string, values: unknown[], schema?: string): string;
33
- getDropNativeEnumSQL(name: string, schema?: string): string;
34
- getAlterNativeEnumSQL(name: string, schema?: string, value?: string, items?: string[], oldItems?: 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;
42
- getChangeColumnCommentSQL(tableName: string, to: Column, schemaName?: string): string;
43
- alterTableComment(table: DatabaseTable, comment?: string): string;
44
- normalizeDefaultValue(defaultValue: string, length: number): string | number;
45
- appendComments(table: DatabaseTable): string[];
46
- getDatabaseExistsSQL(name: string): string;
47
- getDatabaseNotExistsError(dbName: string): string;
48
- getManagementDbName(): string;
49
- disableForeignKeysSQL(): string;
50
- enableForeignKeysSQL(): string;
51
- getRenameIndexSQL(tableName: string, index: IndexDef, oldIndexName: string): string[];
52
- dropIndex(table: string, index: IndexDef, oldIndexName?: string): string;
53
- private getIndexesSQL;
54
- private getChecksSQL;
55
- inferLengthFromColumnType(type: string): number | undefined;
56
- }
@@ -1,545 +0,0 @@
1
- import { EnumType, Type, Utils, DeferMode } from '@mikro-orm/core';
2
- import { SchemaHelper, } from '@mikro-orm/knex';
3
- export class PostgreSqlSchemaHelper extends SchemaHelper {
4
- static DEFAULT_VALUES = {
5
- 'now()': ['now()', 'current_timestamp'],
6
- 'current_timestamp(?)': ['current_timestamp(?)'],
7
- "('now'::text)::timestamp(?) with time zone": ['current_timestamp(?)'],
8
- "('now'::text)::timestamp(?) without time zone": ['current_timestamp(?)'],
9
- 'null::character varying': ['null'],
10
- 'null::timestamp with time zone': ['null'],
11
- 'null::timestamp without time zone': ['null'],
12
- };
13
- getSchemaBeginning(charset, disableForeignKeys) {
14
- if (disableForeignKeys) {
15
- return `set names '${charset}';\n${this.disableForeignKeysSQL()}\n\n`;
16
- }
17
- return `set names '${charset}';\n\n`;
18
- }
19
- getCreateDatabaseSQL(name) {
20
- return `create database ${name}`;
21
- }
22
- getListTablesSQL() {
23
- return `select table_name, table_schema as schema_name, `
24
- + `(select pg_catalog.obj_description(c.oid) from pg_catalog.pg_class c
25
- where c.oid = (select ('"' || table_schema || '"."' || table_name || '"')::regclass::oid) and c.relname = table_name) as table_comment `
26
- + `from information_schema.tables `
27
- + `where ${this.getIgnoredNamespacesConditionSQL('table_schema')} `
28
- + `and table_name != 'geometry_columns' and table_name != 'spatial_ref_sys' and table_type != 'VIEW' `
29
- + `and table_name not in (select inhrelid::regclass::text from pg_inherits) `
30
- + `order by table_name`;
31
- }
32
- async getNamespaces(connection) {
33
- const sql = `select schema_name from information_schema.schemata `
34
- + `where ${this.getIgnoredNamespacesConditionSQL()} `
35
- + `order by schema_name`;
36
- const res = await connection.execute(sql);
37
- return res.map(row => row.schema_name);
38
- }
39
- getIgnoredNamespacesConditionSQL(column = 'schema_name') {
40
- const ignored = [
41
- 'information_schema',
42
- 'tiger',
43
- 'topology',
44
- /* v8 ignore next */
45
- ...this.platform.getConfig().get('schemaGenerator').ignoreSchema ?? [],
46
- ].map(s => this.platform.quoteValue(s)).join(', ');
47
- const ignoredPrefixes = [
48
- 'pg_',
49
- 'crdb_',
50
- '_timescaledb_',
51
- ].map(p => `"${column}" not like '${p}%'`).join(' and ');
52
- return `${ignoredPrefixes} and "${column}" not in (${ignored})`;
53
- }
54
- async loadInformationSchema(schema, connection, tables, schemas) {
55
- schemas ??= tables.length === 0 ? [schema.name] : tables.map(t => t.schema_name);
56
- const nativeEnums = await this.getNativeEnumDefinitions(connection, schemas);
57
- schema.setNativeEnums(nativeEnums);
58
- if (tables.length === 0) {
59
- return;
60
- }
61
- const tablesBySchema = this.getTablesGroupedBySchemas(tables);
62
- const columns = await this.getAllColumns(connection, tablesBySchema, nativeEnums);
63
- const indexes = await this.getAllIndexes(connection, tables);
64
- const checks = await this.getAllChecks(connection, tablesBySchema);
65
- const fks = await this.getAllForeignKeys(connection, tablesBySchema);
66
- for (const t of tables) {
67
- const key = this.getTableKey(t);
68
- const table = schema.addTable(t.table_name, t.schema_name, t.table_comment);
69
- const pks = await this.getPrimaryKeys(connection, indexes[key], table.name, table.schema);
70
- const enums = this.getEnumDefinitions(checks[key] ?? []);
71
- table.init(columns[key], indexes[key], checks[key], pks, fks[key], enums);
72
- }
73
- }
74
- async getAllIndexes(connection, tables) {
75
- const sql = this.getIndexesSQL(tables);
76
- const unquote = (str) => str.replace(/['"`]/g, '');
77
- const allIndexes = await connection.execute(sql);
78
- const ret = {};
79
- for (const index of allIndexes) {
80
- const key = this.getTableKey(index);
81
- const indexDef = {
82
- columnNames: index.index_def.map((name) => unquote(name)),
83
- composite: index.index_def.length > 1,
84
- // JSON columns can have unique index but not unique constraint, and we need to distinguish those, so we can properly drop them
85
- constraint: index.contype === 'u',
86
- keyName: index.constraint_name,
87
- unique: index.unique,
88
- primary: index.primary,
89
- };
90
- if (index.condeferrable) {
91
- indexDef.deferMode = index.condeferred ? DeferMode.INITIALLY_DEFERRED : DeferMode.INITIALLY_IMMEDIATE;
92
- }
93
- if (index.index_def.some((col) => col.match(/[(): ,"'`]/)) || index.expression?.match(/ where /i)) {
94
- indexDef.expression = index.expression;
95
- }
96
- if (index.deferrable) {
97
- indexDef.deferMode = index.initially_deferred ? DeferMode.INITIALLY_DEFERRED : DeferMode.INITIALLY_IMMEDIATE;
98
- }
99
- ret[key] ??= [];
100
- ret[key].push(indexDef);
101
- }
102
- return ret;
103
- }
104
- async getAllColumns(connection, tablesBySchemas, nativeEnums) {
105
- const sql = `select table_schema as schema_name, table_name, column_name,
106
- column_default,
107
- is_nullable,
108
- udt_name,
109
- udt_schema,
110
- coalesce(datetime_precision, character_maximum_length) length,
111
- atttypmod custom_length,
112
- numeric_precision,
113
- numeric_scale,
114
- data_type,
115
- is_identity,
116
- identity_generation,
117
- generation_expression,
118
- pg_catalog.col_description(pgc.oid, cols.ordinal_position::int) column_comment
119
- from information_schema.columns cols
120
- join pg_class pgc on cols.table_name = pgc.relname
121
- join pg_attribute pga on pgc.oid = pga.attrelid and cols.column_name = pga.attname
122
- where (${[...tablesBySchemas.entries()].map(([schema, tables]) => `(table_schema = ${this.platform.quoteValue(schema)} and table_name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(',')}))`).join(' or ')})
123
- order by ordinal_position`;
124
- const allColumns = await connection.execute(sql);
125
- const str = (val) => val != null ? '' + val : val;
126
- const ret = {};
127
- for (const col of allColumns) {
128
- const mappedType = connection.getPlatform().getMappedType(col.data_type);
129
- const increments = (col.column_default?.includes('nextval') || col.is_identity === 'YES') && connection.getPlatform().isNumericColumn(mappedType);
130
- const key = this.getTableKey(col);
131
- ret[key] ??= [];
132
- let type = col.data_type.toLowerCase() === 'array'
133
- ? col.udt_name.replace(/^_(.*)$/, '$1[]')
134
- : col.udt_name;
135
- if (col.data_type === 'USER-DEFINED' && col.udt_schema && col.udt_schema !== this.platform.getDefaultSchemaName()) {
136
- type = `${col.udt_schema}.${type}`;
137
- }
138
- if (type === 'bpchar') {
139
- type = 'char';
140
- }
141
- if (type === 'vector' && col.length == null && col.custom_length != null && col.custom_length !== -1) {
142
- col.length = col.custom_length;
143
- }
144
- if (col.length != null && !type.endsWith(`(${col.length})`) && !['text', 'date'].includes(type)) {
145
- type += `(${col.length})`;
146
- }
147
- if (type === 'numeric' && col.numeric_precision != null && col.numeric_scale != null) {
148
- type += `(${col.numeric_precision},${col.numeric_scale})`;
149
- }
150
- const length = this.inferLengthFromColumnType(type) === -1 ? -1 : col.length;
151
- const column = {
152
- name: col.column_name,
153
- type,
154
- mappedType,
155
- length,
156
- precision: col.numeric_precision,
157
- scale: col.numeric_scale,
158
- nullable: col.is_nullable === 'YES',
159
- default: str(this.normalizeDefaultValue(col.column_default, col.length)),
160
- unsigned: increments,
161
- autoincrement: increments,
162
- generated: col.is_identity === 'YES' ? (col.identity_generation === 'BY DEFAULT' ? 'by default as identity' : 'identity') : (col.generation_expression ? col.generation_expression + ' stored' : undefined),
163
- comment: col.column_comment,
164
- };
165
- if (nativeEnums?.[column.type]) {
166
- column.mappedType = Type.getType(EnumType);
167
- column.nativeEnumName = column.type;
168
- column.enumItems = nativeEnums[column.type]?.items;
169
- }
170
- ret[key].push(column);
171
- }
172
- return ret;
173
- }
174
- async getAllChecks(connection, tablesBySchemas) {
175
- const sql = this.getChecksSQL(tablesBySchemas);
176
- const allChecks = await connection.execute(sql);
177
- const ret = {};
178
- for (const check of allChecks) {
179
- const key = this.getTableKey(check);
180
- ret[key] ??= [];
181
- const m = check.expression.match(/^check \(\((.*)\)\)$/i);
182
- const def = m?.[1].replace(/\((.*?)\)::\w+/g, '$1');
183
- ret[key].push({
184
- name: check.name,
185
- columnName: check.column_name,
186
- definition: check.expression,
187
- expression: def,
188
- });
189
- }
190
- return ret;
191
- }
192
- async getAllForeignKeys(connection, tablesBySchemas) {
193
- const sql = `select nsp1.nspname schema_name, cls1.relname table_name, nsp2.nspname referenced_schema_name,
194
- cls2.relname referenced_table_name, a.attname column_name, af.attname referenced_column_name, conname constraint_name,
195
- confupdtype update_rule, confdeltype delete_rule, array_position(con.conkey,a.attnum) as ord, condeferrable, condeferred,
196
- pg_get_constraintdef(con.oid) as constraint_def
197
- from pg_attribute a
198
- join pg_constraint con on con.conrelid = a.attrelid AND a.attnum = ANY (con.conkey)
199
- join pg_attribute af on af.attnum = con.confkey[array_position(con.conkey,a.attnum)] AND af.attrelid = con.confrelid
200
- join pg_namespace nsp1 on nsp1.oid = con.connamespace
201
- join pg_class cls1 on cls1.oid = con.conrelid
202
- join pg_class cls2 on cls2.oid = confrelid
203
- join pg_namespace nsp2 on nsp2.oid = cls2.relnamespace
204
- where (${[...tablesBySchemas.entries()].map(([schema, tables]) => `(cls1.relname in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(',')}) and nsp1.nspname = ${this.platform.quoteValue(schema)})`).join(' or ')})
205
- and confrelid > 0
206
- order by nsp1.nspname, cls1.relname, constraint_name, ord`;
207
- const allFks = await connection.execute(sql);
208
- const ret = {};
209
- function mapReferentialIntegrity(value, def) {
210
- const match = ['n', 'd'].includes(value) && def.match(/ON DELETE (SET (NULL|DEFAULT) \(.*?\))/);
211
- if (match) {
212
- return match[1];
213
- }
214
- /* v8 ignore next 8 */
215
- switch (value) {
216
- case 'r': return 'RESTRICT';
217
- case 'c': return 'CASCADE';
218
- case 'n': return 'SET NULL';
219
- case 'd': return 'SET DEFAULT';
220
- case 'a':
221
- default: return 'NO ACTION';
222
- }
223
- }
224
- for (const fk of allFks) {
225
- fk.update_rule = mapReferentialIntegrity(fk.update_rule, fk.constraint_def);
226
- fk.delete_rule = mapReferentialIntegrity(fk.delete_rule, fk.constraint_def);
227
- if (fk.condeferrable) {
228
- fk.defer_mode = fk.condeferred ? DeferMode.INITIALLY_DEFERRED : DeferMode.INITIALLY_IMMEDIATE;
229
- }
230
- const key = this.getTableKey(fk);
231
- ret[key] ??= [];
232
- ret[key].push(fk);
233
- }
234
- Object.keys(ret).forEach(key => {
235
- const [schemaName, tableName] = key.split('.');
236
- ret[key] = this.mapForeignKeys(ret[key], tableName, schemaName);
237
- });
238
- return ret;
239
- }
240
- async getNativeEnumDefinitions(connection, schemas) {
241
- const uniqueSchemas = Utils.unique(schemas);
242
- const res = await connection.execute(`select t.typname as enum_name, n.nspname as schema_name, array_agg(e.enumlabel order by e.enumsortorder) as enum_value
243
- from pg_type t
244
- join pg_enum e on t.oid = e.enumtypid
245
- join pg_catalog.pg_namespace n on n.oid = t.typnamespace
246
- where n.nspname in (${Array(uniqueSchemas.length).fill('?').join(', ')})
247
- group by t.typname, n.nspname`, uniqueSchemas);
248
- return res.reduce((o, row) => {
249
- let name = row.enum_name;
250
- if (row.schema_name && row.schema_name !== this.platform.getDefaultSchemaName()) {
251
- name = row.schema_name + '.' + name;
252
- }
253
- let items = row.enum_value;
254
- if (!Array.isArray(items)) {
255
- items = this.platform.unmarshallArray(row.enum_value);
256
- }
257
- o[name] = {
258
- name: row.enum_name,
259
- schema: row.schema_name,
260
- items,
261
- };
262
- return o;
263
- }, {});
264
- }
265
- getCreateNativeEnumSQL(name, values, schema) {
266
- if (schema && schema !== this.platform.getDefaultSchemaName()) {
267
- name = schema + '.' + name;
268
- }
269
- return `create type ${this.quote(name)} as enum (${values.map(value => this.platform.quoteValue(value)).join(', ')})`;
270
- }
271
- getDropNativeEnumSQL(name, schema) {
272
- if (schema && schema !== this.platform.getDefaultSchemaName()) {
273
- name = schema + '.' + name;
274
- }
275
- return `drop type ${this.quote(name)}`;
276
- }
277
- getAlterNativeEnumSQL(name, schema, value, items, oldItems) {
278
- if (schema && schema !== this.platform.getDefaultSchemaName()) {
279
- name = schema + '.' + name;
280
- }
281
- let suffix = '';
282
- if (items && value && oldItems) {
283
- const position = items.indexOf(value);
284
- if (position > 0) {
285
- suffix = ` after ${this.platform.quoteValue(items[position - 1])}`;
286
- }
287
- else if (items.length > 1 && oldItems.length > 0) {
288
- suffix = ` before ${this.platform.quoteValue(oldItems[0])}`;
289
- }
290
- }
291
- return `alter type ${this.quote(name)} add value if not exists ${this.platform.quoteValue(value)}${suffix}`;
292
- }
293
- getEnumDefinitions(checks) {
294
- return checks.reduce((o, item) => {
295
- // check constraints are defined as one of:
296
- // `CHECK ((type = ANY (ARRAY['local'::text, 'global'::text])))`
297
- // `CHECK (("columnName" = ANY (ARRAY['local'::text, 'global'::text])))`
298
- // `CHECK (((enum_test)::text = ANY ((ARRAY['a'::character varying, 'b'::character varying, 'c'::character varying])::text[])))`
299
- // `CHECK ((("enumTest")::text = ANY ((ARRAY['a'::character varying, 'b'::character varying, 'c'::character varying])::text[])))`
300
- // `CHECK ((type = 'a'::text))`
301
- const m1 = item.definition?.match(/check \(\(\("?(\w+)"?\)::/i) || item.definition?.match(/check \(\("?(\w+)"? = /i);
302
- const m2 = item.definition?.match(/\(array\[(.*)]\)/i) || item.definition?.match(/ = (.*)\)/i);
303
- if (item.columnName && m1 && m2) {
304
- const m3 = m2[1].match(/('[^']*'::text)/g);
305
- let items;
306
- /* v8 ignore next 5 */
307
- if (m3) {
308
- items = m3.map((item) => item.trim().match(/^\(?'(.*)'/)?.[1]);
309
- }
310
- else {
311
- items = m2[1].split(',').map((item) => item.trim().match(/^\(?'(.*)'/)?.[1]);
312
- }
313
- items = items.filter(item => item !== undefined);
314
- if (items.length > 0) {
315
- o[item.columnName] = items;
316
- item.expression = `${this.quote(item.columnName)} in ('${items.join("', '")}')`;
317
- item.definition = `check (${item.expression})`;
318
- }
319
- }
320
- return o;
321
- }, {});
322
- }
323
- createTableColumn(column, table) {
324
- const compositePK = table.getPrimaryKey()?.composite;
325
- const primaryKey = !this.hasNonDefaultPrimaryKeyName(table);
326
- const col = [this.quote(column.name)];
327
- if (column.autoincrement && !column.generated && !compositePK) {
328
- col.push(column.mappedType.getColumnType({ autoincrement: true }, this.platform));
329
- }
330
- else {
331
- let columnType = column.type;
332
- if (column.nativeEnumName) {
333
- const parts = column.type.split('.');
334
- if (parts.length === 2 && parts[0] === '*') {
335
- columnType = `${table.schema}.${parts[1]}`;
336
- }
337
- if (columnType.endsWith('[]')) {
338
- columnType = this.quote(columnType.substring(0, columnType.length - 2)) + '[]';
339
- }
340
- else {
341
- columnType = this.quote(columnType);
342
- }
343
- }
344
- if (column.generated === 'by default as identity') {
345
- columnType += ` generated ${column.generated}`;
346
- }
347
- else if (column.generated) {
348
- columnType += ` generated always as ${column.generated}`;
349
- }
350
- col.push(columnType);
351
- Utils.runIfNotEmpty(() => col.push('null'), column.nullable);
352
- Utils.runIfNotEmpty(() => col.push('not null'), !column.nullable);
353
- }
354
- if (column.autoincrement && !column.generated && !compositePK) {
355
- Utils.runIfNotEmpty(() => col.push('primary key'), primaryKey && column.primary);
356
- }
357
- const useDefault = column.default != null && column.default !== 'null' && !column.autoincrement;
358
- Utils.runIfNotEmpty(() => col.push(`default ${column.default}`), useDefault);
359
- return col.join(' ');
360
- }
361
- getPreAlterTable(tableDiff, safe) {
362
- const ret = [];
363
- const parts = tableDiff.name.split('.');
364
- const tableName = parts.pop();
365
- const schemaName = parts.pop();
366
- /* v8 ignore next */
367
- const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
368
- const quotedName = this.quote(name);
369
- // detect that the column was an enum before and remove the check constraint in such case here
370
- const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof EnumType);
371
- for (const col of changedEnums) {
372
- if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.fromColumn.default) {
373
- ret.push(`alter table ${quotedName} alter column "${col.column.name}" drop default`);
374
- }
375
- if (col.fromColumn.nativeEnumName && !col.column.nativeEnumName && col.fromColumn.default) {
376
- ret.push(`alter table ${quotedName} alter column "${col.column.name}" drop default`);
377
- }
378
- }
379
- // changing uuid column type requires to cast it to text first
380
- const uuids = Object.values(tableDiff.changedColumns).filter(col => col.changedProperties.has('type') && col.fromColumn.type === 'uuid');
381
- for (const col of uuids) {
382
- ret.push(`alter table ${quotedName} alter column "${col.column.name}" type text using ("${col.column.name}"::text)`);
383
- }
384
- for (const { column } of Object.values(tableDiff.changedColumns).filter(diff => diff.changedProperties.has('autoincrement'))) {
385
- if (!column.autoincrement && column.default == null) {
386
- ret.push(`alter table ${quotedName} alter column ${this.quote(column.name)} drop default`);
387
- }
388
- }
389
- return ret;
390
- }
391
- castColumn(name, type) {
392
- if (type === 'uuid') {
393
- type = 'text::uuid';
394
- }
395
- return ` using (${this.quote(name)}::${type})`;
396
- }
397
- dropForeignKey(tableName, constraintName) {
398
- return `alter table ${this.quote(tableName)} drop constraint ${this.quote(constraintName)}`;
399
- }
400
- getPostAlterTable(tableDiff, safe) {
401
- const ret = [];
402
- const parts = tableDiff.name.split('.');
403
- const tableName = parts.pop();
404
- const schemaName = parts.pop();
405
- /* v8 ignore next */
406
- const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
407
- const quotedName = this.quote(name);
408
- // detect that the column was an enum before and remove the check constraint in such a case here
409
- const changedEnums = Object.values(tableDiff.changedColumns).filter(col => col.fromColumn.mappedType instanceof EnumType);
410
- for (const col of changedEnums) {
411
- if (!col.fromColumn.nativeEnumName && col.column.nativeEnumName && col.column.default) {
412
- ret.push(`alter table ${quotedName} alter column "${col.column.name}" set default ${col.column.default}`);
413
- }
414
- if (col.fromColumn.nativeEnumName && !col.column.nativeEnumName && col.column.default) {
415
- ret.push(`alter table ${quotedName} alter column "${col.column.name}" set default ${col.column.default}`);
416
- }
417
- }
418
- for (const { column } of Object.values(tableDiff.changedColumns).filter(diff => diff.changedProperties.has('autoincrement'))) {
419
- ret.push(...this.getAlterColumnAutoincrement(tableName, column, schemaName));
420
- }
421
- return ret;
422
- }
423
- getAlterColumnAutoincrement(tableName, column, schemaName) {
424
- const ret = [];
425
- /* v8 ignore next */
426
- const name = (schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName;
427
- if (column.autoincrement) {
428
- const seqName = this.platform.getIndexName(tableName, [column.name], 'sequence');
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}')`);
432
- }
433
- return ret;
434
- }
435
- getChangeColumnCommentSQL(tableName, to, schemaName) {
436
- const name = this.quote((schemaName && schemaName !== this.platform.getDefaultSchemaName() ? schemaName + '.' : '') + tableName);
437
- const value = to.comment ? this.platform.quoteValue(to.comment) : 'null';
438
- return `comment on column ${name}."${to.name}" is ${value}`;
439
- }
440
- alterTableComment(table, comment) {
441
- return `comment on table ${table.getQuotedName()} is ${this.platform.quoteValue(comment ?? '')}`;
442
- }
443
- normalizeDefaultValue(defaultValue, length) {
444
- if (!defaultValue || typeof defaultValue !== 'string') {
445
- return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
446
- }
447
- const match = defaultValue.match(/^'(.*)'::(.*)$/);
448
- if (match) {
449
- if (match[2] === 'integer') {
450
- return +match[1];
451
- }
452
- return `'${match[1]}'`;
453
- }
454
- return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
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
- }
470
- getDatabaseExistsSQL(name) {
471
- return `select 1 from pg_database where datname = '${name}'`;
472
- }
473
- getDatabaseNotExistsError(dbName) {
474
- return `database "${dbName}" does not exist`;
475
- }
476
- getManagementDbName() {
477
- return this.platform.getConfig().get('schemaGenerator', {}).managementDbName ?? 'postgres';
478
- }
479
- disableForeignKeysSQL() {
480
- return `set session_replication_role = 'replica';`;
481
- }
482
- enableForeignKeysSQL() {
483
- return `set session_replication_role = 'origin';`;
484
- }
485
- getRenameIndexSQL(tableName, index, oldIndexName) {
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)}`;
495
- }
496
- getIndexesSQL(tables) {
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,
498
- array(
499
- select pg_get_indexdef(idx.indexrelid, k + 1, true)
500
- from generate_subscripts(idx.indkey, 1) as k
501
- order by k
502
- ) as index_def,
503
- pg_get_indexdef(idx.indexrelid) as expression,
504
- c.condeferrable as deferrable,
505
- c.condeferred as initially_deferred
506
- from pg_index idx
507
- join pg_class as i on i.oid = idx.indexrelid
508
- join pg_namespace as ns on i.relnamespace = ns.oid
509
- left join pg_constraint as c on c.conname = i.relname
510
- where indrelid in (${tables.map(t => `${this.platform.quoteValue(`${this.quote(t.schema_name)}.${this.quote(t.table_name)}`)}::regclass`).join(', ')})
511
- order by relname`;
512
- }
513
- getChecksSQL(tablesBySchemas) {
514
- return `select ccu.table_name as table_name, ccu.table_schema as schema_name, pgc.conname as name, conrelid::regclass as table_from, ccu.column_name as column_name, pg_get_constraintdef(pgc.oid) as expression
515
- from pg_constraint pgc
516
- join pg_namespace nsp on nsp.oid = pgc.connamespace
517
- join pg_class cls on pgc.conrelid = cls.oid
518
- join information_schema.constraint_column_usage ccu on pgc.conname = ccu.constraint_name and nsp.nspname = ccu.constraint_schema
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 ')})
520
- order by pgc.conname`;
521
- }
522
- inferLengthFromColumnType(type) {
523
- const match = type.match(/^(\w+(?:\s+\w+)*)\s*(?:\(\s*(\d+)\s*\)|$)/);
524
- if (!match) {
525
- return;
526
- }
527
- if (!match[2]) {
528
- switch (match[1]) {
529
- case 'character varying':
530
- case 'varchar':
531
- case 'bpchar':
532
- case 'char':
533
- case 'character':
534
- return -1;
535
- case 'interval':
536
- case 'time':
537
- case 'timestamp':
538
- case 'timestamptz':
539
- return this.platform.getDefaultDateTimeLength();
540
- }
541
- return;
542
- }
543
- return +match[2];
544
- }
545
- }
@@ -1,14 +0,0 @@
1
- import { Type, type TransformContext, type RawQueryFragment } from '@mikro-orm/core';
2
- import type { PostgreSqlPlatform } from '../PostgreSqlPlatform.js';
3
- type FullTextWeight = 'A' | 'B' | 'C' | 'D';
4
- export type WeightedFullTextValue = {
5
- [K in FullTextWeight]?: string | null;
6
- };
7
- export declare class FullTextType extends Type<string | WeightedFullTextValue, string | null | RawQueryFragment> {
8
- regconfig: string;
9
- constructor(regconfig?: string);
10
- compareAsType(): string;
11
- getColumnType(): string;
12
- convertToDatabaseValue(value: string | WeightedFullTextValue, platform: PostgreSqlPlatform, context?: TransformContext | boolean): string | null | RawQueryFragment;
13
- }
14
- export {};