-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
PostgresDriver.ts
1492 lines (1354 loc) · 52.5 KB
/
PostgresDriver.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ObjectLiteral } from "../../common/ObjectLiteral"
import { DataSource } from "../../data-source/DataSource"
import { ConnectionIsNotSetError } from "../../error/ConnectionIsNotSetError"
import { DriverPackageNotInstalledError } from "../../error/DriverPackageNotInstalledError"
import { ColumnMetadata } from "../../metadata/ColumnMetadata"
import { EntityMetadata } from "../../metadata/EntityMetadata"
import { PlatformTools } from "../../platform/PlatformTools"
import { QueryRunner } from "../../query-runner/QueryRunner"
import { RdbmsSchemaBuilder } from "../../schema-builder/RdbmsSchemaBuilder"
import { TableColumn } from "../../schema-builder/table/TableColumn"
import { ApplyValueTransformers } from "../../util/ApplyValueTransformers"
import { DateUtils } from "../../util/DateUtils"
import { OrmUtils } from "../../util/OrmUtils"
import { Driver } from "../Driver"
import { ColumnType } from "../types/ColumnTypes"
import { DataTypeDefaults } from "../types/DataTypeDefaults"
import { MappedColumnTypes } from "../types/MappedColumnTypes"
import { ReplicationMode } from "../types/ReplicationMode"
import { VersionUtils } from "../../util/VersionUtils"
import { PostgresConnectionCredentialsOptions } from "./PostgresConnectionCredentialsOptions"
import { PostgresConnectionOptions } from "./PostgresConnectionOptions"
import { PostgresQueryRunner } from "./PostgresQueryRunner"
import { DriverUtils } from "../DriverUtils"
import { TypeORMError } from "../../error"
import { Table } from "../../schema-builder/table/Table"
import { View } from "../../schema-builder/view/View"
import { TableForeignKey } from "../../schema-builder/table/TableForeignKey"
import { InstanceChecker } from "../../util/InstanceChecker"
/**
* Organizes communication with PostgreSQL DBMS.
*/
export class PostgresDriver implements Driver {
// -------------------------------------------------------------------------
// Public Properties
// -------------------------------------------------------------------------
/**
* Connection used by driver.
*/
connection: DataSource
/**
* Postgres underlying library.
*/
postgres: any
/**
* Pool for master database.
*/
master: any
/**
* Pool for slave databases.
* Used in replication.
*/
slaves: any[] = []
/**
* We store all created query runners because we need to release them.
*/
connectedQueryRunners: QueryRunner[] = []
// -------------------------------------------------------------------------
// Public Implemented Properties
// -------------------------------------------------------------------------
/**
* Connection options.
*/
options: PostgresConnectionOptions
/**
* Database name used to perform all write queries.
*/
database?: string
/**
* Schema name used to perform all write queries.
*/
schema?: string
/**
* Schema that's used internally by Postgres for object resolution.
*
* Because we never set this we have to track it in separately from the `schema` so
* we know when we have to specify the full schema or not.
*
* In most cases this will be `public`.
*/
searchSchema?: string
/**
* Indicates if replication is enabled.
*/
isReplicated: boolean = false
/**
* Indicates if tree tables are supported by this driver.
*/
treeSupport = true
/**
* Represent transaction support by this driver
*/
transactionSupport = "nested" as const
/**
* Gets list of supported column data types by a driver.
*
* @see https://www.tutorialspoint.com/postgresql/postgresql_data_types.htm
* @see https://www.postgresql.org/docs/9.2/static/datatype.html
*/
supportedDataTypes: ColumnType[] = [
"int",
"int2",
"int4",
"int8",
"smallint",
"integer",
"bigint",
"decimal",
"numeric",
"real",
"float",
"float4",
"float8",
"double precision",
"money",
"character varying",
"varchar",
"character",
"char",
"text",
"citext",
"hstore",
"bytea",
"bit",
"varbit",
"bit varying",
"timetz",
"timestamptz",
"timestamp",
"timestamp without time zone",
"timestamp with time zone",
"date",
"time",
"time without time zone",
"time with time zone",
"interval",
"bool",
"boolean",
"enum",
"point",
"line",
"lseg",
"box",
"path",
"polygon",
"circle",
"cidr",
"inet",
"macaddr",
"tsvector",
"tsquery",
"uuid",
"xml",
"json",
"jsonb",
"int4range",
"int8range",
"numrange",
"tsrange",
"tstzrange",
"daterange",
"geometry",
"geography",
"cube",
"ltree",
]
/**
* Returns type of upsert supported by driver if any
*/
readonly supportedUpsertType = "on-conflict-do-update"
/**
* Gets list of spatial column data types.
*/
spatialTypes: ColumnType[] = ["geometry", "geography"]
/**
* Gets list of column data types that support length by a driver.
*/
withLengthColumnTypes: ColumnType[] = [
"character varying",
"varchar",
"character",
"char",
"bit",
"varbit",
"bit varying",
]
/**
* Gets list of column data types that support precision by a driver.
*/
withPrecisionColumnTypes: ColumnType[] = [
"numeric",
"decimal",
"interval",
"time without time zone",
"time with time zone",
"timestamp without time zone",
"timestamp with time zone",
]
/**
* Gets list of column data types that support scale by a driver.
*/
withScaleColumnTypes: ColumnType[] = ["numeric", "decimal"]
/**
* Orm has special columns and we need to know what database column types should be for those types.
* Column types are driver dependant.
*/
mappedDataTypes: MappedColumnTypes = {
createDate: "timestamp",
createDateDefault: "now()",
updateDate: "timestamp",
updateDateDefault: "now()",
deleteDate: "timestamp",
deleteDateNullable: true,
version: "int4",
treeLevel: "int4",
migrationId: "int4",
migrationName: "varchar",
migrationTimestamp: "int8",
cacheId: "int4",
cacheIdentifier: "varchar",
cacheTime: "int8",
cacheDuration: "int4",
cacheQuery: "text",
cacheResult: "text",
metadataType: "varchar",
metadataDatabase: "varchar",
metadataSchema: "varchar",
metadataTable: "varchar",
metadataName: "varchar",
metadataValue: "text",
}
/**
* Default values of length, precision and scale depends on column data type.
* Used in the cases when length/precision/scale is not specified by user.
*/
dataTypeDefaults: DataTypeDefaults = {
character: { length: 1 },
bit: { length: 1 },
interval: { precision: 6 },
"time without time zone": { precision: 6 },
"time with time zone": { precision: 6 },
"timestamp without time zone": { precision: 6 },
"timestamp with time zone": { precision: 6 },
}
/**
* Max length allowed by Postgres for aliases.
* @see https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
*/
maxAliasLength = 63
isGeneratedColumnsSupported: boolean = false
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(connection?: DataSource) {
if (!connection) {
return
}
this.connection = connection
this.options = connection.options as PostgresConnectionOptions
this.isReplicated = this.options.replication ? true : false
if (this.options.useUTC) {
process.env.PGTZ = "UTC"
}
// load postgres package
this.loadDependencies()
this.database = DriverUtils.buildDriverOptions(
this.options.replication
? this.options.replication.master
: this.options,
).database
this.schema = DriverUtils.buildDriverOptions(this.options).schema
// ObjectUtils.assign(this.options, DriverUtils.buildDriverOptions(connection.options)); // todo: do it better way
// validate options to make sure everything is set
// todo: revisit validation with replication in mind
// if (!this.options.host)
// throw new DriverOptionNotSetError("host");
// if (!this.options.username)
// throw new DriverOptionNotSetError("username");
// if (!this.options.database)
// throw new DriverOptionNotSetError("database");
}
// -------------------------------------------------------------------------
// Public Implemented Methods
// -------------------------------------------------------------------------
/**
* Performs connection to the database.
* Based on pooling options, it can either create connection immediately,
* either create a pool and create connection when needed.
*/
async connect(): Promise<void> {
if (this.options.replication) {
this.slaves = await Promise.all(
this.options.replication.slaves.map((slave) => {
return this.createPool(this.options, slave)
}),
)
this.master = await this.createPool(
this.options,
this.options.replication.master,
)
} else {
this.master = await this.createPool(this.options, this.options)
}
if (!this.database || !this.searchSchema) {
const queryRunner = await this.createQueryRunner("master")
if (!this.database) {
this.database = await queryRunner.getCurrentDatabase()
}
if (!this.searchSchema) {
this.searchSchema = await queryRunner.getCurrentSchema()
}
await queryRunner.release()
}
if (!this.schema) {
this.schema = this.searchSchema
}
}
/**
* Makes any action after connection (e.g. create extensions in Postgres driver).
*/
async afterConnect(): Promise<void> {
const extensionsMetadata = await this.checkMetadataForExtensions()
const [connection, release] = await this.obtainMasterConnection()
const installExtensions =
this.options.installExtensions === undefined ||
this.options.installExtensions
if (installExtensions && extensionsMetadata.hasExtensions) {
await this.enableExtensions(extensionsMetadata, connection)
}
const results = (await this.executeQuery(
connection,
"SHOW server_version;",
)) as {
rows: {
server_version: string
}[]
}
const versionString = results.rows[0].server_version
this.isGeneratedColumnsSupported = VersionUtils.isGreaterOrEqual(
versionString,
"12.0",
)
await release()
}
protected async enableExtensions(extensionsMetadata: any, connection: any) {
const { logger } = this.connection
const {
hasUuidColumns,
hasCitextColumns,
hasHstoreColumns,
hasCubeColumns,
hasGeometryColumns,
hasLtreeColumns,
hasExclusionConstraints,
} = extensionsMetadata
if (hasUuidColumns)
try {
await this.executeQuery(
connection,
`CREATE EXTENSION IF NOT EXISTS "${
this.options.uuidExtension || "uuid-ossp"
}"`,
)
} catch (_) {
logger.log(
"warn",
`At least one of the entities has uuid column, but the '${
this.options.uuidExtension || "uuid-ossp"
}' extension cannot be installed automatically. Please install it manually using superuser rights, or select another uuid extension.`,
)
}
if (hasCitextColumns)
try {
await this.executeQuery(
connection,
`CREATE EXTENSION IF NOT EXISTS "citext"`,
)
} catch (_) {
logger.log(
"warn",
"At least one of the entities has citext column, but the 'citext' extension cannot be installed automatically. Please install it manually using superuser rights",
)
}
if (hasHstoreColumns)
try {
await this.executeQuery(
connection,
`CREATE EXTENSION IF NOT EXISTS "hstore"`,
)
} catch (_) {
logger.log(
"warn",
"At least one of the entities has hstore column, but the 'hstore' extension cannot be installed automatically. Please install it manually using superuser rights",
)
}
if (hasGeometryColumns)
try {
await this.executeQuery(
connection,
`CREATE EXTENSION IF NOT EXISTS "postgis"`,
)
} catch (_) {
logger.log(
"warn",
"At least one of the entities has a geometry column, but the 'postgis' extension cannot be installed automatically. Please install it manually using superuser rights",
)
}
if (hasCubeColumns)
try {
await this.executeQuery(
connection,
`CREATE EXTENSION IF NOT EXISTS "cube"`,
)
} catch (_) {
logger.log(
"warn",
"At least one of the entities has a cube column, but the 'cube' extension cannot be installed automatically. Please install it manually using superuser rights",
)
}
if (hasLtreeColumns)
try {
await this.executeQuery(
connection,
`CREATE EXTENSION IF NOT EXISTS "ltree"`,
)
} catch (_) {
logger.log(
"warn",
"At least one of the entities has a cube column, but the 'ltree' extension cannot be installed automatically. Please install it manually using superuser rights",
)
}
if (hasExclusionConstraints)
try {
// The btree_gist extension provides operator support in PostgreSQL exclusion constraints
await this.executeQuery(
connection,
`CREATE EXTENSION IF NOT EXISTS "btree_gist"`,
)
} catch (_) {
logger.log(
"warn",
"At least one of the entities has an exclusion constraint, but the 'btree_gist' extension cannot be installed automatically. Please install it manually using superuser rights",
)
}
}
protected async checkMetadataForExtensions() {
const hasUuidColumns = this.connection.entityMetadatas.some(
(metadata) => {
return (
metadata.generatedColumns.filter(
(column) => column.generationStrategy === "uuid",
).length > 0
)
},
)
const hasCitextColumns = this.connection.entityMetadatas.some(
(metadata) => {
return (
metadata.columns.filter(
(column) => column.type === "citext",
).length > 0
)
},
)
const hasHstoreColumns = this.connection.entityMetadatas.some(
(metadata) => {
return (
metadata.columns.filter(
(column) => column.type === "hstore",
).length > 0
)
},
)
const hasCubeColumns = this.connection.entityMetadatas.some(
(metadata) => {
return (
metadata.columns.filter((column) => column.type === "cube")
.length > 0
)
},
)
const hasGeometryColumns = this.connection.entityMetadatas.some(
(metadata) => {
return (
metadata.columns.filter(
(column) => this.spatialTypes.indexOf(column.type) >= 0,
).length > 0
)
},
)
const hasLtreeColumns = this.connection.entityMetadatas.some(
(metadata) => {
return (
metadata.columns.filter((column) => column.type === "ltree")
.length > 0
)
},
)
const hasExclusionConstraints = this.connection.entityMetadatas.some(
(metadata) => {
return metadata.exclusions.length > 0
},
)
return {
hasUuidColumns,
hasCitextColumns,
hasHstoreColumns,
hasCubeColumns,
hasGeometryColumns,
hasLtreeColumns,
hasExclusionConstraints,
hasExtensions:
hasUuidColumns ||
hasCitextColumns ||
hasHstoreColumns ||
hasGeometryColumns ||
hasCubeColumns ||
hasLtreeColumns ||
hasExclusionConstraints,
}
}
/**
* Closes connection with database.
*/
async disconnect(): Promise<void> {
if (!this.master)
return Promise.reject(new ConnectionIsNotSetError("postgres"))
await this.closePool(this.master)
await Promise.all(this.slaves.map((slave) => this.closePool(slave)))
this.master = undefined
this.slaves = []
}
/**
* Creates a schema builder used to build and sync a schema.
*/
createSchemaBuilder() {
return new RdbmsSchemaBuilder(this.connection)
}
/**
* Creates a query runner used to execute database queries.
*/
createQueryRunner(mode: ReplicationMode): QueryRunner {
return new PostgresQueryRunner(this, mode)
}
/**
* Prepares given value to a value to be persisted, based on its column type and metadata.
*/
preparePersistentValue(value: any, columnMetadata: ColumnMetadata): any {
if (columnMetadata.transformer)
value = ApplyValueTransformers.transformTo(
columnMetadata.transformer,
value,
)
if (value === null || value === undefined) return value
if (columnMetadata.type === Boolean) {
return value === true ? 1 : 0
} else if (columnMetadata.type === "date") {
return DateUtils.mixedDateToDateString(value)
} else if (columnMetadata.type === "time") {
return DateUtils.mixedDateToTimeString(value)
} else if (
columnMetadata.type === "datetime" ||
columnMetadata.type === Date ||
columnMetadata.type === "timestamp" ||
columnMetadata.type === "timestamp with time zone" ||
columnMetadata.type === "timestamp without time zone"
) {
return DateUtils.mixedDateToDate(value)
} else if (
["json", "jsonb", ...this.spatialTypes].indexOf(
columnMetadata.type,
) >= 0
) {
return JSON.stringify(value)
} else if (columnMetadata.type === "hstore") {
if (typeof value === "string") {
return value
} else {
// https://www.postgresql.org/docs/9.0/hstore.html
const quoteString = (value: unknown) => {
// If a string to be quoted is `null` or `undefined`, we return a literal unquoted NULL.
// This way, NULL values can be stored in the hstore object.
if (value === null || typeof value === "undefined") {
return "NULL"
}
// Convert non-null values to string since HStore only stores strings anyway.
// To include a double quote or a backslash in a key or value, escape it with a backslash.
return `"${`${value}`.replace(/(?=["\\])/g, "\\")}"`
}
return Object.keys(value)
.map(
(key) =>
quoteString(key) + "=>" + quoteString(value[key]),
)
.join(",")
}
} else if (columnMetadata.type === "simple-array") {
return DateUtils.simpleArrayToString(value)
} else if (columnMetadata.type === "simple-json") {
return DateUtils.simpleJsonToString(value)
} else if (columnMetadata.type === "cube") {
if (columnMetadata.isArray) {
return `{${value
.map((cube: number[]) => `"(${cube.join(",")})"`)
.join(",")}}`
}
return `(${value.join(",")})`
} else if (columnMetadata.type === "ltree") {
return value
.split(".")
.filter(Boolean)
.join(".")
.replace(/[\s]+/g, "_")
} else if (
(columnMetadata.type === "enum" ||
columnMetadata.type === "simple-enum") &&
!columnMetadata.isArray
) {
return "" + value
}
return value
}
/**
* Prepares given value to a value to be persisted, based on its column type or metadata.
*/
prepareHydratedValue(value: any, columnMetadata: ColumnMetadata): any {
if (value === null || value === undefined)
return columnMetadata.transformer
? ApplyValueTransformers.transformFrom(
columnMetadata.transformer,
value,
)
: value
if (columnMetadata.type === Boolean) {
value = value ? true : false
} else if (
columnMetadata.type === "datetime" ||
columnMetadata.type === Date ||
columnMetadata.type === "timestamp" ||
columnMetadata.type === "timestamp with time zone" ||
columnMetadata.type === "timestamp without time zone"
) {
value = DateUtils.normalizeHydratedDate(value)
} else if (columnMetadata.type === "date") {
value = DateUtils.mixedDateToDateString(value)
} else if (columnMetadata.type === "time") {
value = DateUtils.mixedTimeToString(value)
} else if (columnMetadata.type === "hstore") {
if (columnMetadata.hstoreType === "object") {
const unescapeString = (str: string) =>
str.replace(/\\./g, (m) => m[1])
const regexp =
/"([^"\\]*(?:\\.[^"\\]*)*)"=>(?:(NULL)|"([^"\\]*(?:\\.[^"\\]*)*)")(?:,|$)/g
const object: ObjectLiteral = {}
;`${value}`.replace(
regexp,
(_, key, nullValue, stringValue) => {
object[unescapeString(key)] = nullValue
? null
: unescapeString(stringValue)
return ""
},
)
return object
} else {
return value
}
} else if (columnMetadata.type === "simple-array") {
value = DateUtils.stringToSimpleArray(value)
} else if (columnMetadata.type === "simple-json") {
value = DateUtils.stringToSimpleJson(value)
} else if (columnMetadata.type === "cube") {
value = value.replace(/[\(\)\s]+/g, "") // remove whitespace
if (columnMetadata.isArray) {
/**
* Strips these groups from `{"1,2,3","",NULL}`:
* 1. ["1,2,3", undefined] <- cube of arity 3
* 2. ["", undefined] <- cube of arity 0
* 3. [undefined, "NULL"] <- NULL
*/
const regexp = /(?:\"((?:[\d\s\.,])*)\")|(?:(NULL))/g
const unparsedArrayString = value
value = []
let cube: RegExpExecArray | null = null
// Iterate through all regexp matches for cubes/null in array
while ((cube = regexp.exec(unparsedArrayString)) !== null) {
if (cube[1] !== undefined) {
value.push(
cube[1].split(",").filter(Boolean).map(Number),
)
} else {
value.push(undefined)
}
}
} else {
value = value.split(",").filter(Boolean).map(Number)
}
} else if (
columnMetadata.type === "enum" ||
columnMetadata.type === "simple-enum"
) {
if (columnMetadata.isArray) {
if (value === "{}") return []
// manually convert enum array to array of values (pg does not support, see https://github.com/brianc/node-pg-types/issues/56)
value = (value as string)
.substr(1, (value as string).length - 2)
.split(",")
.map((val) => {
// replace double quotes from the beginning and from the end
if (val.startsWith(`"`) && val.endsWith(`"`))
val = val.slice(1, -1)
// replace double escaped backslash to single escaped e.g. \\\\ -> \\
val = val.replace(/(\\\\)/g, "\\")
// replace escaped double quotes to non-escaped e.g. \"asd\" -> "asd"
return val.replace(/(\\")/g, '"')
})
// convert to number if that exists in possible enum options
value = value.map((val: string) => {
return !isNaN(+val) &&
columnMetadata.enum!.indexOf(parseInt(val)) >= 0
? parseInt(val)
: val
})
} else {
// convert to number if that exists in possible enum options
value =
!isNaN(+value) &&
columnMetadata.enum!.indexOf(parseInt(value)) >= 0
? parseInt(value)
: value
}
}
if (columnMetadata.transformer)
value = ApplyValueTransformers.transformFrom(
columnMetadata.transformer,
value,
)
return value
}
/**
* Replaces parameters in the given sql with special escaping character
* and an array of parameter names to be passed to a query.
*/
escapeQueryWithParameters(
sql: string,
parameters: ObjectLiteral,
nativeParameters: ObjectLiteral,
): [string, any[]] {
const escapedParameters: any[] = Object.keys(nativeParameters).map(
(key) => nativeParameters[key],
)
if (!parameters || !Object.keys(parameters).length)
return [sql, escapedParameters]
sql = sql.replace(
/:(\.\.\.)?([A-Za-z0-9_.]+)/g,
(full, isArray: string, key: string): string => {
if (!parameters.hasOwnProperty(key)) {
return full
}
let value: any = parameters[key]
if (isArray) {
return value
.map((v: any) => {
escapedParameters.push(v)
return this.createParameter(
key,
escapedParameters.length - 1,
)
})
.join(", ")
}
if (typeof value === "function") {
return value()
}
escapedParameters.push(value)
return this.createParameter(key, escapedParameters.length - 1)
},
) // todo: make replace only in value statements, otherwise problems
return [sql, escapedParameters]
}
/**
* Escapes a column name.
*/
escape(columnName: string): string {
return '"' + columnName + '"'
}
/**
* Build full table name with schema name and table name.
* E.g. myDB.mySchema.myTable
*/
buildTableName(tableName: string, schema?: string): string {
let tablePath = [tableName]
if (schema) {
tablePath.unshift(schema)
}
return tablePath.join(".")
}
/**
* Parse a target table name or other types and return a normalized table definition.
*/
parseTableName(
target: EntityMetadata | Table | View | TableForeignKey | string,
): { database?: string; schema?: string; tableName: string } {
const driverDatabase = this.database
const driverSchema = this.schema
if (InstanceChecker.isTable(target) || InstanceChecker.isView(target)) {
const parsed = this.parseTableName(target.name)
return {
database: target.database || parsed.database || driverDatabase,
schema: target.schema || parsed.schema || driverSchema,
tableName: parsed.tableName,
}
}
if (InstanceChecker.isTableForeignKey(target)) {
const parsed = this.parseTableName(target.referencedTableName)
return {
database:
target.referencedDatabase ||
parsed.database ||
driverDatabase,
schema:
target.referencedSchema || parsed.schema || driverSchema,
tableName: parsed.tableName,
}
}
if (InstanceChecker.isEntityMetadata(target)) {
// EntityMetadata tableName is never a path
return {
database: target.database || driverDatabase,
schema: target.schema || driverSchema,
tableName: target.tableName,
}
}
const parts = target.split(".")
return {
database: driverDatabase,
schema: (parts.length > 1 ? parts[0] : undefined) || driverSchema,
tableName: parts.length > 1 ? parts[1] : parts[0],
}
}
/**
* Creates a database type from a given column metadata.
*/
normalizeType(column: {
type?: ColumnType
length?: number | string
precision?: number | null
scale?: number
isArray?: boolean
}): string {
if (
column.type === Number ||
column.type === "int" ||
column.type === "int4"
) {
return "integer"
} else if (column.type === String || column.type === "varchar") {
return "character varying"
} else if (column.type === Date || column.type === "timestamp") {
return "timestamp without time zone"
} else if (column.type === "timestamptz") {
return "timestamp with time zone"
} else if (column.type === "time") {
return "time without time zone"
} else if (column.type === "timetz") {
return "time with time zone"
} else if (column.type === Boolean || column.type === "bool") {
return "boolean"
} else if (column.type === "simple-array") {
return "text"
} else if (column.type === "simple-json") {
return "text"
} else if (column.type === "simple-enum") {
return "enum"
} else if (column.type === "int2") {
return "smallint"
} else if (column.type === "int8") {
return "bigint"
} else if (column.type === "decimal") {
return "numeric"
} else if (column.type === "float8" || column.type === "float") {
return "double precision"
} else if (column.type === "float4") {
return "real"
} else if (column.type === "char") {
return "character"
} else if (column.type === "varbit") {
return "bit varying"
} else {
return (column.type as string) || ""
}
}
/**
* Normalizes "default" value of the column.
*/
normalizeDefault(columnMetadata: ColumnMetadata): string | undefined {
const defaultValue = columnMetadata.default
if (defaultValue === null) {
return undefined
}
if (columnMetadata.isArray && Array.isArray(defaultValue)) {
return `'{${defaultValue
.map((val: string) => `${val}`)
.join(",")}}'`
}
if (
(columnMetadata.type === "enum" ||
columnMetadata.type === "simple-enum" ||
typeof defaultValue === "number" ||
typeof defaultValue === "string") &&
defaultValue !== undefined
) {
return `'${defaultValue}'`
}
if (typeof defaultValue === "boolean") {
return defaultValue ? "true" : "false"
}