-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathSqlSyncRules.ts
400 lines (345 loc) · 12 KB
/
SqlSyncRules.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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
import { isScalar, LineCounter, parseDocument, Scalar, YAMLMap, YAMLSeq } from 'yaml';
import { SqlRuleError, SyncRulesErrors, YamlError } from './errors.js';
import { SqlEventDescriptor } from './events/SqlEventDescriptor.js';
import { IdSequence } from './IdSequence.js';
import { validateSyncRulesSchema } from './json_schema.js';
import { SourceTableInterface } from './SourceTableInterface.js';
import { QueryParseResult, SqlBucketDescriptor } from './SqlBucketDescriptor.js';
import { TablePattern } from './TablePattern.js';
import {
EvaluatedParameters,
EvaluatedParametersResult,
EvaluatedRow,
EvaluateRowOptions,
EvaluationError,
EvaluationResult,
isEvaluatedParameters,
isEvaluatedRow,
isEvaluationError,
QueryParseOptions,
RequestParameters,
SourceSchema,
SqliteRow,
SyncRules
} from './types.js';
import { BucketDescription, BucketPriority, isValidPriority } from './BucketDescription.js';
import {
BucketParameterQuerier,
mergeBucketParameterQueriers,
ParameterLookupSource
} from './BucketParameterQuerier.js';
const ACCEPT_POTENTIALLY_DANGEROUS_QUERIES = Symbol('ACCEPT_POTENTIALLY_DANGEROUS_QUERIES');
export interface SyncRulesOptions {
schema?: SourceSchema;
/**
* The default schema to use when only a table name is specified.
*
* 'public' for Postgres, default database for MongoDB/MySQL.
*/
defaultSchema: string;
throwOnError?: boolean;
}
export class SqlSyncRules implements SyncRules {
bucket_descriptors: SqlBucketDescriptor[] = [];
event_descriptors: SqlEventDescriptor[] = [];
idSequence = new IdSequence();
content: string;
errors: YamlError[] = [];
static validate(yaml: string, options: SyncRulesOptions): YamlError[] {
try {
const rules = this.fromYaml(yaml, options);
return rules.errors;
} catch (e) {
if (e instanceof SyncRulesErrors) {
return e.errors;
} else if (e instanceof YamlError) {
return [e];
} else {
return [new YamlError(e)];
}
}
}
static fromYaml(yaml: string, options: SyncRulesOptions) {
const throwOnError = options.throwOnError ?? true;
const schema = options.schema;
const lineCounter = new LineCounter();
const parsed = parseDocument(yaml, {
schema: 'core',
keepSourceTokens: true,
lineCounter,
customTags: [
{
tag: '!accept_potentially_dangerous_queries',
resolve(_text: string, _onError: (error: string) => void) {
return ACCEPT_POTENTIALLY_DANGEROUS_QUERIES;
}
}
]
});
const rules = new SqlSyncRules(yaml);
if (parsed.errors.length > 0) {
rules.errors.push(
...parsed.errors.map((error) => {
return new YamlError(error);
})
);
if (throwOnError) {
rules.throwOnError();
}
return rules;
}
const bucketMap = parsed.get('bucket_definitions') as YAMLMap;
if (bucketMap == null) {
rules.errors.push(new YamlError(new Error(`'bucket_definitions' is required`)));
if (throwOnError) {
rules.throwOnError();
}
return rules;
}
for (let entry of bucketMap.items) {
const { key: keyScalar, value } = entry as { key: Scalar; value: YAMLMap };
const key = keyScalar.toString();
if (value == null || !(value instanceof YAMLMap)) {
rules.errors.push(this.tokenError(keyScalar, `'${key}' bucket definition must be an object`));
continue;
}
const accept_potentially_dangerous_queries =
value.get('accept_potentially_dangerous_queries', true)?.value == true;
let parseOptionPriority: BucketPriority | undefined = undefined;
if (value.has('priority')) {
const priorityValue = value.get('priority', true)!;
if (typeof priorityValue.value != 'number' || !isValidPriority(priorityValue.value)) {
rules.errors.push(
this.tokenError(priorityValue, 'Invalid priority, expected a number between 0 and 3 (inclusive).')
);
} else {
parseOptionPriority = priorityValue.value;
}
}
const queryOptions: QueryParseOptions = {
...options,
accept_potentially_dangerous_queries,
priority: parseOptionPriority
};
const parameters = value.get('parameters', true) as unknown;
const dataQueries = value.get('data', true) as unknown;
const descriptor = new SqlBucketDescriptor(key, rules.idSequence);
if (parameters instanceof Scalar) {
rules.withScalar(parameters, (q) => {
return descriptor.addParameterQuery(q, queryOptions);
});
} else if (parameters instanceof YAMLSeq) {
for (let item of parameters.items) {
rules.withScalar(item, (q) => {
return descriptor.addParameterQuery(q, queryOptions);
});
}
} else {
descriptor.addParameterQuery('SELECT', queryOptions);
}
if (!(dataQueries instanceof YAMLSeq)) {
rules.errors.push(this.tokenError(dataQueries ?? value, `'data' must be an array`));
continue;
}
for (let query of dataQueries.items) {
rules.withScalar(query, (q) => {
return descriptor.addDataQuery(q, queryOptions);
});
}
rules.bucket_descriptors.push(descriptor);
}
const eventMap = parsed.get('event_definitions') as YAMLMap;
for (const event of eventMap?.items ?? []) {
const { key, value } = event as { key: Scalar; value: YAMLSeq };
if (false == value instanceof YAMLMap) {
rules.errors.push(new YamlError(new Error(`Event definitions must be objects.`)));
continue;
}
const payloads = value.get('payloads') as YAMLSeq;
if (false == payloads instanceof YAMLSeq) {
rules.errors.push(new YamlError(new Error(`Event definition payloads must be an array.`)));
continue;
}
const eventDescriptor = new SqlEventDescriptor(key.toString(), rules.idSequence);
for (let item of payloads.items) {
if (!isScalar(item)) {
rules.errors.push(new YamlError(new Error(`Payload queries for events must be scalar.`)));
continue;
}
rules.withScalar(item, (q) => {
return eventDescriptor.addSourceQuery(q, options);
});
}
rules.event_descriptors.push(eventDescriptor);
}
// Validate that there are no additional properties.
// Since these errors don't contain line numbers, do this last.
const valid = validateSyncRulesSchema(parsed.toJSON());
if (!valid) {
rules.errors.push(
...validateSyncRulesSchema.errors!.map((e: any) => {
return new YamlError(e);
})
);
}
if (throwOnError) {
rules.throwOnError();
}
return rules;
}
throwOnError() {
if (this.errors.filter((e) => e.type != 'warning').length > 0) {
throw new SyncRulesErrors(this.errors);
}
}
static tokenError(token: any, message: string) {
const start = token?.srcToken?.offset ?? 0;
const end = start + 1;
return new YamlError(new Error(message), { start, end });
}
withScalar(scalar: Scalar, cb: (value: string) => QueryParseResult) {
const value = scalar.toString();
const wrapped = (value: string): QueryParseResult => {
try {
return cb(value);
} catch (e) {
return {
parsed: false,
errors: [e]
};
}
};
const result = wrapped(value);
for (let err of result.errors) {
let sourceOffset = scalar.srcToken!.offset;
if (scalar.type == Scalar.QUOTE_DOUBLE || scalar.type == Scalar.QUOTE_SINGLE) {
// TODO: Is there a better way to do this?
sourceOffset += 1;
}
let offset: number;
let end: number;
if (err instanceof SqlRuleError && err.location) {
offset = err.location!.start + sourceOffset;
end = err.location!.end + sourceOffset;
} else if (typeof (err as any).token?._location?.start == 'number') {
offset = sourceOffset + (err as any).token?._location?.start;
end = sourceOffset + (err as any).token?._location?.end;
} else {
offset = sourceOffset;
end = sourceOffset + Math.max(value.length, 1);
}
const pos = { start: offset, end };
this.errors.push(new YamlError(err, pos));
}
return result;
}
constructor(content: string) {
this.content = content;
}
/**
* Throws errors.
*/
evaluateRow(options: EvaluateRowOptions): EvaluatedRow[] {
const { results, errors } = this.evaluateRowWithErrors(options);
if (errors.length > 0) {
throw new Error(errors[0].error);
}
return results;
}
evaluateRowWithErrors(options: EvaluateRowOptions): { results: EvaluatedRow[]; errors: EvaluationError[] } {
let rawResults: EvaluationResult[] = [];
for (let query of this.bucket_descriptors) {
rawResults.push(...query.evaluateRow(options));
}
const results = rawResults.filter(isEvaluatedRow) as EvaluatedRow[];
const errors = rawResults.filter(isEvaluationError) as EvaluationError[];
return { results, errors };
}
/**
* Throws errors.
*/
evaluateParameterRow(table: SourceTableInterface, row: SqliteRow): EvaluatedParameters[] {
const { results, errors } = this.evaluateParameterRowWithErrors(table, row);
if (errors.length > 0) {
throw new Error(errors[0].error);
}
return results;
}
evaluateParameterRowWithErrors(
table: SourceTableInterface,
row: SqliteRow
): { results: EvaluatedParameters[]; errors: EvaluationError[] } {
let rawResults: EvaluatedParametersResult[] = [];
for (let query of this.bucket_descriptors) {
rawResults.push(...query.evaluateParameterRow(table, row));
}
const results = rawResults.filter(isEvaluatedParameters) as EvaluatedParameters[];
const errors = rawResults.filter(isEvaluationError) as EvaluationError[];
return { results, errors };
}
getBucketParameterQuerier(parameters: RequestParameters): BucketParameterQuerier {
const queriers = this.bucket_descriptors.map((query) => query.getBucketParameterQuerier(parameters));
return mergeBucketParameterQueriers(queriers);
}
hasDynamicBucketQueries() {
return this.bucket_descriptors.some((query) => query.hasDynamicBucketQueries());
}
getSourceTables(): TablePattern[] {
const sourceTables = new Map<String, TablePattern>();
for (const bucket of this.bucket_descriptors) {
for (const r of bucket.getSourceTables()) {
const key = `${r.connectionTag}.${r.schema}.${r.tablePattern}`;
sourceTables.set(key, r);
}
}
for (const event of this.event_descriptors) {
for (const r of event.getSourceTables()) {
const key = `${r.connectionTag}.${r.schema}.${r.tablePattern}`;
sourceTables.set(key, r);
}
}
return [...sourceTables.values()];
}
getEventTables(): TablePattern[] {
const eventTables = new Map<String, TablePattern>();
for (const event of this.event_descriptors) {
for (const r of event.getSourceTables()) {
const key = `${r.connectionTag}.${r.schema}.${r.tablePattern}`;
eventTables.set(key, r);
}
}
return [...eventTables.values()];
}
tableTriggersEvent(table: SourceTableInterface): boolean {
return this.event_descriptors.some((bucket) => bucket.tableTriggersEvent(table));
}
tableSyncsData(table: SourceTableInterface): boolean {
for (const bucket of this.bucket_descriptors) {
if (bucket.tableSyncsData(table)) {
return true;
}
}
return false;
}
tableSyncsParameters(table: SourceTableInterface): boolean {
for (let bucket of this.bucket_descriptors) {
if (bucket.tableSyncsParameters(table)) {
return true;
}
}
return false;
}
debugGetOutputTables() {
let result: Record<string, any[]> = {};
for (let bucket of this.bucket_descriptors) {
for (let q of bucket.data_queries) {
result[q.table!] ??= [];
const r = {
query: q.sql
};
result[q.table!].push(r);
}
}
return result;
}
}