-
-
Notifications
You must be signed in to change notification settings - Fork 129
/
PgIntrospectionPlugin.js
1351 lines (1262 loc) · 40.7 KB
/
PgIntrospectionPlugin.js
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
// @flow
import type { Plugin } from "graphile-build";
import type { Client } from "pg";
import withPgClient, {
getPgClientAndReleaserFromConfig,
} from "../withPgClient";
import { parseTags } from "../utils";
import { readFile as rawReadFile } from "fs";
import debugFactory from "debug";
import chalk from "chalk";
import throttle from "lodash/throttle";
import flatMap from "lodash/flatMap";
import { makeIntrospectionQuery } from "./introspectionQuery";
import * as pgSql from "pg-sql2";
import { version } from "../../package.json";
import queryFromResolveDataFactory from "../queryFromResolveDataFactory";
const debug = debugFactory("graphile-build-pg");
const WATCH_FIXTURES_PATH = `${__dirname}/../../res/watch-fixtures.sql`;
// Ref: https://github.com/graphile/postgraphile/tree/master/src/postgres/introspection/object
export type PgNamespace = {
kind: "namespace",
id: string,
name: string,
comment: ?string,
description: ?string,
tags: { [string]: string },
};
export type PgProc = {
kind: "procedure",
id: string,
name: string,
comment: ?string,
description: ?string,
namespaceId: string,
namespaceName: string,
isStrict: boolean,
returnsSet: boolean,
isStable: boolean,
returnTypeId: string,
argTypeIds: Array<string>,
argNames: Array<string>,
argModes: Array<"i" | "o" | "b" | "v" | "t">,
inputArgsCount: number,
argDefaultsNum: number,
namespace: PgNamespace,
tags: { [string]: string },
cost: number,
aclExecutable: boolean,
language: string,
};
export type PgClass = {
kind: "class",
id: string,
name: string,
comment: ?string,
description: ?string,
classKind: string,
namespaceId: string,
namespaceName: string,
typeId: string,
isSelectable: boolean,
isInsertable: boolean,
isUpdatable: boolean,
isDeletable: boolean,
isExtensionConfigurationTable: boolean,
namespace: PgNamespace,
type: PgType,
tags: { [string]: string },
attributes: Array<PgAttribute>,
constraints: Array<PgConstraint>,
foreignConstraints: Array<PgConstraint>,
primaryKeyConstraint: ?PgConstraint,
aclSelectable: boolean,
aclInsertable: boolean,
aclUpdatable: boolean,
aclDeletable: boolean,
canUseAsterisk: boolean,
// eslint-disable-next-line flowtype/no-weak-types
_internalEnumData?: any[], // This is Graphile internal, do not use this.
};
export type PgType = {
kind: "type",
id: string,
name: string,
comment: ?string,
description: ?string,
namespaceId: string,
namespaceName: string,
type: string,
category: string,
domainIsNotNull: boolean,
arrayItemTypeId: ?string,
arrayItemType: ?PgType,
arrayType: ?PgType,
typeLength: ?number,
isPgArray: boolean,
classId: ?string,
class: ?PgClass,
domainBaseTypeId: ?string,
domainBaseType: ?PgType,
domainTypeModifier: ?number,
domainHasDefault: boolean,
enumVariants: ?(string[]),
enumDescriptions: ?(string[]),
rangeSubTypeId: ?string,
tags: { [string]: string },
isFake: ?boolean,
};
export type PgAttribute = {
kind: "attribute",
classId: string,
num: number,
name: string,
comment: ?string,
description: ?string,
typeId: string,
typeModifier: number,
isNotNull: boolean,
hasDefault: boolean,
identity: "" | "a" | "d",
class: PgClass,
type: PgType,
namespace: PgNamespace,
tags: { [string]: string },
aclSelectable: boolean,
aclInsertable: boolean,
aclUpdatable: boolean,
isIndexed: ?boolean,
isUnique: ?boolean,
columnLevelSelectGrant: boolean,
};
export type PgConstraint = {
kind: "constraint",
id: string,
name: string,
type: string,
classId: string,
class: PgClass,
foreignClassId: ?string,
foreignClass: ?PgClass,
comment: ?string,
description: ?string,
keyAttributeNums: Array<number>,
keyAttributes: Array<PgAttribute>,
foreignKeyAttributeNums: Array<number>,
foreignKeyAttributes: Array<PgAttribute>,
namespace: PgNamespace,
isIndexed: ?boolean,
tags: { [string]: string },
};
export type PgExtension = {
kind: "extension",
id: string,
name: string,
namespaceId: string,
namespaceName: string,
relocatable: boolean,
version: string,
configurationClassIds?: Array<string>,
comment: ?string,
description: ?string,
tags: { [string]: string },
};
export type PgIndex = {
kind: "index",
id: string,
name: string,
namespaceName: string,
classId: string,
numberOfAttributes: number,
indexType: string,
isUnique: boolean,
isPrimary: boolean,
/*
Though these exist, we don't want to officially
support them yet.
isImmediate: boolean,
isReplicaIdentity: boolean,
isValid: boolean,
*/
isPartial: boolean,
attributeNums: Array<number>,
attributePropertiesAsc: ?Array<boolean>,
attributePropertiesNullsFirst: ?Array<boolean>,
description: ?string,
tags: { [string]: string },
};
export type PgEntity =
| PgNamespace
| PgProc
| PgClass
| PgType
| PgAttribute
| PgConstraint
| PgExtension
| PgIndex;
export type PgIntrospectionResultsByKind = {
__pgVersion: number,
attribute: PgAttribute[],
attributeByClassIdAndNum: {
[classId: string]: { [num: string]: PgAttribute },
},
class: PgClass[],
classById: { [classId: string]: PgClass },
constraint: PgConstraint[],
extension: PgExtension[],
extensionById: { [extId: string]: PgExtension },
index: PgIndex[],
namespace: PgNamespace[],
namespaceById: { [namespaceId: string]: PgNamespace },
procedure: PgProc[],
type: PgType[],
typeById: { [typeId: string]: PgType },
};
function readFile(filename, encoding) {
return new Promise((resolve, reject) => {
rawReadFile(filename, encoding, (err, res) => {
if (err) reject(err);
else resolve(res);
});
});
}
const removeQuotes = str => {
const trimmed = str.trim();
if (trimmed[0] === '"') {
if (trimmed[trimmed.length - 1] !== '"') {
throw new Error(
`We failed to parse a quoted identifier '${str}'. Please avoid putting quotes or commas in smart comment identifiers (or file a PR to fix the parser).`
);
}
return trimmed.substr(1, trimmed.length - 2);
} else {
// PostgreSQL lower-cases unquoted columns, so we should too.
return trimmed.toLowerCase();
}
};
const parseSqlColumnArray = str => {
if (!str) {
throw new Error(`Cannot parse '${str}'`);
}
const parts = str.split(",");
return parts.map(removeQuotes);
};
const parseSqlColumnString = str => {
if (!str) {
throw new Error(`Cannot parse '${str}'`);
}
return removeQuotes(str);
};
function parseConstraintSpec(rawSpec) {
const [spec, ...tagComponents] = rawSpec.split(/\|/);
const parsed = parseTags(tagComponents.join("\n"));
return {
spec,
tags: parsed.tags,
description: parsed.text,
};
}
function smartCommentConstraints(introspectionResults) {
const attributesByNames = (tbl, cols, debugStr) => {
const attributes = introspectionResults.attribute
.filter(a => a.classId === tbl.id)
.sort((a, b) => a.num - b.num);
if (!cols) {
const pk = introspectionResults.constraint.find(
c => c.classId == tbl.id && c.type === "p"
);
if (pk) {
return pk.keyAttributeNums.map(n => attributes.find(a => a.num === n));
} else {
throw new Error(
`No columns specified for '${tbl.namespaceName}.${tbl.name}' (oid: ${tbl.id}) and no PK found (${debugStr}).`
);
}
}
return cols.map(colName => {
const attr = attributes.find(a => a.name === colName);
if (!attr) {
throw new Error(
`Could not find attribute '${colName}' in '${tbl.namespaceName}.${tbl.name}'`
);
}
return attr;
});
};
// First: primary and unique keys
introspectionResults.class.forEach(klass => {
const namespace = introspectionResults.namespace.find(
n => n.id === klass.namespaceId
);
if (!namespace) {
return;
}
function addKey(key: string, isPrimary = false) {
const tag = isPrimary ? "@primaryKey" : "@unique";
if (typeof key !== "string") {
if (isPrimary) {
throw new Error(
`${tag} configuration of '${klass.namespaceName}.${klass.name}' is invalid; please specify just once "${tag} col1,col2"`
);
}
throw new Error(
`${tag} configuration of '${klass.namespaceName}.${
klass.name
}' is invalid; expected ${
isPrimary ? "a string" : "a string or string array"
} but found ${typeof key}`
);
}
const { spec: keySpec, tags, description } = parseConstraintSpec(key);
const columns: string[] = parseSqlColumnArray(keySpec);
const attributes = attributesByNames(klass, columns, `${tag} ${key}`);
if (isPrimary) {
attributes.forEach(attr => {
attr.tags.notNull = true;
});
}
const keyAttributeNums = attributes.map(a => a.num);
// Now we need to fake a constraint for this:
const fakeConstraint = {
kind: "constraint",
isFake: true,
isIndexed: true, // otherwise it gets ignored by ignoreIndexes
id: Math.random(),
name: `FAKE_${klass.namespaceName}_${klass.name}_${tag}`,
type: isPrimary ? "p" : "u",
classId: klass.id,
foreignClassId: null,
comment: null,
description,
keyAttributeNums,
foreignKeyAttributeNums: null,
tags,
};
introspectionResults.constraint.push(fakeConstraint);
}
if (klass.tags.primaryKey) {
addKey(klass.tags.primaryKey, true);
}
if (klass.tags.unique) {
if (Array.isArray(klass.tags.unique)) {
klass.tags.unique.forEach(key => addKey(key));
} else {
addKey(klass.tags.unique);
}
}
});
// Now primary keys are in place, we can apply foreign keys
introspectionResults.class.forEach(klass => {
const namespace = introspectionResults.namespace.find(
n => n.id === klass.namespaceId
);
if (!namespace) {
return;
}
const getType = () =>
introspectionResults.type.find(t => t.id === klass.typeId);
const foreignKey = klass.tags.foreignKey || getType().tags.foreignKey;
if (foreignKey) {
const foreignKeys =
typeof foreignKey === "string" ? [foreignKey] : foreignKey;
if (!Array.isArray(foreignKeys)) {
throw new Error(
`Invalid foreign key smart comment specified on '${klass.namespaceName}.${klass.name}'`
);
}
foreignKeys.forEach((fkSpecRaw, index) => {
if (typeof fkSpecRaw !== "string") {
throw new Error(
`Invalid foreign key spec (${index}) on '${klass.namespaceName}.${klass.name}'`
);
}
const {
spec: fkSpec,
tags,
description,
} = parseConstraintSpec(fkSpecRaw);
const matches = fkSpec.match(
/^\(([^()]+)\) references ([^().]+)(?:\.([^().]+))?(?:\s*\(([^()]+)\))?$/i
);
if (!matches) {
throw new Error(
`Invalid foreignKey syntax for '${klass.namespaceName}.${klass.name}'; expected something like "(col1,col2) references schema.table (c1, c2)", you passed '${fkSpecRaw}'`
);
}
const [
,
rawColumns,
rawSchemaOrTable,
rawTableOnly,
rawForeignColumns,
] = matches;
const rawSchema = rawTableOnly
? rawSchemaOrTable
: `"${klass.namespaceName}"`;
const rawTable = rawTableOnly || rawSchemaOrTable;
const columns: string[] = parseSqlColumnArray(rawColumns);
const foreignSchema: string = parseSqlColumnString(rawSchema);
const foreignTable: string = parseSqlColumnString(rawTable);
const foreignColumns: string[] | null = rawForeignColumns
? parseSqlColumnArray(rawForeignColumns)
: null;
const foreignKlass = introspectionResults.class.find(
k => k.name === foreignTable && k.namespaceName === foreignSchema
);
if (!foreignKlass) {
throw new Error(
`@foreignKey smart comment referenced non-existant table/view '${foreignSchema}'.'${foreignTable}'. Note that this reference must use *database names* (i.e. it does not respect @name). (${fkSpecRaw})`
);
}
const foreignNamespace = introspectionResults.namespace.find(
n => n.id === foreignKlass.namespaceId
);
if (!foreignNamespace) {
return;
}
const keyAttributeNums = attributesByNames(
klass,
columns,
`@foreignKey ${fkSpecRaw}`
).map(a => a.num);
const foreignKeyAttributeNums = attributesByNames(
foreignKlass,
foreignColumns,
`@foreignKey ${fkSpecRaw}`
).map(a => a.num);
// Now we need to fake a constraint for this:
const fakeConstraint = {
kind: "constraint",
isFake: true,
isIndexed: true, // otherwise it gets ignored by ignoreIndexes
id: Math.random(),
name: `FAKE_${klass.namespaceName}_${klass.name}_foreignKey_${index}`,
type: "f", // foreign key
classId: klass.id,
foreignClassId: foreignKlass.id,
comment: null,
description,
keyAttributeNums,
foreignKeyAttributeNums,
tags,
};
introspectionResults.constraint.push(fakeConstraint);
});
}
});
}
function isEnumConstraint(
klass: PgClass,
con: PgConstraint,
isEnumTable: boolean
) {
if (con.classId === klass.id) {
const isPrimaryKey = con.type === "p";
const isUniqueConstraint = con.type === "u";
if (isPrimaryKey || isUniqueConstraint) {
const isExplicitEnumConstraint =
con.tags.enum === true || typeof con.tags.enum === "string";
const isPrimaryKeyOfEnumTableConstraint = con.type === "p" && isEnumTable;
if (isExplicitEnumConstraint || isPrimaryKeyOfEnumTableConstraint) {
const hasExactlyOneColumn = con.keyAttributeNums.length === 1;
if (!hasExactlyOneColumn) {
throw new Error(
`Enum table "${klass.namespaceName}"."${klass.name}" enum constraint '${con.name}' is composite; it should have exactly one column (found: ${con.keyAttributeNums.length})`
);
}
return true;
}
}
}
return false;
}
function enumTables(introspectionResults) {
introspectionResults.class.map(async klass => {
const isEnumTable =
klass.tags.enum === true || typeof klass.tags.enum === "string";
if (isEnumTable) {
// Prevent the table being recognised as a table
// eslint-disable-next-line require-atomic-updates
klass.tags.omit = true;
// eslint-disable-next-line require-atomic-updates
klass.isSelectable = false;
// eslint-disable-next-line require-atomic-updates
klass.isInsertable = false;
// eslint-disable-next-line require-atomic-updates
klass.isUpdatable = false;
// eslint-disable-next-line require-atomic-updates
klass.isDeletable = false;
}
// By this point, even views should have "fake" constraints we can use
// (e.g. `@primaryKey`)
const enumConstraints = introspectionResults.constraint.filter(con =>
isEnumConstraint(klass, con, isEnumTable)
);
// Get all the columns
const enumTableColumns = introspectionResults.attribute.filter(
attr => attr.classId === klass.id
);
// Get description column
const descriptionColumn = enumTableColumns.find(
attr => attr.name === "description" || attr.tags.enumDescription
);
const allData = klass._internalEnumData || [];
enumConstraints.forEach(constraint => {
const col = enumTableColumns.find(
col => col.num === constraint.keyAttributeNums[0]
);
if (!col) {
// Should never happen
throw new Error(
"Graphile Engine error - could not find column for enum constraint"
);
}
const data = allData.filter(row => row[col.name] != null);
if (data.length < 1) {
throw new Error(
`Enum table "${klass.namespaceName}"."${klass.name}" contains no visible entries for enum constraint '${constraint.name}'. Check that the table contains at least one row and that the rows are not hidden by row-level security policies.`
);
}
// Create fake enum type
const constraintIdent =
constraint.type === "p" ? "" : `_${constraint.name}`;
const enumTypeArray = {
kind: "type",
isFake: true,
id: `FAKE_ENUM_${klass.namespaceName}_${klass.name}${constraintIdent}_list`,
name: `_${klass.name}${constraintIdent}`,
description: null,
tags: {},
namespaceId: klass.namespaceId,
namespaceName: klass.namespaceName,
type: "b",
category: "A",
domainIsNotNull: null,
arrayItemTypeId: null,
typeLength: -1,
isPgArray: true,
classId: null,
domainBaseTypeId: null,
domainTypeModifier: null,
domainHasDefault: false,
enumVariants: null,
enumDescriptions: null,
rangeSubTypeId: null,
};
const enumType = {
kind: "type",
isFake: true,
id: `FAKE_ENUM_${klass.namespaceName}_${klass.name}${constraintIdent}`,
name: `${klass.name}${constraintIdent}`,
description: klass.description,
tags: { ...klass.tags, ...constraint.tags },
namespaceId: klass.namespaceId,
namespaceName: klass.namespaceName,
type: "e",
category: "E",
domainIsNotNull: null,
arrayItemTypeId: enumTypeArray.id,
typeLength: 4, // ???
isPgArray: false,
classId: null,
domainBaseTypeId: null,
domainTypeModifier: null,
domainHasDefault: false,
enumVariants: data.map(r => r[col.name]),
enumDescriptions: descriptionColumn
? data.map(r => r[descriptionColumn.name])
: null,
// TODO: enumDescriptions
rangeSubTypeId: null,
};
introspectionResults.type.push(enumType, enumTypeArray);
introspectionResults.typeById[enumType.id] = enumType;
introspectionResults.typeById[enumTypeArray.id] = enumTypeArray;
// Change type of all attributes that reference this table to
// reference this enum type
introspectionResults.constraint.forEach(c => {
if (
c.type === "f" &&
c.foreignClassId === klass.id &&
c.foreignKeyAttributeNums.length === 1 &&
c.foreignKeyAttributeNums[0] === col.num
) {
// Get the attribute
const fkattr = introspectionResults.attribute.find(
attr =>
attr.classId === c.classId && attr.num === c.keyAttributeNums[0]
);
if (fkattr) {
// Override the detected type to pretend to be our enum
fkattr.typeId = enumType.id;
}
}
});
});
});
}
/* The argument to this must not contain cyclic references! */
const deepClone = value => {
if (Array.isArray(value)) {
return value.map(val => deepClone(val));
} else if (typeof value === "object" && value) {
return Object.keys(value).reduce((memo, k) => {
memo[k] = deepClone(value[k]);
return memo;
}, {});
} else {
return value;
}
};
export default (async function PgIntrospectionPlugin(
builder,
{
pgConfig,
pgSchemas: schemas,
pgEnableTags,
persistentMemoizeWithKey = (key, fn) => fn(),
pgThrowOnMissingSchema = false,
pgIncludeExtensionResources = false,
pgLegacyFunctionsOnly = false,
pgIgnoreRBAC = true,
pgSkipInstallingWatchFixtures = false,
pgOwnerConnectionString,
}
) {
/**
* Introspect database and get the table/view/constraints.
*/
async function introspect(): Promise<PgIntrospectionResultsByKind> {
// Perform introspection
if (!Array.isArray(schemas)) {
throw new Error("Argument 'schemas' (array) is required");
}
const cacheKey = `PgIntrospectionPlugin-introspectionResultsByKind-v${version}`;
const introspectionResultsByKind = deepClone(
await persistentMemoizeWithKey(cacheKey, () =>
withPgClient(pgConfig, async pgClient => {
const versionResult = await pgClient.query(
"show server_version_num;"
);
const serverVersionNum = parseInt(
versionResult.rows[0].server_version_num,
10
);
const introspectionQuery = makeIntrospectionQuery(serverVersionNum, {
pgLegacyFunctionsOnly,
pgIgnoreRBAC,
});
const { rows } = await pgClient.query(introspectionQuery, [
schemas,
pgIncludeExtensionResources,
]);
const result = {
__pgVersion: serverVersionNum,
namespace: [],
class: [],
attribute: [],
type: [],
constraint: [],
procedure: [],
extension: [],
index: [],
};
for (const { object } of rows) {
result[object.kind].push(object);
}
// Parse tags from comments
[
"namespace",
"class",
"attribute",
"type",
"constraint",
"procedure",
"extension",
"index",
].forEach(kind => {
result[kind].forEach(object => {
// Keep a copy of the raw comment
object.comment = object.description;
if (pgEnableTags && object.description) {
const parsed = parseTags(object.description);
object.tags = parsed.tags;
object.description = parsed.text;
} else {
object.tags = {};
}
});
});
const extensionConfigurationClassIds = flatMap(
result.extension,
e => e.configurationClassIds
);
result.class.forEach(klass => {
klass.isExtensionConfigurationTable =
extensionConfigurationClassIds.indexOf(klass.id) >= 0;
});
// Assert the columns are text
const VARCHAR_ID = "1043";
const TEXT_ID = "25";
const CHAR_ID = "18";
const BPCHAR_ID = "1042";
const VALID_TYPE_IDS = [VARCHAR_ID, TEXT_ID, CHAR_ID, BPCHAR_ID];
await Promise.all(
result.class.map(async klass => {
if (!schemas.includes(klass.namespaceName)) {
// Only support enums in public tables/views
return;
}
const isEnumTable =
klass.tags.enum === true || typeof klass.tags.enum === "string";
// NOTE: this only matches on tables (not views, since they don't
// have constraints), which is why we repeat the isEnumTable check below.
const hasEnumConstraints = result.constraint.some(con =>
isEnumConstraint(klass, con, isEnumTable)
);
if (isEnumTable || hasEnumConstraints) {
// Get the list of columns enums are defined for
const enumTableColumns = result.attribute
.filter(
attr =>
attr.classId === klass.id &&
VALID_TYPE_IDS.includes(attr.typeId)
)
.sort((a, z) => a.num - z.num);
// Load data from the table/view.
const query = pgSql.compile(
pgSql.fragment`select ${pgSql.join(
enumTableColumns.map(col => pgSql.identifier(col.name)),
", "
)} from ${pgSql.identifier(klass.namespaceName, klass.name)};`
);
let allData;
try {
({ rows: allData } = await pgClient.query(query));
} catch (e) {
let role = "RELEVANT_POSTGRES_USER";
try {
const {
rows: [{ user }],
} = await pgClient.query("select user;");
role = user;
} catch (e) {
/*
* Ignore; this is likely a 25P02 (transaction aborted)
* error caused by the statement above failing.
*/
}
throw new Error(`Introspection could not read from enum table "${klass.namespaceName}"."${klass.name}", perhaps you need to grant access:
GRANT USAGE ON SCHEMA "${klass.namespaceName}" TO "${role}";
GRANT SELECT ON "${klass.namespaceName}"."${klass.name}" TO "${role}";
Original error: ${e.message}
`);
}
klass._internalEnumData = allData;
}
})
);
[
"namespace",
"class",
"attribute",
"type",
"constraint",
"procedure",
"extension",
"index",
].forEach(k => {
result[k].forEach(Object.freeze);
});
return Object.freeze(result);
})
)
);
const knownSchemas = introspectionResultsByKind.namespace.map(n => n.name);
const missingSchemas = schemas.filter(s => knownSchemas.indexOf(s) < 0);
if (missingSchemas.length) {
const errorMessage = `You requested to use schema '${schemas.join(
"', '"
)}'; however we couldn't find some of those! Missing schemas are: '${missingSchemas.join(
"', '"
)}'`;
if (pgThrowOnMissingSchema) {
throw new Error(errorMessage);
} else {
console.warn("⚠️ WARNING⚠️ " + errorMessage); // eslint-disable-line no-console
}
}
return introspectionResultsByKind;
}
function introspectionResultsFromRaw(
rawResults,
pgAugmentIntrospectionResults
) {
const introspectionResultsByKind = deepClone(rawResults);
const xByY = (arrayOfX, attrKey) =>
arrayOfX.reduce((memo, x) => {
memo[x[attrKey]] = x;
return memo;
}, {});
const xByYAndZ = (arrayOfX, attrKey, attrKey2) =>
arrayOfX.reduce((memo, x) => {
if (!memo[x[attrKey]]) memo[x[attrKey]] = {};
memo[x[attrKey]][x[attrKey2]] = x;
return memo;
}, {});
introspectionResultsByKind.namespaceById = xByY(
introspectionResultsByKind.namespace,
"id"
);
introspectionResultsByKind.classById = xByY(
introspectionResultsByKind.class,
"id"
);
introspectionResultsByKind.typeById = xByY(
introspectionResultsByKind.type,
"id"
);
introspectionResultsByKind.attributeByClassIdAndNum = xByYAndZ(
introspectionResultsByKind.attribute,
"classId",
"num"
);
introspectionResultsByKind.extensionById = xByY(
introspectionResultsByKind.extension,
"id"
);
const relate = (array, newAttr, lookupAttr, lookup, missingOk = false) => {
array.forEach(entry => {
const key = entry[lookupAttr];
if (Array.isArray(key)) {
entry[newAttr] = key
.map(innerKey => {
const result = lookup[innerKey];
if (innerKey && !result) {
if (missingOk) {
return;
}
throw new Error(
`Could not look up '${newAttr}' by '${lookupAttr}' ('${innerKey}') on '${JSON.stringify(
entry
)}'`
);
}
return result;
})
.filter(_ => _);
} else {
const result = lookup[key];
if (key && !result) {
if (missingOk) {
return;
}
throw new Error(
`Could not look up '${newAttr}' by '${lookupAttr}' (= '${key}') on '${JSON.stringify(
entry
)}'`
);
}
entry[newAttr] = result;
}
});
};
const augment = introspectionResults => {
[
pgAugmentIntrospectionResults,
smartCommentConstraints,
enumTables,
].forEach(fn => (fn ? fn(introspectionResults) : null));
};
augment(introspectionResultsByKind);
relate(
introspectionResultsByKind.class,
"namespace",
"namespaceId",
introspectionResultsByKind.namespaceById,
true // Because it could be a type defined in a different namespace - which is fine so long as we don't allow querying it directly
);
relate(
introspectionResultsByKind.class,
"type",
"typeId",
introspectionResultsByKind.typeById
);
relate(
introspectionResultsByKind.attribute,
"class",
"classId",
introspectionResultsByKind.classById
);
relate(
introspectionResultsByKind.attribute,
"type",
"typeId",
introspectionResultsByKind.typeById
);
relate(
introspectionResultsByKind.procedure,
"namespace",
"namespaceId",
introspectionResultsByKind.namespaceById
);
relate(
introspectionResultsByKind.type,
"class",
"classId",
introspectionResultsByKind.classById,
true
);
relate(
introspectionResultsByKind.type,
"domainBaseType",
"domainBaseTypeId",
introspectionResultsByKind.typeById,
true // Because not all types are domains
);
relate(
introspectionResultsByKind.type,
"arrayItemType",
"arrayItemTypeId",
introspectionResultsByKind.typeById,
true // Because not all types are arrays
);
relate(
introspectionResultsByKind.constraint,
"class",
"classId",
introspectionResultsByKind.classById
);
relate(
introspectionResultsByKind.constraint,
"foreignClass",
"foreignClassId",
introspectionResultsByKind.classById,
true // Because many constraints don't apply to foreign classes