-
Notifications
You must be signed in to change notification settings - Fork 148
/
compilers.ts
198 lines (184 loc) · 5.74 KB
/
compilers.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
import { AssertionContext } from "@dataform/core/assertion";
import { OperationContext } from "@dataform/core/operation";
import { ISqlxParseResults, parseSqlx } from "@dataform/core/sqlx_parser";
import { TableContext } from "@dataform/core/table";
import * as utils from "@dataform/core/utils";
export function compile(code: string, path: string, defaultSchema: string) {
if (path.endsWith(".sqlx")) {
return compileSqlx(parseSqlx(code), path, defaultSchema);
}
if (path.endsWith(".assert.sql")) {
return compileAssertionSql(code, path);
}
if (path.endsWith(".ops.sql")) {
return compileOperationSql(code, path);
}
if (path.endsWith(".sql")) {
return compileTableSql(code, path);
}
return code;
}
function compileTableSql(code: string, path: string) {
const { sql, js } = extractJsBlocks(code);
const functionsBindings = getFunctionPropertyNames(TableContext.prototype).map(
name => `const ${name} = ctx.${name}.bind(ctx);`
);
return `
publish("${utils.baseFilename(path)}").query(ctx => {
${functionsBindings.join("\n")}
${js}
return \`${sql}\`;
})`;
}
function compileOperationSql(code: string, path: string) {
const { sql, js } = extractJsBlocks(code);
const functionsBindings = getFunctionPropertyNames(OperationContext.prototype).map(
name => `const ${name} = ctx.${name}.bind(ctx);`
);
return `
operate("${utils.baseFilename(path)}").queries(ctx => {
${functionsBindings.join("\n")}
${js}
return \`${sql}\`.split("\\n---\\n");
})`;
}
function compileAssertionSql(code: string, path: string) {
const { sql, js } = extractJsBlocks(code);
const functionsBindings = getFunctionPropertyNames(AssertionContext.prototype).map(
name => `const ${name} = ctx.${name}.bind(ctx);`
);
return `
assert("${utils.baseFilename(path)}").query(ctx => {
${functionsBindings.join("\n")}
${js}
return \`${sql}\`;
})`;
}
export function extractJsBlocks(code: string): { sql: string; js: string } {
const JS_REGEX = /^\s*\/\*[jJ][sS]\s*[\r\n]+((?:[^*]|[\r\n]|(?:\*+(?:[^*/]|[\r\n])))*)\*+\/|^\s*\-\-[jJ][sS]\s(.*)/gm;
// This captures any single backticks that aren't escaped with a preceding \.
const RAW_BACKTICKS_REGEX = /([^\\])`/g;
const jsBlocks: string[] = [];
const cleanSql = code
.replace(JS_REGEX, (_, group1, group2) => {
if (group1) {
jsBlocks.push(group1);
}
if (group2) {
jsBlocks.push(group2);
}
return "";
})
.replace(RAW_BACKTICKS_REGEX, (_, group1) => group1 + "\\`");
return {
sql: cleanSql.trim(),
js: jsBlocks.map(block => block.trim()).join("\n")
};
}
function compileSqlx(results: ISqlxParseResults, path: string, defaultSchema: string) {
const resConfig =
results.config != null
? JSON.parse(results.config.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2": '))
: null;
const queryConfigSchema = "schema" in resConfig && resConfig != null ? resConfig.schema : null;
const fQName = [queryConfigSchema || defaultSchema, utils.baseFilename(path)].join(".");
return `
const parsedConfig = ${results.config || "{}"};
// sqlxConfig should conform to the ISqlxConfig interface.
const sqlxConfig = {
name: "${fQName}",
type: "operations",
dependencies: [],
tags: [],
...parsedConfig
};
const sqlStatementCount = ${results.sql.length};
const hasIncremental = ${!!results.incremental};
const hasPreOperations = ${results.preOperations.length > 1 || results.preOperations[0] !== ""};
const hasPostOperations = ${results.postOperations.length > 1 || results.postOperations[0] !== ""};
const hasInputs = ${Object.keys(results.input).length > 0};
const action = session.sqlxAction({
sqlxConfig,
sqlStatementCount,
hasIncremental,
hasPreOperations,
hasPostOperations,
hasInputs
});
switch (sqlxConfig.type) {
case "view":
case "table":
case "incremental":
case "inline": {
action.query(ctx => {
${["self", "ref", "resolve"].map(name => `const ${name} = ctx.${name}.bind(ctx);`).join("\n")}
${results.js}
if (hasIncremental) {
action.where(\`${results.incremental}\`);
}
if (hasPreOperations) {
const preOperations = [${results.preOperations.map(sql => `\`${sql}\``)}];
action.preOps(preOperations);
}
if (hasPostOperations) {
const postOperations = [${results.postOperations.map(sql => `\`${sql}\``)}];
action.postOps(postOperations);
}
return \`${results.sql[0]}\`;
});
break;
}
case "assertion": {
action.query(ctx => {
${["ref", "resolve"].map(name => `const ${name} = ctx.${name}.bind(ctx);`).join("\n")}
${results.js}
return \`${results.sql[0]}\`;
});
break;
}
case "operations": {
action.queries(ctx => {
${["self", "ref", "resolve"].map(name => `const ${name} = ctx.${name}.bind(ctx);`).join("\n")}
${results.js}
const operations = [${results.sql.map(sql => `\`${sql}\``)}];
return operations;
});
break;
}
case "test": {
${Object.keys(results.input).map(
inputLabel =>
`
action.input("${inputLabel}", ctx => {
${results.js}
return \`${results.input[inputLabel]}\`;
});
`
)}
action.expect(ctx => {
${results.js}
return \`${results.sql}\`;
});
break;
}
default: {
session.compileError(new Error(\`Unrecognized action type: \${sqlxConfig.type}\`));
break;
}
}`;
}
function getFunctionPropertyNames(prototype: any) {
return [
...new Set(
Object.getOwnPropertyNames(prototype).filter(propertyName => {
if (typeof prototype[propertyName] !== "function") {
return false;
}
if (propertyName === "constructor") {
return false;
}
return true;
})
)
];
}