/
PgBasicsPlugin.js
546 lines (530 loc) · 18 KB
/
PgBasicsPlugin.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
// @flow
import sql from "pg-sql2";
import type { Plugin } from "graphile-build";
import { version } from "../../package.json";
import type {
PgProc,
PgType,
PgClass,
PgAttribute,
PgConstraint,
} from "./PgIntrospectionPlugin";
import queryFromResolveData from "../queryFromResolveData";
import addStartEndCursor from "./addStartEndCursor";
import omit, {
CREATE,
READ,
UPDATE,
DELETE,
ALL,
MANY,
ORDER,
FILTER,
EXECUTE,
} from "../omit";
import makeProcField from "./makeProcField";
import parseIdentifier from "../parseIdentifier";
import viaTemporaryTable from "./viaTemporaryTable";
const defaultPgColumnFilter = (_attr, _build, _context) => true;
type Keys = Array<{
column: string,
table: string,
schema: ?string,
}>;
export function preventEmptyResult<
// eslint-disable-next-line flowtype/no-weak-types
O: { [key: string]: (...args: Array<any>) => string }
>(obj: O): $ObjMap<O, <V>(V) => V> {
return Object.keys(obj).reduce((memo, key) => {
const fn = obj[key];
memo[key] = function(...args) {
const result = fn.apply(this, args);
if (typeof result !== "string" || result.length === 0) {
const stringifiedArgs = require("util").inspect(args);
throw new Error(
`Inflector for '${key}' returned '${String(
result
)}'; expected non-empty string\n` +
`See: https://github.com/graphile/graphile-build/blob/master/packages/graphile-build-pg/src/plugins/PgBasicsPlugin.js\n` +
`Arguments passed to ${key}:\n${stringifiedArgs}`
);
}
return result;
};
return memo;
}, {});
}
function omitWithRBACChecks(
entity: PgProc | PgClass | PgAttribute | PgConstraint,
permission: string
) {
const ORDINARY_TABLE = "r";
const VIEW = "v";
const MATERIALIZED_VIEW = "m";
const isTableLike = entity =>
entity &&
entity.kind === "class" &&
(entity.classKind === ORDINARY_TABLE ||
entity.classKind === VIEW ||
entity.classKind === MATERIALIZED_VIEW);
if (entity.kind === "procedure") {
if (permission === EXECUTE && !entity.aclExecutable) {
return true;
}
} else if (entity.kind === "class" && isTableLike(entity)) {
const tableEntity: PgClass = entity;
if (
(permission === READ || permission === ALL || permission === MANY) &&
(!tableEntity.aclSelectable &&
!tableEntity.attributes.some(attr => attr.aclSelectable))
) {
return true;
} else if (
permission === CREATE &&
(!tableEntity.aclInsertable &&
!tableEntity.attributes.some(attr => attr.aclInsertable))
) {
return true;
} else if (
permission === UPDATE &&
(!tableEntity.aclUpdatable &&
!tableEntity.attributes.some(attr => attr.aclUpdatable))
) {
return true;
} else if (permission === DELETE && !tableEntity.aclDeletable) {
return true;
}
} else if (entity.kind === "attribute" && isTableLike(entity.class)) {
const attributeEntity: PgAttribute = entity;
const klass = attributeEntity.class;
// Have we got *any* permissions on the table?
if (
klass.aclSelectable ||
klass.attributes.some(attr => attr.aclSelectable)
) {
// Yes; this is a regular table; omit if RBAC permissions tell us to.
if (
(permission === READ ||
permission === FILTER ||
permission === ORDER) &&
!attributeEntity.aclSelectable
) {
return true;
} else if (permission === CREATE && !attributeEntity.aclInsertable) {
return true;
} else if (permission === UPDATE && !attributeEntity.aclUpdatable) {
return true;
}
} else {
// No permissions on the table at all, so normal connections will skip
// over it. Thus we must be being exposed via a security definer function
// or similar, so we should expose all fields except those that are
// explicitly @omit-ed.
}
}
return omit(entity, permission);
}
export default (function PgBasicsPlugin(
builder,
{
pgStrictFunctions = false,
pgColumnFilter = defaultPgColumnFilter,
pgIgnoreRBAC = false,
}
) {
const pgOmit = pgIgnoreRBAC ? omit : omitWithRBACChecks;
builder.hook("build", build => {
return build.extend(build, {
graphileBuildPgVersion: version,
pgSql: sql,
pgStrictFunctions,
pgColumnFilter,
pgQueryFromResolveData: queryFromResolveData,
pgAddStartEndCursor: addStartEndCursor,
pgOmit,
pgMakeProcField: makeProcField,
pgParseIdentifier: parseIdentifier,
pgViaTemporaryTable: viaTemporaryTable,
});
});
builder.hook("inflection", (inflection, build) => {
return build.extend(
inflection,
preventEmptyResult({
// These helpers are passed GraphQL type names as strings
conditionType(typeName: string) {
return this.upperCamelCase(`${typeName}-condition`);
},
inputType(typeName: string) {
return this.upperCamelCase(`${typeName}-input`);
},
rangeBoundType(typeName: string) {
return this.upperCamelCase(`${typeName}-range-bound`);
},
rangeType(typeName: string) {
return this.upperCamelCase(`${typeName}-range`);
},
patchType(typeName: string) {
return this.upperCamelCase(`${typeName}-patch`);
},
baseInputType(typeName: string) {
return this.upperCamelCase(`${typeName}-base-input`);
},
patchField(itemName: string) {
return this.camelCase(`${itemName}-patch`);
},
orderByType(typeName: string) {
return this.upperCamelCase(`${this.pluralize(typeName)}-order-by`);
},
edge(typeName: string) {
return this.upperCamelCase(`${this.pluralize(typeName)}-edge`);
},
connection(typeName: string) {
return this.upperCamelCase(`${this.pluralize(typeName)}-connection`);
},
// These helpers handle overrides via smart comments. They should only
// be used in other inflectors, hence the underscore prefix.
//
// IMPORTANT: do NOT do case transforms here, because detail can be
// lost, e.g.
// `constantCase(camelCase('foo_1')) !== constantCase('foo_1')`
_functionName(proc: PgProc) {
return proc.tags.name || proc.name;
},
_typeName(type: PgType) {
// 'type' introspection result
return type.tags.name || type.name;
},
_tableName(table: PgClass) {
return table.tags.name || table.type.tags.name || table.name;
},
_singularizedTableName(table: PgClass): string {
return this.singularize(this._tableName(table)).replace(
/.(?:(?:[_-]i|I)nput|(?:[_-]p|P)atch)$/,
"$&_record"
);
},
_columnName(attr: PgAttribute, _options?: { skipRowId?: boolean }) {
return attr.tags.name || attr.name;
},
// From here down, functions are passed database introspection results
enumType(type: PgType) {
return this.upperCamelCase(this._typeName(type));
},
argument(name: ?string, index: number) {
return this.camelCase(name || `arg${index}`);
},
orderByColumnEnum(attr: PgAttribute, ascending: boolean) {
const columnName = this._columnName(attr, {
skipRowId: true, // Because we messed up 😔
});
return this.constantCase(
`${columnName}_${ascending ? "asc" : "desc"}`
);
},
domainType(type: PgType) {
return this.upperCamelCase(this._typeName(type));
},
enumName(inValue: string) {
let value = inValue;
if (value === "") {
return "_EMPTY_";
}
// Some enums use asterisks to signify wildcards - this might be for
// the whole item, or prefixes/suffixes, or even in the middle. This
// is provided on a best efforts basis, if it doesn't suit your
// purposes then please pass a custom inflector as mentioned below.
value = value
.replace(/\*/g, "_ASTERISK_")
.replace(/^(_?)_+ASTERISK/, "$1ASTERISK")
.replace(/ASTERISK_(_?)_*$/, "ASTERISK$1");
// This is a best efforts replacement for common symbols that you
// might find in enums. Generally we only support enums that are
// alphanumeric, if these replacements don't work for you, you should
// pass a custom inflector that replaces this `enumName` method
// with one of your own chosing.
value =
{
// SQL comparison operators
">": "GREATER_THAN",
">=": "GREATER_THAN_OR_EQUAL",
"=": "EQUAL",
"!=": "NOT_EQUAL",
"<>": "DIFFERENT",
"<=": "LESS_THAN_OR_EQUAL",
"<": "LESS_THAN",
// PostgreSQL LIKE shortcuts
"~~": "LIKE",
"~~*": "ILIKE",
"!~~": "NOT_LIKE",
"!~~*": "NOT_ILIKE",
// '~' doesn't necessarily represent regexps, but the three
// operators following it likely do, so we'll use the word TILDE
// in all for consistency.
"~": "TILDE",
"~*": "TILDE_ASTERISK",
"!~": "NOT_TILDE",
"!~*": "NOT_TILDE_ASTERISK",
// A number of other symbols where we're not sure of their
// meaning. We give them common generic names so that they're
// suitable for multiple purposes, e.g. favouring 'PLUS' over
// 'ADDITION' and 'DOT' over 'FULL_STOP'
"%": "PERCENT",
"+": "PLUS",
"-": "MINUS",
"/": "SLASH",
"\\": "BACKSLASH",
_: "UNDERSCORE",
"#": "POUND",
"£": "STERLING",
$: "DOLLAR",
"&": "AMPERSAND",
"@": "AT",
"'": "APOSTROPHE",
'"': "QUOTE",
"`": "BACKTICK",
":": "COLON",
";": "SEMICOLON",
"!": "EXCLAMATION_POINT",
"?": "QUESTION_MARK",
",": "COMMA",
".": "DOT",
"^": "CARET",
"|": "BAR",
"[": "OPEN_BRACKET",
"]": "CLOSE_BRACKET",
"(": "OPEN_PARENTHESIS",
")": "CLOSE_PARENTHESIS",
"{": "OPEN_BRACE",
"}": "CLOSE_BRACE",
}[value] || value;
return value;
},
tableNode(table: PgClass) {
return this.camelCase(this._singularizedTableName(table));
},
tableFieldName(table: PgClass) {
return this.camelCase(this._singularizedTableName(table));
},
allRows(table: PgClass) {
return this.camelCase(
`all-${this.pluralize(this._singularizedTableName(table))}`
);
},
allRowsSimple(table: PgClass) {
return this.camelCase(
`all-${this.pluralize(this._singularizedTableName(table))}-list`
);
},
functionMutationName(proc: PgProc) {
return this.camelCase(this._functionName(proc));
},
functionQueryName(proc: PgProc) {
return this.camelCase(this._functionName(proc));
},
functionQueryNameList(proc: PgProc) {
return this.camelCase(`${this._functionName(proc)}-list`);
},
functionPayloadType(proc: PgProc) {
return this.upperCamelCase(`${this._functionName(proc)}-payload`);
},
functionInputType(proc: PgProc) {
return this.upperCamelCase(`${this._functionName(proc)}-input`);
},
tableType(table: PgClass) {
return this.upperCamelCase(this._singularizedTableName(table));
},
column(attr: PgAttribute) {
return this.camelCase(this._columnName(attr));
},
computedColumn(
pseudoColumnName: string,
proc: PgProc,
_table: PgClass
) {
return proc.tags.fieldName || this.camelCase(pseudoColumnName);
},
computedColumnList(
pseudoColumnName: string,
proc: PgProc,
_table: PgClass
) {
return proc.tags.fieldName
? proc.tags.fieldName + "List"
: this.camelCase(`${pseudoColumnName}-list`);
},
singleRelationByKeys(
detailedKeys: Keys,
table: PgClass,
_foreignTable: PgClass,
constraint: PgConstraint
) {
if (constraint.tags.fieldName) {
return constraint.tags.fieldName;
}
return this.camelCase(
`${this._singularizedTableName(table)}-by-${detailedKeys
.map(key => this.column(key))
.join("-and-")}`
);
},
manyRelationByKeys(
detailedKeys: Keys,
table: PgClass,
_foreignTable: PgClass,
constraint: PgConstraint
) {
if (constraint.tags.foreignFieldName) {
return constraint.tags.foreignFieldName;
}
return this.camelCase(
`${this.pluralize(
this._singularizedTableName(table)
)}-by-${detailedKeys.map(key => this.column(key)).join("-and-")}`
);
},
manyRelationByKeysSimple(
detailedKeys: Keys,
table: PgClass,
_foreignTable: PgClass,
constraint: PgConstraint
) {
if (constraint.tags.foreignFieldName) {
return constraint.tags.foreignFieldName;
}
return this.camelCase(
`${this.pluralize(
this._singularizedTableName(table)
)}-by-${detailedKeys
.map(key => this.column(key))
.join("-and-")}-list`
);
},
rowByUniqueKeys(
detailedKeys: Keys,
table: PgClass,
constraint: PgConstraint
) {
if (constraint.tags.fieldName) {
return constraint.tags.fieldName;
}
return this.camelCase(
`${this._singularizedTableName(table)}-by-${detailedKeys
.map(key => this.column(key))
.join("-and-")}`
);
},
updateByKeys(
detailedKeys: Keys,
table: PgClass,
constraint: PgConstraint
) {
if (constraint.tags.updateFieldName) {
return constraint.tags.updateFieldName;
}
return this.camelCase(
`update-${this._singularizedTableName(table)}-by-${detailedKeys
.map(key => this.column(key))
.join("-and-")}`
);
},
deleteByKeys(
detailedKeys: Keys,
table: PgClass,
constraint: PgConstraint
) {
if (constraint.tags.deleteFieldName) {
return constraint.tags.deleteFieldName;
}
return this.camelCase(
`delete-${this._singularizedTableName(table)}-by-${detailedKeys
.map(key => this.column(key))
.join("-and-")}`
);
},
updateByKeysInputType(
detailedKeys: Keys,
table: PgClass,
constraint: PgConstraint
) {
if (constraint.tags.updateFieldName) {
return this.upperCamelCase(
`${constraint.tags.updateFieldName}-input`
);
}
return this.upperCamelCase(
`update-${this._singularizedTableName(table)}-by-${detailedKeys
.map(key => this.column(key))
.join("-and-")}-input`
);
},
deleteByKeysInputType(
detailedKeys: Keys,
table: PgClass,
constraint: PgConstraint
) {
if (constraint.tags.deleteFieldName) {
return this.upperCamelCase(
`${constraint.tags.deleteFieldName}-input`
);
}
return this.upperCamelCase(
`delete-${this._singularizedTableName(table)}-by-${detailedKeys
.map(key => this.column(key))
.join("-and-")}-input`
);
},
updateNode(table: PgClass) {
return this.camelCase(`update-${this._singularizedTableName(table)}`);
},
deleteNode(table: PgClass) {
return this.camelCase(`delete-${this._singularizedTableName(table)}`);
},
updateNodeInputType(table: PgClass) {
return this.upperCamelCase(
`update-${this._singularizedTableName(table)}-input`
);
},
deleteNodeInputType(table: PgClass) {
return this.upperCamelCase(
`delete-${this._singularizedTableName(table)}-input`
);
},
edgeField(table: PgClass) {
return this.camelCase(`${this._singularizedTableName(table)}-edge`);
},
scalarFunctionConnection(proc: PgProc) {
return this.upperCamelCase(`${this._functionName(proc)}-connection`);
},
scalarFunctionEdge(proc: PgProc) {
return this.upperCamelCase(
`${this.singularize(this._functionName(proc))}-edge`
);
},
createField(table: PgClass) {
return this.camelCase(`create-${this._singularizedTableName(table)}`);
},
createInputType(table: PgClass) {
return this.upperCamelCase(
`create-${this._singularizedTableName(table)}-input`
);
},
createPayloadType(table: PgClass) {
return this.upperCamelCase(
`create-${this._singularizedTableName(table)}-payload`
);
},
updatePayloadType(table: PgClass) {
return this.upperCamelCase(
`update-${this._singularizedTableName(table)}-payload`
);
},
deletePayloadType(table: PgClass) {
return this.upperCamelCase(
`delete-${this._singularizedTableName(table)}-payload`
);
},
})
);
});
}: Plugin);