/
PgTypesPlugin.js
1755 lines (1671 loc) · 58.7 KB
/
PgTypesPlugin.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 makeGraphQLJSONType from "../GraphQLJSON";
import rawParseInterval from "postgres-interval";
import LRU from "@graphile/lru";
function indent(str) {
return " " + str.replace(/\n/g, "\n ");
}
function identity(value) {
return value;
}
const parseCache = new LRU({ maxLength: 500 });
function parseInterval(str) {
let result = parseCache.get(str);
if (!result) {
result = rawParseInterval(str);
Object.freeze(result);
parseCache.set(str, result);
}
return result;
}
export default (function PgTypesPlugin(
builder,
{
pgExtendedTypes = true,
// Adding hstore support is technically a breaking change; this allows people to opt out easily:
pgSkipHstore = false,
pgGeometricTypes = false,
pgUseCustomNetworkScalars = false,
disableIssue390Fix = false,
}
) {
// XXX: most of this should be in an "init" hook, not a "build" hook
builder.hook(
"build",
build => {
const {
pgIntrospectionResultsByKind: introspectionResultsByKind,
getTypeByName,
pgSql: sql,
inflection,
graphql,
} = build;
/*
* Note these do not do `foo.bind(build)` because they want to reference
* the *latest* value of foo (i.e. after all the build hooks run) rather
* than the current value of foo in this current hook.
*
* Also don't use this in your own code, only construct types *after* the
* build hook has completed (i.e. 'init' or later).
*
* TODO:v5: move this to the 'init' hook.
*/
const newWithHooks = (...args) => build.newWithHooks(...args);
const addType = (...args) => build.addType(...args);
const {
GraphQLNonNull,
GraphQLString,
GraphQLInt,
GraphQLFloat,
GraphQLBoolean,
GraphQLList,
GraphQLEnumType,
GraphQLObjectType,
GraphQLInputObjectType,
GraphQLScalarType,
isInputType,
getNamedType,
Kind,
} = graphql;
const gqlTypeByTypeIdGenerator = {};
const gqlInputTypeByTypeIdGenerator = {};
if (build.pgGqlTypeByTypeId || build.pgGqlInputTypeByTypeId) {
// I don't expect anyone to receive this error, because I don't think anyone uses this interface.
throw new Error(
"Sorry! This interface is no longer supported because it is not granular enough. It's not hard to port it to the new system - please contact Benjie and he'll walk you through it."
);
}
const gqlTypeByTypeIdAndModifier = {
...build.pgGqlTypeByTypeIdAndModifier,
};
const gqlInputTypeByTypeIdAndModifier = {
...build.pgGqlInputTypeByTypeIdAndModifier,
};
const isNull = val => val == null || val.__isNull;
const pg2GqlMapper = {};
const pg2gqlForType = type => {
if (pg2GqlMapper[type.id]) {
const map = pg2GqlMapper[type.id].map;
return val => (isNull(val) ? null : map(val));
} else if (type.domainBaseType) {
return pg2gqlForType(type.domainBaseType);
} else if (type.isPgArray) {
const elementHandler = pg2gqlForType(type.arrayItemType);
return val => {
if (isNull(val)) return null;
if (!Array.isArray(val)) {
throw new Error(
`Expected array when converting PostgreSQL data into GraphQL; failing type: '${type.namespaceName}.${type.name}'`
);
}
return val.map(elementHandler);
};
} else {
return identity;
}
};
const pg2gql = (val, type) => pg2gqlForType(type)(val);
const gql2pg = (val, type, modifier) => {
if (modifier === undefined) {
let stack;
try {
throw new Error();
} catch (e) {
stack = e.stack;
}
// eslint-disable-next-line no-console
console.warn(
"gql2pg should be called with three arguments, the third being the type modifier (or `null`); " +
(stack || "")
);
// Hack for backwards compatibility:
modifier = null;
}
if (val == null) {
return sql.null;
}
if (pg2GqlMapper[type.id]) {
return pg2GqlMapper[type.id].unmap(val, modifier);
} else if (type.domainBaseType) {
return gql2pg(val, type.domainBaseType, type.domainTypeModifier);
} else if (type.isPgArray) {
if (!Array.isArray(val)) {
throw new Error(
`Expected array when converting GraphQL data into PostgreSQL data; failing type: '${
type.namespaceName
}.${type.name}' (type: ${type === null ? "null" : typeof type})`
);
}
return sql.fragment`array[${sql.join(
val.map(v => gql2pg(v, type.arrayItemType, modifier)),
", "
)}]::${sql.identifier(type.namespaceName)}.${sql.identifier(
type.name
)}`;
} else {
return sql.value(val);
}
};
const makeIntervalFields = () => {
return {
seconds: {
description:
"A quantity of seconds. This is the only non-integer field, as all the other fields will dump their overflow into a smaller unit of time. Intervals don’t have a smaller unit than seconds.",
type: GraphQLFloat,
},
minutes: {
description: "A quantity of minutes.",
type: GraphQLInt,
},
hours: {
description: "A quantity of hours.",
type: GraphQLInt,
},
days: {
description: "A quantity of days.",
type: GraphQLInt,
},
months: {
description: "A quantity of months.",
type: GraphQLInt,
},
years: {
description: "A quantity of years.",
type: GraphQLInt,
},
};
};
const GQLInterval = newWithHooks(
GraphQLObjectType,
{
name: inflection.builtin("Interval"),
description:
"An interval of time that has passed where the smallest distinct unit is a second.",
fields: makeIntervalFields(),
},
{
isIntervalType: true,
}
);
addType(GQLInterval, "graphile-build-pg built-in");
const GQLIntervalInput = newWithHooks(
GraphQLInputObjectType,
{
name: inflection.inputType(inflection.builtin("Interval")),
description:
"An interval of time that has passed where the smallest distinct unit is a second.",
fields: makeIntervalFields(),
},
{
isIntervalInputType: true,
}
);
addType(GQLIntervalInput, "graphile-build-pg built-in");
const stringType = (name, description, coerce) =>
new GraphQLScalarType({
name,
description,
serialize: value => String(value),
parseValue: coerce
? value => coerce(String(value))
: value => String(value),
parseLiteral: ast => {
if (ast.kind !== Kind.STRING) {
throw new Error("Can only parse string values");
}
if (coerce) {
return coerce(ast.value);
} else {
return ast.value;
}
},
});
const BigFloat = stringType(
inflection.builtin("BigFloat"),
"A floating point number that requires more precision than IEEE 754 binary 64"
);
const BitString = stringType(
inflection.builtin("BitString"),
"A string representing a series of binary bits"
);
addType(BigFloat, "graphile-build-pg built-in");
addType(BitString, "graphile-build-pg built-in");
const rawTypes = [
1186, // interval
1082, // date
1114, // timestamp
1184, // timestamptz
1083, // time
1266, // timetz
];
const tweakToJson = fragment => fragment; // Since everything is to_json'd now, just pass through
const tweakToJsonArray = fragment => fragment;
const tweakToText = fragment => sql.fragment`(${fragment})::text`;
const tweakToTextArray = fragment => sql.fragment`(${fragment})::text[]`;
const tweakToNumericText = fragment =>
sql.fragment`(${fragment})::numeric::text`;
const tweakToNumericTextArray = fragment =>
sql.fragment`(${fragment})::numeric[]::text[]`;
const pgTweaksByTypeIdAndModifer = {};
const pgTweaksByTypeId = {
// '::text' rawTypes
...rawTypes.reduce((memo, typeId) => {
memo[typeId] = tweakToText;
return memo;
}, {}),
// cast numbers above our ken to strings to avoid loss of precision
20: tweakToText,
1700: tweakToText,
// to_json all dates to make them ISO (overrides rawTypes above)
1082: tweakToJson,
1114: tweakToJson,
1184: tweakToJson,
1083: tweakToJson,
1266: tweakToJson,
790: tweakToNumericText,
};
const pgTweakFragmentForTypeAndModifier = (
fragment,
type,
typeModifier = null,
resolveData
) => {
const typeModifierKey = typeModifier != null ? typeModifier : -1;
const tweaker =
(pgTweaksByTypeIdAndModifer[type.id] &&
pgTweaksByTypeIdAndModifer[type.id][typeModifierKey]) ||
pgTweaksByTypeId[type.id];
if (tweaker) {
return tweaker(fragment, resolveData);
} else if (type.domainBaseType) {
if (type.domainBaseType.isPgArray) {
// If we have a domain that's for example an `int8[]`, we must
// process it into a `text[]` otherwise we risk loss of accuracy
// when taking PostgreSQL's JSON into Node.js.
const arrayItemType = type.domainBaseType.arrayItemType;
const domainBaseTypeModifierKey =
type.domainBaseTypeModifier != null
? type.domainBaseTypeModifier
: -1;
const arrayItemTweaker =
(pgTweaksByTypeIdAndModifer[arrayItemType.id] &&
pgTweaksByTypeIdAndModifer[arrayItemType.id][
domainBaseTypeModifierKey
]) ||
pgTweaksByTypeId[arrayItemType.id];
// If it's a domain over a known type array (e.g. `bigint[]`), use
// the Array version of the tweaker.
switch (arrayItemTweaker) {
case tweakToText:
return tweakToTextArray(fragment);
case tweakToNumericText:
return tweakToNumericTextArray(fragment);
case tweakToJson:
return tweakToJsonArray(fragment);
}
// If we get here, it's not a simple type, so use our
// infrastructure to figure out what tweaks to apply to the array
// item.
const sqlVal = sql.fragment`val`;
const innerFragment = pgTweakFragmentForTypeAndModifier(
sqlVal,
arrayItemType,
type.domainBaseTypeModifier,
resolveData
);
if (innerFragment === sqlVal) {
// There was no tweak applied to the fragment, no change
// necessary.
return fragment;
} else {
// Tweaking was necessary, process each item in the array in this
// way, and then return the resulting array, being careful that
// nulls are preserved.
return sql.fragment`(case when ${fragment} is null then null else array(select ${innerFragment} from unnest(${fragment}) as unnest(${sqlVal})) end)`;
}
} else {
// TODO: check that domains don't support atttypemod
return pgTweakFragmentForTypeAndModifier(
fragment,
type.domainBaseType,
type.domainBaseTypeModifier,
resolveData
);
}
} else if (type.isPgArray) {
const error = new Error(
`Internal graphile-build-pg error: should not attempt to tweak an array, please process array before tweaking (type: "${type.namespaceName}.${type.name}")`
);
if (process.env.NODE_ENV === "test") {
// This is to ensure that Graphile core does not introduce these problems
throw error;
}
// eslint-disable-next-line no-console
console.error(error);
return fragment;
} else {
return fragment;
}
};
/*
Determined by running:
select oid, typname, typarray, typcategory, typtype from pg_catalog.pg_type where typtype = 'b' order by oid;
We only need to add oidLookups for types that don't have the correct fallback
*/
const SimpleDate = stringType(
inflection.builtin("Date"),
"The day, does not include a time."
);
const SimpleDatetime = stringType(
inflection.builtin("Datetime"),
"A point in time as described by the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) standard. May or may not include a timezone."
);
const SimpleTime = stringType(
inflection.builtin("Time"),
"The exact time of day, does not include the date. May or may not have a timezone offset."
);
const SimpleJSON = stringType(
inflection.builtin("JSON"),
"A JavaScript object encoded in the JSON format as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf)."
);
const SimpleUUID = stringType(
inflection.builtin("UUID"),
"A universally unique identifier as defined by [RFC 4122](https://tools.ietf.org/html/rfc4122).",
string => {
if (
!/^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i.test(
string
)
) {
throw new Error(
"Invalid UUID, expected 32 hexadecimal characters, optionally with hypens"
);
}
return string;
}
);
const InetType = stringType(
inflection.builtin("InternetAddress"),
"An IPv4 or IPv6 host address, and optionally its subnet."
);
const RegProcType = stringType(
inflection.builtin("RegProc"),
"A builtin object identifier type for a function name"
);
const RegProcedureType = stringType(
inflection.builtin("RegProcedure"),
"A builtin object identifier type for a function with argument types"
);
const RegOperType = stringType(
inflection.builtin("RegOper"),
"A builtin object identifier type for an operator"
);
const RegOperatorType = stringType(
inflection.builtin("RegOperator"),
"A builtin object identifier type for an operator with argument types"
);
const RegClassType = stringType(
inflection.builtin("RegClass"),
"A builtin object identifier type for a relation name"
);
const RegTypeType = stringType(
inflection.builtin("RegType"),
"A builtin object identifier type for a data type name"
);
const RegRoleType = stringType(
inflection.builtin("RegRole"),
"A builtin object identifier type for a role name"
);
const RegNamespaceType = stringType(
inflection.builtin("RegNamespace"),
"A builtin object identifier type for a namespace name"
);
const RegConfigType = stringType(
inflection.builtin("RegConfig"),
"A builtin object identifier type for a text search configuration"
);
const RegDictionaryType = stringType(
inflection.builtin("RegDictionary"),
"A builtin object identifier type for a text search dictionary"
);
const CidrType = pgUseCustomNetworkScalars
? stringType(
inflection.builtin("CidrAddress"),
"An IPv4 or IPv6 CIDR address."
)
: GraphQLString;
const MacAddrType = pgUseCustomNetworkScalars
? stringType(inflection.builtin("MacAddress"), "A 6-byte MAC address.")
: GraphQLString;
const MacAddr8Type = pgUseCustomNetworkScalars
? stringType(
inflection.builtin("MacAddress8"),
"An 8-byte MAC address."
)
: GraphQLString;
// pgExtendedTypes might change what types we use for things
const JSONType = pgExtendedTypes
? makeGraphQLJSONType(graphql, inflection.builtin("JSON"))
: SimpleJSON;
const UUIDType = SimpleUUID; // GraphQLUUID
const DateType = SimpleDate; // GraphQLDate
const DateTimeType = SimpleDatetime; // GraphQLDateTime
const TimeType = SimpleTime; // GraphQLTime
// 'point' in PostgreSQL is a 16-byte type that's comprised of two 8-byte floats.
const Point = newWithHooks(
GraphQLObjectType,
{
name: inflection.builtin("Point"),
fields: {
x: {
type: new GraphQLNonNull(GraphQLFloat),
},
y: {
type: new GraphQLNonNull(GraphQLFloat),
},
},
},
{
isPointType: true,
}
);
const PointInput = newWithHooks(
GraphQLInputObjectType,
{
name: inflection.inputType(inflection.builtin("Point")),
fields: {
x: {
type: new GraphQLNonNull(GraphQLFloat),
},
y: {
type: new GraphQLNonNull(GraphQLFloat),
},
},
},
{
isPointInputType: true,
}
);
// Other plugins might want to use JSON
addType(JSONType, "graphile-build-pg built-in");
addType(UUIDType, "graphile-build-pg built-in");
addType(DateType, "graphile-build-pg built-in");
addType(DateTimeType, "graphile-build-pg built-in");
addType(TimeType, "graphile-build-pg built-in");
addType(RegProcType, "graphile-build-pg built-in");
addType(RegProcedureType, "graphile-build-pg built-in");
addType(RegOperType, "graphile-build-pg built-in");
addType(RegOperatorType, "graphile-build-pg built-in");
addType(RegClassType, "graphile-build-pg built-in");
addType(RegTypeType, "graphile-build-pg built-in");
addType(RegRoleType, "graphile-build-pg built-in");
addType(RegNamespaceType, "graphile-build-pg built-in");
addType(RegConfigType, "graphile-build-pg built-in");
addType(RegDictionaryType, "graphile-build-pg built-in");
const oidLookup = {
20: stringType(
inflection.builtin("BigInt"),
"A signed eight-byte integer. The upper big integer values are greater than the max value for a JavaScript number. Therefore all big integers will be output as strings and not numbers."
), // bitint - even though this is int8, it's too big for JS int, so cast to string.
21: GraphQLInt, // int2
23: GraphQLInt, // int4
700: GraphQLFloat, // float4
701: GraphQLFloat, // float8
1700: BigFloat, // numeric
790: GraphQLFloat, // money
1186: GQLInterval, // interval
1082: DateType, // date
1114: DateTimeType, // timestamp
1184: DateTimeType, // timestamptz
1083: TimeType, // time
1266: TimeType, // timetz
114: JSONType, // json
3802: JSONType, // jsonb
2950: UUIDType, // uuid
1560: BitString, // bit
1562: BitString, // varbit
18: GraphQLString, // char
25: GraphQLString, // text
1043: GraphQLString, // varchar
600: Point, // point
869: InetType,
650: CidrType,
829: MacAddrType,
774: MacAddr8Type,
24: RegProcType,
2202: RegProcedureType,
2203: RegOperType,
2204: RegOperatorType,
2205: RegClassType,
2206: RegTypeType,
4096: RegRoleType,
4089: RegNamespaceType,
3734: RegConfigType,
3769: RegDictionaryType,
};
const oidInputLookup = {
1186: GQLIntervalInput, // interval
600: PointInput, // point
};
const jsonStringify = o => JSON.stringify(o);
if (pgExtendedTypes) {
pg2GqlMapper[114] = {
map: identity,
unmap: o => sql.value(jsonStringify(o)),
};
} else {
pg2GqlMapper[114] = {
map: jsonStringify,
unmap: str => sql.value(str),
};
}
pg2GqlMapper[3802] = pg2GqlMapper[114]; // jsonb
// interval
pg2GqlMapper[1186] = {
map: str => parseInterval(str),
unmap: o => {
const keys = [
"seconds",
"minutes",
"hours",
"days",
"months",
"years",
];
const parts = [];
for (const key of keys) {
if (o[key]) {
parts.push(`${o[key]} ${key}`);
}
}
return sql.value(parts.join(" ") || "0 seconds");
},
};
pg2GqlMapper[790] = {
map: _ => _,
unmap: val => sql.fragment`(${sql.value(val)})::money`,
};
// point
pg2GqlMapper[600] = {
map: f => {
if (f[0] === "(" && f[f.length - 1] === ")") {
const [x, y] = f
.substr(1, f.length - 2)
.split(",")
.map(f => parseFloat(f));
return { x, y };
}
},
unmap: o => sql.fragment`point(${sql.value(o.x)}, ${sql.value(o.y)})`,
};
// TODO: add more support for geometric types
let depth = 0;
/*
* Enforce: this is the fallback when we can't find a specific GraphQL type
* for a specific PG type. Use the generators from
* `pgRegisterGqlTypeByTypeId` first, this is a last resort.
*/
const enforceGqlTypeByPgTypeId = (typeId, typeModifier) => {
const type = introspectionResultsByKind.type.find(t => t.id === typeId);
depth++;
if (depth > 50) {
throw new Error("Type enforcement went too deep - infinite loop?");
}
try {
return reallyEnforceGqlTypeByPgTypeAndModifier(type, typeModifier);
} catch (e) {
const error = new Error(
`Error occurred when processing database type '${
type.namespaceName
}.${type.name}' (type=${type.type}):\n${indent(e.message)}`
);
// $FlowFixMe
error.originalError = e;
throw error;
} finally {
depth--;
}
};
const reallyEnforceGqlTypeByPgTypeAndModifier = (type, typeModifier) => {
if (!type.id) {
throw new Error(
`Invalid argument to enforceGqlTypeByPgTypeId - expected a full type, received '${type}'`
);
}
if (!gqlTypeByTypeIdAndModifier[type.id]) {
gqlTypeByTypeIdAndModifier[type.id] = {};
}
if (!gqlInputTypeByTypeIdAndModifier[type.id]) {
gqlInputTypeByTypeIdAndModifier[type.id] = {};
}
const typeModifierKey = typeModifier != null ? typeModifier : -1;
// Explicit overrides
if (!gqlTypeByTypeIdAndModifier[type.id][typeModifierKey]) {
const gqlType = oidLookup[type.id];
if (gqlType) {
gqlTypeByTypeIdAndModifier[type.id][typeModifierKey] = gqlType;
}
}
if (!gqlInputTypeByTypeIdAndModifier[type.id][typeModifierKey]) {
const gqlInputType = oidInputLookup[type.id];
if (gqlInputType) {
gqlInputTypeByTypeIdAndModifier[type.id][
typeModifierKey
] = gqlInputType;
}
}
// Enums
if (
!gqlTypeByTypeIdAndModifier[type.id][typeModifierKey] &&
type.type === "e"
) {
gqlTypeByTypeIdAndModifier[type.id][typeModifierKey] = newWithHooks(
GraphQLEnumType,
{
name: inflection.enumType(type),
description: type.description,
values: type.enumVariants.reduce((memo, value, i) => {
memo[inflection.enumName(value)] = {
description: type.enumDescriptions
? type.enumDescriptions[i]
: null,
value: value,
};
return memo;
}, {}),
},
{
pgIntrospection: type,
isPgEnumType: true,
}
);
}
// Ranges
if (
!gqlTypeByTypeIdAndModifier[type.id][typeModifierKey] &&
type.type === "r"
) {
const subtype =
introspectionResultsByKind.typeById[type.rangeSubTypeId];
const gqlRangeSubType = getGqlTypeByTypeIdAndModifier(
subtype.id,
typeModifier
);
const gqlRangeInputSubType = getGqlInputTypeByTypeIdAndModifier(
subtype.id,
typeModifier
);
if (!gqlRangeSubType) {
throw new Error("Range of unsupported");
}
if (!gqlRangeInputSubType) {
throw new Error("Range of unsupported input type");
}
let Range = getTypeByName(inflection.rangeType(gqlRangeSubType.name));
let RangeInput;
if (!Range) {
const RangeBound = newWithHooks(
GraphQLObjectType,
{
name: inflection.rangeBoundType(gqlRangeSubType.name),
description:
"The value at one end of a range. A range can either include this value, or not.",
fields: {
value: {
description: "The value at one end of our range.",
type: new GraphQLNonNull(gqlRangeSubType),
},
inclusive: {
description:
"Whether or not the value of this bound is included in the range.",
type: new GraphQLNonNull(GraphQLBoolean),
},
},
},
{
isPgRangeBoundType: true,
pgIntrospection: type,
pgSubtypeIntrospection: subtype,
pgTypeModifier: typeModifier,
}
);
const RangeBoundInput = newWithHooks(
GraphQLInputObjectType,
{
name: inflection.inputType(RangeBound.name),
description:
"The value at one end of a range. A range can either include this value, or not.",
fields: {
value: {
description: "The value at one end of our range.",
type: new GraphQLNonNull(gqlRangeInputSubType),
},
inclusive: {
description:
"Whether or not the value of this bound is included in the range.",
type: new GraphQLNonNull(GraphQLBoolean),
},
},
},
{
isPgRangeBoundInputType: true,
pgIntrospection: type,
pgSubtypeIntrospection: subtype,
pgTypeModifier: typeModifier,
}
);
Range = newWithHooks(
GraphQLObjectType,
{
name: inflection.rangeType(gqlRangeSubType.name),
description: `A range of \`${gqlRangeSubType.name}\`.`,
fields: {
start: {
description: "The starting bound of our range.",
type: RangeBound,
},
end: {
description: "The ending bound of our range.",
type: RangeBound,
},
},
},
{
isPgRangeType: true,
pgIntrospection: type,
pgSubtypeIntrospection: subtype,
pgTypeModifier: typeModifier,
}
);
RangeInput = newWithHooks(
GraphQLInputObjectType,
{
name: inflection.inputType(Range.name),
description: `A range of \`${gqlRangeSubType.name}\`.`,
fields: {
start: {
description: "The starting bound of our range.",
type: RangeBoundInput,
},
end: {
description: "The ending bound of our range.",
type: RangeBoundInput,
},
},
},
{
isPgRangeInputType: true,
pgIntrospection: type,
pgSubtypeIntrospection: subtype,
pgTypeModifier: typeModifier,
}
);
addType(Range, "graphile-build-pg built-in");
addType(RangeInput, "graphile-build-pg built-in");
} else {
RangeInput = getTypeByName(inflection.inputType(Range.name));
}
gqlTypeByTypeIdAndModifier[type.id][typeModifierKey] = Range;
gqlInputTypeByTypeIdAndModifier[type.id][
typeModifierKey
] = RangeInput;
if (pgTweaksByTypeIdAndModifer[type.id] === undefined) {
pgTweaksByTypeIdAndModifer[type.id] = {};
}
pgTweaksByTypeIdAndModifer[type.id][
typeModifierKey
] = fragment => sql.fragment`\
case
when (${fragment}) is null then null
else json_build_object(
'start',
case when lower(${fragment}) is null then null
else json_build_object('value', ${pgTweakFragmentForTypeAndModifier(
sql.fragment`lower(${fragment})`,
subtype,
typeModifier,
{}
)}, 'inclusive', lower_inc(${fragment}))
end,
'end',
case when upper(${fragment}) is null then null
else json_build_object('value', ${pgTweakFragmentForTypeAndModifier(
sql.fragment`upper(${fragment})`,
subtype,
typeModifier,
{}
)}, 'inclusive', upper_inc(${fragment}))
end
)
end`;
pg2GqlMapper[type.id] = {
map: identity,
unmap: ({ start, end }) => {
// Ref: https://www.postgresql.org/docs/9.6/static/rangetypes.html#RANGETYPES-CONSTRUCT
const lower =
(start && gql2pg(start.value, subtype, null)) || sql.null;
const upper =
(end && gql2pg(end.value, subtype, null)) || sql.null;
const lowerInclusive = start && !start.inclusive ? "(" : "[";
const upperInclusive = end && !end.inclusive ? ")" : "]";
return sql.fragment`${sql.identifier(
type.namespaceName,
type.name
)}(${lower}, ${upper}, ${sql.literal(
lowerInclusive + upperInclusive
)})`;
},
};
}
// Domains
if (
!gqlTypeByTypeIdAndModifier[type.id][typeModifierKey] &&
type.type === "d" &&
type.domainBaseTypeId
) {
const baseType = getGqlTypeByTypeIdAndModifier(
type.domainBaseTypeId,
typeModifier
);
const baseInputType =
gqlInputTypeByTypeIdAndModifier[type.domainBaseTypeId][
typeModifierKey
];
// Hack stolen from: https://github.com/graphile/postgraphile/blob/ade728ed8f8e3ecdc5fdad7d770c67aa573578eb/src/graphql/schema/type/aliasGqlType.ts#L16
gqlTypeByTypeIdAndModifier[type.id][typeModifierKey] = Object.assign(
Object.create(baseType),
{
name: inflection.domainType(type),
description: type.description,
}
);
if (baseInputType && baseInputType !== baseType) {
gqlInputTypeByTypeIdAndModifier[type.id][
typeModifierKey
] = Object.assign(Object.create(baseInputType), {
name: inflection.inputType(
gqlTypeByTypeIdAndModifier[type.id][typeModifierKey]
),
description: type.description,
});
}
}
// Arrays
if (
!gqlTypeByTypeIdAndModifier[type.id][typeModifierKey] &&
type.category === "A"
) {
const arrayEntryOutputType = getGqlTypeByTypeIdAndModifier(
type.arrayItemTypeId,
typeModifier
);
gqlTypeByTypeIdAndModifier[type.id][
typeModifierKey
] = new GraphQLList(arrayEntryOutputType);
if (!disableIssue390Fix) {
const arrayEntryInputType = getGqlInputTypeByTypeIdAndModifier(
type.arrayItemTypeId,
typeModifier
);
if (arrayEntryInputType) {
gqlInputTypeByTypeIdAndModifier[type.id][
typeModifierKey
] = new GraphQLList(arrayEntryInputType);
}
}
}
// Booleans
if (
!gqlTypeByTypeIdAndModifier[type.id][typeModifierKey] &&
type.category === "B"
) {
gqlTypeByTypeIdAndModifier[type.id][typeModifierKey] = GraphQLBoolean;
}
// Numbers may be too large for GraphQL/JS to handle, so stringify by
// default.
if (
!gqlTypeByTypeIdAndModifier[type.id][typeModifierKey] &&
type.category === "N"
) {
pgTweaksByTypeId[type.id] = tweakToText;
gqlTypeByTypeIdAndModifier[type.id][typeModifierKey] = BigFloat;
}
// Nothing else worked; pass through as string!
if (!gqlTypeByTypeIdAndModifier[type.id][typeModifierKey]) {
// XXX: consider using stringType(upperFirst(camelCase(`fallback_${type.name}`)), type.description)?
gqlTypeByTypeIdAndModifier[type.id][typeModifierKey] = GraphQLString;
}
// Now for input types, fall back to output types if possible
if (!gqlInputTypeByTypeIdAndModifier[type.id][typeModifierKey]) {
if (
isInputType(gqlTypeByTypeIdAndModifier[type.id][typeModifierKey])
) {
gqlInputTypeByTypeIdAndModifier[type.id][typeModifierKey] =
gqlTypeByTypeIdAndModifier[type.id][typeModifierKey];
}
}
addType(
getNamedType(gqlTypeByTypeIdAndModifier[type.id][typeModifierKey])
);
return gqlTypeByTypeIdAndModifier[type.id][typeModifierKey];
};
function getGqlTypeByTypeIdAndModifier(