-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathAggregateSpecsPlugin.ts
More file actions
329 lines (311 loc) · 11.2 KB
/
Copy pathAggregateSpecsPlugin.ts
File metadata and controls
329 lines (311 loc) · 11.2 KB
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
import type { PgCodec } from "postgraphile/@dataplan/pg";
import { EXPORTABLE } from "./EXPORTABLE.js";
import type { AggregateGroupBySpec, AggregateSpec } from "./interfaces.js";
import {
BIGINT_OID,
FLOAT4_OID,
FLOAT8_OID,
INT2_OID,
INT4_OID,
INTERVAL_OID,
MONEY_OID,
NUMERIC_OID,
} from "./interfaces.js";
const { version } = require("../package.json");
const isNumberLike = (codec: PgCodec<any, any, any, any>): boolean =>
!!codec.extensions?.isNumberLike;
const isIntervalLike = (codec: PgCodec<any, any, any, any>): boolean =>
!!codec.extensions?.isIntervalLike;
const isIntervalLikeOrNumberLike = EXPORTABLE(
(isIntervalLike, isNumberLike) =>
(codec: PgCodec<any, any, any, any>): boolean =>
isIntervalLike(codec) || isNumberLike(codec),
[isIntervalLike, isNumberLike]
);
export const PgAggregatesSpecsPlugin: GraphileConfig.Plugin = {
name: "PgAggregatesSpecsPlugin",
description:
"Created the default (extensible) aggregate specs and group-by specs used throughout this preset.",
version,
provides: ["aggregates"],
after: ["PgBasicsPlugin"],
gather: {
hooks: {
pgCodecs_PgCodec(_info, event) {
const { pgType, pgCodec } = event;
const isReg =
pgType.getNamespace()?.nspname === "pg_catalog" &&
pgType.typname.startsWith("reg");
const isCatN = !isReg && pgType.typcategory === "N";
const isInterval = !isReg && pgType._id === INTERVAL_OID;
if (isCatN || isInterval) {
if (!pgCodec.extensions) {
pgCodec.extensions = Object.create(null);
}
}
if (isCatN) {
pgCodec.extensions!.isNumberLike = true;
}
if (isInterval) {
pgCodec.extensions!.isIntervalLike = true;
}
},
},
},
schema: {
hooks: {
build(build) {
if (!build.dataplanPg || !build.sql) {
throw new Error(`PgBasicsPlugin must be loaded first`);
}
const {
sql,
dataplanPg: { TYPES },
EXPORTABLE,
} = build;
/** Maps from the data type of the attribute to the data type of the sum aggregate */
/** BigFloat is our fallback type; it should be valid for almost all numeric types */
const convertWithMapAndFallback = (
dataTypeToAggregateTypeMap: {
[key: string]: PgCodec<any, any, any, any>;
},
fallback: PgCodec<any, any, any, any>
) => {
return EXPORTABLE(
(dataTypeToAggregateTypeMap, fallback) =>
(
codec: PgCodec<any, any, any, any>
): PgCodec<any, any, any, any> => {
const oid = codec.extensions?.oid;
const targetType =
(oid ? dataTypeToAggregateTypeMap[oid] : null) ?? fallback;
return targetType;
},
[dataTypeToAggregateTypeMap, fallback]
);
};
const pgAggregateSpecs: AggregateSpec[] = [
{
id: "sum",
humanLabel: "sum",
HumanLabel: "Sum",
isSuitableType: isIntervalLikeOrNumberLike,
// I've wrapped it in `coalesce` so that it cannot be null
sqlAggregateWrap: EXPORTABLE(
(sql) => (sqlFrag) => sql`coalesce(sum(${sqlFrag}), '0')`,
[sql]
),
isNonNull: true,
// A SUM(...) often ends up significantly larger than any individual
// value; see
// https://www.postgresql.org/docs/current/functions-aggregate.html for
// how the sum aggregate changes result type.
pgTypeCodecModifier: convertWithMapAndFallback(
{
// TODO: this should use codecs rather than OIDs
[INT2_OID]: TYPES.bigint, // smallint -> bigint
[INT4_OID]: TYPES.bigint, // integer -> bigint
[BIGINT_OID]: TYPES.numeric, // bigint -> numeric
[FLOAT4_OID]: TYPES.float4, // real -> real
[FLOAT8_OID]: TYPES.float, // double precision -> double precision
[INTERVAL_OID]: TYPES.interval, // interval -> interval
[MONEY_OID]: TYPES.money, // money -> money
},
TYPES.numeric /* numeric */
),
},
{
id: "distinctCount",
humanLabel: "distinct count",
HumanLabel: "Distinct count",
isSuitableType: () => true,
sqlAggregateWrap: EXPORTABLE(
(sql) => (sqlFrag) => sql`count(distinct ${sqlFrag})`,
[sql]
),
pgTypeCodecModifier: convertWithMapAndFallback(
{},
TYPES.bigint /* always use bigint */
),
},
{
id: "min",
humanLabel: "minimum",
HumanLabel: "Minimum",
isSuitableType: isIntervalLikeOrNumberLike,
sqlAggregateWrap: EXPORTABLE(
(sql) => (sqlFrag) => sql`min(${sqlFrag})`,
[sql]
),
},
{
id: "max",
humanLabel: "maximum",
HumanLabel: "Maximum",
isSuitableType: isIntervalLikeOrNumberLike,
sqlAggregateWrap: EXPORTABLE(
(sql) => (sqlFrag) => sql`max(${sqlFrag})`,
[sql]
),
},
{
id: "average",
humanLabel: "mean average",
HumanLabel: "Mean average",
isSuitableType: isIntervalLikeOrNumberLike,
sqlAggregateWrap: EXPORTABLE(
(sql) => (sqlFrag) => sql`avg(${sqlFrag})`,
[sql]
),
// An AVG(...) ends up more precise than any individual value; see
// https://www.postgresql.org/docs/current/functions-aggregate.html for
// how the avg aggregate changes result type.
pgTypeCodecModifier: convertWithMapAndFallback(
{
[INT2_OID]: TYPES.numeric, // smallint -> numeric
[INT4_OID]: TYPES.numeric, // integer -> numeric
[BIGINT_OID]: TYPES.numeric, // bigint -> numeric
[NUMERIC_OID]: TYPES.numeric, // numeric -> numeric
[FLOAT4_OID]: TYPES.float, // real -> double precision
[FLOAT8_OID]: TYPES.float, // double precision -> double precision
[INTERVAL_OID]: TYPES.interval, // interval -> interval
},
TYPES.numeric /* numeric */
),
},
{
id: "stddevSample",
humanLabel: "sample standard deviation",
HumanLabel: "Sample standard deviation",
isSuitableType: isNumberLike,
sqlAggregateWrap: EXPORTABLE(
(sql) => (sqlFrag) => sql`stddev_samp(${sqlFrag})`,
[sql]
),
// See https://www.postgresql.org/docs/current/functions-aggregate.html
// for how this aggregate changes result type.
pgTypeCodecModifier: convertWithMapAndFallback(
{
[FLOAT4_OID]: TYPES.float, // real -> double precision
[FLOAT8_OID]: TYPES.float, // double precision -> double precision
},
TYPES.numeric /* numeric */
),
},
{
id: "stddevPopulation",
humanLabel: "population standard deviation",
HumanLabel: "Population standard deviation",
isSuitableType: isNumberLike,
sqlAggregateWrap: EXPORTABLE(
(sql) => (sqlFrag) => sql`stddev_pop(${sqlFrag})`,
[sql]
),
// See https://www.postgresql.org/docs/current/functions-aggregate.html
// for how this aggregate changes result type.
pgTypeCodecModifier: convertWithMapAndFallback(
{
[FLOAT4_OID]: TYPES.float, // real -> double precision
[FLOAT8_OID]: TYPES.float, // double precision -> double precision
},
TYPES.numeric /* numeric */
),
},
{
id: "varianceSample",
humanLabel: "sample variance",
HumanLabel: "Sample variance",
isSuitableType: isNumberLike,
sqlAggregateWrap: EXPORTABLE(
(sql) => (sqlFrag) => sql`var_samp(${sqlFrag})`,
[sql]
),
// See https://www.postgresql.org/docs/current/functions-aggregate.html
// for how this aggregate changes result type.
pgTypeCodecModifier: convertWithMapAndFallback(
{
[FLOAT4_OID]: TYPES.float, // real -> double precision
[FLOAT8_OID]: TYPES.float, // double precision -> double precision
},
TYPES.numeric /* numeric */
),
},
{
id: "variancePopulation",
humanLabel: "population variance",
HumanLabel: "Population variance",
isSuitableType: isNumberLike,
sqlAggregateWrap: EXPORTABLE(
(sql) => (sqlFrag) => sql`var_pop(${sqlFrag})`,
[sql]
),
// See https://www.postgresql.org/docs/current/functions-aggregate.html
// for how this aggregate changes result type.
pgTypeCodecModifier: convertWithMapAndFallback(
{
[FLOAT4_OID]: TYPES.float, // real -> double precision
[FLOAT8_OID]: TYPES.float, // double precision -> double precision
},
TYPES.numeric /* numeric */
),
},
];
const pgAggregateGroupBySpecs: AggregateGroupBySpec[] = [
{
id: "truncated-to-hour",
isSuitableType: EXPORTABLE(
(TYPES) => (codec) =>
codec === TYPES.timestamp || codec === TYPES.timestamptz,
[TYPES]
),
sqlWrap: EXPORTABLE(
(sql) => (sqlFrag) => sql`date_trunc('hour', ${sqlFrag})`,
[sql]
),
sqlWrapCodec(codec) {
return codec;
},
},
{
id: "truncated-to-day",
isSuitableType: EXPORTABLE(
(TYPES) => (codec) =>
codec === TYPES.timestamp || codec === TYPES.timestamptz,
[TYPES]
),
sqlWrap: EXPORTABLE(
(sql) => (sqlFrag) => sql`date_trunc('day', ${sqlFrag})`,
[sql]
),
sqlWrapCodec(codec) {
return codec;
},
},
];
return build.extend(
build,
{
pgAggregateSpecs,
pgAggregateGroupBySpecs,
},
"Adding aggregate specs to build"
);
},
finalize(schema, build) {
build.pgAggregateSpecs.forEach((spec) => {
build.exportNameHint(
spec,
`pgAggregateSpec_${spec.id.replace(/-/g, "_")}`
);
});
build.pgAggregateGroupBySpecs.forEach((spec) => {
build.exportNameHint(
spec,
`pgAggregateGroupBySpec_${spec.id.replace(/-/g, "_")}`
);
});
return schema;
},
},
},
};