-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathapp.ts
294 lines (268 loc) · 6.92 KB
/
app.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
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
// I cant' get this import to work locally. The import in node_modules is
// javy/dist but esbuild requires the import to be javy/fs
//
// @ts-expect-error
import { readFileSync, writeFileSync, STDIO } from "javy/fs";
import {
EmitHint,
FunctionDeclaration,
NewLineKind,
TypeNode,
ScriptKind,
ScriptTarget,
SyntaxKind,
Node,
NodeFlags,
createPrinter,
createSourceFile,
factory,
} from "typescript";
import {
GenerateRequest,
GenerateResponse,
Parameter,
Column,
File,
Query,
} from "./gen/plugin/codegen_pb";
import { argName, colName } from "./drivers/utlis";
import betterSQLite3 from "./drivers/better-sqlite3";
import pg from "./drivers/pg";
import postgres from "./drivers/postgres";
import mysql2 from "./drivers/mysql2";
// Read input from stdin
const input = readInput();
// Call the function with the input
const result = codegen(input);
// Write the result to stdout
writeOutput(result);
interface Options {
runtime?: string;
driver?: string;
}
interface Driver {
preamble: (queries: Query[]) => Node[];
columnType: (c?: Column) => TypeNode;
execDecl: (
name: string,
text: string,
iface: string | undefined,
params: Parameter[]
) => Node;
manyDecl: (
name: string,
text: string,
argIface: string | undefined,
returnIface: string,
params: Parameter[],
columns: Column[]
) => Node;
oneDecl: (
name: string,
text: string,
argIface: string | undefined,
returnIface: string,
params: Parameter[],
columns: Column[]
) => Node;
}
function createNodeGenerator(driver?: string): Driver {
switch (driver) {
case "mysql2": {
return mysql2;
}
case "pg": {
return pg;
}
case "postgres": {
return postgres;
}
case "better-sqlite3": {
return betterSQLite3;
}
}
throw new Error(`unknown driver: ${driver}`);
}
function codegen(input: GenerateRequest): GenerateResponse {
let files = [];
let options: Options = {};
if (input.pluginOptions.length > 0) {
const text = new TextDecoder().decode(input.pluginOptions);
options = JSON.parse(text) as Options;
}
const driver = createNodeGenerator(options.driver);
// TODO: Verify options, parse them from protobuf honestly
const querymap = new Map<string, Query[]>();
for (const query of input.queries) {
if (!querymap.has(query.filename)) {
querymap.set(query.filename, []);
}
const qs = querymap.get(query.filename);
qs?.push(query);
}
for (const [filename, queries] of querymap.entries()) {
const nodes = driver.preamble(queries);
for (const query of queries) {
const colmap = new Map<string, number>();
for (let column of query.columns) {
if (!column.name) {
continue;
}
const count = colmap.get(column.name) || 0;
if (count > 0) {
column.name = `${column.name}_${count + 1}`;
}
colmap.set(column.name, count + 1);
}
const lowerName = query.name[0].toLowerCase() + query.name.slice(1);
const textName = `${lowerName}Query`;
nodes.push(
queryDecl(
textName,
`-- name: ${query.name} ${query.cmd}
${query.text}`
)
);
const ctype = driver.columnType;
let argIface = undefined;
let returnIface = undefined;
if (query.params.length > 0) {
argIface = `${query.name}Args`;
nodes.push(argsDecl(argIface, ctype, query.params));
}
if (query.columns.length > 0) {
returnIface = `${query.name}Row`;
nodes.push(rowDecl(returnIface, ctype, query.columns));
}
switch (query.cmd) {
case ":exec": {
nodes.push(
driver.execDecl(lowerName, textName, argIface, query.params)
);
break;
}
case ":one": {
nodes.push(
driver.oneDecl(
lowerName,
textName,
argIface,
returnIface ?? "void",
query.params,
query.columns
)
);
break;
}
case ":many": {
nodes.push(
driver.manyDecl(
lowerName,
textName,
argIface,
returnIface ?? "void",
query.params,
query.columns
)
);
break;
}
}
if (nodes) {
files.push(
new File({
name: `${filename.replace(".", "_")}.ts`,
contents: new TextEncoder().encode(printNode(nodes)),
})
);
}
}
}
return new GenerateResponse({
files: files,
});
}
// Read input from stdin
function readInput(): GenerateRequest {
const buffer = readFileSync(STDIO.Stdin);
return GenerateRequest.fromBinary(buffer);
}
function queryDecl(name: string, sql: string) {
return factory.createVariableStatement(
[factory.createToken(SyntaxKind.ExportKeyword)],
factory.createVariableDeclarationList(
[
factory.createVariableDeclaration(
factory.createIdentifier(name),
undefined,
undefined,
factory.createNoSubstitutionTemplateLiteral(sql, sql)
),
],
NodeFlags.Const //| NodeFlags.Constant | NodeFlags.Constant
)
);
}
function argsDecl(
name: string,
ctype: (c?: Column) => TypeNode,
params: Parameter[]
) {
return factory.createInterfaceDeclaration(
[factory.createToken(SyntaxKind.ExportKeyword)],
factory.createIdentifier(name),
undefined,
undefined,
params.map((param, i) =>
factory.createPropertySignature(
undefined,
factory.createIdentifier(argName(i, param.column)),
undefined,
ctype(param.column)
)
)
);
}
function rowDecl(
name: string,
ctype: (c?: Column) => TypeNode,
columns: Column[]
) {
return factory.createInterfaceDeclaration(
[factory.createToken(SyntaxKind.ExportKeyword)],
factory.createIdentifier(name),
undefined,
undefined,
columns.map((column, i) =>
factory.createPropertySignature(
undefined,
factory.createIdentifier(colName(i, column)),
undefined,
ctype(column)
)
)
);
}
function printNode(nodes: Node[]): string {
// https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API#creating-and-printing-a-typescript-ast
const resultFile = createSourceFile(
"file.ts",
"",
ScriptTarget.Latest,
/*setParentNodes*/ false,
ScriptKind.TS
);
const printer = createPrinter({ newLine: NewLineKind.LineFeed });
let output = "// Code generated by sqlc. DO NOT EDIT.\n\n";
for (let node of nodes) {
output += printer.printNode(EmitHint.Unspecified, node, resultFile);
output += "\n\n";
}
return output;
}
// Write output to stdout
function writeOutput(output: GenerateResponse) {
const encodedOutput = output.toBinary();
const buffer = new Uint8Array(encodedOutput);
writeFileSync(STDIO.Stdout, buffer);
}