-
-
Notifications
You must be signed in to change notification settings - Fork 129
/
PgTablesPlugin.js
653 lines (640 loc) · 24 KB
/
PgTablesPlugin.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
// @flow
import type { Plugin } from "graphile-build";
const base64 = str => Buffer.from(String(str)).toString("base64");
const hasNonNullKey = row => {
if (
Array.isArray(row.__identifiers) &&
row.__identifiers.every(i => i != null)
) {
return true;
}
for (const k in row) {
if (Object.prototype.hasOwnProperty.call(row, k)) {
if ((k[0] !== "_" || k[1] !== "_") && row[k] !== null) {
return true;
}
}
}
return false;
};
export default (function PgTablesPlugin(
builder,
{ pgForbidSetofFunctionsToReturnNull = false, subscriptions = false }
) {
const handleNullRow = pgForbidSetofFunctionsToReturnNull
? (row, _identifiers) => row
: (row, identifiers) => {
if ((identifiers && hasNonNullKey(identifiers)) || hasNonNullKey(row)) {
return row;
} else {
return null;
}
};
builder.hook(
"init",
(_, build) => {
const {
getNodeIdForTypeAndIdentifiers,
nodeIdFieldName,
newWithHooks,
getSafeAliasFromResolveInfo,
pgSql: sql,
pgIntrospectionResultsByKind: introspectionResultsByKind,
getTypeByName,
pgGetGqlTypeByTypeIdAndModifier,
pgGetGqlInputTypeByTypeIdAndModifier,
pgRegisterGqlTypeByTypeId,
pgRegisterGqlInputTypeByTypeId,
pg2GqlMapper,
gql2pg,
graphql: {
GraphQLObjectType,
GraphQLNonNull,
GraphQLID,
GraphQLList,
GraphQLInputObjectType,
},
inflection,
describePgEntity,
sqlCommentByAddingTags,
pgField,
} = build;
const nullableIf = (condition, Type) =>
condition ? Type : new GraphQLNonNull(Type);
const Cursor = getTypeByName("Cursor");
introspectionResultsByKind.class.forEach(table => {
if (table.tags.enum) {
return;
}
const tablePgType = table.type;
if (!tablePgType) {
throw new Error("Could not determine the type for this table");
}
const arrayTablePgType = tablePgType.arrayType;
const primaryKeyConstraint = table.primaryKeyConstraint;
const primaryKeys =
primaryKeyConstraint && primaryKeyConstraint.keyAttributes;
const attributes = table.attributes;
const tableTypeName = inflection.tableType(table);
const shouldHaveNodeId: boolean =
nodeIdFieldName &&
table.isSelectable &&
table.namespace &&
primaryKeys &&
primaryKeys.length
? true
: false;
let TableType;
let TablePatchType;
let TableBaseInputType;
pgRegisterGqlTypeByTypeId(
tablePgType.id,
cb => {
if (TableType) {
return TableType;
}
if (pg2GqlMapper[tablePgType.id]) {
// Already handled
throw new Error(
`Register was called but there's already a mapper in place for '${tablePgType.id}'!`
);
}
TableType = newWithHooks(
GraphQLObjectType,
{
description: table.description || tablePgType.description,
name: tableTypeName,
interfaces: () => {
if (shouldHaveNodeId) {
return [getTypeByName(inflection.builtin("Node"))];
} else {
return [];
}
},
fields: ({ addDataGeneratorForField, Self }) => {
const fields = {};
if (shouldHaveNodeId) {
// Enable nodeId interface
addDataGeneratorForField(nodeIdFieldName, () => {
return {
pgQuery: queryBuilder => {
queryBuilder.selectIdentifiers(table);
},
};
});
fields[nodeIdFieldName] = {
description: build.wrapDescription(
"A globally unique identifier. Can be used in various places throughout the system to identify this single value.",
"field"
),
type: new GraphQLNonNull(GraphQLID),
resolve(data) {
const identifiers = data.__identifiers;
if (!identifiers) {
return null;
}
/*
* For bigint we want NodeIDs to be the same as int up
* to the limits of int, and only to be strings after
* that point.
*/
const finalIdentifiers = identifiers.map(
(identifier, idx) => {
const key = primaryKeys[idx];
const type = key.type.domainBaseType || key.type;
if (type.id === "20" /* bigint */) {
/*
* When migrating from 'int' to 'bigint' we want
* to maintain nodeIDs in the safe range before
* moving to strings for larger numbers. Since we
* can represent ints up to MAX_SAFE_INTEGER
* (2^53 - 1) fine, we're using that as the
* boundary.
*/
const int = parseInt(identifier, 10);
if (
int >= -Number.MAX_SAFE_INTEGER &&
int <= Number.MAX_SAFE_INTEGER
) {
return int;
}
}
return identifier;
}
);
return getNodeIdForTypeAndIdentifiers(
Self,
...finalIdentifiers
);
},
};
}
return fields;
},
},
{
__origin: `Adding table type for ${describePgEntity(
table
)}. You can rename the table's GraphQL type via a 'Smart Comment':\n\n ${sqlCommentByAddingTags(
table,
{
name: "newNameHere",
}
)}`,
pgIntrospection: table,
isPgRowType: table.isSelectable,
isPgCompoundType: !table.isSelectable, // TODO:v5: remove - typo
isPgCompositeType: !table.isSelectable,
}
);
cb(TableType);
const pgCreateInputFields = {};
const pgPatchInputFields = {};
const pgBaseInputFields = {};
newWithHooks(
GraphQLInputObjectType,
{
description: build.wrapDescription(
`An input for mutations affecting \`${tableTypeName}\``,
"type"
),
name: inflection.inputType(TableType),
},
{
__origin: `Adding table input type for ${describePgEntity(
table
)}. You can rename the table's GraphQL type via a 'Smart Comment':\n\n ${sqlCommentByAddingTags(
table,
{
name: "newNameHere",
}
)}`,
pgIntrospection: table,
isInputType: true,
isPgRowType: table.isSelectable,
isPgCompoundType: !table.isSelectable,
pgAddSubfield(fieldName, attrName, pgType, spec, typeModifier) {
pgCreateInputFields[fieldName] = {
name: attrName,
type: pgType,
typeModifier,
};
return spec;
},
},
true // If no fields, skip type automatically
);
if (table.isSelectable) {
// XXX: these don't belong here; but we have to keep them here
// because third-party code depends on `getTypeByName` to find
// them; so we have to register them ahead of time. A better
// approach is to use the modifier to specify the type you need,
// 'patch' or 'base', so they can be registered just in time.
TablePatchType = newWithHooks(
GraphQLInputObjectType,
{
description: build.wrapDescription(
`Represents an update to a \`${tableTypeName}\`. Fields that are set will be updated.`,
"type"
),
name: inflection.patchType(TableType),
},
{
__origin: `Adding table patch type for ${describePgEntity(
table
)}. You can rename the table's GraphQL type via a 'Smart Comment':\n\n ${sqlCommentByAddingTags(
table,
{
name: "newNameHere",
}
)}`,
pgIntrospection: table,
isPgRowType: table.isSelectable,
isPgCompoundType: !table.isSelectable,
isPgPatch: true,
pgAddSubfield(
fieldName,
attrName,
pgType,
spec,
typeModifier
) {
pgPatchInputFields[fieldName] = {
name: attrName,
type: pgType,
typeModifier,
};
return spec;
},
},
true // Safe to skip this if no fields support updating
);
TableBaseInputType = newWithHooks(
GraphQLInputObjectType,
{
description: build.wrapDescription(
`An input representation of \`${tableTypeName}\` with nullable fields.`,
"type"
),
name: inflection.baseInputType(TableType),
},
{
__origin: `Adding table base input type for ${describePgEntity(
table
)}. You can rename the table's GraphQL type via a 'Smart Comment':\n\n ${sqlCommentByAddingTags(
table,
{
name: "newNameHere",
}
)}`,
pgIntrospection: table,
isPgRowType: table.isSelectable,
isPgCompoundType: !table.isSelectable,
isPgBaseInput: true,
pgAddSubfield(
fieldName,
attrName,
pgType,
spec,
typeModifier
) {
pgBaseInputFields[fieldName] = {
name: attrName,
type: pgType,
typeModifier,
};
return spec;
},
}
);
}
pg2GqlMapper[tablePgType.id] = {
map: _ => _,
unmap: (obj, modifier) => {
let fieldLookup;
if (modifier === "patch") {
fieldLookup = pgPatchInputFields;
} else if (modifier === "base") {
fieldLookup = pgBaseInputFields;
} else {
fieldLookup = pgCreateInputFields;
}
const attr2sql = attr => {
// TODO: this should use `fieldInput[*].name` to find the attribute
const fieldName = inflection.column(attr);
const inputField = fieldLookup[fieldName];
const v = obj[fieldName];
if (inputField && v != null) {
const { type, typeModifier } = inputField;
return sql.fragment`${gql2pg(v, type, typeModifier)}::${
type.isFake
? sql.identifier("unknown")
: sql.identifier(type.namespaceName, type.name)
}`;
} else {
return sql.null; // TODO: return default instead.
}
};
return sql.fragment`row(${sql.join(
attributes.map(attr2sql),
","
)})::${
tablePgType.isFake
? sql.identifier("unknown")
: sql.identifier(
tablePgType.namespaceName,
tablePgType.name
)
}`;
},
};
const EdgeType = newWithHooks(
GraphQLObjectType,
{
description: build.wrapDescription(
`A \`${tableTypeName}\` edge in the connection.`,
"type"
),
name: inflection.edge(TableType.name),
fields: ({ fieldWithHooks }) => {
return {
cursor: fieldWithHooks(
"cursor",
({ addDataGenerator }) => {
addDataGenerator(() => ({
usesCursor: [true],
pgQuery: queryBuilder => {
if (primaryKeys) {
queryBuilder.selectIdentifiers(table);
}
},
}));
return {
description: build.wrapDescription(
"A cursor for use in pagination.",
"field"
),
type: Cursor,
resolve(data) {
return (
data.__cursor &&
base64(JSON.stringify(data.__cursor))
);
},
};
},
{
isCursorField: true,
}
),
node: pgField(
build,
fieldWithHooks,
"node",
{
description: build.wrapDescription(
`The \`${tableTypeName}\` at the end of the edge.`,
"field"
),
type: nullableIf(
!pgForbidSetofFunctionsToReturnNull,
TableType
),
resolve(data, _args, resolveContext, resolveInfo) {
const safeAlias =
getSafeAliasFromResolveInfo(resolveInfo);
const record = handleNullRow(
data[safeAlias],
data.__identifiers
);
const liveRecord =
resolveInfo.rootValue &&
resolveInfo.rootValue.liveRecord;
if (
record &&
primaryKeys &&
liveRecord &&
data.__identifiers
) {
liveRecord("pg", table, data.__identifiers);
}
return record;
},
},
{},
false,
{
withQueryBuilder: queryBuilder => {
if (subscriptions) {
queryBuilder.selectIdentifiers(table);
}
},
}
),
};
},
},
{
__origin: `Adding table edge type for ${describePgEntity(
table
)}. You can rename the table's GraphQL type via a 'Smart Comment':\n\n ${sqlCommentByAddingTags(
table,
{
name: "newNameHere",
}
)}`,
isEdgeType: true,
isPgRowEdgeType: true,
nodeType: TableType,
pgIntrospection: table,
}
);
const PageInfo = getTypeByName(inflection.builtin("PageInfo"));
/*const ConnectionType = */
newWithHooks(
GraphQLObjectType,
{
description: build.wrapDescription(
`A connection to a list of \`${tableTypeName}\` values.`,
"type"
),
name: inflection.connection(TableType.name),
fields: ({ recurseDataGeneratorsForField, fieldWithHooks }) => {
recurseDataGeneratorsForField("pageInfo", true);
return {
nodes: pgField(
build,
fieldWithHooks,
"nodes",
{
description: build.wrapDescription(
`A list of \`${tableTypeName}\` objects.`,
"field"
),
type: new GraphQLNonNull(
new GraphQLList(
nullableIf(
!pgForbidSetofFunctionsToReturnNull,
TableType
)
)
),
resolve(data, _args, resolveContext, resolveInfo) {
const safeAlias =
getSafeAliasFromResolveInfo(resolveInfo);
const liveRecord =
resolveInfo.rootValue &&
resolveInfo.rootValue.liveRecord;
return data.data.map(entry => {
const record = handleNullRow(
entry[safeAlias],
entry[safeAlias].__identifiers
);
if (
record &&
liveRecord &&
primaryKeys &&
entry[safeAlias].__identifiers
) {
liveRecord(
"pg",
table,
entry[safeAlias].__identifiers
);
}
return record;
});
},
},
{},
false,
{
withQueryBuilder: queryBuilder => {
if (subscriptions) {
queryBuilder.selectIdentifiers(table);
}
},
}
),
edges: pgField(
build,
fieldWithHooks,
"edges",
{
description: build.wrapDescription(
`A list of edges which contains the \`${tableTypeName}\` and cursor to aid in pagination.`,
"field"
),
type: new GraphQLNonNull(
new GraphQLList(new GraphQLNonNull(EdgeType))
),
resolve(data, _args, _context, resolveInfo) {
const safeAlias =
getSafeAliasFromResolveInfo(resolveInfo);
return data.data.map(entry => ({
...entry,
...entry[safeAlias],
}));
},
},
{},
false,
{
hoistCursor: true,
}
),
pageInfo: PageInfo && {
description: build.wrapDescription(
"Information to aid in pagination.",
"field"
),
type: new GraphQLNonNull(PageInfo),
resolve(data) {
return data;
},
},
};
},
},
{
__origin: `Adding table connection type for ${describePgEntity(
table
)}. You can rename the table's GraphQL type via a 'Smart Comment':\n\n ${sqlCommentByAddingTags(
table,
{
name: "newNameHere",
}
)}`,
isConnectionType: true,
isPgRowConnectionType: true,
edgeType: EdgeType,
nodeType: TableType,
pgIntrospection: table,
}
);
},
true
);
pgRegisterGqlInputTypeByTypeId(
tablePgType.id,
(_set, modifier) => {
// This must come first, it triggers creation of all the types
const TableType = pgGetGqlTypeByTypeIdAndModifier(
tablePgType.id,
null
);
// This must come after the pgGetGqlTypeByTypeIdAndModifier call
if (modifier === "patch") {
// TODO: v5: move the definition from above down here
return TablePatchType;
}
if (modifier === "base") {
// TODO: v5: move the definition from above down here
return TableBaseInputType;
}
if (TableType) {
return getTypeByName(inflection.inputType(TableType));
}
return null;
},
true
);
if (arrayTablePgType) {
// Note: these do not return
//
// `new GraphQLList(new GraphQLNonNull(...))`
//
// because it's possible to return null entries from postgresql
// functions. We should probably add a flag to instead export
// the non-null version as that's more typical.
pgRegisterGqlTypeByTypeId(
arrayTablePgType.id,
() => {
const TableType = pgGetGqlTypeByTypeIdAndModifier(
tablePgType.id,
null
);
return new GraphQLList(TableType);
},
true
);
pgRegisterGqlInputTypeByTypeId(
arrayTablePgType.id,
(_set, modifier) => {
const RelevantTableInputType =
pgGetGqlInputTypeByTypeIdAndModifier(tablePgType.id, modifier);
if (RelevantTableInputType) {
return new GraphQLList(RelevantTableInputType);
}
},
true
);
}
});
return _;
},
["PgTables"],
[],
["PgTypes"]
);
}: Plugin);