-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathquery.go
1310 lines (1082 loc) · 30.8 KB
/
query.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 pto3
import (
"bufio"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
)
type QueryCache struct {
// Server configuration
config *PTOConfiguration
// Database connection
db *pg.DB
// Cache of conditions
cidCache ConditionCache
// Path to result cache directory
path string
// Cached queries we know about
query map[string]*Query
// channel for execution tokens
exectokens chan struct{}
// Lock for submitted and cached maps
lock sync.RWMutex
}
// NewQueryCache creates a query cache given a configuration and an
// authorizer. The query cache contains metadata and results (when available),
// backed by permanent storage on disk, and an in-memory cache of recently executed
func NewQueryCache(config *PTOConfiguration) (*QueryCache, error) {
qc := QueryCache{
config: config,
db: pg.Connect(&config.ObsDatabase),
path: config.QueryCacheRoot,
query: make(map[string]*Query),
exectokens: make(chan struct{}, config.ConcurrentQueries),
}
var err error
qc.cidCache, err = LoadConditionCache(qc.db)
if err != nil {
return nil, err
}
return &qc, nil
}
// LoadTestData loads an observation file into a database. It is used as part
// of the setup for testing the query cache, and should not be called in the
// normal case.
func (qc *QueryCache) LoadTestData(obsFilename string) (int, error) {
pidCache := make(PathCache)
set, err := CopySetFromObsFile(obsFilename, qc.db, qc.cidCache, pidCache)
if err != nil {
return 0, err
} else {
return set.ID, nil
}
}
func (qc *QueryCache) EnableQueryLogging() {
EnableQueryLogging(qc.db)
}
func (qc *QueryCache) metadataPath(identifier string) string {
return filepath.Join(qc.config.QueryCacheRoot, fmt.Sprintf("%s.json", identifier))
}
func (qc *QueryCache) writeMetadataFile(identifier string) (*os.File, error) {
return os.Create(qc.metadataPath(identifier))
}
func (qc *QueryCache) readMetadataFile(identifier string) (*os.File, error) {
return os.Open(qc.metadataPath(identifier))
}
func (qc *QueryCache) statMetadataFile(identifier string) (os.FileInfo, error) {
return os.Stat(qc.metadataPath(identifier))
}
func (qc *QueryCache) fetchQuery(identifier string) (*Query, error) {
// we're modifying the cache
qc.lock.Lock()
defer qc.lock.Unlock()
in, err := qc.readMetadataFile(identifier)
if err != nil {
if os.IsNotExist(err) {
// nothing on disk, but that's not an error.
return nil, nil
} else {
return nil, PTOWrapError(err)
}
}
defer in.Close()
b, err := ioutil.ReadAll(in)
if err != nil {
return nil, PTOWrapError(err)
}
q := Query{qc: qc}
if err := json.Unmarshal(b, &q); err != nil {
return nil, PTOWrapError(err)
}
if q.Identifier != identifier {
return nil, PTOErrorf("Identifier mismatch on query fetch: fetched %s got %s", identifier, q.Identifier)
}
// Stick query in the cache
qc.query[identifier] = &q
// FIXME any query we fetch in executing state necessarily crashed.
// we need to restart these. see #59.
return &q, nil
}
func (qc *QueryCache) QueryByIdentifier(identifier string) (*Query, error) {
q := func() *Query {
qc.lock.RLock()
defer qc.lock.RUnlock()
// in in-memory cache?
q := qc.query[identifier]
if q != nil {
return q
}
return nil
}()
if q != nil {
return q, nil
}
// nope, check on disk
return qc.fetchQuery(identifier)
}
func (qc *QueryCache) CachedQueryLinks() ([]string, error) {
out := make([]string, 0)
// FIXME: cache this somewhere, allow invalidation
direntries, err := ioutil.ReadDir(qc.config.QueryCacheRoot)
if err != nil {
return nil, PTOWrapError(err)
}
for _, direntry := range direntries {
metafilename := direntry.Name()
if strings.HasSuffix(metafilename, ".json") {
linkname := metafilename[0 : len(metafilename)-len(".json")]
link, _ := qc.config.LinkTo(fmt.Sprintf("query/%s", linkname))
out = append(out, link)
}
}
return out, nil
}
func (qc *QueryCache) Purge(identifier string) error {
qc.lock.RLock()
defer qc.lock.RUnlock()
if err := os.Remove(qc.dataPath(identifier)); err != nil {
if !os.IsNotExist(err) {
return PTOWrapError(err)
}
}
if err := os.Remove(qc.metadataPath(identifier)); err != nil {
if !os.IsNotExist(err) {
return PTOWrapError(err)
}
}
delete(qc.query, identifier)
return nil
}
// GroupSpec can group a pg-go query by some set of criteria
type GroupSpec interface {
URLEncoded() string
ColumnSpec() string
}
// SimpleGroupSpec groups a pg-go query by a single column
type SimpleGroupSpec struct {
Name string
Column string
ExtTable string
}
func (gs *SimpleGroupSpec) URLEncoded() string {
return gs.Name
}
func (gs *SimpleGroupSpec) ColumnSpec() string {
return gs.Column
}
// DateTruncGroupSpec groups a pg-go query by applying PostgreSQL's date_trunc function to a column
type DateTruncGroupSpec struct {
Truncation string
Column string
}
func (gs *DateTruncGroupSpec) URLEncoded() string {
return gs.Truncation
}
func (gs *DateTruncGroupSpec) ColumnSpec() string {
return fmt.Sprintf("date_trunc('%s', %s)", gs.Truncation, gs.Column)
}
// DatePartGroupSpec groups a pg-go query by applying PostgreSQL's date_part function to a column
type DatePartGroupSpec struct {
Part string
Column string
}
func (gs *DatePartGroupSpec) URLEncoded() string {
switch gs.Part {
case "dow":
return "week_day"
case "hour":
return "day_hour"
default:
panic("bad date part group specification")
}
}
func (gs *DatePartGroupSpec) ColumnSpec() string {
return fmt.Sprintf("date_part('%s', %s)", gs.Part, gs.Column)
}
type Query struct {
// Reference to cache containing query
qc *QueryCache
// Hash-based identifier
Identifier string
// Timestamps for state management
Submitted *time.Time
Executed *time.Time
Completed *time.Time
// Result Row Count (cached)
resultRowCount int
// Errors, references, and sources
ExecutionError error
ExtRef string
Sources []int
// Arbitrary metadata
Metadata map[string]string
// Parsed query parameters
timeStart *time.Time
timeEnd *time.Time
selectSets []int
selectOnPath []string
selectSources []string
selectTargets []string
selectConditions []Condition
selectFeatures []string
selectAspects []string
selectValues []string
groups []GroupSpec
// Query options
optionSetsOnly bool
optionCountDistinctTargets bool
}
func (q *Query) populateFromForm(form url.Values) error {
var ok bool
// Parse start and end times
timeStartStrs, ok := form["time_start"]
if !ok || len(timeStartStrs) < 1 || timeStartStrs[0] == "" {
return PTOErrorf("Query missing mandatory time_start parameter").StatusIs(http.StatusBadRequest)
}
timeStart, err := ParseTime(timeStartStrs[0])
if err != nil {
return PTOErrorf("Error parsing time_start: %s", err.Error()).StatusIs(http.StatusBadRequest)
}
q.timeStart = &timeStart
timeEndStrs, ok := form["time_end"]
if !ok || len(timeEndStrs) < 1 || timeEndStrs[0] == "" {
return PTOErrorf("Query missing mandatory time_start parameter").StatusIs(http.StatusBadRequest)
}
timeEnd, err := ParseTime(timeEndStrs[0])
if err != nil {
return PTOErrorf("Error parsing time_end: %s", err.Error()).StatusIs(http.StatusBadRequest)
}
q.timeEnd = &timeEnd
if q.timeStart.After(*q.timeEnd) {
q.timeStart, q.timeEnd = q.timeEnd, q.timeStart
}
// Parse set parameters into set IDs as integers
setStrs, ok := form["set"]
if ok {
q.selectSets = make([]int, len(setStrs))
for i := range setStrs {
seti64, err := strconv.ParseInt(setStrs[i], 16, 32)
if err != nil {
return PTOErrorf("Error parsing set ID: %s", err.Error()).StatusIs(http.StatusBadRequest)
}
q.selectSets[i] = int(seti64)
}
}
// Can't really validate path components, values, features, or aspects, so just store these slices directly from the form.
q.selectOnPath = form["on_path"]
q.selectSources = form["source"]
q.selectTargets = form["target"]
q.selectValues = form["value"]
q.selectFeatures = form["feature"]
q.selectAspects = form["aspect"]
// Validate and expand conditions
conditionStrs, ok := form["condition"]
if ok {
// don't panic on nil qc/cidcache (DEBUG)
if q.qc == nil {
return PTOErrorf("qc is nil expanding condition array %v", form["condition"])
} else if q.qc.cidCache == nil {
return PTOErrorf("cidCache is nil expanding condition array %v", form["condition"])
}
q.selectConditions = make([]Condition, 0)
for _, conditionStr := range conditionStrs {
conditions, err := q.qc.cidCache.ConditionsByName(q.qc.db, conditionStr)
if err != nil {
return err
}
for _, condition := range conditions {
q.selectConditions = append(q.selectConditions, condition)
}
}
}
groupStrs, ok := form["group"]
if ok {
if len(groupStrs) > 2 {
return PTOErrorf("Group by more than two dimensions not supported").StatusIs(http.StatusBadRequest)
}
q.groups = make([]GroupSpec, len(groupStrs))
for i, groupStr := range groupStrs {
switch groupStr {
case "year":
q.groups[i] = &DateTruncGroupSpec{Truncation: "year", Column: "time_start"}
case "month":
q.groups[i] = &DateTruncGroupSpec{Truncation: "month", Column: "time_start"}
case "week":
q.groups[i] = &DateTruncGroupSpec{Truncation: "week", Column: "time_start"}
case "day":
q.groups[i] = &DateTruncGroupSpec{Truncation: "day", Column: "time_start"}
case "hour":
q.groups[i] = &DateTruncGroupSpec{Truncation: "hour", Column: "time_start"}
case "week_day":
q.groups[i] = &DatePartGroupSpec{Part: "dow", Column: "time_start"}
case "day_hour":
q.groups[i] = &DatePartGroupSpec{Part: "hour", Column: "time_start"}
case "condition":
q.groups[i] = &SimpleGroupSpec{Name: "condition", Column: "condition.name", ExtTable: "conditions"}
case "feature":
q.groups[i] = &SimpleGroupSpec{Name: "feature", Column: "condition.feature", ExtTable: "conditions"}
case "aspect":
q.groups[i] = &SimpleGroupSpec{Name: "aspect", Column: "condition.aspect", ExtTable: "conditions"}
case "source":
q.groups[i] = &SimpleGroupSpec{Name: "source", Column: "path.source", ExtTable: "paths"}
case "target":
q.groups[i] = &SimpleGroupSpec{Name: "target", Column: "path.target", ExtTable: "paths"}
case "value":
q.groups[i] = &SimpleGroupSpec{Name: "value", Column: "value", ExtTable: ""}
default:
return PTOErrorf("unsupported group name %s", groupStr).StatusIs(http.StatusBadRequest)
}
}
}
// parse options
optionStrs, ok := form["option"]
if ok {
for _, optionStr := range optionStrs {
switch optionStr {
case "sets_only":
q.optionSetsOnly = true
case "count_targets":
q.optionCountDistinctTargets = true
}
}
}
// hash everything into an identifier
q.generateIdentifier()
return nil
}
func (q *Query) populateFromEncoded(urlencoded string) error {
v, err := url.ParseQuery(urlencoded)
if err != nil {
return PTOWrapError(err)
}
return q.populateFromForm(v)
}
// ParseQueryFromForm creates a new query from an HTTP form, but does not
// submit it. Used by SubmitQueryFromForm, and for testing.
func (qc *QueryCache) ParseQueryFromForm(form url.Values) (*Query, error) {
// new query bound to this cache
q := Query{qc: qc}
if err := q.populateFromForm(form); err != nil {
return nil, err
}
return &q, nil
}
// SubmitQueryFromForm submits a new query to a cache from an HTTP form. If an
// identical query is already cached, it returns the cached query. Use this to
// handle POST queries.
func (qc *QueryCache) SubmitQueryFromForm(form url.Values) (*Query, bool, error) {
// parse the query
q, err := qc.ParseQueryFromForm(form)
if err != nil {
return nil, false, err
}
// check to see if it's been cached
oq, err := qc.QueryByIdentifier(q.Identifier)
if err != nil {
return nil, false, err
}
if oq != nil {
return oq, false, nil
}
// nope, new query. set submitted timestamp.
t := time.Now()
q.Submitted = &t
// we're modifying the cache
qc.lock.Lock()
defer qc.lock.Unlock()
// write to disk
if err := q.FlushMetadata(); err != nil {
return nil, false, err
}
// add to cache
qc.query[q.Identifier] = q
return q, true, nil
}
func (qc *QueryCache) ExecuteQueryFromForm(form url.Values, done chan struct{}) (*Query, bool, error) {
// submit the query
q, new, err := qc.SubmitQueryFromForm(form)
if err != nil {
return nil, false, err
}
// execute and do an immediate wait for it if it's new
if new {
q.ExecuteWaitImmediate(done)
} else {
close(done)
}
return q, new, nil
}
// ParseQueryFromURLEncoded creates a new query bound to a cache from a URL encoded query string. Used for parser testing and JSON unmarshaling.
func (qc *QueryCache) ParseQueryFromURLEncoded(urlencoded string) (*Query, error) {
// new query bound to this cache
q := Query{qc: qc}
if err := q.populateFromEncoded(urlencoded); err != nil {
return nil, err
}
return &q, nil
}
// SubmitQueryFromURLEncoded creates a new query bound to a cache from a URL encoded query string. Use this to handle GET queries.
func (qc *QueryCache) SubmitQueryFromURLEncoded(urlencoded string) (*Query, bool, error) {
v, err := url.ParseQuery(urlencoded)
if err != nil {
return nil, false, err
}
return qc.SubmitQueryFromForm(v)
}
func (qc *QueryCache) ExecuteQueryFromURLEncoded(encoded string, done chan struct{}) (*Query, bool, error) {
// submit the query
q, new, err := qc.SubmitQueryFromURLEncoded(encoded)
if err != nil {
return nil, false, err
}
// execute and do an immediate wait for it if it's new
if new {
q.ExecuteWaitImmediate(done)
} else {
close(done)
}
return q, new, nil
}
// URLEncoded returns the normalized query string representing this query.
// This is used to generate query identifiers, and to serialize queries to
// disk.
func (q *Query) URLEncoded() string {
// generate query specification as normalized, urlencoded
// start with start and end time
out := fmt.Sprintf("time_start=%s&time_end=%s",
url.QueryEscape(q.timeStart.Format(time.RFC3339)),
url.QueryEscape(q.timeEnd.Format(time.RFC3339)))
// add sorted observation sets
sort.SliceStable(q.selectSets, func(i, j int) bool {
return q.selectSets[i] < q.selectSets[j]
})
for i := range q.selectSets {
out += fmt.Sprintf("&set=%d", q.selectSets[i])
}
// add sorted path elements
sort.SliceStable(q.selectOnPath, func(i, j int) bool {
return q.selectOnPath[i] < q.selectOnPath[j]
})
for i := range q.selectOnPath {
out += fmt.Sprintf("&on_path=%s", q.selectOnPath[i])
}
// add sorted sources
sort.SliceStable(q.selectSources, func(i, j int) bool {
return q.selectSources[i] < q.selectSources[j]
})
for i := range q.selectSources {
out += fmt.Sprintf("&source=%s", q.selectSources[i])
}
// add sorted targets
sort.SliceStable(q.selectTargets, func(i, j int) bool {
return q.selectTargets[i] < q.selectTargets[j]
})
for i := range q.selectTargets {
out += fmt.Sprintf("&target=%s", q.selectTargets[i])
}
// add sorted conditions
sort.SliceStable(q.selectConditions, func(i, j int) bool {
return q.selectConditions[i].Name < q.selectConditions[j].Name
})
for i := range q.selectConditions {
out += fmt.Sprintf("&condition=%s", q.selectConditions[i].Name)
}
// add sorted features
sort.SliceStable(q.selectFeatures, func(i, j int) bool {
return q.selectFeatures[i] < q.selectFeatures[j]
})
for i := range q.selectFeatures {
out += fmt.Sprintf("&feature=%s", q.selectFeatures[i])
}
// add sorted aspects
sort.SliceStable(q.selectAspects, func(i, j int) bool {
return q.selectAspects[i] < q.selectAspects[j]
})
for i := range q.selectAspects {
out += fmt.Sprintf("&aspect=%s", q.selectAspects[i])
}
// add sorted values
sort.SliceStable(q.selectValues, func(i, j int) bool {
return q.selectValues[i] < q.selectValues[j]
})
for i := range q.selectValues {
out += fmt.Sprintf("&value=%s", q.selectValues[i])
}
// add sorted groups
sort.SliceStable(q.groups, func(i, j int) bool {
return q.groups[i].URLEncoded() < q.groups[j].URLEncoded()
})
for i := range q.groups {
out += fmt.Sprintf("&group=%s", q.groups[i].URLEncoded())
}
// add options
if q.optionSetsOnly {
out += "&option=sets_only"
}
if q.optionCountDistinctTargets {
out += "&option=count_targets"
}
return out
}
func (q *Query) generateIdentifier() {
// normalize form of the specification and generate a query identifier
hashbytes := sha256.Sum256([]byte(q.URLEncoded()))
q.Identifier = hex.EncodeToString(hashbytes[:])
}
func (q *Query) generateSources() error {
if len(q.selectSets) > 0 {
// Sets specified in query. Let's just use them.
q.Sources = q.selectSets
} else {
// We have to actually run a query here.
var err error
if q.Sources, err = q.selectObservationSetIDs(); err != nil {
return err
}
}
return nil
}
func (q *Query) ResultRowCount() int {
if q.resultRowCount > 0 {
return q.resultRowCount
}
if q.Completed == nil {
return 0
}
// okay, we have to scan the file
resultFile, err := q.ReadResultFile()
if err != nil {
return 0
}
defer resultFile.Close()
q.resultRowCount = 0
resultScanner := bufio.NewScanner(resultFile)
for resultScanner.Scan() {
q.resultRowCount++
}
return q.resultRowCount
}
// ResultLink generates a link to the file containing query results.
func (q *Query) ResultLink() string {
link, _ := q.qc.config.LinkTo(fmt.Sprintf("query/%s/result", q.Identifier))
return link
}
// SourceLinks generates links to the observation sets contributing to this query
func (q *Query) SourceLinks() []string {
out := make([]string, len(q.Sources))
for i, setid := range q.Sources {
out[i] = LinkForSetID(q.qc.config, setid)
}
return out
}
func (q *Query) modificationTime() *time.Time {
fi, err := q.qc.statMetadataFile(q.Identifier)
if err != nil {
return q.Submitted
} else {
mt := fi.ModTime()
return &mt
}
}
func (q *Query) DumpJSONObject(toDisk bool) ([]byte, error) {
jobj := make(map[string]interface{})
// Store/emit the query itself in its urlencoded form
jobj["__encoded"] = q.URLEncoded()
// Store/emit timestamps
if q.Completed != nil {
jobj["__completed"] = q.Completed.Format(time.RFC3339)
}
if q.Executed != nil {
jobj["__executed"] = q.Executed.Format(time.RFC3339)
}
if q.Submitted != nil {
jobj["__created"] = q.Submitted.Format(time.RFC3339)
}
// Store/emit error
if q.ExecutionError != nil {
jobj["__error"] = q.ExecutionError.Error()
}
// Store/emit arbitrary metadata
for k := range q.Metadata {
if !strings.HasPrefix(k, "__") {
jobj[k] = q.Metadata[k]
}
}
// Store/emit external reference
if q.ExtRef != "" {
jobj["_ext_ref"] = q.ExtRef
}
// Now emit ancillary data if we're not storing to disk
if !toDisk {
// link to this query
var err error
jobj["__link"], err = q.qc.config.LinkTo("query/" + q.Identifier)
if err != nil {
return nil, err
}
// modification time
if q.Submitted != nil {
jobj["__modified"] = q.modificationTime().Format(time.RFC3339)
}
// state, result, and row count
if q.Completed != nil {
if q.ExecutionError != nil {
jobj["__state"] = "failed"
} else if q.ExtRef != "" {
jobj["__state"] = "permanent"
jobj["__result"] = jobj["__link"].(string) + "/result"
jobj["__row_count"] = q.ResultRowCount()
} else {
jobj["__state"] = "complete"
jobj["__result"] = jobj["__link"].(string) + "/result"
jobj["__row_count"] = q.ResultRowCount()
}
} else {
jobj["__state"] = "pending"
}
}
return json.Marshal(jobj)
}
func (q *Query) MarshalJSON() ([]byte, error) {
return q.DumpJSONObject(false)
}
func (q *Query) setMetadata(jmap map[string]string) {
// store external reference
q.ExtRef = jmap["_ext_ref"]
// copy and replace arbitrary metadata
q.Metadata = make(map[string]string)
for k := range jmap {
if !strings.HasPrefix(k, "__") && k != "_ext_ref" {
q.Metadata[k] = jmap[k]
}
}
}
func (q *Query) UnmarshalJSON(b []byte) error {
// get a JSON map
var jmap map[string]string
if err := json.Unmarshal(b, &jmap); err != nil {
return PTOWrapError(err)
}
// parse the query from its encoded representation
encoded := jmap["__encoded"]
if err := q.populateFromEncoded(encoded); err != nil {
return err
}
// parse timestamps
if jmap["__created"] != "" {
ts, err := time.Parse(time.RFC3339, jmap["__created"])
if err != nil {
return PTOWrapError(err)
}
q.Submitted = &ts
}
if jmap["__executed"] != "" {
ts, err := time.Parse(time.RFC3339, jmap["__executed"])
if err != nil {
return PTOWrapError(err)
}
q.Executed = &ts
}
if jmap["__completed"] != "" {
ts, err := time.Parse(time.RFC3339, jmap["__completed"])
if err != nil {
return PTOWrapError(err)
}
q.Completed = &ts
}
if jmap["__error"] != "" {
q.ExecutionError = errors.New(jmap["__error"])
}
q.setMetadata(jmap)
return nil
}
func (q *Query) UpdateFromJSON(b []byte) error {
// get a JSON map
var jmap map[string]string
if err := json.Unmarshal(b, &jmap); err != nil {
return PTOWrapError(err)
}
q.setMetadata(jmap)
return nil
}
func (q *Query) Purge() error {
return q.qc.Purge(q.Identifier)
}
func (q *Query) FlushMetadata() error {
out, err := q.qc.writeMetadataFile(q.Identifier)
if err != nil {
return PTOWrapError(err)
}
b, err := q.DumpJSONObject(true)
if err != nil {
return PTOWrapError(err)
}
if _, err = out.Write(b); err != nil {
return PTOWrapError(err)
}
return nil
}
func (qc *QueryCache) dataPath(identifier string) string {
return filepath.Join(qc.config.QueryCacheRoot, fmt.Sprintf("%s.ndjson", identifier))
}
func (q *Query) writeResultFile() (*os.File, error) {
return os.Create(q.qc.dataPath(q.Identifier))
}
func (q *Query) ReadResultFile() (*os.File, error) {
return os.Open(q.qc.dataPath(q.Identifier))
}
func (q *Query) PaginateResultObject(offset int, count int) (map[string]interface{}, bool, error) {
// create output object
outData := make([]interface{}, 0)
// open result file
resultFile, err := q.ReadResultFile()
if err != nil {
return nil, false, PTOWrapError(err)
}
defer resultFile.Close()
// attempt to seek to offset
lineno := 0
resultScanner := bufio.NewScanner(resultFile)
for resultScanner.Scan() {
lineno++
if offset >= lineno {
continue
}
if lineno > offset+count {
break
}
// unmarshal data from JSON and add to output
var lineData interface{}
if err := json.Unmarshal([]byte(resultScanner.Text()), &lineData); err != nil {
return nil, false, PTOWrapError(err)
}
outData = append(outData, lineData)
}
out := make(map[string]interface{})
out[q.resultObjectLabel()] = outData
return out, lineno > offset+count, nil
}
func (q *Query) whereClauses(pq *orm.Query) *orm.Query {
// time
pq = pq.Where("time_start > ?", q.timeStart).Where("time_end < ?", q.timeEnd)
// sets
if len(q.selectSets) > 0 {
pq = pq.WhereGroup(func(qq *orm.Query) (*orm.Query, error) {
for _, setid := range q.selectSets {
qq = qq.WhereOr("set_id = ?", setid)
}
return qq, nil
})
}
// conditions
if len(q.selectConditions) > 0 {
pq = pq.WhereGroup(func(qq *orm.Query) (*orm.Query, error) {
for _, c := range q.selectConditions {
qq = qq.WhereOr("condition_id = ?", c.ID)
}
return qq, nil
})
}
// feature
if len(q.selectFeatures) > 0 {
pq = pq.WhereGroup(func(qq *orm.Query) (*orm.Query, error) {
for _, f := range q.selectFeatures {
qq = qq.WhereOr("condition.feature = ?", f)
}
return qq, nil
})
}
// aspect
if len(q.selectAspects) > 0 {
pq = pq.WhereGroup(func(qq *orm.Query) (*orm.Query, error) {
for _, a := range q.selectAspects {
qq = qq.WhereOr("condition.aspect = ?", a)
}
return qq, nil
})
}
// values
if len(q.selectValues) > 0 {
pq = pq.WhereGroup(func(qq *orm.Query) (*orm.Query, error) {
for _, val := range q.selectValues {
qq = qq.WhereOr("value = ?", val)
}
return qq, nil
})
}
// source
if len(q.selectSources) > 0 {
pq = pq.WhereGroup(func(qq *orm.Query) (*orm.Query, error) {
for _, src := range q.selectSources {
qq = qq.WhereOr("path.source = ?", src)
}
return qq, nil
})