@narrative.io/data-collaboration-sdk-ts 0.0.50 → 0.0.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,788 @@
1
+ /*!
2
+ Copyright 2023 Narrative I/O, Inc.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ NOTICE: THIS FILE HAS BEEN MODIFIED BY NARRATIVE I/O UNDER COMPLIANCE WITH THE APACHE 2.0 LICENCE FROM THE ORIGINAL WORK
11
+ OF THE COMPANY Substrait (https://github.com/substrait-io/substrait-js).
12
+ */
13
+ var AggregationInvocation;
14
+ (function (AggregationInvocation) {
15
+ AggregationInvocation[AggregationInvocation["AGGREGATION_INVOCATION_UNSPECIFIED"] = 0] = "AGGREGATION_INVOCATION_UNSPECIFIED";
16
+ AggregationInvocation[AggregationInvocation["AGGREGATION_INVOCATION_ALL"] = 1] = "AGGREGATION_INVOCATION_ALL";
17
+ AggregationInvocation[AggregationInvocation["AGGREGATION_INVOCATION_DISTINCT"] = 2] = "AGGREGATION_INVOCATION_DISTINCT";
18
+ })(AggregationInvocation || (AggregationInvocation = {}));
19
+ var AggregationPhase;
20
+ (function (AggregationPhase) {
21
+ AggregationPhase[AggregationPhase["AGGREGATION_PHASE_UNSPECIFIED"] = 0] = "AGGREGATION_PHASE_UNSPECIFIED";
22
+ AggregationPhase[AggregationPhase["AGGREGATION_PHASE_INITIAL_TO_INTERMEDIATE"] = 1] = "AGGREGATION_PHASE_INITIAL_TO_INTERMEDIATE";
23
+ AggregationPhase[AggregationPhase["AGGREGATION_PHASE_INTERMEDIATE_TO_INTERMEDIATE"] = 2] = "AGGREGATION_PHASE_INTERMEDIATE_TO_INTERMEDIATE";
24
+ AggregationPhase[AggregationPhase["AGGREGATION_PHASE_INITIAL_TO_RESULT"] = 3] = "AGGREGATION_PHASE_INITIAL_TO_RESULT";
25
+ AggregationPhase[AggregationPhase["AGGREGATION_PHASE_INTERMEDIATE_TO_RESULT"] = 4] = "AGGREGATION_PHASE_INTERMEDIATE_TO_RESULT";
26
+ })(AggregationPhase || (AggregationPhase = {}));
27
+ var JoinType;
28
+ (function (JoinType) {
29
+ JoinType[JoinType["JOIN_TYPE_UNSPECIFIED"] = 0] = "JOIN_TYPE_UNSPECIFIED";
30
+ JoinType[JoinType["JOIN_TYPE_INNER"] = 1] = "JOIN_TYPE_INNER";
31
+ JoinType[JoinType["JOIN_TYPE_OUTER"] = 2] = "JOIN_TYPE_OUTER";
32
+ JoinType[JoinType["JOIN_TYPE_LEFT"] = 3] = "JOIN_TYPE_LEFT";
33
+ JoinType[JoinType["JOIN_TYPE_RIGHT"] = 4] = "JOIN_TYPE_RIGHT";
34
+ JoinType[JoinType["JOIN_TYPE_SEMI"] = 5] = "JOIN_TYPE_SEMI";
35
+ JoinType[JoinType["JOIN_TYPE_ANTI"] = 6] = "JOIN_TYPE_ANTI";
36
+ JoinType[JoinType["JOIN_TYPE_SINGLE"] = 7] = "JOIN_TYPE_SINGLE";
37
+ })(JoinType || (JoinType = {}));
38
+ var SetOp;
39
+ (function (SetOp) {
40
+ SetOp[SetOp["SET_OP_UNSPECIFIED"] = 0] = "SET_OP_UNSPECIFIED";
41
+ SetOp[SetOp["SET_OP_MINUS_PRIMARY"] = 1] = "SET_OP_MINUS_PRIMARY";
42
+ SetOp[SetOp["SET_OP_MINUS_MULTISET"] = 2] = "SET_OP_MINUS_MULTISET";
43
+ SetOp[SetOp["SET_OP_INTERSECTION_PRIMARY"] = 3] = "SET_OP_INTERSECTION_PRIMARY";
44
+ SetOp[SetOp["SET_OP_INTERSECTION_MULTISET"] = 4] = "SET_OP_INTERSECTION_MULTISET";
45
+ SetOp[SetOp["SET_OP_UNION_DISTINCT"] = 5] = "SET_OP_UNION_DISTINCT";
46
+ SetOp[SetOp["SET_OP_UNION_ALL"] = 6] = "SET_OP_UNION_ALL";
47
+ })(SetOp || (SetOp = {}));
48
+ var SortDirection;
49
+ (function (SortDirection) {
50
+ SortDirection[SortDirection["UNSPECIFIED"] = 0] = "UNSPECIFIED";
51
+ SortDirection[SortDirection["ASCENDING_NULLS_FIRST"] = 1] = "ASCENDING_NULLS_FIRST";
52
+ SortDirection[SortDirection["ASCENDING_NULLS_LAST"] = 2] = "ASCENDING_NULLS_LAST";
53
+ SortDirection[SortDirection["DESCENDING_NULLS_FIRST"] = 3] = "DESCENDING_NULLS_FIRST";
54
+ SortDirection[SortDirection["DESCENDING_NULLS_LAST"] = 4] = "DESCENDING_NULLS_LAST";
55
+ SortDirection[SortDirection["CLUSTERED"] = 5] = "CLUSTERED";
56
+ })(SortDirection || (SortDirection = {}));
57
+ class SubstraitParser {
58
+ idCounters;
59
+ extSet;
60
+ fieldNames = [];
61
+ selectedFields = [];
62
+ filters = [];
63
+ logicalOperators = [];
64
+ /**
65
+ * Constructs a SubstraitParser
66
+ * @param {SubstraitPlan} plan the Substrait plan
67
+ */
68
+ constructor(plan) {
69
+ this.idCounters = new Map();
70
+ this.extSet = this.buildExtensionSet(plan);
71
+ }
72
+ /**
73
+ * Creates a map from anchor to function name
74
+ * @param {SubstraitPlan} plan the Substrait plan
75
+ * @return {Map<number, string>} the created mapping
76
+ */
77
+ buildExtensionSet(plan) {
78
+ const extSet = new Map();
79
+ for (const extensionDecl of plan.extensions) {
80
+ const func = extensionDecl.extensionFunction;
81
+ extSet.set(func.functionAnchor, func.name.split(':')[0].toLowerCase());
82
+ }
83
+ return extSet;
84
+ }
85
+ /**
86
+ * Geneate a unique id for the node
87
+ * @param {string} type The type of the node
88
+ * @return {string} A unique id
89
+ */
90
+ nextId(type) {
91
+ const value = this.idCounters.get(type) ?? 0;
92
+ this.idCounters.set(type, value + 1);
93
+ return `${type}_${value}`;
94
+ }
95
+ /**
96
+ * Create a schema field
97
+ *
98
+ * This is a special field with an empty name and an empty type string
99
+ * and uknown nullability
100
+ *
101
+ * @param {Field[]} fields the fields of the schema
102
+ * @return {Field} a schema field
103
+ */
104
+ makeSchemaField(fields) {
105
+ return {
106
+ name: '',
107
+ children: fields,
108
+ type: '',
109
+ nullability: 'NULLABILITY_UNSPECIFIED'
110
+ };
111
+ }
112
+ /**
113
+ * Applies a Substrait emit to an output schema
114
+ * @param {Field} schema the original output schema
115
+ * @param {Object} emit a potential remapping of fields
116
+ * @return {Field} the remapped output schema
117
+ */
118
+ applyEmit(schema, emit) {
119
+ let outputFields = schema.children;
120
+ if ((emit?.outputMapping) != null) {
121
+ outputFields = emit.outputMapping.map((idx) => schema.children[idx]);
122
+ }
123
+ return this.makeSchemaField(outputFields);
124
+ }
125
+ /**
126
+ * Create a print node, generating a new id
127
+ *
128
+ * @param {string} type the node type
129
+ * @param {PrintNode[]} inputs the inputs to the node
130
+ * @param {SimpleProperty[]} props properties describing the node
131
+ * @param {Field} schema the output schema of the node
132
+ * @param {Object} emit the Substrait emit for the node
133
+ * @return {PrintNode} a print node
134
+ */
135
+ makePrintNode(type, inputs, props, schema, emit) {
136
+ const emitSchema = this.applyEmit(schema, emit);
137
+ return {
138
+ id: this.nextId(type),
139
+ type,
140
+ inputs,
141
+ props,
142
+ schema: emitSchema
143
+ };
144
+ }
145
+ /**
146
+ * Recursive helper for structFieldToStr
147
+ * @param {*} field the Substrait field to convert
148
+ * @param {*} currentName the current name
149
+ * @param {Field} currentField the current input field
150
+ * @return {Field} a stringified represenstation
151
+ */
152
+ structFieldHelper(field, currentName, currentField) {
153
+ const fieldNum = field.field;
154
+ const fieldName = (currentField.name !== '') ? currentField.name : `$${fieldNum}`;
155
+ const nextName = `${currentName}${fieldName}`;
156
+ if (field.child != null) {
157
+ return this.structFieldHelper(field.child, `${nextName}.`, currentField.children[fieldNum]);
158
+ }
159
+ return currentField.children[fieldNum];
160
+ }
161
+ /**
162
+ * Convert a struct field to a stringified representation
163
+ *
164
+ * Struct fields are usually intuitively written with names.
165
+ * For example, a.b.c. However, fields in Substrait plans
166
+ * are not typically named. So instead we represent them as
167
+ * $0, $1, $2, ... where $N means the field at index N.
168
+ *
169
+ * If the field does happen to be named we will use that.
170
+ *
171
+ * @param {StructItem} field a Substrait struct field
172
+ * @param {Field} exprIn the input to the expression
173
+ * @return {Field} a stringified representation
174
+ */
175
+ structFieldToField(field, exprIn) {
176
+ return this.structFieldHelper(field, '', exprIn);
177
+ }
178
+ /**
179
+ * Convert a direct reference to a stringified representation
180
+ * @param {Object} ref A Substrait direct reference
181
+ * @param {Object} exprIn the input to the expression
182
+ * @return {Field} a string representation
183
+ */
184
+ directReferenceToField(ref, exprIn) {
185
+ if (ref.structField != null) {
186
+ return this.structFieldToField(ref.structField, exprIn);
187
+ }
188
+ else {
189
+ throw new Error(`Unrecognized direct reference: ${JSON.stringify(ref)}`);
190
+ }
191
+ }
192
+ /**
193
+ * Convert a reference to a stringified representation
194
+ * @param {Object} ref A Substrait reference expression
195
+ * @param {Object} exprIn the input to the expression
196
+ * @return {Field} a string representation
197
+ */
198
+ referenceToField(ref, exprIn) {
199
+ if (ref.directReference != null) {
200
+ return this.directReferenceToField(ref.directReference, exprIn);
201
+ }
202
+ else {
203
+ throw new Error(`Unrecognized reference: ${JSON.stringify(ref)}`);
204
+ }
205
+ }
206
+ /**
207
+ * Convert a Substrait function argument to a string
208
+ * @param {Object} arg the argument to convert
209
+ * @param {Field} inp the input field
210
+ * @return {string} a string representation
211
+ */
212
+ functionArgumentToStr(arg, inp) {
213
+ if (arg.enum != null) {
214
+ if (arg.enum.specified == null) {
215
+ return 'unspecified';
216
+ }
217
+ return arg.enum.specified;
218
+ }
219
+ else if (arg.type != null) {
220
+ return this.typeToField(arg.type).type;
221
+ }
222
+ else if (arg.value != null) {
223
+ return this.expressionToStr(arg.value, inp).name;
224
+ }
225
+ else {
226
+ throw new Error('A FunctionArgument did not have an enum/type/value');
227
+ }
228
+ }
229
+ /**
230
+ * Converts a Substrait function reference to a string
231
+ * @param {number} ref a Substrait function reference
232
+ * @return {string} a string version of the reference
233
+ */
234
+ functionRefToName(ref) {
235
+ return this.extSet.get(ref) ?? 'unknown';
236
+ }
237
+ /**
238
+ * Convert arguments to a joined string
239
+ * @param {FunctionTyp} func A Substrait function call
240
+ * @param {Field} schema The input type
241
+ * @return {string} A string representation
242
+ */
243
+ argsToString(func, schema) {
244
+ const args = func.arguments.length > 0
245
+ ? func.arguments.map((arg) => this.functionArgumentToStr(arg, schema))
246
+ : [];
247
+ return args.join(',');
248
+ }
249
+ /**
250
+ * Convert a scalar function to a stringified representation
251
+ * @param {Object} func the function to convert
252
+ * @param {Field} schema the input type info
253
+ * @return {Field} a string version of the function
254
+ */
255
+ scalarFunctionToField(func, schema) {
256
+ const argsString = this.argsToString(func, schema);
257
+ const outputType = this.typeToField(func.outputType);
258
+ const functionName = this.functionRefToName(func.functionReference);
259
+ if (!['and', 'or', 'not', 'cast'].includes(functionName)) {
260
+ const args = argsString.split(',');
261
+ if (args.length === 1) {
262
+ this.filters.push(`${args[0]} ${functionName} `);
263
+ }
264
+ else if (args.length === 2) {
265
+ this.filters.push(`${args[0]} ${functionName} ${args[1]}`);
266
+ }
267
+ else {
268
+ this.filters.push(`${functionName}(${args.join(', ')})`);
269
+ }
270
+ }
271
+ else {
272
+ this.logicalOperators.push(functionName);
273
+ }
274
+ const fieldName = `${functionName}(${argsString})`;
275
+ outputType.name = fieldName;
276
+ return outputType;
277
+ }
278
+ /**
279
+ * Converts a Substrait literal to a field
280
+ * @param {Object} lit the Substrait literal
281
+ * @return {Field} a field representation
282
+ */
283
+ literalToField(lit) {
284
+ const nullability = lit.nullable ? 'NULLABILITY_NULLABLE' : 'NULLABILITY_REQUIRED';
285
+ if (lit.bool != null) {
286
+ return {
287
+ name: String(lit.bool.value),
288
+ type: 'boolean',
289
+ nullability,
290
+ children: []
291
+ };
292
+ }
293
+ else if (lit.date != null) {
294
+ return {
295
+ name: new Date((lit.date?.value ?? 0) * 8.64e7).toISOString(),
296
+ type: 'date',
297
+ nullability,
298
+ children: []
299
+ };
300
+ }
301
+ else if (lit.decimal != null) {
302
+ return {
303
+ name: String(this.base64ToDecimal(lit.decimal.value, lit.decimal.precision, lit.decimal.scale)),
304
+ type: 'decimal',
305
+ nullability,
306
+ children: []
307
+ };
308
+ }
309
+ else if (lit.i32 != null) {
310
+ return {
311
+ name: lit.i32?.value?.toString() ?? 'unspecified',
312
+ type: 'i32',
313
+ nullability,
314
+ children: []
315
+ };
316
+ }
317
+ else if (lit.intervalDayToSecond != null) {
318
+ const val = lit.intervalDayToSecond;
319
+ return {
320
+ name: `${val.days}d${val.seconds}s${val.microseconds}u`,
321
+ type: 'interval_day',
322
+ nullability,
323
+ children: []
324
+ };
325
+ }
326
+ else if (lit.fixedChar != null) {
327
+ const val = typeof lit.fixedChar === 'string' ? lit.fixedChar : lit.fixedChar.value ?? 'unspecified';
328
+ return {
329
+ name: `${val}`,
330
+ type: 'interval_day',
331
+ nullability,
332
+ children: []
333
+ };
334
+ }
335
+ else {
336
+ throw new Error(`Unrecognized literal: ${JSON.stringify(lit)}`);
337
+ }
338
+ }
339
+ /**
340
+ * Convert a cast expression to a stringified representation
341
+ * @param {Object} cast A Substrait cast expression
342
+ * @param {Field} schema The input schema
343
+ * @return {Field} A field representation
344
+ */
345
+ castToField(cast, schema) {
346
+ const input = this.expressionToStr(cast.input, schema);
347
+ const outputType = this.typeToField(cast.type);
348
+ let fb = 'unspecified';
349
+ if (cast.failureBehavior === 'FAILURE_BEHAVIOR_RETURN_NULL') {
350
+ fb = 'or null';
351
+ }
352
+ else if (cast.failureBehavior === 'THROW_EXCEPTION') {
353
+ fb = 'or die';
354
+ }
355
+ const name = `cast(${input.name}, ${outputType.type}, ${fb})`;
356
+ outputType.name = name;
357
+ return outputType;
358
+ }
359
+ /**
360
+ * Convert an expression to a stringified representation
361
+ *
362
+ * The expression is returned as a field where the type
363
+ * of the field is the output type of the expression and the
364
+ * name of the field is a string representation of the expression
365
+ *
366
+ * @param {Object} expr A Substrait expression
367
+ * @param {Object} exprIn the input to the expression
368
+ * @return {Field} a string representation
369
+ */
370
+ expressionToStr(expr, exprIn) {
371
+ if (expr.selection != null) {
372
+ return this.referenceToField(expr.selection, exprIn);
373
+ }
374
+ else if (expr.scalarFunction != null) {
375
+ return this.scalarFunctionToField(expr.scalarFunction, exprIn);
376
+ }
377
+ else if (expr.literal != null) {
378
+ return this.literalToField(expr.literal);
379
+ }
380
+ else if (expr.cast != null) {
381
+ return this.castToField(expr.cast, exprIn);
382
+ }
383
+ else {
384
+ throw new Error(`Unrecognized expression: ${JSON.stringify(expr)}`);
385
+ }
386
+ }
387
+ /**
388
+ * Convert a project relation to a print node
389
+ * @param {Object} project A Substrait ProjectRel
390
+ * @return {PrintNode} a print node
391
+ */
392
+ projectToNode(project) {
393
+ const input = this.relToNode(project.input);
394
+ const expressions = project.expressions.map((val, idx) => {
395
+ return {
396
+ name: `expressions[${idx}]`,
397
+ field: this.expressionToStr(val, input.schema)
398
+ };
399
+ });
400
+ const outFields = expressions.map((expr) => expr.field);
401
+ const fields = input.schema.children.concat(outFields);
402
+ const schema = this.makeSchemaField(fields);
403
+ const props = expressions.map((expr) => ({
404
+ name: expr.name,
405
+ value: expr.field.name
406
+ }));
407
+ const inputs = [this.relToNode(project.input)];
408
+ return this.makePrintNode('project', inputs, props, schema, project.common?.emit);
409
+ }
410
+ /**
411
+ * Convert a Substrait data type to an unnamed Field
412
+ *
413
+ * The field's name will be an empty string
414
+ *
415
+ * @param {Object} type a Substrait data type
416
+ * @return {Field} an unnamed field
417
+ */
418
+ typeToField(type) {
419
+ let typeStr = null;
420
+ let nullability = 'NULLABILITY_UNSPECIFIED';
421
+ if (type.varchar != null) {
422
+ typeStr = `VARCHAR<${type.varchar.length}>`;
423
+ nullability = type.varchar.nullability;
424
+ }
425
+ else if (type.fixedChar != null) {
426
+ typeStr = `FIXEDCHAR<${type.fixedChar.length}>`;
427
+ nullability = typeof type.fixedChar !== 'string' ? type.fixedChar?.nullability : 'NULLABILITY_REQUIRED';
428
+ }
429
+ else if (type.date != null) {
430
+ typeStr = 'date';
431
+ nullability = type.date.nullability;
432
+ }
433
+ else if (type.decimal != null) {
434
+ typeStr = `DECIMAL<${type.decimal.precision},${type.decimal.scale}>`;
435
+ nullability = type.decimal.nullability ?? 'NULLABILITY_UNSPECIFIED';
436
+ }
437
+ else if (type.i32 != null) {
438
+ typeStr = 'i32';
439
+ nullability = type.i32.nullability;
440
+ }
441
+ else if (type.i64 != null) {
442
+ typeStr = 'i64';
443
+ nullability = type.i64.nullability;
444
+ }
445
+ else if (type.bool != null) {
446
+ typeStr = 'boolean';
447
+ nullability = type.bool.nullability;
448
+ }
449
+ else if (type.string != null) {
450
+ typeStr = 'string';
451
+ nullability = type.string.nullability;
452
+ }
453
+ else if (type.fp64 != null) {
454
+ typeStr = 'fp64';
455
+ nullability = type.fp64.nullability;
456
+ }
457
+ else if (type.timestampTz != null) {
458
+ typeStr = 'timestampTz';
459
+ nullability = type.timestampTz.nullability;
460
+ }
461
+ else if (type.struct != null) {
462
+ typeStr = 'struct';
463
+ nullability = type.struct.nullability;
464
+ }
465
+ else if (type.fixedBinary != null) {
466
+ typeStr = 'fixedBinary';
467
+ nullability = type.fixedBinary.nullability;
468
+ }
469
+ else {
470
+ throw new Error(`Unrecognized type: ${JSON.stringify(type)}`);
471
+ }
472
+ return {
473
+ name: '',
474
+ type: typeStr,
475
+ nullability,
476
+ children: []
477
+ };
478
+ }
479
+ /**
480
+ * Convert a named struct to an array of Field
481
+ * @param {NamedStruct} struct a Substrait named struct
482
+ * @return {Field[]} named fields
483
+ */
484
+ namedStructToSchema(struct) {
485
+ // const names = struct.names
486
+ // const types = this.flattenTypes(struct.struct)
487
+ // console.log('names', names.length)
488
+ // console.log('types', types.length)
489
+ // if (names.length !== types.length) {
490
+ // throw new Error('Mismatched names and types')
491
+ // }
492
+ return {
493
+ name: 'test',
494
+ type: 'struct',
495
+ nullability: 'NULLABILITY_UNSPECIFIED',
496
+ children: []
497
+ };
498
+ // return this.makeSchemaField(outTypes)
499
+ }
500
+ // mapNames (input: NamedStruct, prefix: string = ''): string[] {
501
+ // const output: string[] = []
502
+ // for (let i = 0; i < input.names.length; i++) {
503
+ // const name = input.names[i]
504
+ // const type = input.struct.types[i]
505
+ // if (type.struct != null) {
506
+ // output.push(...this.mapNames({ name, types: type.struct.types }, `${prefix}${name}.`))
507
+ // } else {
508
+ // output.push(`${prefix}${name}`)
509
+ // }
510
+ // }
511
+ // return output
512
+ // }
513
+ /**
514
+ * Extract the properties from a read relation
515
+ * @param {Object} read a Substrait read relation
516
+ * @return {SimpleProperty[]} properties for the relation
517
+ */
518
+ readTypeToProps(read) {
519
+ return [{ name: 'namedTable.names', value: read.namedTable.names.join('.') }];
520
+ }
521
+ /**
522
+ * Convert a Substrait read relation to a print node
523
+ * @param {Object} read a Substrait read relation
524
+ * @return {PrintNode} a print node
525
+ */
526
+ readToNode(read) {
527
+ const schema = this.namedStructToSchema(read.baseSchema);
528
+ const props = this.readTypeToProps(read);
529
+ return this.makePrintNode('read', [], props, schema, read.common?.emit);
530
+ }
531
+ /**
532
+ * True if the object has a field with the given name
533
+ * @param {Object} obj the object to test
534
+ * @param {string} fieldName the field name to look for
535
+ * @return {boolean} the result of the test
536
+ */
537
+ hasValue(obj, fieldName) {
538
+ return fieldName in obj;
539
+ }
540
+ /**
541
+ * Convert a Substrait fetch relation to a print node
542
+ * @param {Object} fetch a Substrait fetch relation
543
+ * @return {PrintNode} a print node
544
+ */
545
+ fetchToNode(fetch) {
546
+ const input = this.relToNode(fetch.input);
547
+ const schema = input.schema;
548
+ const props = [];
549
+ if (this.hasValue(fetch, 'offset')) {
550
+ props.push({ name: 'offset', value: String(fetch.offset) });
551
+ }
552
+ if (this.hasValue(fetch, 'count')) {
553
+ props.push({ name: 'count', value: String(fetch.count) });
554
+ }
555
+ return this.makePrintNode('fetch', [input], props, schema, fetch.common.emit);
556
+ }
557
+ /**
558
+ * Convert a Substrait sort field to a property
559
+ * @param {Object} sortField a Substrait sort field
560
+ * @param {Field} schema the schema of the sort input
561
+ * @return {SimpleProperty} a property describing the sort
562
+ */
563
+ sortFieldToStr(sortField, schema) {
564
+ const exprStr = this.expressionToStr(sortField.expr, schema).name;
565
+ if (sortField.direction !== null) {
566
+ const dir = sortField.direction;
567
+ let sortDesc = '';
568
+ if (dir === SortDirection.ASCENDING_NULLS_FIRST) {
569
+ sortDesc = 'ascending (nulls first)';
570
+ }
571
+ else if (dir === SortDirection.ASCENDING_NULLS_LAST) {
572
+ sortDesc = 'ascending (nulls last)';
573
+ }
574
+ else if (dir === SortDirection.DESCENDING_NULLS_FIRST) {
575
+ sortDesc = 'descending (nulls first)';
576
+ }
577
+ else if (dir === SortDirection.DESCENDING_NULLS_LAST) {
578
+ sortDesc = 'descending (nulls last)';
579
+ }
580
+ else if (dir === SortDirection.CLUSTERED) {
581
+ sortDesc = 'clustered';
582
+ }
583
+ else {
584
+ sortDesc = 'unspecified';
585
+ }
586
+ return `${exprStr} | ${sortDesc}`;
587
+ }
588
+ }
589
+ /**
590
+ * Convert a Substrait sort relation to a print node
591
+ * @param {Object} sort a Substrait sort relation
592
+ * @return {PrintNode} a print node
593
+ */
594
+ sortToNode(sort) {
595
+ const input = this.relToNode(sort.input);
596
+ const schema = input.schema;
597
+ const props = sort.sorts.map((sort, idx) => {
598
+ return {
599
+ name: `sorts[${idx}]`,
600
+ value: this.sortFieldToStr(sort, schema) ?? 'undefined'
601
+ };
602
+ });
603
+ return this.makePrintNode('sort', [input], props, schema, sort.common.emit);
604
+ }
605
+ /**
606
+ * Convert a Substrait aggregate function to a field
607
+ * @param {Object} func the Substrait aggregate function
608
+ * @param {Field} inp the input field
609
+ * @return {Field} a field representation of the function
610
+ */
611
+ aggregateFunctionToField(func, inp) {
612
+ // TODO (weston) sorts, phases, invocation
613
+ return this.scalarFunctionToField(func, inp);
614
+ }
615
+ /**
616
+ * Convert a Substrait aggregate relation to a print node
617
+ * @param {Object} agg a Substrait aggregate relation
618
+ * @return {PrintNode} a print node
619
+ */
620
+ aggToNode(agg) {
621
+ const input = this.relToNode(agg.input);
622
+ const props = [];
623
+ const fields = [];
624
+ agg.groupings.forEach((grouping, idx) => {
625
+ for (const groupingExpr of grouping.groupingExpressions) {
626
+ const groupingField = this.expressionToStr(groupingExpr, input.schema);
627
+ props.push({ name: `grouping[${idx}]`, value: groupingField.name });
628
+ fields.push(groupingField);
629
+ }
630
+ });
631
+ agg.measures.forEach((measure, idx) => {
632
+ const aggregate = this.aggregateFunctionToField(measure.measure, input.schema);
633
+ fields.push(aggregate);
634
+ const innerProps = [
635
+ {
636
+ name: 'measure',
637
+ value: aggregate.name
638
+ }
639
+ ];
640
+ innerProps.push({
641
+ name: 'filter',
642
+ value: this.expressionToStr(measure.filter, input.schema).name
643
+ });
644
+ props.push({
645
+ name: `measures[${idx}]`,
646
+ value: JSON.stringify(innerProps) // TODO Is this right?
647
+ });
648
+ });
649
+ const schema = this.makeSchemaField(fields);
650
+ return this.makePrintNode('aggregate', [input], props, schema, agg.common.emit);
651
+ }
652
+ /**
653
+ * Convert a Substrait filter relation to a print node
654
+ * @param {Object} filt a Substrait filter relation
655
+ * @return {PrintNode} a print node
656
+ */
657
+ filterToNode(filt) {
658
+ const input = this.relToNode(filt.input);
659
+ const props = [];
660
+ const schema = input.schema;
661
+ props.push({
662
+ name: 'condition',
663
+ value: this.expressionToStr(filt.condition, schema).name
664
+ });
665
+ const printNode = this.makePrintNode('filter', [input], props, schema, filt.common.emit);
666
+ return printNode;
667
+ }
668
+ /**
669
+ * Converts a Substrait join relation to a print node
670
+ * @param {Object} join a Substrait join relation
671
+ * @return {PrintNode} a print node
672
+ */
673
+ joinToNode(join) {
674
+ const left = this.relToNode(join.left);
675
+ const right = this.relToNode(join.right);
676
+ const props = [];
677
+ const schema = this.makeSchemaField(left.schema.children.concat(right.schema.children));
678
+ let joinType = 'unspecified';
679
+ if (join.type !== null) {
680
+ joinType = JoinType[join.type];
681
+ }
682
+ props.push({ name: 'type', value: joinType });
683
+ if (join.expression !== null) {
684
+ const exprStr = this.expressionToStr(join.expression, schema).name;
685
+ props.push({ name: 'expression', value: exprStr });
686
+ }
687
+ return this.makePrintNode('join', [left, right], props, schema, join.common.emit);
688
+ }
689
+ /**
690
+ * Converts a Substrait relation to a print node
691
+ * @param {Object} rel the Substrait relation to convert
692
+ * @return {PrintNode} a print node
693
+ */
694
+ relToNode(rel) {
695
+ if (rel.project != null) {
696
+ return this.projectToNode(rel.project);
697
+ }
698
+ else if (rel.read != null) {
699
+ return this.readToNode(rel.read);
700
+ }
701
+ else if (rel.fetch != null) {
702
+ return this.fetchToNode(rel.fetch);
703
+ }
704
+ else if (rel.sort != null) {
705
+ return this.sortToNode(rel.sort);
706
+ }
707
+ else if (rel.aggregate != null) {
708
+ return this.aggToNode(rel.aggregate);
709
+ }
710
+ else if (rel.filter != null) {
711
+ return this.filterToNode(rel.filter);
712
+ }
713
+ else if (rel.join != null) {
714
+ return this.joinToNode(rel.join);
715
+ }
716
+ else {
717
+ throw new Error(`Unrecognized relation: ${JSON.stringify(rel)}`);
718
+ }
719
+ }
720
+ /**
721
+ * Converts a Substrait root relation to a print node
722
+ * @param {Object} rel the Substrait relation to convert
723
+ * @return {PrintNode} a print node
724
+ */
725
+ rootRelToNode(rel) {
726
+ const props = rel.names.map((val, idx) => ({
727
+ name: `name[${idx}]`,
728
+ value: val
729
+ }));
730
+ this.selectedFields = this.selectedFields.concat(rel.names);
731
+ const inputs = [this.relToNode(rel.input)];
732
+ const schema = this.makeSchemaField([]);
733
+ return this.makePrintNode('sink', inputs, props, schema);
734
+ }
735
+ /**
736
+ * Converts a Substrait plan to a print node
737
+ * @param {Object} plan the Substrait plan to convert
738
+ * @return {PrintNode} a print node
739
+ */
740
+ planToNode(plan) {
741
+ const nodes = [];
742
+ for (const relation of plan.relations) {
743
+ if (relation.root != null) {
744
+ nodes.push(this.rootRelToNode(relation.root));
745
+ }
746
+ else {
747
+ throw new Error(`Unrecognized plan relation ${JSON.stringify(relation)}`);
748
+ }
749
+ }
750
+ const schema = this.makeSchemaField([]);
751
+ return this.makePrintNode('plan', nodes, [], schema);
752
+ }
753
+ parse(plan) {
754
+ this.selectedFields = [];
755
+ this.planToNode(plan);
756
+ return {
757
+ selection: this.selectedFields,
758
+ filters: this.deduplicate(this.filters),
759
+ logicalOperators: this.deduplicate(this.logicalOperators)
760
+ };
761
+ }
762
+ /**
763
+ * Converts a base64 string into a decimal number.
764
+ *
765
+ * @public
766
+ * @param {string} base64 - The base64 string to convert.
767
+ * @param {number} precision - The total number of digits in the output number.
768
+ * @param {number} scale - The number of digits after the decimal point in the output number.
769
+ * @throws {Error} Will throw an error if the conversion fails.
770
+ * @returns {number} The converted decimal number.
771
+ * @example
772
+ * // returns 123.45
773
+ * this.base64ToDecimal('MTIzNDU=', 5, 2);
774
+ */
775
+ base64ToDecimal(base64, precision, scale) {
776
+ // Decode base64 string to a Buffer
777
+ const buffer = Buffer.from(base64, 'base64');
778
+ let value = BigInt(0);
779
+ for (let i = buffer.length - 1; i >= 0; i--) {
780
+ value = (value << BigInt(8)) + BigInt(buffer[i]);
781
+ }
782
+ return Number(value) / Math.pow(10, scale);
783
+ }
784
+ deduplicate(array) {
785
+ return Array.from(new Set(array));
786
+ }
787
+ }
788
+ export { SubstraitParser };