-
Notifications
You must be signed in to change notification settings - Fork 9
/
service.go
executable file
·1490 lines (1343 loc) · 41.7 KB
/
service.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 dsunit
import (
"context"
"fmt"
"github.com/pkg/errors"
"github.com/viant/afs"
"github.com/viant/afs/file"
"github.com/viant/afs/url"
"github.com/viant/assertly"
"github.com/viant/dsc"
"github.com/viant/dsunit/script"
dsurl "github.com/viant/dsunit/url"
_ "github.com/viant/scy/kms/blowfish"
"github.com/viant/toolbox"
"github.com/viant/toolbox/data"
"strings"
"sync"
"time"
"unicode"
)
var batchSize = 200
// SubstitutionMapKey if provided in context, it will be used to substitute/expand dataset
var SubstitutionMapKey = (*data.Map)(nil)
// Service represents test service
type Service interface {
//registry returns registry of registered database managers
Registry() dsc.ManagerRegistry
//Register registers new datastore connection
Register(request *RegisterRequest) *RegisterResponse
//Recreate remove and creates datastore
Recreate(request *RecreateRequest) *RecreateResponse
//RunSQL runs supplied SQL
RunSQL(request *RunSQLRequest) *RunSQLResponse
//RunScript runs supplied SQL scripts
RunScript(request *RunScriptRequest) *RunSQLResponse
//Add table mapping
AddTableMapping(request *MappingRequest) *MappingResponse
//Init datastore, (register, recreated, run sql, add mapping)
Init(request *InitRequest) *InitResponse
//Populate database with datasets
Prepare(request *PrepareRequest) *PrepareResponse
//Verify datastore with supplied expected datasets
Expect(request *ExpectRequest) *ExpectResponse
//Query returns query from database
Query(request *QueryRequest) *QueryResponse
//Sequence returns sequence for supplied tables
Sequence(request *SequenceRequest) *SequenceResponse
//Freeze creates a dataset from existing database/datastore (reverse engineering test setup/verification)
Freeze(request *FreezeRequest) *FreezeResponse
//Dump creates a database schema from existing database for supplied tables, datastore
Dump(request *DumpRequest) *DumpResponse
//Compare compares data produces by specified SQLs
Compare(request *CompareRequest) *CompareResponse
//CheckSchema checks source and dest schema
CheckSchema(request *CheckSchemaRequest) *CheckSchemaResponse
//Ping waits until if database is online or error
Ping(request *PingRequest) *PingResponse
SetContext(context toolbox.Context)
}
type service struct {
registry dsc.ManagerRegistry
mapper *Mapper
context toolbox.Context
adminDatastores map[string]string
}
func (s *service) Registry() dsc.ManagerRegistry {
return s.registry
}
func (s *service) Register(request *RegisterRequest) *RegisterResponse {
var response = &RegisterResponse{
BaseResponse: NewBaseOkResponse(),
}
var err = request.Init()
if err == nil {
err = request.Validate()
}
if err != nil {
response.SetError(err)
return response
}
config, err := expandDscConfig(request.Config, request.Datastore)
if err != nil {
response.SetError(err)
return response
}
manager, err := dsc.NewManagerFactory().Create(config)
if err == nil {
s.registry.Register(request.Datastore, manager)
if len(request.Tables) > 0 {
for _, table := range request.Tables {
_ = manager.TableDescriptorRegistry().Register(table)
}
}
}
if err != nil {
response.SetError(err)
}
if request.Ping {
request.PingRequest.Datastore = request.Datastore
pingResponse := s.Ping(&request.PingRequest)
response.SetError(pingResponse.Error())
}
return response
}
// Recreate removes and re-creates datastore
func (s *service) Recreate(request *RecreateRequest) *RecreateResponse {
var response = &RecreateResponse{
BaseResponse: NewBaseOkResponse(),
}
if request.AdminDatastore == "" {
request.AdminDatastore = request.Datastore
}
err := RecreateDatastore(request.AdminDatastore, request.Datastore, s.registry)
response.SetError(err)
return response
}
// expandSQLIfNeeded expand content of SQL with context.state key
func (s *service) expandSQLIfNeeded(request *RunSQLRequest, manager dsc.Manager) []string {
if !request.Expand {
return request.SQL
}
ctx := s.newContext(manager)
state := s.getContextState(ctx)
if state == nil {
return request.SQL
}
result := make([]string, 0)
for _, SQL := range request.SQL {
result = append(result, state.ExpandAsText(SQL))
}
return result
}
func (s *service) RunSQL(request *RunSQLRequest) *RunSQLResponse {
var response = &RunSQLResponse{
BaseResponse: NewBaseOkResponse(),
}
if !validateDatastores(s.registry, response.BaseResponse, request.Datastore) {
return response
}
manager := s.registry.Get(request.Datastore)
var SQL = s.expandSQLIfNeeded(request, manager)
results, err := manager.ExecuteAll(SQL)
if err != nil {
response.SetError(err)
return response
}
for _, result := range results {
count, err := result.RowsAffected()
if err != nil {
response.SetError(err)
return response
}
response.RowsAffected += int(count)
}
return response
}
func (s *service) RunScript(request *RunScriptRequest) *RunSQLResponse {
var response = &RunSQLResponse{
BaseResponse: NewBaseOkResponse(),
}
if len(request.Scripts) == 0 {
return response
}
var SQL = []string{}
var err error
var storageService = afs.New()
var ctx = context.Background()
for _, resource := range request.Scripts {
err = resource.Init()
if err != nil {
break
}
var data []byte
if data, err = storageService.DownloadWithURL(ctx, resource.URL); err == nil {
if len(data) != 0 {
SQL = append(SQL, script.Parse(string(data))...)
}
}
if err != nil {
break
}
}
if err != nil {
response.SetError(err)
return response
}
return s.RunSQL(&RunSQLRequest{
Expand: request.Expand,
Datastore: request.Datastore,
SQL: SQL,
})
}
func (s *service) AddTableMapping(request *MappingRequest) *MappingResponse {
var response = &MappingResponse{
BaseResponse: NewBaseOkResponse(),
Tables: make([]string, 0),
}
err := request.Init()
if err == nil {
err = request.Validate()
}
if err != nil {
response.SetError(err)
return response
}
if len(request.Mappings) == 0 {
return response
}
for _, mapping := range request.Mappings {
s.mapper.Add(mapping)
response.Tables = append(response.Tables, mapping.Tables()...)
}
return response
}
// Init datastore, (register, recreated, run sql, add mapping)
func (s *service) Init(request *InitRequest) *InitResponse {
var response = &InitResponse{BaseResponse: NewBaseOkResponse()}
err := request.Init()
if err == nil {
err = request.Validate()
}
if err != nil {
response.SetError(err)
return response
}
registerRequest := request.RegisterRequest
if registerRequest.Datastore == "" {
registerRequest.Datastore = request.Datastore
}
registerRequests := []*RegisterRequest{registerRequest, request.Admin}
for _, registerRequest := range registerRequests {
if registerRequest == nil {
continue
}
serviceResponse := s.Register(registerRequest)
if serviceResponse.Status != StatusOk {
response.BaseResponse = serviceResponse.BaseResponse
return response
}
}
var adminDatastore = registerRequest.Datastore
if request.Admin != nil {
adminDatastore = request.Admin.Datastore
}
s.adminDatastores[request.Datastore] = adminDatastore
if request.Recreate {
serviceResponse := s.Recreate(NewRecreateRequest(registerRequest.Datastore, adminDatastore))
if serviceResponse.Status != StatusOk {
response.BaseResponse = serviceResponse.BaseResponse
return response
}
} else {
err := s.createDbIfDoesNotExists(registerRequest.Datastore, adminDatastore)
if err != nil {
response.SetError(err)
return response
}
}
if request.RunScriptRequest != nil && len(request.Scripts) > 0 {
if request.RunScriptRequest.Datastore == "" {
request.RunScriptRequest.Datastore = request.Datastore
}
serviceResponse := s.RunScript(request.RunScriptRequest)
if serviceResponse.Status != StatusOk {
response.BaseResponse = serviceResponse.BaseResponse
return response
}
}
if request.MappingRequest != nil && len(request.Mappings) > 0 {
serviceResponse := s.AddTableMapping(request.MappingRequest)
if serviceResponse.Status != StatusOk {
response.BaseResponse = serviceResponse.BaseResponse
return response
}
response.Tables = serviceResponse.Tables
}
return response
}
func (s *service) getContextState(context toolbox.Context) *data.Map {
if !context.Contains(SubstitutionMapKey) {
return nil
}
var state = context.GetOptional(SubstitutionMapKey).(*data.Map)
return state
}
func (s *service) newContext(manager dsc.Manager) toolbox.Context {
ctx := toolbox.NewContext()
if s.context != nil {
ctx = s.context.Clone()
}
dialect := dsc.GetDatastoreDialect(manager.Config().DriverName)
_ = ctx.Replace((*dsc.Manager)(nil), &manager)
_ = ctx.Replace((*dsc.DatastoreDialect)(nil), &dialect)
return ctx
}
func (s *service) deleteDatasetIfNeeded(datastore string, dataset *Dataset, table *dsc.TableDescriptor, response *PrepareResponse, context toolbox.Context, manager dsc.Manager, connection dsc.Connection) (err error) {
if dataset.Records.ShouldDeleteAll() {
sqlResult, err := manager.ExecuteOnConnection(connection, fmt.Sprintf("DELETE FROM %s", table.Table), nil)
if err != nil {
return err
}
deleted, _ := sqlResult.RowsAffected()
response.Modification[dataset.Table].Deleted = int(deleted)
//since deletion has to happen before new entries are added to address new modification, deletion needs to be committed first
//for classified as insertable or updatable to work correctly
_ = connection.Commit()
_ = connection.Begin()
_, err = s.disableForeignKeyCheck(datastore, connection, true)
}
return err
}
func (s *service) getTableDescriptor(dataset *Dataset, manager dsc.Manager, context toolbox.Context) (*dsc.TableDescriptor, error) {
macroEvaluator := assertly.NewDefaultMacroEvaluator()
expandedTable, err := macroEvaluator.Expand(context, dataset.Table)
if err != nil {
return nil, err
}
var state = s.getContextState(context)
tableName := state.ExpandAsText(toolbox.AsString(expandedTable))
table := manager.TableDescriptorRegistry().Get(tableName)
if table == nil {
table = &dsc.TableDescriptor{Table: tableName}
_ = manager.TableDescriptorRegistry().Register(table)
}
var autoincrement = dataset.Records.Autoincrement()
var uniqueKeys = dataset.Records.UniqueKeys()
var fromQuery, fromQueryAlias = dataset.Records.FromQuery()
if !table.Autoincrement {
table.Autoincrement = autoincrement
}
if fromQuery != "" {
state := s.getContextState(context)
if state != nil {
fromQuery = state.ExpandAsText(fromQuery)
}
}
table.FromQuery = fromQuery
table.FromQueryAlias = fromQueryAlias
if len(table.PkColumns) == 0 {
table.PkColumns = uniqueKeys
} else if len(uniqueKeys) == 0 {
if len(dataset.Records) > 0 {
if len(dataset.Records[0]) == 0 {
dataset.Records =
append([]map[string]interface{}{{
assertly.IndexByDirective: table.PkColumns,
},
}, dataset.Records...)
} else {
dataset.Records[0][assertly.IndexByDirective] = table.PkColumns
}
}
}
var columns = dataset.Records.Columns()
if len(columns) > 0 {
table.Columns = columns
}
return table, nil
}
func (s *service) populate(datastore string, dataset *Dataset, response *PrepareResponse, context toolbox.Context, manager dsc.Manager, connection dsc.Connection) (err error) {
if s.mapper.Has(dataset.Table) {
datasets := s.mapper.Map(dataset)
for _, dataset := range datasets {
if err = s.populate(datastore, dataset, response, context, manager, connection); err != nil {
return err
}
}
return
}
response.mux.Lock()
if len(response.Modification) == 0 {
response.Modification = make(map[string]*ModificationInfo)
}
response.Modification[dataset.Table] = &ModificationInfo{Subject: dataset.Table, Method: "persist"}
response.mux.Unlock()
var modification = response.Modification[dataset.Table]
var table *dsc.TableDescriptor
if table, err = s.getTableDescriptor(dataset, manager, context); err != nil {
return err
}
if err = s.deleteDatasetIfNeeded(datastore, dataset, table, response, context, manager, connection); err != nil {
return err
}
_ = context.Replace((*Dataset)(nil), dataset)
_ = context.Replace((*dsc.TableDescriptor)(nil), table)
var records []interface{}
expandDataIfNeeded(context, dataset.Records)
if records, err = dataset.Records.Expand(context, false); err != nil {
return err
}
var dmlBuilder = newDatasetDmlProvider(dsc.NewDmlBuilder(table))
if len(table.PkColumns) == 0 { //no keys perform insert
modification.Method = "load"
modification.Added, err = manager.PersistData(connection, records, table.Table, nil, insertSQLProvider(dmlBuilder)) //TODO add insert sql provider
return err
}
modification.Added, modification.Modified, err = manager.PersistAllOnConnection(connection, &records, table.Table, dmlBuilder)
return err
}
func (s *service) prepare(request *PrepareRequest, response *PrepareResponse, manager dsc.Manager, connection dsc.Connection) {
err := connection.Begin()
if err != nil {
response.SetError(err)
}
threads := request.Threads
if threads <= 0 {
threads = 1
}
ctx := s.newContext(manager)
var pending = make(chan bool, threads)
wg := sync.WaitGroup{}
for i := range request.Datasets {
wg.Add(1)
dataset := request.Datasets[i]
pending <- true
go func(dataset *Dataset) {
defer func() {
wg.Done()
<-pending
}()
err = s.populate(request.Datastore, dataset, response, ctx, manager, connection)
if err != nil {
response.SetError(err)
return
}
}(dataset)
}
wg.Wait()
if err == nil {
err = connection.Commit()
} else {
_ = connection.Rollback()
}
if err != nil {
response.SetError(err)
}
}
func (s *service) Prepare(request *PrepareRequest) *PrepareResponse {
var response = &PrepareResponse{
BaseResponse: NewBaseOkResponse(),
}
err := s.prepareWithRequest(request, response)
if err != nil {
response.SetError(err)
return response
}
return response
}
func (s *service) prepareWithRequest(request *PrepareRequest, response *PrepareResponse) (err error) {
err = request.Init()
if err == nil {
err = request.Validate()
}
if err != nil {
return err
}
if !validateDatastores(s.registry, response.BaseResponse, request.Datastore) {
return nil
}
var connection dsc.Connection
manager := s.registry.Get(request.Datastore)
err = request.Load()
response.SetError(err)
if err != nil {
return err
}
if err == nil {
if len(request.Datasets) == 0 {
return fmt.Errorf("no dataset: %v/%v", request.URL, request.Prefix+"*"+request.Postfix)
}
connection, err = manager.ConnectionProvider().Get()
}
if err != nil {
return err
}
// TODO How to handle returned error with error from defer?
defer func() {
_ = connection.Close()
}()
adminConnection, err := s.disableForeignKeyCheck(request.Datastore, connection, false)
if err != nil {
return err
}
s.prepare(request, response, manager, connection)
return s.enableForeignKeyCheck(request.Datastore, adminConnection)
}
func (s *service) enableForeignKeyCheck(datastore string, connection dsc.Connection) error {
dialect := GetDatastoreDialect(datastore, s.registry)
manager := s.registry.Get(datastore)
adminManager := manager
var err error
if !dialect.IsKeyCheckSwitchSessionLevel() {
adminManager, err = s.getAdminManager(datastore)
if err != nil {
return err
}
}
err = dialect.EnableForeignKeyCheck(adminManager, connection)
if manager != adminManager {
return connection.Close()
}
return err
}
func (s *service) disableForeignKeyCheck(datastore string, connection dsc.Connection, closeIfAdmin bool) (dsc.Connection, error) {
dialect := GetDatastoreDialect(datastore, s.registry)
manager := s.registry.Get(datastore)
var err error
adminManager := manager
if !dialect.IsKeyCheckSwitchSessionLevel() {
adminManager, err = s.getAdminManager(datastore)
if err != nil {
return nil, err
}
}
isAdmin := manager != adminManager
if isAdmin {
connection, err = adminManager.ConnectionProvider().Get()
}
err = dialect.DisableForeignKeyCheck(adminManager, connection)
if isAdmin && closeIfAdmin {
if err == nil {
err = connection.Close()
}
}
return connection, err
}
func (s *service) expect(policy int, dataset *Dataset, response *ExpectResponse, context toolbox.Context, manager dsc.Manager) (err error) {
if s.mapper.Has(dataset.Table) {
datasets := s.mapper.Map(dataset)
for _, dataset := range datasets {
if err = s.expect(policy, dataset, response, context, manager); err != nil {
return err
}
}
return err
}
var table *dsc.TableDescriptor
if table, err = s.getTableDescriptor(dataset, manager, context); err != nil {
return err
}
_ = context.Replace((*Dataset)(nil), dataset)
_ = context.Replace((*dsc.TableDescriptor)(nil), table)
expandDataIfNeeded(context, dataset.Records)
expectedRecords, err := dataset.Records.Expand(context, true)
if err != nil {
return err
}
expected := dataset.Records
var columns = dataset.Records.Columns()
dialect := dsc.GetDatastoreDialect(manager.Config().DriverName)
datastore, _ := dialect.GetCurrentDatastore(manager)
var sqlColumns []dsc.Column
if table.FromQuery == "" {
sqlColumns, _ = dialect.GetColumns(manager, datastore, table.Table)
}
var mapper = newDatasetRowMapper(columns, sqlColumns)
var parametrizedSQL *dsc.ParametrizedSQL
sqlBuilder := dsc.NewQueryBuilder(table, "")
var actual = make([]interface{}, 0)
var validation = &DatasetValidation{
Dataset: dataset.Table,
}
if policy == FullTableDatasetCheckPolicy || len(table.PkColumns) == 0 { //no keys perform insert
parametrizedSQL = sqlBuilder.BuildQueryAll(columns)
if err = manager.ReadAll(&actual, parametrizedSQL.SQL, parametrizedSQL.Values, mapper); err != nil {
return err
}
} else {
indexBy := table.PkColumns
if len(expected) > 0 {
values, ok := expected[0][assertly.IndexByDirective]
if ok {
switch actual := values.(type) {
case string:
indexBy = strings.Split(actual, ",")
case []string:
indexBy = actual
}
}
}
indexedBy := buildBatchedPkValues(expected, indexBy)
for _, parametrizedSQL = range sqlBuilder.BuildBatchedInQuery(columns, indexedBy, indexBy, batchSize) {
var batched = make([]interface{}, 0)
err := manager.ReadAll(&batched, parametrizedSQL.SQL, parametrizedSQL.Values, mapper)
if err != nil {
return err
}
actual = append(actual, batched...)
}
}
validation.Expected = expectedRecords
validation.Actual = actual
validation.Validation, err = assertly.Assert(expectedRecords, actual, assertly.NewDataPath(table.Table))
if err == nil {
if policy == FullTableDatasetCheckPolicy {
expectedRecords = removeDirectiveRecord(expectedRecords)
if len(actual) != len(expectedRecords) {
validation.Validation.AddFailure(assertly.NewFailure("", "count", assertly.EqualViolation, len(expectedRecords), len(actual)))
}
}
response.Validation = append(response.Validation, validation)
response.FailedCount += validation.Validation.FailedCount
response.PassedCount += validation.Validation.PassedCount
response.Message += "\n" + dataset.Table + "\n" + validation.Report()
if validation.HasFailure() {
response.Status = "failed"
} else {
response.Status = "ok"
}
}
return err
}
func (s *service) Expect(request *ExpectRequest) *ExpectResponse {
var response = &ExpectResponse{
BaseResponse: NewBaseOkResponse(),
}
err := request.Init()
if err == nil {
err = request.Validate()
}
if err != nil {
response.SetError(err)
return response
}
if !validateDatastores(s.registry, response.BaseResponse, request.Datastore) {
return response
}
manager := s.registry.Get(request.Datastore)
ctx := s.newContext(manager)
err = request.Load()
response.SetError(err)
if err == nil {
if len(request.Datasets) == 0 {
response.SetError(fmt.Errorf("no dataset: %v/%v", request.URL, request.Prefix+"*"+request.Postfix))
return response
}
for _, dataset := range request.Datasets {
if err = s.expect(request.CheckPolicy, dataset, response, ctx, manager); err != nil {
break
}
}
}
response.SetError(err)
return response
}
// Query returns query from database
func (s *service) Query(request *QueryRequest) *QueryResponse {
var response = &QueryResponse{
BaseResponse: NewBaseOkResponse(),
Records: make([]map[string]interface{}, 0),
Validation: &assertly.Validation{},
}
if !validateDatastores(s.registry, response.BaseResponse, request.Datastore) {
return response
}
manager := s.registry.Get(request.Datastore)
macroEvaluator := assertly.NewDefaultMacroEvaluator()
ctx := toolbox.NewContext()
state := s.getContextState(ctx)
SQL, err := macroEvaluator.Expand(ctx, request.SQL)
if err != nil {
response.SetError(err)
return response
}
if state != nil {
SQL = state.Expand(toolbox.AsString(SQL))
}
err = manager.ReadAll(&response.Records, toolbox.AsString(SQL), nil, nil)
if err != nil {
response.SetError(err)
return response
}
if len(request.Expect) > 0 {
response.Validation, err = assertly.Assert(request.Expect, response.Records, assertly.NewDataPath("sql"))
response.SetError(err)
}
return response
}
// Freeze creates a dataset from dataset (reverse engineering test setup/verification)
func (s *service) Freeze(request *FreezeRequest) *FreezeResponse {
var response = &FreezeResponse{BaseResponse: NewBaseOkResponse()}
if !validateDatastores(s.registry, response.BaseResponse, request.Datastore) {
return response
}
if err := request.Init(); err != nil {
response.SetError(err)
return response
}
manager := s.registry.Get(request.Datastore)
macroEvaluator := assertly.NewDefaultMacroEvaluator()
ctx := toolbox.NewContext()
SQL, err := macroEvaluator.Expand(ctx, request.SQL)
if err != nil {
response.SetError(err)
return response
}
var records = make([]map[string]interface{}, 0)
err = manager.ReadAll(&records, toolbox.AsString(SQL), nil, nil)
if err != nil {
response.SetError(err)
return response
}
var locationTimezone *time.Location
if request.LocationTimezone != "" {
if locationTimezone, err = time.LoadLocation(request.LocationTimezone); err != nil {
response.SetError(err)
return response
}
}
relativeDates := map[string]bool{}
if len(request.RelativeDate) > 0 {
for _, item := range request.RelativeDate {
relativeDates[item] = true
}
}
if len(request.Obfuscation) > 0 {
for i := range request.Obfuscation {
item := request.Obfuscation[i]
item.Init(context.Background())
}
}
destResource := dsurl.NewResource(request.DestURL)
if len(records) > 0 {
for i := range records {
if request.OmitEmpty {
records[i] = toolbox.DeleteEmptyKeys(records[i])
}
adjustTime(locationTimezone, request, records[i], relativeDates)
if err = obfuscateData(context.Background(), records[i], request.Obfuscation); err != nil {
response.SetError(err)
return response
}
if len(request.Override) > 0 {
for k, v := range request.Override {
if _, has := records[i][k]; has {
records[i][k] = v
}
}
}
if len(request.Ignore) > 0 {
var record = data.Map(records[i])
for _, path := range request.Ignore {
record.Delete(path)
}
records[i] = record
}
if len(request.Replace) > 0 {
var record = data.Map(records[i])
for k, v := range request.Replace {
record.Replace(k, escapeVariableIfNeeded(v))
}
records[i] = record
}
if len(request.ASCII) > 0 {
for _, column := range request.ASCII {
if val, ok := records[i][column]; ok {
switch actual := val.(type) {
case string:
records[i][column] = strings.TrimFunc(actual, func(r rune) bool {
return !unicode.IsGraphic(r)
})
case []byte:
records[i][column] = strings.TrimFunc(string(actual), func(r rune) bool {
return !unicode.IsGraphic(r)
})
}
}
}
}
}
}
if request.Reset {
records = append([]map[string]interface{}{
map[string]interface{}{},
}, records...)
}
payload, err := toolbox.AsIndentJSONText(records)
if err != nil {
response.SetError(err)
return response
}
response.Count = len(records)
response.DestURL = destResource.URL
uploadContent(destResource, response.BaseResponse, []byte(payload))
return response
}
func obfuscateData(ctx context.Context, m map[string]interface{}, obfuscation []Obfuscation) error {
if len(obfuscation) == 0 {
return nil
}
var err error
for i := range obfuscation {
o := &obfuscation[i]
if len(o.Columns) == 0 {
continue
}
for _, column := range o.Columns {
if value, ok := m[column]; ok {
if m[column], err = o.Obfuscate(ctx, toolbox.AsString(value), m, column); err != nil {
return err
}
}
}
}
return err
}
func adjustTime(locationTimezone *time.Location, request *FreezeRequest, record map[string]interface{}, relativeDates map[string]bool) {
if locationTimezone != nil || request.TimeLayout != "" {
for k, v := range record {
if toolbox.IsTime(v) {
timeValue := toolbox.AsTime(v, "")
if timeValue != nil {
if locationTimezone != nil {
timeInLocation := timeValue.In(locationTimezone)
timeValue = &timeInLocation
}
if relativeDates[k] && timeValue != nil && request.TimeFormat != "" {
diff := time.Now().Sub(*timeValue)
hours := int(diff.Hours())
if hours < 0 {
hours = -1 * hours
record[k] = fmt.Sprintf("$FormatTime('%v hours ahead In UTC', '%v')", hours, request.TimeFormat)
} else {
record[k] = fmt.Sprintf("$FormatTime('%v hours ago In UTC', '%v')", hours, request.TimeFormat)
}
continue
}
if request.TimeLayout != "" {
record[k] = timeValue.Format(request.TimeLayout)
} else {
record[k] = timeValue
}
}
}
}
}
}
//Dump creates a database schema from existing database
func (s *service) Dump(request *DumpRequest) *DumpResponse {
var response = &DumpResponse{BaseResponse: NewBaseOkResponse()}
if !validateDatastores(s.registry, response.BaseResponse, request.Datastore) {
return response
}
if err := s.dump(request, response); err != nil {
response.SetError(err)
}
return response
}
func (s *service) getTableNames(manager dsc.Manager, datastore string) ([]string, error) {
dialect := dsc.GetDatastoreDialect(manager.Config().DriverName)
dbNme, err := dialect.GetCurrentDatastore(manager)
if err != nil {
return nil, err
}
return dialect.GetTables(manager, dbNme)
}
func (s *service) dump(request *DumpRequest, response *DumpResponse) error {
var err error
manager := s.registry.Get(request.Datastore)
dialect := dsc.GetDatastoreDialect(manager.Config().DriverName)
tables := request.Tables
if len(tables) == 0 {
if tables, err = s.getTableNames(manager, request.Datastore); err != nil {
return err
}
}
destResource := dsurl.NewResource(request.DestURL)
var DDLs = []string{}
hasTarget := request.Target != ""
if manager.Config().DriverName == request.Target {
hasTarget = false
}
for _, table := range tables {
if hasTarget {
targetDDL, err := s.getCreateTableDDL(manager, request, table)
if err != nil {
return err
}
DDLs = append(DDLs, targetDDL)
continue
}
ddl, err := dialect.ShowCreateTable(manager, table)
if err != nil {
return err
}
DDLs = append(DDLs, ddl)
}
var payload = strings.Join(DDLs, "\n\n")
response.Count = len(DDLs)
response.DestURL = destResource.URL
uploadContent(destResource, response.BaseResponse, []byte(payload))
return nil
}
func (s *service) getOrLoadMapping(target, mappingURL string) (map[string]string, error) {
var result = make(map[string]string)