/
PgAllRows.js
234 lines (229 loc) · 9.07 KB
/
PgAllRows.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
// @flow
import type { Plugin } from "graphile-build";
import debugSql from "./debugSql";
export default (async function PgAllRows(
builder,
{ pgViewUniqueKey, pgSimpleCollections, subscriptions }
) {
builder.hook(
"GraphQLObjectType:fields",
(fields, build, context) => {
const {
parseResolveInfo,
extend,
getTypeByName,
pgGetGqlTypeByTypeIdAndModifier,
pgSql: sql,
pgIntrospectionResultsByKind: introspectionResultsByKind,
inflection,
graphql: { GraphQLList, GraphQLNonNull },
pgQueryFromResolveData: queryFromResolveData,
pgAddStartEndCursor: addStartEndCursor,
pgOmit: omit,
pgPrepareAndRun,
} = build;
const {
fieldWithHooks,
scope: { isRootQuery },
} = context;
if (!isRootQuery) {
return fields;
}
return extend(
fields,
introspectionResultsByKind.class.reduce((memo, table) => {
// PERFORMANCE: These used to be .filter(...) calls
if (!table.isSelectable) return memo;
if (!table.namespace) return memo;
if (omit(table, "all")) return memo;
const TableType = pgGetGqlTypeByTypeIdAndModifier(
table.type.id,
null
);
if (!TableType) {
return memo;
}
const tableTypeName = TableType.name;
const ConnectionType = getTypeByName(
inflection.connection(TableType.name)
);
if (!TableType) {
throw new Error(
`Could not find GraphQL type for table '${table.name}'`
);
}
const attributes = table.attributes;
const primaryKeyConstraint = table.primaryKeyConstraint;
const primaryKeys =
primaryKeyConstraint && primaryKeyConstraint.keyAttributes;
const isView = t => t.classKind === "v";
const viewUniqueKey = table.tags.uniqueKey || pgViewUniqueKey;
const uniqueIdAttribute = viewUniqueKey
? attributes.find(attr => attr.name === viewUniqueKey)
: undefined;
if (isView && table.tags.uniqueKey && !uniqueIdAttribute) {
throw new Error(
`Could not find the named unique key '${table.tags.uniqueKey}' on view '${table.namespaceName}.${table.name}'`
);
}
if (!ConnectionType) {
throw new Error(
`Could not find GraphQL connection type for table '${table.name}'`
);
}
const schema = table.namespace;
const sqlFullTableName = sql.identifier(schema.name, table.name);
function makeField(isConnection) {
const fieldName = isConnection
? inflection.allRows(table)
: inflection.allRowsSimple(table);
memo[fieldName] = fieldWithHooks(
fieldName,
({ getDataFromParsedResolveInfoFragment }) => {
return {
description: build.wrapDescription(
isConnection
? `Reads and enables pagination through a set of \`${tableTypeName}\`.`
: `Reads a set of \`${tableTypeName}\`.`,
"field"
),
type: isConnection
? ConnectionType
: new GraphQLList(new GraphQLNonNull(TableType)),
args: {},
async resolve(parent, args, resolveContext, resolveInfo) {
const { pgClient } = resolveContext;
const parsedResolveInfoFragment = parseResolveInfo(
resolveInfo
);
parsedResolveInfoFragment.args = args; // Allow overriding via makeWrapResolversPlugin
const resolveData = getDataFromParsedResolveInfoFragment(
parsedResolveInfoFragment,
resolveInfo.returnType
);
let checkerGenerator;
const query = queryFromResolveData(
sqlFullTableName,
undefined,
resolveData,
{
useAsterisk: table.canUseAsterisk,
withPaginationAsFields: isConnection,
},
queryBuilder => {
if (subscriptions) {
queryBuilder.makeLiveCollection(
table,
_checkerGenerator => {
checkerGenerator = _checkerGenerator;
}
);
}
if (primaryKeys) {
if (subscriptions && !isConnection) {
queryBuilder.selectIdentifiers(table);
}
queryBuilder.beforeLock("orderBy", () => {
if (!queryBuilder.isOrderUnique(false)) {
// Order by PK if no order specified
queryBuilder.data.cursorPrefix = [
"primary_key_asc",
];
primaryKeys.forEach(key => {
queryBuilder.orderBy(
sql.fragment`${queryBuilder.getTableAlias()}.${sql.identifier(
key.name
)}`,
true
);
});
queryBuilder.setOrderIsUnique();
}
});
} else if (isView(table) && !!uniqueIdAttribute) {
queryBuilder.beforeLock("orderBy", () => {
if (!queryBuilder.isOrderUnique(false)) {
queryBuilder.data.cursorPrefix = [
"view_unique_key_asc",
];
queryBuilder.orderBy(
sql.fragment`${queryBuilder.getTableAlias()}.${sql.identifier(
uniqueIdAttribute.name
)}`,
true
);
queryBuilder.setOrderIsUnique();
}
});
}
},
resolveContext,
resolveInfo.rootValue
);
const { text, values } = sql.compile(query);
if (debugSql.enabled) debugSql(text);
const result = await pgPrepareAndRun(
pgClient,
text,
values
);
const liveCollection =
resolveInfo.rootValue &&
resolveInfo.rootValue.liveCollection;
if (subscriptions && liveCollection && checkerGenerator) {
const checker = checkerGenerator();
liveCollection("pg", table, checker);
}
if (isConnection) {
const {
rows: [row],
} = result;
return addStartEndCursor(row);
} else {
const liveRecord =
resolveInfo.rootValue &&
resolveInfo.rootValue.liveRecord;
if (
subscriptions &&
!isConnection &&
primaryKeys &&
liveRecord
) {
result.rows.forEach(
row =>
row && liveRecord("pg", table, row.__identifiers)
);
}
return result.rows;
}
},
};
},
{
isPgFieldConnection: isConnection,
isPgFieldSimpleCollection: !isConnection,
pgFieldIntrospection: table,
}
);
}
const simpleCollections =
table.tags.simpleCollections || pgSimpleCollections;
const hasConnections = simpleCollections !== "only";
const hasSimpleCollections =
simpleCollections === "only" || simpleCollections === "both";
if (TableType && ConnectionType && hasConnections) {
makeField(true);
}
if (TableType && hasSimpleCollections) {
makeField(false);
}
return memo;
}, {}),
`Adding 'all*' relations to root Query`
);
},
["PgAllRows"],
[],
["PgTables"]
);
}: Plugin);