-
Notifications
You must be signed in to change notification settings - Fork 2
/
compiler.go
1543 lines (1269 loc) · 42.5 KB
/
compiler.go
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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package analyst
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"github.com/michaelbironneau/analyst/aql"
"github.com/michaelbironneau/analyst/engine"
"github.com/michaelbironneau/analyst/plugins"
builtins "github.com/michaelbironneau/analyst/transforms"
"strings"
"time"
"reflect"
)
const (
sourceUniquifier = " > "
destinationUniquifier = " > "
globalDbDriver = "sqlite3"
globalDbConnString = "file::memory:?mode=memory&cache=shared&_busy_timeout=5000"
sqlSelectAll = "SELECT * FROM %s"
)
type RuntimeOptions struct {
Options []aql.Option
Logger engine.Logger
Hooks []interface{}
Context context.Context
ScriptDirectory string
}
// neutralizeExecs is a source hook to prevent side effects with execs whilst in test mode
func neutralizeExecs(name string, src engine.Source) (engine.Source, error) {
if s, ok := src.(*engine.SQLSource); ok && s.ExecOnly {
s.Query = "SELECT 1"
}
return nil, nil
}
// neutralizeDestination replaces a given destination by a DevNull destination
func neutralizeDestinations(name string, dest engine.Destination) (engine.Destination, error) {
val := reflect.ValueOf(dest).Elem().FieldByName("Alias")
if val.Kind() == reflect.String && val.String() != "" {
return &engine.DevNull{Name: val.String()}, nil
}
val = reflect.ValueOf(dest).Elem().FieldByName("Name")
if val.Kind() == reflect.String && val.String() != "" {
return &engine.DevNull{Name: val.String()}, nil
}
return &engine.DevNull{Name: name}, nil
}
func formatOptions(options []aql.Option) string {
var s []string
for _, opt := range options {
var ss string
ss = opt.Key + " -> "
if opt.Value.Str != nil {
ss += *opt.Value.Str
} else {
ss += fmt.Sprintf("%7.2f", *opt.Value.Number)
}
s = append(s, ss)
}
return fmt.Sprintf("%v", s)
}
func checkWrapLogger(l engine.Logger, options []aql.Option) (engine.Logger, error) {
if _, ok := aql.FindOption(options, "SLACK_WEBHOOK_URL"); !ok {
return nil, nil
}
opts := engine.SlackOpts{}
scan := aql.OptionScanner("", "", options)
maybeScan := aql.MaybeOptionScanner("", "", options)
err := aql.ScanOptions(scan, maybeScan, &opts)
if err != nil {
return nil, err
}
if _, ok := engine.StrToLevel(opts.MinLevel); !ok {
return nil, fmt.Errorf("invalid log level for Slack hook %s", opts.MinLevel)
}
return engine.SlackWrapper(l, opts), nil
}
func execute(js *aql.JobScript, options []aql.Option, lg engine.Logger, compileOnly bool, hooks []interface{}, ctx context.Context, cwd string, runTests bool) error {
logger := lg
options = mergeOptions(js, options)
if !compileOnly {
l, err := checkWrapLogger(logger, options)
if err != nil {
return err
}
if l != nil {
logger = l
logger.Chan() <- engine.Event{
Source: "Compiler",
Level: engine.Info,
Time: time.Now(),
Message: "Logger re-configured to send specified output to Slack",
}
}
}
logger.Chan() <- engine.Event{
Source: "Compiler",
Level: engine.Trace,
Time: time.Now(),
Message: fmt.Sprintf("Found globals %s", formatOptions(options)),
}
params := engine.NewParameterTable()
err := js.EvaluateParametrizedExtern(options)
if err != nil {
return fmt.Errorf("error evaluating parametrized external sources: %v", err)
}
err = js.ResolveExternalContent(cwd)
if err != nil {
return fmt.Errorf("error resolving external content: %v", err)
}
err = js.EvaluateParametrizedContent(options)
if err != nil {
return fmt.Errorf("error evaluating parametrized content: %v", err)
}
connMap, err := connectionMap(js)
if err != nil {
return fmt.Errorf("error parsing connections: %v", err)
}
txManager, err := txManager(logger, connMap)
if err != nil {
return fmt.Errorf("error startin transaction manager: %v", err)
}
dag := engine.NewCoordinator(logger, txManager)
dag.UseContext(ctx)
dag.RegisterHooks(hooks...)
err = declarations(js, params)
if err != nil {
return err
}
if !compileOnly {
err = globalInit(js)
if err != nil {
return err
}
}
err = sources(js, dag, connMap, params, options, txManager)
if err != nil {
return err
}
err = transforms(js, dag, connMap, options, txManager)
if err != nil {
return err
}
err = destinations(js, dag, connMap, params, options, txManager)
if err != nil {
return err
}
if runTests {
//Only run tests in test mode - in production mode they could slow things down too much
err = tests(js, dag)
if err != nil {
return err
}
}
err = constraints(js, dag, connMap)
if err != nil {
return err
}
err = terminateExecs(js, dag)
if err != nil {
return err
}
err = dag.Compile()
if err != nil {
return err
}
if compileOnly {
return nil
}
return dag.Execute()
}
func txManager(l engine.Logger, connMap map[string]*aql.Connection) (engine.TransactionManager, error) {
tm := engine.NewTransactionManager(l)
for _, conn := range connMap {
if strings.ToLower(conn.Driver) == "excel" || strings.ToLower(conn.Driver) == "http" {
//these don't support transactions
continue
}
if err := tm.Register(*conn); err != nil {
return nil, err
}
}
return tm, nil
}
//mergeOptions merges the CLI options and the global options in the job script.
//The options in the job script override the CLI options with the same name.
func mergeOptions(js *aql.JobScript, options []aql.Option) []aql.Option {
if js.GlobalOptions == nil {
return options
}
opts := make(map[string]bool)
for _, opt := range js.GlobalOptions {
opts[strings.ToLower(opt.Key)] = true
}
var ret []aql.Option
for _, opt := range options {
if opts[strings.ToLower(opt.Key)] {
continue //override the CLI option with the global one
}
ret = append(ret, opt)
}
for _, opt := range js.GlobalOptions {
var thisOpt aql.Option
thisOpt.Key = opt.Key
thisOpt.Value = opt.Value
ret = append(ret, thisOpt)
}
return ret
}
func ExecuteString(script string, opts *RuntimeOptions) error {
if opts.Logger == nil {
opts.Logger = engine.NewConsoleLogger(engine.Trace)
}
js, err := aql.ParseString(script)
if err != nil {
return err
}
return execute(js, opts.Options, opts.Logger, false, opts.Hooks, opts.Context, opts.ScriptDirectory, false)
}
func TestString(script string, opts *RuntimeOptions) error {
if opts.Logger == nil {
opts.Logger = engine.NewConsoleLogger(engine.Trace)
}
js, err := aql.ParseString(script)
if err != nil {
return err
}
hooks := append(opts.Hooks, engine.DestinationHook(neutralizeDestinations), engine.SourceHook(neutralizeExecs))
return execute(js, opts.Options, opts.Logger, false, hooks, opts.Context, opts.ScriptDirectory, true)
}
func TestFile(filename string, opts *RuntimeOptions) error {
if opts.Logger == nil {
opts.Logger = engine.NewConsoleLogger(engine.Trace)
}
js, err := aql.ParseFile(filename)
if err != nil {
return err
}
hooks := append(opts.Hooks, engine.DestinationHook(neutralizeDestinations), engine.SourceHook(neutralizeExecs))
return execute(js, opts.Options, opts.Logger, false, hooks, opts.Context, opts.ScriptDirectory, true)
}
func ExecuteFile(filename string, opts *RuntimeOptions) error {
if opts.Logger == nil {
opts.Logger = engine.NewConsoleLogger(engine.Trace)
}
js, err := aql.ParseFile(filename)
if err != nil {
return err
}
return execute(js, opts.Options, opts.Logger, false, opts.Hooks, opts.Context, opts.ScriptDirectory, false)
}
func ValidateString(script string, opts *RuntimeOptions) error {
if opts.Logger == nil {
opts.Logger = engine.NewConsoleLogger(engine.Error)
}
js, err := aql.ParseString(script)
if err != nil {
return err
}
return execute(js, opts.Options, opts.Logger, true, opts.Hooks, opts.Context, opts.ScriptDirectory, false)
}
func ValidateFile(filename string, opts *RuntimeOptions) error {
if opts.Logger == nil {
opts.Logger = &engine.ConsoleLogger{}
}
js, err := aql.ParseFile(filename)
if err != nil {
return err
}
return execute(js, opts.Options, opts.Logger, true, opts.Hooks, opts.Context, opts.ScriptDirectory, false)
}
func declarations(js *aql.JobScript, p *engine.ParameterTable) error {
for _, declaration := range js.Declarations {
if err := p.Declare(declaration.Name); err != nil {
return err
}
}
return nil
}
//globalInit initializes the GLOBAL db based on user-defined queries
//Any valid SQL can be used to initialize the database.
//Currently, the GLOBAL database must live in-memory. In future releases
//the SET [OPTION_NAME] [OPTION_VALUE] syntax will be available to configure this.
func globalInit(js *aql.JobScript) error {
db, err := sql.Open(globalDbDriver, globalDbConnString)
if err != nil {
return err
}
for _, block := range js.Globals {
_, err := db.Exec(block.Content)
if err != nil {
return fmt.Errorf("error initializing GLOBAL with block %s: %v", block.Name, err)
}
}
return nil
}
//terminateExecs adds a DevNull destination after the source to terminate the flow.
//It should be invoked AFTER sources() so that the exec nodes are created first.
func terminateExecs(js *aql.JobScript, dag engine.Coordinator) error {
for _, exec := range js.Execs {
name := exec.Name + destinationUniquifier + " dev/null"
if err := dag.AddDestination(name, "dev/null",
&engine.DevNull{"dev/null"}); err != nil {
return err
}
if err := dag.Connect(strings.ToLower(exec.Name), name); err != nil {
return err
}
}
return nil
}
//constraints applies AFTER constraints.
func constraints(js *aql.JobScript, dag engine.Coordinator, connMap map[string]*aql.Connection) error {
for _, query := range append(js.Queries, js.Execs...) {
for _, before := range query.Dependencies {
err := dag.AddConstraint(strings.ToLower(before), strings.ToLower(query.Name))
if err != nil {
return err
}
}
}
for _, transform := range js.Transforms {
for _, before := range transform.Dependencies {
err := dag.AddConstraint(strings.ToLower(before), strings.ToLower(transform.Name))
if err != nil {
return err
}
}
}
return nil
}
//scripts makes engine.Transforms out of JobScript scripts.
//Script sources/destinations are not yet supported. We can have:
// [NOT YET IMPLEMENTED] script source -> GLOBAL
// [NOT YET IMPLEMENTED] script source -> script transform
// [NOT YET IMPLEMENTED] script source -> script destination
// SQL source -> script transform
// GLOBAL -> script transform
// script transform -> script transform
// [NOT YET IMPLEMENTED] script transform -> script destination
// script transform -> GLOBAL destination
// script transform -> SQL destination
func transforms(js *aql.JobScript, dag engine.Coordinator, connMap map[string]*aql.Connection, globalOptions []aql.Option, txManager engine.TransactionManager) error {
for _, transform := range js.Transforms {
var (
plugin engine.SequenceableTransform
err error
)
if !transform.Plugin {
plugin, err = builtins.Parse(transform.Content)
if err != nil {
return err
}
err = dag.AddTransform(strings.ToLower(transform.Name), strings.ToLower(transform.Name), plugin)
plugin.SetName(strings.ToLower(transform.Name))
} else {
//Create the plugin
plugin, err = addPlugin(js, dag, transform)
}
if err != nil {
return err
}
var sourceSequence []string
for _, source := range transform.Sources {
//If the source is a connection rather than a query, it is either:
// - Excel spreadsheet with details in connection
// - SQL database with SELECT * FROM Table query
// - GLOBAL with SELECT * FROM Table query
var (
sourceTable string
connectionAlias string
)
if source.Global || source.Database != nil {
var ok bool
connectionAlias = alias(*source, nil)
tableOpt, ok := aql.FindOverridableOption("TABLE", connectionAlias, transform.Options)
if !ok {
return fmt.Errorf("expected TABLE option for %s in the TRANSFORM %s options", connectionAlias, transform.Name)
}
sourceTable, ok = tableOpt.String()
if !ok {
return fmt.Errorf("expected TABLE option to be a STRING for %s source in TRANSFORM %s", connectionAlias, transform.Name)
}
}
if source.Global {
g := engine.SQLSource{
Name: strings.ToLower(transform.Name) + sourceUniquifier + connectionAlias,
Driver: globalDbDriver,
ConnectionString: globalDbConnString,
Query: fmt.Sprintf(sqlSelectAll, sourceTable),
}
g.SetName(connectionAlias)
if err := dag.AddSource(strings.ToLower(transform.Name)+sourceUniquifier+connectionAlias, connectionAlias, &g); err != nil {
return err
}
if err := dag.Connect(strings.ToLower(transform.Name)+sourceUniquifier+connectionAlias, strings.ToLower(transform.Name)); err != nil {
return err
}
sourceSequence = append(sourceSequence, connectionAlias)
continue
}
if source.Database != nil {
if connMap[strings.ToLower(*source.Database)] == nil {
return fmt.Errorf("could not find connection %s for TRANSFORM %s", *source.Database, transform.Name)
}
conn := connMap[strings.ToLower(*source.Database)]
if strings.ToLower(conn.Driver) == "excel" {
if err := excelSource(js, dag, connMap, &transform, *conn, *source, globalOptions); err != nil {
return err
}
if err := dag.Connect(strings.ToLower(transform.Name)+sourceUniquifier+connectionAlias, strings.ToLower(transform.Name)); err != nil {
return err
}
sourceSequence = append(sourceSequence, connectionAlias)
continue
}
if strings.ToLower(conn.Driver) == "http" {
if err := httpSource(js, dag, connMap, &transform, *conn, *source, globalOptions); err != nil {
return err
}
if err := dag.Connect(strings.ToLower(transform.Name)+sourceUniquifier+connectionAlias, strings.ToLower(transform.Name)); err != nil {
return err
}
sourceSequence = append(sourceSequence, connectionAlias)
continue
}
s := engine.SQLSource{
Name: strings.ToLower(transform.Name) + sourceUniquifier + connectionAlias,
Driver: conn.Driver,
ConnectionString: conn.ConnectionString,
Query: fmt.Sprintf(sqlSelectAll, sourceTable),
}
s.SetName(connectionAlias)
if err := dag.AddSource(strings.ToLower(transform.Name)+sourceUniquifier+connectionAlias, connectionAlias, &s); err != nil {
return err
}
if err := dag.Connect(strings.ToLower(transform.Name)+sourceUniquifier+connectionAlias, strings.ToLower(transform.Name)); err != nil {
return err
}
sourceSequence = append(sourceSequence, connectionAlias)
continue
}
//This is a fallthrough in case the source is neither CONNECTION or GLOBAL
//It must therefore be another TRANSFORM. We don't need to add it yet.
if source.Block != nil {
if source.Alias != nil {
sourceSequence = append(sourceSequence, *source.Alias)
} else {
sourceSequence = append(sourceSequence, *source.Block)
}
dataBlock, ok := findDataBlock(js, *source.Block)
if !ok {
//query is already created, so connect it
if err := dag.Connect(strings.ToLower(*source.Block), strings.ToLower(transform.Name)); err != nil {
return err
}
continue
}
err = createDataBlock(js, dag, dataBlock, source)
if err != nil {
return err
}
//query is already created, so connect it
if err := dag.Connect(strings.ToLower(*source.Block), strings.ToLower(transform.Name)); err != nil {
return err
}
}
}
//Sequence sources
if err := sequenceSources(plugin, &transform, sourceSequence); err != nil {
return err
}
}
return nil
}
func createDataBlock(js *aql.JobScript, dag engine.Coordinator, dataBlock *aql.Data, source *aql.SourceSink) error {
var columns []string
colsOpt, ok := aql.FindOption(dataBlock.Options, "COLUMNS")
if !ok {
return fmt.Errorf("expected COLUMNS option for data block %s", dataBlock.Name)
}
cols, ok2 := colsOpt.String()
if !ok2 {
return fmt.Errorf("expected COLUMNS option to be a STRING for data block %s", dataBlock.Name)
}
columns = strings.Split(cols, ",")
for i := range columns {
columns[i] = strings.TrimSpace(columns[i])
}
var dataFormat engine.LiteralSourceFormat
format, ok := aql.FindOption(dataBlock.Options, "FORMAT")
if !ok {
dataFormat = engine.JSONArray
} else {
fStr, ok2 := format.String()
if !ok2 {
return fmt.Errorf("expected FORMAT option to be a STRING in data block %s", dataBlock.Name)
}
f, ok := engine.LiteralSourceFormats[strings.ToUpper(fStr)]
if !ok {
return fmt.Errorf("expected FORMAT option to be one of JSON_ARRAY, JSON_OBJECTS or CSV but got %v", format)
}
dataFormat = f
}
//create new literal source before attempting to connect
ls := engine.LiteralSource{
Name: strings.ToLower(dataBlock.Name),
Content: dataBlock.Content,
Columns: columns,
Format: dataFormat,
}
var err error
if source == nil {
return dag.AddSource(strings.ToLower(dataBlock.Name), strings.ToLower(dataBlock.Name), &ls)
}
if source.Alias != nil {
ls.SetName(*source.Alias)
err = dag.AddSource(strings.ToLower(*source.Block), *source.Alias, &ls)
} else {
ls.SetName(strings.ToLower(dataBlock.Name))
err = dag.AddSource(strings.ToLower(*source.Block), *source.Block, &ls)
}
if err != nil {
return err
}
return nil
}
//findDataBlock attempts to find the data block with the given name, if it exists.
func findDataBlock(js *aql.JobScript, blockName string) (*aql.Data, bool) {
b := strings.ToLower(blockName)
for _, block := range js.Data {
if strings.ToLower(block.Name) == b {
return &block, true
}
}
return nil, false
}
func sequenceSources(transform engine.SequenceableTransform, block aql.Block, sourceSequence []string) error {
//Sequence sources, if required
var sequence bool
seq, ok := aql.FindOption(block.GetOptions(), "MULTISOURCE_ORDER")
if ok {
seqStr, ok2 := seq.String()
if !ok2 {
return fmt.Errorf("expected MULTISOURCE_ORDER option to be a string in transform %s", block.GetName())
}
switch strings.ToUpper(seqStr) {
case "PARALLEL":
//default option
case "SEQUENTIAL":
sequence = true
default:
return fmt.Errorf("expected MULTISOURCE_ORDER to be PARALLEL or SEQUENTIAL in transform %s but got '%s'", block.GetName(), seqStr)
}
}
if sequence {
transform.Sequence(sourceSequence)
}
return nil
}
//addPlugin adds the plugin Transform to the dag.
// As of current release:
// - Limited to shell plugins only (built-in Python scripts not yet implemented).
// This is not a hard limitation in the sense that Python plugins can still be written
// and used, just not stored in the job as part of the transform body.
func addPlugin(js *aql.JobScript, dag engine.Coordinator, transform aql.Transform) (*plugins.Transform, error) {
opts := transform.Options
var (
execStr string
argStr string
ok bool
)
scan := aql.OptionScanner(transform.Name, "", opts)
maybeScan := aql.MaybeOptionScanner(transform.Name, "", opts)
err := scan("EXECUTABLE", &execStr)
if err != nil {
return nil, err
}
ok, err = maybeScan("ARGS", &argStr)
if err != nil {
}
var argList []string
if ok {
if err := json.Unmarshal([]byte(argStr), &argList); err != nil {
return nil, fmt.Errorf("error parsing JSON for ARGS option in transform %s: %v", transform.Name, err)
}
}
//Create plugin instance and configure with options
sRPC := plugins.TransformJSONRPC{Path: execStr, Args: argList}
s := plugins.Transform{
Plugin: &sRPC,
Alias: transform.Name, //FIXME: What if it is a source for another block??
}
if err := s.Configure(transform.Options); err != nil {
return nil, err
}
//FIXME: Transform aliases don't work. There are a few issues here:
// 1) How does a transform know what its aliases are?
// 2) If there are multiple aliases, how should this be dealt with?
dag.AddTransform(strings.ToLower(transform.Name), strings.ToLower(transform.Name), &s)
return &s, nil
}
func toCondition(assertion aql.Assertion) (engine.Condition, error){
switch {
case assertion.Global != nil:
switch {
case assertion.Global.Expr != nil:
return engine.NewSQLCondition(*assertion.Global.Expr)
case assertion.Global.NRows != nil:
if assertion.Global.NRows.AtLeast {
return engine.HasAtLeastNRowsCondition(assertion.Global.NRows.N)
} else if assertion.Global.NRows.AtMost {
return engine.HasAtMostNRowsCondition(assertion.Global.NRows.N)
} else {
//exactly
return engine.HasExactlyNRowsCondition(assertion.Global.NRows.N)
}
default:
panic("unmapped global assertion")
}
case assertion.Column != nil:
switch {
case assertion.Column.Distinct != nil :
if assertion.Column.Distinct.AtLeast {
return engine.HasAtLeastNDistinctValuesCondition(*assertion.Column.TargetColumn, assertion.Column.Distinct.N)
} else if assertion.Column.Distinct.AtMost {
return engine.HasAtMostNDistinctValuesCondition(*assertion.Column.TargetColumn, assertion.Column.Distinct.N)
} else {
return engine.HasExactlyNDistinctValuesCondition(*assertion.Column.TargetColumn, assertion.Column.Distinct.N)
}
case assertion.Column.NoDuplicates :
return engine.HasNoDuplicates(*assertion.Column.TargetColumn)
case assertion.Column.NoNulls:
return engine.HasNoNullValues(*assertion.Column.TargetColumn)
default:
panic("unmapped column assertion")
}
default:
panic("encountered completely blank assertion!")
}
}
// tests parses the AQL assertions and maps them to engine.Conditions. These are then
// added to the DAG. These will be ignored if the job is not in test mode.
func tests(js *aql.JobScript, dag engine.Coordinator) error {
for tNumber, t := range js.Tests {
assertions, err := t.Parse()
if err != nil {
return err
}
for i := range assertions {
c, err := toCondition(assertions[i])
if err != nil {
return err
}
if err := dag.AddTest(strings.ToLower(t.TargetBlock), assertionNodeName(tNumber,i), "", c); err != nil {
return err
}
}
}
return nil
}
func assertionNodeName(testIndex, assertionIndex int) string {
return fmt.Sprintf("Test %d, assertion %d", testIndex+1, assertionIndex+1)
}
//sources makes engine.Source s out of JobScript sources.
//As of current release:
// - Limited to SQL sources (Excel sources require scripts or built-ins to process data which won't come until vNext)
// - Queries limited to single source (this will probably remain a limitation for the foreseeable future)
func sources(js *aql.JobScript, dag engine.Coordinator, connMap map[string]*aql.Connection, params *engine.ParameterTable, globalOptions []aql.Option, txManager engine.TransactionManager) error {
for _, dataBlock := range js.Data {
if dataBlock.Destinations != nil {
err := createDataBlock(js, dag, &dataBlock, nil)
if err != nil {
return err
}
}
}
for _, exec := range js.Execs {
if len(exec.Destinations) > 0 {
return fmt.Errorf("execs are queries that returns no results, and thus cannot have destinations: %s", exec.Name)
}
}
var index = -1
for _, query := range append(js.Queries, js.Execs...) {
index++
execOnly := index >= len(js.Queries)
if len(query.Sources) != 1 {
return fmt.Errorf("queries must have exactly one source but %s has %v", query.Name, len(query.Sources))
}
if query.Sources[0].Console {
return fmt.Errorf("console sources are not supported: %s", query.Name)
}
if query.Sources[0].Global {
g := engine.SQLSource{
Name: query.Name,
Driver: globalDbDriver,
ConnectionString: globalDbConnString,
Query: query.Content,
ParameterTable: params,
ParameterNames: query.Parameters,
ExecOnly: execOnly,
}
//alias := alias(query.Sources[0], nil)
alias := query.Name //Queries can only have one source, so let's do away with this confusing alias nonsense
g.SetName(alias)
dag.AddSource(strings.ToLower(query.Name), alias, &g)
continue
}
if query.Sources[0].Database == nil {
return fmt.Errorf("at present only GLOBAL, SCRIPT and CONNECTION sources are supported for query %s", query.Name)
}
if connMap[strings.ToLower(*query.Sources[0].Database)] == nil {
return fmt.Errorf("could not find connection %s for query %s", *query.Sources[0].Database, query.Name)
}
conn := connMap[strings.ToLower(*query.Sources[0].Database)]
var autoSQL bool
if strings.ToLower(conn.Driver) == "excel" && !execOnly {
if err := excelSource(js, dag, connMap, &query, *conn, query.Sources[0], globalOptions); err != nil {
return err
}
autoSQL = true
}
if strings.ToLower(conn.Driver) == "http" && !execOnly {
if err := httpSource(js, dag, connMap, &query, *conn, query.Sources[0], globalOptions); err != nil {
return err
}
autoSQL = true
}
if autoSQL {
scanner := aql.OptionScanner(query.Name, "", query.Options, conn.Options, globalOptions)
maybeScanner := aql.MaybeOptionScanner(query.Name, "", query.Options, conn.Options, globalOptions)
s := engine.AutoSQLTransform{
Name: query.Name,
Table: conn.Name,
Query: query.Content,
ParameterTable: params,
ParameterNames: query.Parameters,
}
err := aql.ScanOptions(scanner, maybeScanner, &s)
if err != nil {
return err
}
s.SetName(query.Name)
if err := dag.AddTransform(strings.ToLower(query.Name), query.Name, &s); err != nil {
return err
}
sourceAlias := alias(query.Sources[0], conn)
if err := dag.Connect(strings.ToLower(query.Name+sourceUniquifier+sourceAlias), strings.ToLower(query.Name)); err != nil {
return err
}
continue
}
maybeScan := aql.MaybeOptionScanner(query.Name, "", query.Options, conn.Options, globalOptions)
var (
manageTx bool
okM bool
errM error
)
okM, errM = maybeScan("MANAGED_TRANSACTION", &manageTx)
if errM != nil {
return errM
}
var txUseFunc func() (*sql.Tx, error)
if !okM || manageTx {
txUseFunc = func() (*sql.Tx, error) { return txManager.Tx(conn.Name) }
}
s := engine.SQLSource{
Name: query.Name,
Driver: conn.Driver,
ConnectionString: conn.ConnectionString,
Query: query.Content,
ParameterTable: params,
ParameterNames: query.Parameters,
ExecOnly: execOnly,
TxReleaseFunc: func() { txManager.Release(conn.Name) },
TxUseFunc: txUseFunc,
}
//alias := alias(query.Sources[0], conn)
alias := query.Name //Queries can only have one source, so let's do away with this confusing alias nonsense
s.SetName(alias)
dag.AddSource(strings.ToLower(query.Name), alias, &s)
}
return nil
}
func alias(ss aql.SourceSink, conn *aql.Connection) string {
if ss.Alias != nil {
return *ss.Alias
}
if ss.Global {
return "GLOBAL"
}
if conn == nil {
panic("alias panic: should be unreachable")
}
return conn.Name
}
//TODO: refactor all this option parsing nonsense
func sqlDest(js *aql.JobScript, dag engine.Coordinator, connMap map[string]*aql.Connection, block aql.Block, conn aql.Connection, dest aql.SourceSink, globalOptions []aql.Option, txManager engine.TransactionManager) error {
driver := conn.Driver
connString := conn.ConnectionString
var table string
maybeScan := aql.MaybeOptionScanner(block.GetName(), conn.Name, block.GetOptions(), conn.Options, globalOptions)
scan := aql.OptionScanner(block.GetName(), conn.Name, block.GetOptions(), conn.Options, globalOptions)
err := scan("TABLE", &table)
if err != nil {
return err
}
alias := alias(dest, &conn)
var (
manageTx bool
rowsPerBatch int
dropNulls bool
)
_, err = maybeScan("DROP_NULLS", &dropNulls)
if err != nil {
return err
}
ok, err := maybeScan("MANAGED_TRANSACTION", &manageTx)
if err != nil {
return err
}
var txUseFunc func() (*sql.Tx, error)
if !ok || manageTx {
txUseFunc = func() (*sql.Tx, error) { return txManager.Tx(conn.Name) }
}
ok, err = maybeScan("ROWS_PER_BATCH", &rowsPerBatch)
if err != nil {
return err
}
//Uniquify destination name