-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathtable.ts
899 lines (807 loc) · 28.4 KB
/
table.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
import { verifyObjectMatchesProto, VerifyProtoErrorBehaviour } from "df/common/protos";
import { ActionBuilder } from "df/core/actions";
import { Assertion } from "df/core/actions/assertion";
import { LegacyColumnDescriptors } from "df/core/column_descriptors";
import {
Contextable,
IActionConfig,
IColumnsDescriptor,
ICommonContext,
IDependenciesConfig,
IDocumentableConfig,
INamedConfig,
ITargetableConfig,
Resolvable
} from "df/core/common";
import * as Path from "df/core/path";
import { Session } from "df/core/session";
import {
actionConfigToCompiledGraphTarget,
addDependenciesToActionDependencyTargets,
checkExcessProperties,
nativeRequire,
resolvableAsTarget,
resolveActionsConfigFilename,
setNameAndTarget,
strictKeysOf,
tableTypeStringToEnum,
toResolvable,
validateQueryString
} from "df/core/utils";
import { dataform } from "df/protos/ts";
/**
* @hidden
*/
export const TableType = ["table", "view", "incremental"] as const;
/**
* Supported types of table actions.
*
* Tables of type `view` will be created as views.
*
* Tables of type `table` will be created as tables.
*
* Tables of type `incremental` must have a where clause provided. For more information, see the [incremental tables guide](guides/incremental-datasets).
*/
export type TableType = typeof TableType[number];
/**
* BigQuery-specific warehouse options.
*/
export interface IBigQueryOptions {
/**
* The key with which to partition the table. Typically the name of a timestamp or date column.
*
* For more information, read the [BigQuery partitioned tables docs](https://cloud.google.com/bigquery/docs/partitioned-tables).
*/
partitionBy?: string;
/**
* The keys by which to cluster partitions by.
*
* For more information, read the [BigQuery clustered tables docs](https://cloud.google.com/bigquery/docs/clustered-tables).
*/
clusterBy?: string[];
/**
* SQL based filter for when incremental updates are applied.
*
* For more information, see our [incremental dataset docs](https://docs.dataform.co/guides/incremental-datasets).
*/
updatePartitionFilter?: string;
/**
* Key-value pairs for [BigQuery labels](https://cloud.google.com/bigquery/docs/labels-intro).
*
* If the label name contains special characters, e.g. hyphens, then quote its name, e.g. labels: { "label-name": "value" }.
*/
labels?: { [name: string]: string };
/**
* This setting specifies how long BigQuery keeps the data in each partition. The setting applies to all partitions in the table,
* but is calculated independently for each partition based on the partition time.
*
* For more information, see our [docs](https://cloud.google.com/bigquery/docs/managing-partitioned-tables#partition-expiration).
*/
partitionExpirationDays?: number;
/**
* When you create a partitioned table, you can require that all queries on the table must include a predicate filter (
* a WHERE clause) that filters on the partitioning column.
* This setting can improve performance and reduce costs,
* because BigQuery can use the filter to prune partitions that don't match the predicate.
*
* For more information, see our [docs](https://cloud.google.com/bigquery/docs/managing-partitioned-tables#require-filter).
*/
requirePartitionFilter?: boolean;
/**
* Key-value pairs for options [table](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#table_option_list), [view](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#view_option_list), [materialized view](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#materialized_view_option_list).
*
* Some options (e.g. `partitionExpirationDays`) have dedicated type/validity checked fields; prefer using those.
* String values need double-quotes, e.g. additionalOptions: {numeric_option: "5", string_option: '"string-value"'}
* If the option name contains special characters, e.g. hyphens, then quote its name, e.g. additionalOptions: { "option-name": "value" }.
*/
additionalOptions?: { [name: string]: string };
}
const IBigQueryOptionsProperties = () =>
strictKeysOf<IBigQueryOptions>()([
"partitionBy",
"clusterBy",
"updatePartitionFilter",
"labels",
"partitionExpirationDays",
"requirePartitionFilter",
"additionalOptions"
]);
/**
* Options for creating assertions as part of a dataset definition.
*/
export interface ITableAssertions {
/**
* Column(s) which constitute the dataset's unique key index.
*
* If set, the resulting assertion will fail if there is more than one row in the dataset with the same values for all of these column(s).
*/
uniqueKey?: string | string[];
/**
* Combinations of column(s), each of which should constitute a unique key index for the dataset.
*
* If set, the resulting assertion(s) will fail if there is more than one row in the dataset with the same values for all of the column(s)
* in the unique key(s).
*/
uniqueKeys?: string[][];
/**
* Column(s) which may never be `NULL`.
*
* If set, the resulting assertion will fail if any row contains `NULL` values for these column(s).
*/
nonNull?: string | string[];
/**
* General condition(s) which should hold true for all rows in the dataset.
*
* If set, the resulting assertion will fail if any row violates any of these condition(s).
*/
rowConditions?: string[];
}
const ITableAssertionsProperties = () =>
strictKeysOf<ITableAssertions>()(["uniqueKey", "uniqueKeys", "nonNull", "rowConditions"]);
/**
* Configuration options for `dataset` actions, including `table`, `view` and `incremental` action types.
*/
export interface ITableConfig
extends IActionConfig,
IDependenciesConfig,
IDocumentableConfig,
INamedConfig,
ITargetableConfig {
/**
* The type of the dataset. For more information on how this setting works, check out some of the [guides](guides)
* on publishing different types of datasets with Dataform.
*/
type?: TableType;
/**
* Only allowed when the table type is `incremental`.
*
* If set to true, running this action will ignore the full-refresh option.
* This is useful for tables which are built from transient data, to ensure that historical data is never lost.
*/
protected?: boolean;
/**
* BigQuery-specific warehouse options.
*/
bigquery?: IBigQueryOptions;
/**
* Assertions to be run on the dataset.
*
* If configured, relevant assertions will automatically be created and run as a dependency of this dataset.
*/
assertions?: ITableAssertions;
/**
* Unique keys for merge criteria for incremental tables.
*
* If configured, records with matching unique key(s) will be updated, rather than new rows being inserted.
*/
uniqueKey?: string[];
/**
* Only valid when the table type is `view`.
*
* If set to true, will make the view materialized.
*
* For more information, read the [BigQuery materialized view docs](https://cloud.google.com/bigquery/docs/materialized-views-intro).
*/
materialized?: boolean;
}
// TODO: This needs to be a method, I'm really not sure why, but it hits a runtime failure otherwise.
export const ITableConfigProperties = () =>
strictKeysOf<ITableConfig>()([
"type",
"disabled",
"protected",
"name",
"bigquery",
"tags",
"uniqueKey",
"dependencies",
"hermetic",
"schema",
"assertions",
"database",
"columns",
"description",
"materialized",
"dependOnDependencyAssertions"
]);
/**
* Context methods are available when evaluating contextable SQL code, such as
* within SQLX files, or when using a [Contextable](#Contextable) argument with the JS API.
*/
export interface ITableContext extends ICommonContext {
/**
* Shorthand for an `if` condition. Equivalent to `cond ? trueCase : falseCase`.
* `falseCase` is optional, and defaults to an empty string.
*/
when: (cond: boolean, trueCase: string, falseCase?: string) => string;
/**
* Indicates whether the config indicates the file is dealing with an incremental table.
*/
incremental: () => boolean;
}
/**
* @hidden
*/
export class Table extends ActionBuilder<dataform.Table> {
// TODO(ekrekr): make this field private, to enforce proto update logic to happen in this class.
public proto: dataform.ITable = dataform.Table.create({
type: "view",
enumType: dataform.TableType.VIEW,
disabled: false,
tags: []
});
// Hold a reference to the Session instance.
public session: Session;
// If true, adds the inline assertions of dependencies as direct dependencies for this action.
public dependOnDependencyAssertions: boolean = false;
// We delay contextification until the final compile step, so hold these here for now.
public contextableQuery: Contextable<ITableContext, string>;
private contextableWhere: Contextable<ITableContext, string>;
private contextablePreOps: Array<Contextable<ITableContext, string | string[]>> = [];
private contextablePostOps: Array<Contextable<ITableContext, string | string[]>> = [];
private uniqueKeyAssertions: Assertion[] = [];
private rowConditionsAssertion: Assertion;
constructor(
session?: Session,
tableTypeConfig?:
| dataform.ActionConfig.TableConfig
| dataform.ActionConfig.ViewConfig
| dataform.ActionConfig.IncrementalTableConfig,
// TODO(ekrekr): As part of JS API updates, instead of overloading, add new class files for the
// view and incremental action types, instead of using this table type workaround.
tableType?: TableType,
configPath?: string
) {
super(session);
this.session = session;
if (!tableTypeConfig) {
return;
}
if (!tableType) {
throw Error("Expected table type");
}
if (!tableTypeConfig.name) {
tableTypeConfig.name = Path.basename(tableTypeConfig.filename);
}
const target = actionConfigToCompiledGraphTarget(tableTypeConfig);
this.proto.target = this.applySessionToTarget(
target,
session.projectConfig,
tableTypeConfig.filename,
true
);
this.proto.canonicalTarget = this.applySessionToTarget(target, session.canonicalProjectConfig);
tableTypeConfig.filename = resolveActionsConfigFilename(tableTypeConfig.filename, configPath);
this.proto.fileName = tableTypeConfig.filename;
// TODO(ekrekr): load config proto column descriptors.
if (tableType === "table") {
const config = tableTypeConfig as dataform.ActionConfig.TableConfig;
// TODO(ekrekr): this is a workaround for avoiding keys that aren't present, and should be
// cleaned up when the JS API is redone.
const bigqueryOptions: IBigQueryOptions | undefined =
config.partitionBy ||
config.partitionExpirationDays ||
config.requirePartitionFilter ||
config.clusterBy.length ||
Object.keys(config.labels).length ||
Object.keys(config.additionalOptions).length
? {}
: undefined;
if (bigqueryOptions) {
if (config.partitionBy) {
bigqueryOptions.partitionBy = config.partitionBy;
}
if (config.partitionExpirationDays) {
bigqueryOptions.partitionExpirationDays = config.partitionExpirationDays;
}
if (config.requirePartitionFilter) {
bigqueryOptions.requirePartitionFilter = config.requirePartitionFilter;
}
if (config.clusterBy.length) {
bigqueryOptions.clusterBy = config.clusterBy;
}
if (Object.keys(config.labels).length) {
bigqueryOptions.labels = config.labels;
}
if (Object.keys(config.additionalOptions).length) {
bigqueryOptions.additionalOptions = config.additionalOptions;
}
}
this.config({
type: "table",
dependencies: config.dependencyTargets.map(dependencyTarget =>
actionConfigToCompiledGraphTarget(dataform.ActionConfig.Target.create(dependencyTarget))
),
tags: config.tags,
disabled: config.disabled,
description: config.description,
bigquery: bigqueryOptions,
dependOnDependencyAssertions: config.dependOnDependencyAssertions,
hermetic: config.hermetic === true ? true : undefined,
assertions: this.legacyMapConfigAssertions(config.assertions)
});
}
if (tableType === "view") {
const config = tableTypeConfig as dataform.ActionConfig.ViewConfig;
// TODO(ekrekr): this is a workaround for avoiding keys that aren't present, and should be
// cleaned up when the JS API is redone.
const bigqueryOptions: IBigQueryOptions | undefined =
Object.keys(config.labels).length || Object.keys(config.additionalOptions).length
? {}
: undefined;
if (bigqueryOptions) {
if (Object.keys(config.labels).length) {
bigqueryOptions.labels = config.labels;
}
if (Object.keys(config.additionalOptions).length) {
bigqueryOptions.additionalOptions = config.additionalOptions;
}
}
this.config({
type: "view",
dependencies: config.dependencyTargets.map(dependencyTarget =>
actionConfigToCompiledGraphTarget(dataform.ActionConfig.Target.create(dependencyTarget))
),
disabled: config.disabled,
materialized: config.materialized,
tags: config.tags,
description: config.description,
bigquery: bigqueryOptions,
dependOnDependencyAssertions: config.dependOnDependencyAssertions,
hermetic: config.hermetic === true ? true : undefined,
assertions: this.legacyMapConfigAssertions(config.assertions)
});
}
if (tableType === "incremental") {
const config = tableTypeConfig as dataform.ActionConfig.IncrementalTableConfig;
// TODO(ekrekr): this is a workaround for avoiding keys that aren't present, and should be
// cleaned up when the JS API is redone.
const bigqueryOptions: IBigQueryOptions | undefined =
config.partitionBy ||
config.partitionExpirationDays ||
config.requirePartitionFilter ||
config.updatePartitionFilter ||
config.clusterBy.length ||
Object.keys(config.labels).length ||
Object.keys(config.additionalOptions).length
? {}
: undefined;
if (bigqueryOptions) {
if (config.partitionBy) {
bigqueryOptions.partitionBy = config.partitionBy;
}
if (config.partitionExpirationDays) {
bigqueryOptions.partitionExpirationDays = config.partitionExpirationDays;
}
if (config.requirePartitionFilter) {
bigqueryOptions.requirePartitionFilter = config.requirePartitionFilter;
}
if (config.updatePartitionFilter) {
bigqueryOptions.updatePartitionFilter = config.updatePartitionFilter;
}
if (config.clusterBy.length) {
bigqueryOptions.clusterBy = config.clusterBy;
}
if (Object.keys(config.labels).length) {
bigqueryOptions.labels = config.labels;
}
if (Object.keys(config.additionalOptions).length) {
bigqueryOptions.additionalOptions = config.additionalOptions;
}
}
this.config({
type: "incremental",
dependencies: config.dependencyTargets.map(dependencyTarget =>
actionConfigToCompiledGraphTarget(dataform.ActionConfig.Target.create(dependencyTarget))
),
disabled: config.disabled,
protected: config.protected,
uniqueKey: config.uniqueKey,
tags: config.tags,
description: config.description,
bigquery: bigqueryOptions,
dependOnDependencyAssertions: config.dependOnDependencyAssertions,
hermetic: config.hermetic === true ? true : undefined,
assertions: this.legacyMapConfigAssertions(config.assertions)
});
}
this.query(nativeRequire(tableTypeConfig.filename).query);
if (tableTypeConfig.preOperations) {
this.preOps(tableTypeConfig.preOperations);
}
if (tableTypeConfig.postOperations) {
this.postOps(tableTypeConfig.postOperations);
}
}
public config(config: ITableConfig) {
checkExcessProperties(
(e: Error) => this.session.compileError(e),
config,
ITableConfigProperties(),
"table config"
);
if (config.type) {
this.type(config.type);
}
if (config.dependOnDependencyAssertions) {
this.setDependOnDependencyAssertions(config.dependOnDependencyAssertions);
}
if (config.dependencies) {
this.dependencies(config.dependencies);
}
if (config.hermetic !== undefined) {
this.hermetic(config.hermetic);
}
if (config.disabled) {
this.disabled();
}
if (config.type === "incremental") {
this.protected(config.protected);
}
if (config.bigquery && Object.keys(config.bigquery).length > 0) {
this.bigquery(config.bigquery);
}
if (config.tags) {
this.tags(config.tags);
}
if (config.description) {
this.description(config.description);
}
if (config.columns) {
this.columns(config.columns);
}
if (config.database) {
this.database(config.database);
}
if (config.schema) {
this.schema(config.schema);
}
if (config.assertions) {
this.assertions(config.assertions);
}
if (config.uniqueKey) {
this.uniqueKey(config.uniqueKey);
}
if (config.materialized) {
this.materialized(config.materialized);
}
return this;
}
public type(type: TableType) {
this.proto.type = type;
this.proto.enumType = tableTypeStringToEnum(type, false);
return this;
}
public query(query: Contextable<ITableContext, string>) {
this.contextableQuery = query;
return this;
}
public where(where: Contextable<ITableContext, string>) {
this.contextableWhere = where;
return this;
}
public preOps(pres: Contextable<ITableContext, string | string[]>) {
this.contextablePreOps.push(pres);
return this;
}
public postOps(posts: Contextable<ITableContext, string | string[]>) {
this.contextablePostOps.push(posts);
return this;
}
public disabled(disabled = true) {
this.proto.disabled = disabled;
this.uniqueKeyAssertions.forEach(assertion => assertion.disabled(disabled));
this.rowConditionsAssertion?.disabled(disabled);
return this;
}
public protected(defaultsToTrueProtected: boolean) {
// To prevent accidental data deletion, protected defaults to true if unspecified.
if (defaultsToTrueProtected === undefined || defaultsToTrueProtected === null) {
defaultsToTrueProtected = true;
}
this.proto.protected = defaultsToTrueProtected;
return this;
}
public uniqueKey(uniqueKey: string[]) {
this.proto.uniqueKey = uniqueKey;
}
public materialized(materialized: boolean) {
this.proto.materialized = materialized;
}
public bigquery(bigquery: dataform.IBigQueryOptions) {
checkExcessProperties(
(e: Error) => this.session.compileError(e),
bigquery,
IBigQueryOptionsProperties(),
"bigquery config"
);
this.proto.bigquery = dataform.BigQueryOptions.create(bigquery);
if (!!bigquery.labels) {
if (!this.proto.actionDescriptor) {
this.proto.actionDescriptor = {};
}
this.proto.actionDescriptor.bigqueryLabels = bigquery.labels;
}
return this;
}
public dependencies(value: Resolvable | Resolvable[]) {
const newDependencies = Array.isArray(value) ? value : [value];
newDependencies.forEach(resolvable =>
addDependenciesToActionDependencyTargets(this, resolvable)
);
return this;
}
public hermetic(hermetic: boolean) {
this.proto.hermeticity = hermetic
? dataform.ActionHermeticity.HERMETIC
: dataform.ActionHermeticity.NON_HERMETIC;
}
public tags(value: string | string[]) {
const newTags = typeof value === "string" ? [value] : value;
newTags.forEach(t => {
this.proto.tags.push(t);
});
this.uniqueKeyAssertions.forEach(assertion => assertion.tags(value));
this.rowConditionsAssertion?.tags(value);
return this;
}
public description(description: string) {
if (!this.proto.actionDescriptor) {
this.proto.actionDescriptor = {};
}
this.proto.actionDescriptor.description = description;
return this;
}
public columns(columns: IColumnsDescriptor) {
if (!this.proto.actionDescriptor) {
this.proto.actionDescriptor = {};
}
this.proto.actionDescriptor.columns = LegacyColumnDescriptors.mapToColumnProtoArray(
columns,
(e: Error) => this.session.compileError(e)
);
return this;
}
public database(database: string) {
setNameAndTarget(
this.session,
this.proto,
this.proto.target.name,
this.proto.target.schema,
database
);
return this;
}
public schema(schema: string) {
setNameAndTarget(
this.session,
this.proto,
this.proto.target.name,
schema,
this.proto.target.database
);
return this;
}
// TODO(ekrekr): update session JS assertions to action construtors instead.
public assertions(assertions: ITableAssertions) {
checkExcessProperties(
(e: Error) => this.session.compileError(e),
assertions,
ITableAssertionsProperties(),
"assertions config"
);
if (!!assertions.uniqueKey && !!assertions.uniqueKeys) {
this.session.compileError(
new Error("Specify at most one of 'assertions.uniqueKey' and 'assertions.uniqueKeys'.")
);
}
let uniqueKeys = assertions.uniqueKeys;
if (!!assertions.uniqueKey) {
uniqueKeys =
typeof assertions.uniqueKey === "string"
? [[assertions.uniqueKey]]
: [assertions.uniqueKey];
}
if (uniqueKeys) {
uniqueKeys.forEach((uniqueKey, index) => {
const uniqueKeyAssertion = this.session.assert(
`${this.proto.target.schema}_${this.proto.target.name}_assertions_uniqueKey_${index}`,
ctx => this.session.compilationSql().indexAssertion(ctx.ref(this.proto.target), uniqueKey)
);
if (this.proto.tags) {
uniqueKeyAssertion.tags(this.proto.tags);
}
uniqueKeyAssertion.proto.parentAction = this.proto.target;
if (this.proto.disabled) {
uniqueKeyAssertion.disabled();
}
this.uniqueKeyAssertions.push(uniqueKeyAssertion);
});
}
const mergedRowConditions = assertions.rowConditions || [];
if (!!assertions.nonNull) {
const nonNullCols =
typeof assertions.nonNull === "string" ? [assertions.nonNull] : assertions.nonNull;
nonNullCols.forEach(nonNullCol => mergedRowConditions.push(`${nonNullCol} IS NOT NULL`));
}
if (!!mergedRowConditions && mergedRowConditions.length > 0) {
this.rowConditionsAssertion = this.session.assert(
`${this.proto.target.schema}_${this.proto.target.name}_assertions_rowConditions`,
ctx =>
this.session
.compilationSql()
.rowConditionsAssertion(ctx.ref(this.proto.target), mergedRowConditions)
);
this.rowConditionsAssertion.proto.parentAction = this.proto.target;
if (this.proto.disabled) {
this.rowConditionsAssertion.disabled();
}
if (this.proto.tags) {
this.rowConditionsAssertion.tags(this.proto.tags);
}
}
return this;
}
public setDependOnDependencyAssertions(dependOnDependencyAssertions: boolean) {
this.dependOnDependencyAssertions = dependOnDependencyAssertions;
return this;
}
/**
* @hidden
*/
public getFileName() {
return this.proto.fileName;
}
/**
* @hidden
*/
public getTarget() {
return dataform.Target.create(this.proto.target);
}
public compile() {
const context = new TableContext(this);
const incrementalContext = new TableContext(this, true);
this.proto.query = context.apply(this.contextableQuery);
if (this.proto.enumType === dataform.TableType.INCREMENTAL) {
this.proto.incrementalQuery = incrementalContext.apply(this.contextableQuery);
this.proto.incrementalPreOps = this.contextifyOps(this.contextablePreOps, incrementalContext);
this.proto.incrementalPostOps = this.contextifyOps(
this.contextablePostOps,
incrementalContext
);
}
if (this.contextableWhere) {
this.proto.where = context.apply(this.contextableWhere);
}
this.proto.preOps = this.contextifyOps(this.contextablePreOps, context).filter(
op => !!op.trim()
);
this.proto.postOps = this.contextifyOps(this.contextablePostOps, context).filter(
op => !!op.trim()
);
validateQueryString(this.session, this.proto.query, this.proto.fileName);
validateQueryString(this.session, this.proto.incrementalQuery, this.proto.fileName);
return verifyObjectMatchesProto(
dataform.Table,
this.proto,
VerifyProtoErrorBehaviour.SUGGEST_REPORTING_TO_DATAFORM_TEAM
);
}
private contextifyOps(
contextableOps: Array<Contextable<ITableContext, string | string[]>>,
currentContext: TableContext
) {
let protoOps: string[] = [];
contextableOps.forEach(contextableOp => {
const appliedOps = currentContext.apply(contextableOp);
protoOps = protoOps.concat(typeof appliedOps === "string" ? [appliedOps] : appliedOps);
});
return protoOps;
}
private legacyMapConfigAssertions(
configAssertions: dataform.ActionConfig.ITableAssertionsConfig
): ITableAssertions | undefined {
let legacyAssertions: ITableAssertions | undefined;
if (configAssertions) {
legacyAssertions = {};
if (configAssertions.uniqueKey?.length > 0) {
legacyAssertions.uniqueKey = configAssertions.uniqueKey;
}
if (configAssertions.uniqueKeys) {
legacyAssertions.uniqueKeys = configAssertions.uniqueKeys.map(
uniqueKeys => uniqueKeys?.uniqueKey
);
}
if (configAssertions.nonNull?.length > 0) {
legacyAssertions.nonNull = configAssertions.nonNull;
}
if (configAssertions.rowConditions?.length > 0) {
legacyAssertions.rowConditions = configAssertions.rowConditions;
}
}
return legacyAssertions;
}
}
/**
* @hidden
*/
export class TableContext implements ITableContext {
constructor(private table: Table, private isIncremental = false) {}
public config(config: ITableConfig) {
this.table.config(config);
return "";
}
public self(): string {
return this.resolve(this.table.proto.target);
}
public name(): string {
return this.table.session.finalizeName(this.table.proto.target.name);
}
public ref(ref: Resolvable | string[], ...rest: string[]): string {
ref = toResolvable(ref, rest);
if (!resolvableAsTarget(ref)) {
this.table.session.compileError(new Error(`Action name is not specified`));
return "";
}
this.table.dependencies(ref);
return this.resolve(ref);
}
public resolve(ref: Resolvable | string[], ...rest: string[]) {
return this.table.session.resolve(ref, ...rest);
}
public schema(): string {
return this.table.session.finalizeSchema(this.table.proto.target.schema);
}
public database(): string {
if (!this.table.proto.target.database) {
this.table.session.compileError(new Error(`Warehouse does not support multiple databases`));
return "";
}
return this.table.session.finalizeDatabase(this.table.proto.target.database);
}
public type(type: TableType) {
this.table.type(type);
return "";
}
public where(where: Contextable<ITableContext, string>) {
this.table.where(where);
return "";
}
public when(cond: boolean, trueCase: string, falseCase: string = "") {
return cond ? trueCase : falseCase;
}
public incremental() {
return !!this.isIncremental;
}
public preOps(statement: Contextable<ITableContext, string | string[]>) {
this.table.preOps(statement);
return "";
}
public postOps(statement: Contextable<ITableContext, string | string[]>) {
this.table.postOps(statement);
return "";
}
public disabled() {
this.table.disabled();
return "";
}
public bigquery(bigquery: dataform.IBigQueryOptions) {
this.table.bigquery(bigquery);
return "";
}
public dependencies(res: Resolvable) {
this.table.dependencies(res);
return "";
}
public apply<T>(value: Contextable<ITableContext, T>): T {
if (typeof value === "function") {
return (value as any)(this);
} else {
return value;
}
}
public tags(tags: string[]) {
this.table.tags(tags);
return "";
}
}