-
Notifications
You must be signed in to change notification settings - Fork 61
/
analyzeQuery.ts
171 lines (161 loc) · 4.8 KB
/
analyzeQuery.ts
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
import { ArrayCodec } from "../codecs/array";
import { AT_LEAST_ONE, AT_MOST_ONE, MANY, ONE } from "../codecs/consts";
import { EnumCodec } from "../codecs/enum";
import type { ICodec } from "../codecs/ifaces";
import { ScalarCodec } from "../codecs/ifaces";
import { NamedTupleCodec } from "../codecs/namedtuple";
import { ObjectCodec } from "../codecs/object";
import { MultiRangeCodec, RangeCodec } from "../codecs/range";
import { NullCodec } from "../codecs/codecs";
import { SetCodec } from "../codecs/set";
import { TupleCodec } from "../codecs/tuple";
import { Cardinality, OutputFormat } from "../ifaces";
import { Options, Session } from "../options";
import type { Client, BaseClientPool } from "../baseClient";
type QueryType = {
args: string;
result: string;
cardinality: Cardinality;
query: string;
imports: Set<string>;
};
export async function analyzeQuery(
client: Client,
query: string
): Promise<QueryType> {
const [cardinality, inCodec, outCodec] = await parseQuery(client, query);
const imports = new Set<string>();
const args = walkCodec(inCodec, {
indent: "",
optionalNulls: true,
readonly: true,
imports,
});
const result = applyCardinalityToTsType(
walkCodec(outCodec, {
indent: "",
optionalNulls: false,
readonly: false,
imports,
}),
cardinality
);
return {
result,
args,
cardinality,
query,
imports,
};
}
export async function parseQuery(client: Client, query: string) {
const pool: BaseClientPool = (client as any).pool;
const holder = await pool.acquireHolder(Options.defaults());
try {
const cxn = await holder._getConnection();
return await cxn._parse(
query,
OutputFormat.BINARY,
Cardinality.MANY,
Session.defaults()
);
} finally {
await holder.release();
}
}
export function applyCardinalityToTsType(
type: string,
cardinality: Cardinality
): string {
switch (cardinality) {
case Cardinality.MANY:
return `${type}[]`;
case Cardinality.ONE:
return type;
case Cardinality.AT_MOST_ONE:
return `${type} | null`;
case Cardinality.AT_LEAST_ONE:
return `[(${type}), ...(${type})[]]`;
}
throw Error(`unexpected cardinality: ${cardinality}`);
}
// type AtLeastOne<T> = [T, ...T[]];
export { walkCodec as walkCodecToTsType };
function walkCodec(
codec: ICodec,
ctx: {
indent: string;
optionalNulls: boolean;
readonly: boolean;
imports: Set<string>;
}
): string {
if (codec instanceof NullCodec) {
return "null";
}
if (codec instanceof ScalarCodec) {
if (codec instanceof EnumCodec) {
return `(${codec.values.map((val) => JSON.stringify(val)).join(" | ")})`;
}
if (codec.importedType) {
ctx.imports.add(codec.tsType);
}
return codec.tsType;
}
if (codec instanceof ObjectCodec || codec instanceof NamedTupleCodec) {
const fields =
codec instanceof ObjectCodec
? codec.getFields()
: codec.getNames().map((name) => ({ name, cardinality: ONE }));
const subCodecs = codec.getSubcodecs();
const objectShape = `{\n${fields
.map((field, i) => {
let subCodec = subCodecs[i];
if (subCodec instanceof SetCodec) {
if (
!(field.cardinality === MANY || field.cardinality === AT_LEAST_ONE)
) {
throw Error("subcodec is SetCodec, but upper cardinality is one");
}
subCodec = subCodec.getSubcodecs()[0];
}
return `${ctx.indent} ${JSON.stringify(field.name)}${
ctx.optionalNulls && field.cardinality === AT_MOST_ONE ? "?" : ""
}: ${applyCardinalityToTsType(
walkCodec(subCodec, { ...ctx, indent: ctx.indent + " " }),
field.cardinality
)};`;
})
.join("\n")}\n${ctx.indent}}`;
return ctx.readonly ? `Readonly<${objectShape}>` : objectShape;
}
if (codec instanceof ArrayCodec) {
return `${ctx.readonly ? "readonly " : ""}${walkCodec(
codec.getSubcodecs()[0],
ctx
)}[]`;
}
if (codec instanceof TupleCodec) {
return `${ctx.readonly ? "readonly " : ""}[${codec
.getSubcodecs()
.map((subCodec) => walkCodec(subCodec, ctx))
.join(", ")}]`;
}
if (codec instanceof RangeCodec) {
const subCodec = codec.getSubcodecs()[0];
if (!(subCodec instanceof ScalarCodec)) {
throw Error("expected range subtype to be scalar type");
}
ctx.imports.add("Range");
return `Range<${walkCodec(subCodec, ctx)}>`;
}
if (codec instanceof MultiRangeCodec) {
const subCodec = codec.getSubcodecs()[0];
if (!(subCodec instanceof ScalarCodec)) {
throw Error("expected multirange subtype to be scalar type");
}
ctx.imports.add("MultiRange");
return `MultiRange<${walkCodec(subCodec, ctx)}>`;
}
throw Error(`Unexpected codec kind: ${codec.getKind()}`);
}