/
PostgreSqlPlatform.ts
381 lines (304 loc) · 11.2 KB
/
PostgreSqlPlatform.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import { Client } from 'pg';
import parseDate from 'postgres-date';
import PostgresInterval, { type IPostgresInterval } from 'postgres-interval';
import { raw, ALIAS_REPLACEMENT, JsonProperty, Utils, type EntityProperty, Type, type SimpleColumnMeta, type Dictionary } from '@mikro-orm/core';
import { AbstractSqlPlatform, type IndexDef } from '@mikro-orm/knex';
import { PostgreSqlSchemaHelper } from './PostgreSqlSchemaHelper';
import { PostgreSqlExceptionConverter } from './PostgreSqlExceptionConverter';
import { FullTextType } from './types/FullTextType';
export class PostgreSqlPlatform extends AbstractSqlPlatform {
protected override readonly schemaHelper: PostgreSqlSchemaHelper = new PostgreSqlSchemaHelper(this);
protected override readonly exceptionConverter = new PostgreSqlExceptionConverter();
override usesReturningStatement(): boolean {
return true;
}
override usesCascadeStatement(): boolean {
return true;
}
override supportsNativeEnums(): boolean {
return true;
}
override supportsCustomPrimaryKeyNames(): boolean {
return true;
}
/**
* Postgres will complain if we try to batch update uniquely constrained property (moving the value from one entity to another).
* This flag will result in postponing 1:1 updates (removing them from the batched query).
* @see https://stackoverflow.com/questions/5403437/atomic-multi-row-update-with-a-unique-constraint
*/
override allowsUniqueBatchUpdates() {
return false;
}
override getCurrentTimestampSQL(length: number): string {
return `current_timestamp(${length})`;
}
override getDateTimeTypeDeclarationSQL(column: { length?: number }): string {
/* istanbul ignore next */
return 'timestamptz' + (column.length != null ? `(${column.length})` : '');
}
override getDefaultDateTimeLength(): number {
return 6; // timestamptz actually means timestamptz(6)
}
override convertIntervalToJSValue(value: string): unknown {
return PostgresInterval(value);
}
override convertIntervalToDatabaseValue(value: IPostgresInterval): unknown {
if (Utils.isObject(value) && 'toPostgres' in value && typeof value.toPostgres === 'function') {
return value.toPostgres();
}
return value;
}
override getTimeTypeDeclarationSQL(): string {
return 'time(0)';
}
override getIntegerTypeDeclarationSQL(column: { length?: number; autoincrement?: boolean; generated?: string }): string {
if (column.autoincrement && !column.generated) {
return `serial`;
}
return `int`;
}
override getBigIntTypeDeclarationSQL(column: { autoincrement?: boolean }): string {
/* istanbul ignore next */
if (column.autoincrement) {
return `bigserial`;
}
return 'bigint';
}
override getTinyIntTypeDeclarationSQL(column: { length?: number; unsigned?: boolean; autoincrement?: boolean }): string {
return 'smallint';
}
override getUuidTypeDeclarationSQL(column: { length?: number }): string {
return `uuid`;
}
override getFullTextWhereClause(prop: EntityProperty): string {
if (prop.customType instanceof FullTextType) {
return `:column: @@ plainto_tsquery('${prop.customType.regconfig}', :query)`;
}
/* istanbul ignore next */
if (prop.columnTypes[0] === 'tsvector') {
return `:column: @@ plainto_tsquery('simple', :query)`;
}
return `to_tsvector('simple', :column:) @@ plainto_tsquery('simple', :query)`;
}
override supportsCreatingFullTextIndex(): boolean {
return true;
}
override getFullTextIndexExpression(indexName: string, schemaName: string | undefined, tableName: string, columns: SimpleColumnMeta[]): string {
/* istanbul ignore next */
const quotedTableName = this.quoteIdentifier(schemaName ? `${schemaName}.${tableName}` : tableName);
const quotedColumnNames = columns.map(c => this.quoteIdentifier(c.name));
const quotedIndexName = this.quoteIdentifier(indexName);
if (columns.length === 1 && columns[0].type === 'tsvector') {
return `create index ${quotedIndexName} on ${quotedTableName} using gin(${quotedColumnNames[0]})`;
}
return `create index ${quotedIndexName} on ${quotedTableName} using gin(to_tsvector('simple', ${quotedColumnNames.join(` || ' ' || `)}))`;
}
override getMappedType(type: string): Type<unknown> {
switch (this.extractSimpleType(type)) {
case 'tsvector': return Type.getType(FullTextType);
default: return super.getMappedType(type);
}
}
override getRegExpOperator(val?: unknown, flags?: string): string {
/* istanbul ignore next */
if ((val instanceof RegExp && val.flags.includes('i')) || flags?.includes('i')) {
return '~*';
}
return '~';
}
override getRegExpValue(val: RegExp): { $re: string; $flags?: string } {
/* istanbul ignore else */
if (val.flags.includes('i')) {
return { $re: val.source, $flags: val.flags };
}
/* istanbul ignore next */
return { $re: val.source };
}
override isBigIntProperty(prop: EntityProperty): boolean {
return super.isBigIntProperty(prop) || (['bigserial', 'int8'].includes(prop.columnTypes?.[0]));
}
override getArrayDeclarationSQL(): string {
return 'text[]';
}
override getFloatDeclarationSQL(): string {
return 'real';
}
override getDoubleDeclarationSQL(): string {
return 'double precision';
}
override getEnumTypeDeclarationSQL(column: { fieldNames: string[]; items?: unknown[]; nativeEnumName?: string }): string {
/* istanbul ignore next */
if (column.nativeEnumName) {
return column.nativeEnumName;
}
if (column.items?.every(item => Utils.isString(item))) {
return 'text';
}
return `smallint`;
}
override supportsMultipleStatements(): boolean {
return true;
}
override marshallArray(values: string[]): string {
const quote = (v: string) => v === '' || v.match(/["{},\\]/) ? JSON.stringify(v) : v;
return `{${values.map(v => quote('' + v)).join(',')}}`;
}
override unmarshallArray(value: string): string[] {
if (value === '{}') {
return [];
}
/* istanbul ignore next */
return value.substring(1, value.length - 1).split(',').map(v => v === `""` ? '' : v);
}
override getBlobDeclarationSQL(): string {
return 'bytea';
}
override getJsonDeclarationSQL(): string {
return 'jsonb';
}
override getSearchJsonPropertyKey(path: string[], type: string | undefined | Type, aliased: boolean, value?: unknown): string {
const first = path.shift();
const last = path.pop();
const root = this.quoteIdentifier(aliased ? `${ALIAS_REPLACEMENT}.${first}` : first!);
type = typeof type === 'string' ? this.getMappedType(type).runtimeType : String(type);
const types = {
number: 'float8',
bigint: 'int8',
boolean: 'bool',
} as Dictionary;
const cast = (key: string) => raw(type as string in types ? `(${key})::${types[type as string]}` : key);
let lastOperator = '->>';
// force `->` for operator payloads with array values
if (Utils.isPlainObject(value) && Object.keys(value).every(key => Utils.isArrayOperator(key) && Array.isArray(value[key]))) {
lastOperator = '->';
}
if (path.length === 0) {
return cast(`${root}${lastOperator}'${last}'`);
}
return cast(`${root}->${path.map(a => this.quoteValue(a)).join('->')}${lastOperator}'${last}'`);
}
override getJsonIndexDefinition(index: IndexDef): string[] {
return index.columnNames
.map(column => {
if (!column.includes('.')) {
return column;
}
const path = column.split('.');
const first = path.shift()!;
const last = path.pop()!;
if (path.length === 0) {
return `(${this.quoteIdentifier(first)}->>${this.quoteValue(last)})`;
}
return `(${this.quoteIdentifier(first)}->${path.map(c => this.quoteValue(c)).join('->')}->>${this.quoteValue(last)})`;
});
}
override quoteIdentifier(id: string, quote = '"'): string {
return `${quote}${id.replace('.', `${quote}.${quote}`)}${quote}`;
}
override quoteValue(value: any): string {
/* istanbul ignore if */
if (Utils.isPlainObject(value) || value?.[JsonProperty]) {
value = JSON.stringify(value);
}
if (typeof value === 'string') {
return Client.prototype.escapeLiteral(value);
}
if (value instanceof Date) {
return `'${value.toISOString()}'`;
}
if (ArrayBuffer.isView(value)) {
return `E'\\\\x${(value as Buffer).toString('hex')}'`;
}
return super.quoteValue(value);
}
override indexForeignKeys() {
return false;
}
override getDefaultMappedType(type: string): Type<unknown> {
const normalizedType = this.extractSimpleType(type);
const map = {
'int2': 'smallint',
'smallserial': 'smallint',
'int': 'integer',
'int4': 'integer',
'serial': 'integer',
'serial4': 'integer',
'int8': 'bigint',
'bigserial': 'bigint',
'serial8': 'bigint',
'numeric': 'decimal',
'bool': 'boolean',
'real': 'float',
'float4': 'float',
'float8': 'double',
'timestamp': 'datetime',
'timestamptz': 'datetime',
'bytea': 'blob',
'jsonb': 'json',
'character varying': 'varchar',
};
return super.getDefaultMappedType(map[normalizedType as keyof typeof map] ?? type);
}
override supportsSchemas(): boolean {
return true;
}
override getDefaultSchemaName(): string | undefined {
return 'public';
}
/**
* Returns the default name of index for the given columns
* cannot go past 64 character length for identifiers in MySQL
*/
override getIndexName(tableName: string, columns: string[], type: 'index' | 'unique' | 'foreign' | 'primary' | 'sequence'): string {
const indexName = super.getIndexName(tableName, columns, type);
if (indexName.length > 64) {
return `${indexName.substring(0, 56 - type.length)}_${Utils.hash(indexName, 5)}_${type}`;
}
return indexName;
}
override getDefaultPrimaryName(tableName: string, columns: string[]): string {
const indexName = `${tableName}_pkey`;
if (indexName.length > 64) {
return `${indexName.substring(0, 56 - 'primary'.length)}_${Utils.hash(indexName, 5)}_primary`;
}
return indexName;
}
/**
* @inheritDoc
*/
override castColumn(prop?: { columnTypes?: string[] }): string {
switch (prop?.columnTypes?.[0]) {
case this.getUuidTypeDeclarationSQL({}): return '::text';
case this.getBooleanTypeDeclarationSQL(): return '::int';
default: return '';
}
}
/**
* @inheritDoc
*/
override castJsonValue(prop?: { columnTypes?: string[] }): string {
/* istanbul ignore next */
if (prop?.columnTypes?.[0] === 'json') {
return '::text';
}
return '';
}
/**
* @inheritDoc
*/
override parseDate(value: string | number): Date {
// postgres-date returns `null` for a JS ISO string which has the `T` separator
if (typeof value === 'string' && value.charAt(10) === 'T') {
return new Date(value);
}
/* istanbul ignore next */
if (typeof value === 'number') {
return new Date(value);
}
const parsed = parseDate(value);
if (parsed === null) {
return value as unknown as Date;
}
return parsed as Date;
}
}