-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathvalue.go
1363 lines (1265 loc) · 41.2 KB
/
value.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
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package result
import (
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"time"
anypb "google.golang.org/protobuf/types/known/anypb"
timestamppb "google.golang.org/protobuf/types/known/timestamppb"
datepb "google.golang.org/genproto/googleapis/type/date"
timeofdaypb "google.golang.org/genproto/googleapis/type/timeofday"
"github.com/google/cql/internal/datehelpers"
"github.com/google/cql/model"
crpb "github.com/google/cql/protos/cql_result_go_proto"
"github.com/google/cql/types"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
// Value is a CQL Value evaluated by the interpreter.
type Value struct {
goValue any
runtimeType types.IType
sourceExpr model.IExpression
sourceVals []Value
}
// GolangValue returns the underlying Golang value representing the CQL value. Specifically:
// CQL Null returns Golang nil
// CQL Boolean returns Golang bool
// CQL String returns Golang string
// CQL Integer returns Golang int32
// CQL Long returns Golang int64
// CQL Decimal returns Golang float64
// CQL Quantity returns Golang Quantity struct
// CQL Ratio returns Golang Ratio struct
// CQL Date returns Golang Date struct
// CQL DateTime returns Golang DateTime struct
// CQL Time returns Golang Time struct
// CQL Interval returns Golang Interval struct
// CQL List returns Golang List struct
// CQL Tuple returns Golang Tuple struct
// CQL Named (a type defined in the data model) returns Golang Proto struct
// CQL CodeSystem returns Golang CodeSystem struct
// CQL ValueSet returns Golang ValueSet struct
// CQL Concept returns Golang Concept struct
// CQL Code returns Goland Code struct
//
// You can call GolangValue() and type switch to handle values. Alternatively, if you know that the
// result will be a specific type such as an int32, it is recommended to use the result.ToInt32()
// helper function.
func (v Value) GolangValue() any { return v.goValue }
// RuntimeType returns the type used by the Is system operator
// https://cql.hl7.org/09-b-cqlreference.html#is. This may be different than the type statically
// determined by the Parser. For example, if the Parser statically determines the type to be
// Choice<String, Integer> the runtime type will be the actual type during evaluation, either
// Integer, String or Null. In some cases where a runtime is not known (for example an empty list,
// or an interval with where low and high are nulls) this will fall back to the static type.
func (v Value) RuntimeType() types.IType {
switch t := v.goValue.(type) {
case Interval:
return inferIntervalType(t)
case List:
return inferListType(t.Value, t.StaticType)
default:
return v.runtimeType
}
}
// SourceExpression is the CQL expression that created this value. For instance, if the returned
// result is from the CQL expression "a < b", the source expression will be the `model.Less` struct.
func (v Value) SourceExpression() model.IExpression { return v.sourceExpr }
// SourceValues returns the underlying values that were used by the SourceExpression to compute the
// returned value. The ordering of source values is not guaranteed to have any meaning, although
// expressions that produce them should attempt to preserve order when it does have meaning. For
// instance, for the value returned by "a < b", the source values are `a` and `b`.
//
// Source Values will have their own sources, creating a recursive tree structure that allows users
// to trace through the tree of expressions and values used to create it.
func (v Value) SourceValues() []Value { return v.sourceVals }
// For simple types, we can just marshal the value and type.
// More complex representations are handled in marshalJSON() functions of specific types.
type simpleJSONMessage struct {
Type json.RawMessage `json:"@type"`
Value any `json:"value"`
}
// customJSONMarshaler is an interface for types that need to marshal their own JSON representation.
// I.E. types that are not simple types.
type customJSONMarshaler interface {
// marshalJSON accepts a bytes array of the type string and returns the JSON representation.
marshalJSON(json.RawMessage) ([]byte, error)
}
// MarshalJSON returns the value as a JSON string.
// Uses CQL-Serialization spec as a template:
// https://github.com/cqframework/clinical_quality_language/wiki/CQL-Serialization
func (v Value) MarshalJSON() ([]byte, error) {
rt, err := v.RuntimeType().MarshalJSON()
if err != nil {
return nil, err
}
// TODO: b/301606416 - Vocabulary support.
switch gv := v.goValue.(type) {
case customJSONMarshaler:
return gv.marshalJSON(rt)
case bool, float64, int32, int64, string, nil:
return json.Marshal(simpleJSONMessage{
Value: gv,
Type: rt,
})
case Date:
date, err := datehelpers.DateString(gv.Date, gv.Precision)
if err != nil {
return nil, err
}
return json.Marshal(simpleJSONMessage{
Type: rt,
Value: date,
})
case DateTime:
dt, err := datehelpers.DateTimeString(gv.Date, gv.Precision)
if err != nil {
return nil, err
}
return json.Marshal(simpleJSONMessage{
Type: rt,
Value: dt,
})
case Time:
t, err := datehelpers.TimeString(gv.Date, gv.Precision)
if err != nil {
return nil, err
}
return json.Marshal(simpleJSONMessage{
Type: rt,
Value: t,
})
case List:
// Lists don't embed the type so they can be directly marshalled.
return json.Marshal(gv.Value)
case Tuple:
// Tuples don't embed the type so they can be directly marshalled.
return json.Marshal(gv.Value)
default:
return nil, fmt.Errorf("tried to marshal unsupported type %T, %w", gv, errUnsupportedType)
}
}
// Proto converts Value to a proto. The source expression and source values are dropped.
func (v Value) Proto() (*crpb.Value, error) {
pbValue := &crpb.Value{}
switch t := v.goValue.(type) {
case nil:
// TODO(b/301606416): Consider supporting typed nulls.
return pbValue, nil
case bool:
pbValue.Value = &crpb.Value_BooleanValue{BooleanValue: t}
case string:
pbValue.Value = &crpb.Value_StringValue{StringValue: t}
case int32:
pbValue.Value = &crpb.Value_IntegerValue{IntegerValue: t}
case int64:
pbValue.Value = &crpb.Value_LongValue{LongValue: t}
case float64:
pbValue.Value = &crpb.Value_DecimalValue{DecimalValue: t}
case Quantity:
pbValue.Value = &crpb.Value_QuantityValue{QuantityValue: t.Proto()}
case Ratio:
pbValue.Value = &crpb.Value_RatioValue{RatioValue: t.Proto()}
case Date:
pb, err := t.Proto()
if err != nil {
return nil, err
}
pbValue.Value = &crpb.Value_DateValue{DateValue: pb}
case DateTime:
pb, err := t.Proto()
if err != nil {
return nil, err
}
pbValue.Value = &crpb.Value_DateTimeValue{DateTimeValue: pb}
case Time:
pb, err := t.Proto()
if err != nil {
return nil, err
}
pbValue.Value = &crpb.Value_TimeValue{TimeValue: pb}
case Interval:
pb, err := t.Proto()
if err != nil {
return nil, err
}
pbValue.Value = &crpb.Value_IntervalValue{IntervalValue: pb}
case List:
pb, err := t.Proto()
if err != nil {
return nil, err
}
pbValue.Value = &crpb.Value_ListValue{ListValue: pb}
case Named:
pb, err := t.Proto()
if err != nil {
return nil, err
}
pbValue.Value = &crpb.Value_NamedValue{NamedValue: pb}
case Tuple:
pb, err := t.Proto()
if err != nil {
return nil, err
}
pbValue.Value = &crpb.Value_TupleValue{TupleValue: pb}
case CodeSystem:
pbValue.Value = &crpb.Value_CodeSystemValue{CodeSystemValue: t.Proto()}
case ValueSet:
pbValue.Value = &crpb.Value_ValueSetValue{ValueSetValue: t.Proto()}
case Concept:
pbValue.Value = &crpb.Value_ConceptValue{ConceptValue: t.Proto()}
case Code:
pbValue.Value = &crpb.Value_CodeValue{CodeValue: t.Proto()}
}
return pbValue, nil
}
// Equal is our custom implementation of equality used primarily by cmp.Diff in tests. This is not
// CQL equality. Equal only compares the GolangValue and RuntimeType, ignoring SourceExpression and
// SourceValues.
func (v Value) Equal(a Value) bool {
if !v.RuntimeType().Equal(a.RuntimeType()) {
return false
}
switch t := v.goValue.(type) {
case Date:
vDate, ok := a.GolangValue().(Date)
if !ok {
return false
}
return t.Equal(vDate)
case DateTime:
vDateTime, ok := a.GolangValue().(DateTime)
if !ok {
return false
}
return t.Equal(vDateTime)
case Time:
vTime, ok := a.GolangValue().(Time)
if !ok {
return false
}
return t.Equal(vTime)
case Interval:
vInterval, ok := a.GolangValue().(Interval)
if !ok {
return false
}
return t.Equal(vInterval)
case List:
vList, ok := a.GolangValue().(List)
if !ok {
return false
}
return t.Equal(vList)
case Tuple:
vTuple, ok := a.GolangValue().(Tuple)
if !ok {
return false
}
return t.Equal(vTuple)
case Named:
vProto, ok := a.GolangValue().(Named)
if !ok {
return false
}
return t.Equal(vProto)
case ValueSet:
vValueSet, ok := a.GolangValue().(ValueSet)
if !ok {
return false
}
return t.Equal(vValueSet)
case Concept:
vConcept, ok := a.GolangValue().(Concept)
if !ok {
return false
}
return t.Equal(vConcept)
default:
return v.GolangValue() == a.GolangValue()
}
}
var errUnsupportedType = errors.New("unsupported type")
// New converts Golang values to CQL values. This function should be used when creating values from
// call sites where the supporting sources are not know, and to be added with the WithSources()
// function later. Call sites with the needed sources are encouraged to use NewWithSources below.
// Specifically:
// Golang bool converts to CQL Boolean
// Golang string converts to CQL String
// Golang int32 converts to CQL Integer
// Golang int64 converts to CQL Long
// Golang float64 converts to CQL Decimal
// Golang Quantity struct converts to CQL Quantity
// Golang Ratio struct converts to CQL Ratio
// Golang Date struct converts to CQL Date
// Golang DateTime struct converts to CQL DateTime
// Golang Time struct converts to CQL Time
// Golang Interval struct converts to CQL Interval
// Golang []Value converts to CQL List
// Golang map[string]Value converts to CQL Tuple
// Golang proto.Message (a type defined in the data model) converts to CQL Named
// Golang CodeSystem struct converts to CQL CodeSystem
// Golang ValueSet struct converts to CQL ValueSet
// Golang Concept struct converts to CQL Concept
// Golang Code struct converts to CQL Code
func New(val any) (Value, error) {
if val == nil {
return Value{runtimeType: types.Any, goValue: nil}, nil
}
switch v := val.(type) {
case int:
return Value{runtimeType: types.Integer, goValue: int32(v)}, nil
case int32:
return Value{runtimeType: types.Integer, goValue: v}, nil
case int64:
return Value{runtimeType: types.Long, goValue: v}, nil
case float64:
return Value{runtimeType: types.Decimal, goValue: v}, nil
case Quantity:
return Value{runtimeType: types.Quantity, goValue: v}, nil
case Ratio:
return Value{runtimeType: types.Ratio, goValue: v}, nil
case bool:
return Value{runtimeType: types.Boolean, goValue: v}, nil
case string:
return Value{runtimeType: types.String, goValue: v}, nil
case Date:
switch v.Precision {
case model.YEAR, model.MONTH, model.DAY, model.UNSETDATETIMEPRECISION:
return Value{runtimeType: types.Date, goValue: v}, nil
}
return Value{}, fmt.Errorf("unsupported precision in Date with value %v %w", v.Precision, datehelpers.ErrUnsupportedPrecision)
case DateTime:
switch v.Precision {
case model.YEAR,
model.MONTH,
model.DAY,
model.HOUR,
model.MINUTE,
model.SECOND,
model.MILLISECOND,
model.UNSETDATETIMEPRECISION:
return Value{runtimeType: types.DateTime, goValue: v}, nil
}
return Value{}, fmt.Errorf("unsupported precision in DateTime with value %v %w", v.Precision, datehelpers.ErrUnsupportedPrecision)
case Time:
switch v.Precision {
case model.HOUR, model.MINUTE, model.SECOND, model.MILLISECOND, model.UNSETDATETIMEPRECISION:
if v.Date.Year() != 0 || v.Date.Month() != 1 || v.Date.Day() != 1 {
return Value{}, fmt.Errorf("internal error - Time must be Year 0000, Month 01, Day 01, instead got %v", v.Date)
}
return Value{runtimeType: types.Time, goValue: v}, nil
}
return Value{}, fmt.Errorf("unsupported precision in Time with value %v %w", v.Precision, datehelpers.ErrUnsupportedPrecision)
case Interval:
// RuntimeType is not set here because it is inferred at RuntimeType() is called.
return Value{goValue: v}, nil
case List:
// RuntimeType is not set here because it is inferred when RuntimeType() is called.
return Value{goValue: v}, nil
case Named:
return Value{runtimeType: v.RuntimeType, goValue: v}, nil
case Tuple:
return Value{runtimeType: v.RuntimeType, goValue: v}, nil
case CodeSystem:
if v.ID == "" {
return Value{}, fmt.Errorf("%v must have an ID", types.CodeSystem)
}
return Value{runtimeType: types.CodeSystem, goValue: v}, nil
case Concept:
if v.Codes == nil {
return Value{}, fmt.Errorf("%v must specify the codes field", types.Concept)
}
return Value{runtimeType: types.Concept, goValue: v}, nil
case ValueSet:
if v.ID == "" {
return Value{}, fmt.Errorf("%v must have an ID", types.ValueSet)
}
return Value{runtimeType: types.ValueSet, goValue: v}, nil
case Code:
if v.Code == "" {
return Value{}, fmt.Errorf("%v must have a Code", types.Code)
}
return Value{runtimeType: types.Code, goValue: v}, nil
default:
return Value{}, fmt.Errorf("%T %w", v, errUnsupportedType)
}
}
// NewWithSources converts Golang values to CQL values when the sources are known. See New()
// function for full documentation.
func NewWithSources(val any, sourceExp model.IExpression, sourceObjs ...Value) (Value, error) {
o, err := New(val)
if err != nil {
return Value{}, err
}
return o.WithSources(sourceExp, sourceObjs...), nil
}
// WithSources returns a version of the value with the given sources. This function has
// the following semantics to ensure all child values and expressions are recursively preserved
// as values propagate through the evaluation tree:
//
// First, if the value already has sources, this creates a copy of that value with the newly
// provided sources, so the original and its sources are preserved. Therefore an value with
// existing sources is never mutated and can be safely stored or reused across many consuming
// expressions if needed by the engine implementation.
//
// Second, if a caller does not explicitly provide a new set of source values, this function will
// use the existing value this is invoked on as the source. For instance, function implementations
// can do this to propagate a trace up the call stack by simply calling
// `valueToReturn.WithSources(theFunctionExpression)` prior to returning.
func (v Value) WithSources(sourceExp model.IExpression, sourceObjs ...Value) Value {
if v.sourceExpr == nil {
v.sourceExpr = sourceExp
v.sourceVals = sourceObjs
return v
}
// TODO b/301606416: This does not make a copy of val for lists, tuples and proto types. This is
// ok since we currently don't mutate Values after they are created.
if len(sourceObjs) == 0 {
return Value{runtimeType: v.runtimeType, goValue: v.goValue, sourceExpr: sourceExp, sourceVals: []Value{v}}
}
return Value{runtimeType: v.runtimeType, goValue: v.goValue, sourceExpr: sourceExp, sourceVals: sourceObjs}
}
// NewFromProto converts a proto to a Value. The source expression and source values are dropped.
func NewFromProto(pb *crpb.Value) (Value, error) {
switch t := pb.GetValue().(type) {
case nil:
return New(nil)
case *crpb.Value_BooleanValue:
return New(t.BooleanValue)
case *crpb.Value_StringValue:
return New(t.StringValue)
case *crpb.Value_IntegerValue:
return New(t.IntegerValue)
case *crpb.Value_LongValue:
return New(t.LongValue)
case *crpb.Value_DecimalValue:
return New(t.DecimalValue)
case *crpb.Value_QuantityValue:
return New(QuantityFromProto(t.QuantityValue))
case *crpb.Value_RatioValue:
return New(RatioFromProto(t.RatioValue))
case *crpb.Value_DateValue:
v, err := DateFromProto(t.DateValue)
if err != nil {
return Value{}, err
}
return New(v)
case *crpb.Value_DateTimeValue:
v, err := DateTimeFromProto(t.DateTimeValue)
if err != nil {
return Value{}, err
}
return New(v)
case *crpb.Value_TimeValue:
v, err := TimeFromProto(t.TimeValue)
if err != nil {
return Value{}, err
}
return New(v)
case *crpb.Value_IntervalValue:
v, err := IntervalFromProto(t.IntervalValue)
if err != nil {
return Value{}, err
}
return New(v)
case *crpb.Value_ListValue:
v, err := ListFromProto(t.ListValue)
if err != nil {
return Value{}, err
}
return New(v)
case *crpb.Value_TupleValue:
v, err := TupleFromProto(t.TupleValue)
if err != nil {
return Value{}, err
}
return New(v)
case *crpb.Value_NamedValue:
v, err := NamedFromProto(t.NamedValue)
if err != nil {
return Value{}, err
}
return New(v)
case *crpb.Value_CodeSystemValue:
return New(CodeSystemFromProto(t.CodeSystemValue))
case *crpb.Value_ValueSetValue:
return New(ValueSetFromProto(t.ValueSetValue))
case *crpb.Value_ConceptValue:
return New(ConceptFromProto(t.ConceptValue))
case *crpb.Value_CodeValue:
return New(CodeFromProto(t.CodeValue))
default:
return Value{}, fmt.Errorf("%T %w", pb, errUnsupportedType)
}
}
// Quantity represents a decimal value with an associated unit string.
type Quantity struct {
Value float64
Unit model.Unit
}
// Proto converts Quantity to a proto.
func (q Quantity) Proto() *crpb.Quantity {
return &crpb.Quantity{
Value: proto.Float64(q.Value),
Unit: proto.String(string(q.Unit)),
}
}
// QuantityFromProto converts a proto to a Quantity.
func QuantityFromProto(pb *crpb.Quantity) Quantity {
return Quantity{Value: pb.GetValue(), Unit: model.Unit(pb.GetUnit())}
}
func (q Quantity) marshalJSON(t json.RawMessage) ([]byte, error) {
return json.Marshal(struct {
Type json.RawMessage `json:"@type"`
Value float64 `json:"value"`
Unit string `json:"unit"`
}{
Type: t,
Value: q.Value,
Unit: string(q.Unit),
})
}
// Ratio represents a ratio of two quantities.
type Ratio struct {
Numerator Quantity
Denominator Quantity
}
// RatioFromProto converts a proto to a Ratio.
func RatioFromProto(pb *crpb.Ratio) Ratio {
return Ratio{Numerator: QuantityFromProto(pb.Numerator), Denominator: QuantityFromProto(pb.Denominator)}
}
// Proto converts Ratio to a proto.
func (r Ratio) Proto() *crpb.Ratio {
return &crpb.Ratio{
Numerator: r.Numerator.Proto(),
Denominator: r.Denominator.Proto(),
}
}
func (r Ratio) marshalJSON(t json.RawMessage) ([]byte, error) {
quantityType, err := types.Quantity.MarshalJSON()
if err != nil {
return nil, err
}
marshalledNumerator, err := r.Numerator.marshalJSON(quantityType)
if err != nil {
return nil, err
}
marshalledDenominator, err := r.Denominator.marshalJSON(quantityType)
if err != nil {
return nil, err
}
return json.Marshal(struct {
Type json.RawMessage `json:"@type"`
Numerator json.RawMessage `json:"numerator"`
Denominator json.RawMessage `json:"denominator"`
}{
Type: t,
Numerator: marshalledNumerator,
Denominator: marshalledDenominator,
})
}
// Date is the Golang representation of a CQL Date. CQL Dates do not have timezone offsets, but
// Golang time.Time requires a location. The time.Time should always have the offset of the
// evaluation timestamp. The precision will be is Year, Month or Day.
type Date DateTime
// Equal returns true if this Date matches the provided one, otherwise false.
func (d Date) Equal(v Date) bool {
return DateTime(d).Equal(DateTime(v))
}
// Proto converts Date to a proto.
func (d Date) Proto() (*crpb.Date, error) {
pbCQLDate := &crpb.Date{}
pbDate := &datepb.Date{}
switch d.Precision {
case model.YEAR:
pbDate.Year = int32(d.Date.Year())
pbCQLDate.Precision = crpb.Date_PRECISION_YEAR.Enum()
case model.MONTH:
pbDate.Year = int32(d.Date.Year())
pbDate.Month = int32(d.Date.Month())
pbCQLDate.Precision = crpb.Date_PRECISION_MONTH.Enum()
case model.DAY:
pbDate.Year = int32(d.Date.Year())
pbDate.Month = int32(d.Date.Month())
pbDate.Day = int32(d.Date.Day())
pbCQLDate.Precision = crpb.Date_PRECISION_DAY.Enum()
default:
return nil, fmt.Errorf("unsupported precision in Date with value %v %w", d.Precision, datehelpers.ErrUnsupportedPrecision)
}
pbCQLDate.Date = pbDate
return pbCQLDate, nil
}
// DateFromProto converts a proto to a Date.
func DateFromProto(pb *crpb.Date) (Date, error) {
var modelPrecision model.DateTimePrecision
switch pb.GetPrecision() {
case crpb.Date_PRECISION_YEAR:
modelPrecision = model.YEAR
case crpb.Date_PRECISION_MONTH:
modelPrecision = model.MONTH
case crpb.Date_PRECISION_DAY:
modelPrecision = model.DAY
default:
return Date{}, fmt.Errorf("unsupported precision converting proto to Date %v %w", pb.GetPrecision(), datehelpers.ErrUnsupportedPrecision)
}
return Date{Date: time.Date(int(pb.Date.GetYear()), time.Month(pb.Date.GetMonth()), int(pb.Date.GetDay()), 0, 0, 0, 0, time.UTC), Precision: modelPrecision}, nil
}
// DateTime is the Golang representation of a CQL DateTime. The time.Time may have different
// offsets. The precision will be anything from Year to Millisecond.
type DateTime struct {
Date time.Time
Precision model.DateTimePrecision
}
// Proto converts DateTime to a proto.
func (d DateTime) Proto() (*crpb.DateTime, error) {
pbCQLDateTime := &crpb.DateTime{}
switch d.Precision {
case model.YEAR:
pbCQLDateTime.Precision = crpb.DateTime_PRECISION_YEAR.Enum()
case model.MONTH:
pbCQLDateTime.Precision = crpb.DateTime_PRECISION_MONTH.Enum()
case model.DAY:
pbCQLDateTime.Precision = crpb.DateTime_PRECISION_DAY.Enum()
case model.HOUR:
pbCQLDateTime.Precision = crpb.DateTime_PRECISION_HOUR.Enum()
case model.MINUTE:
pbCQLDateTime.Precision = crpb.DateTime_PRECISION_MINUTE.Enum()
case model.SECOND:
pbCQLDateTime.Precision = crpb.DateTime_PRECISION_SECOND.Enum()
case model.MILLISECOND:
pbCQLDateTime.Precision = crpb.DateTime_PRECISION_MILLISECOND.Enum()
default:
return nil, fmt.Errorf("unsupported precision in DateTime with value %v %w", d.Precision, datehelpers.ErrUnsupportedPrecision)
}
pbCQLDateTime.Date = timestamppb.New(d.Date)
return pbCQLDateTime, nil
}
// DateTimeFromProto converts a proto to a DateTime.
func DateTimeFromProto(pb *crpb.DateTime) (DateTime, error) {
var modelPrecision model.DateTimePrecision
switch pb.GetPrecision() {
case crpb.DateTime_PRECISION_YEAR:
modelPrecision = model.YEAR
case crpb.DateTime_PRECISION_MONTH:
modelPrecision = model.MONTH
case crpb.DateTime_PRECISION_DAY:
modelPrecision = model.DAY
case crpb.DateTime_PRECISION_HOUR:
modelPrecision = model.HOUR
case crpb.DateTime_PRECISION_MINUTE:
modelPrecision = model.MINUTE
case crpb.DateTime_PRECISION_SECOND:
modelPrecision = model.SECOND
case crpb.DateTime_PRECISION_MILLISECOND:
modelPrecision = model.MILLISECOND
default:
return DateTime{}, fmt.Errorf("unsupported precision converting Proto to DateTime %v %w", pb.GetPrecision(), datehelpers.ErrUnsupportedPrecision)
}
return DateTime{Date: pb.Date.AsTime(), Precision: modelPrecision}, nil
}
// Equal returns true if this DateTime matches the provided one, otherwise false.
func (d DateTime) Equal(v DateTime) bool {
if !d.Date.Equal(v.Date) {
return false
}
if d.Precision != v.Precision {
return false
}
return true
}
// Time is the Golang representation of a CQL Time. CQL Times do not have year, month, days or a
// timezone but Golang time.Time does. We use the date 0000-01-01 and timezone UTC for all golang
// time.Time. The precision will be between Hour and Millisecond.
type Time DateTime
// Equal returns true if this Time matches the provided one, otherwise false.
func (t Time) Equal(v Time) bool {
return DateTime(t).Equal(DateTime(v))
}
// Proto converts Time to a proto.
func (t Time) Proto() (*crpb.Time, error) {
pbCQLTime := &crpb.Time{}
pbTime := &timeofdaypb.TimeOfDay{}
switch t.Precision {
case model.HOUR:
pbTime.Hours = int32(t.Date.Hour())
pbCQLTime.Precision = crpb.Time_PRECISION_HOUR.Enum()
case model.MINUTE:
pbTime.Hours = int32(t.Date.Hour())
pbTime.Minutes = int32(t.Date.Minute())
pbCQLTime.Precision = crpb.Time_PRECISION_MINUTE.Enum()
case model.SECOND:
pbTime.Hours = int32(t.Date.Hour())
pbTime.Minutes = int32(t.Date.Minute())
pbTime.Seconds = int32(t.Date.Second())
pbCQLTime.Precision = crpb.Time_PRECISION_SECOND.Enum()
case model.MILLISECOND:
pbTime.Hours = int32(t.Date.Hour())
pbTime.Minutes = int32(t.Date.Minute())
pbTime.Seconds = int32(t.Date.Second())
pbTime.Nanos = int32(t.Date.Nanosecond())
pbCQLTime.Precision = crpb.Time_PRECISION_MILLISECOND.Enum()
default:
return nil, fmt.Errorf("unsupported precision converting proto to Time %v %w", t.Precision, datehelpers.ErrUnsupportedPrecision)
}
pbCQLTime.Date = pbTime
return pbCQLTime, nil
}
// TimeFromProto converts a proto to a Time.
func TimeFromProto(pb *crpb.Time) (Time, error) {
var modelPrecision model.DateTimePrecision
switch pb.GetPrecision() {
case crpb.Time_PRECISION_HOUR:
modelPrecision = model.HOUR
case crpb.Time_PRECISION_MINUTE:
modelPrecision = model.MINUTE
case crpb.Time_PRECISION_SECOND:
modelPrecision = model.SECOND
case crpb.Time_PRECISION_MILLISECOND:
modelPrecision = model.MILLISECOND
default:
return Time{}, fmt.Errorf("unsupported precision in Time with value %v %w", pb.GetPrecision(), datehelpers.ErrUnsupportedPrecision)
}
pbDate := pb.GetDate()
return Time{Date: time.Date(0, time.January, 1, int(pbDate.GetHours()), int(pbDate.GetMinutes()), int(pbDate.GetSeconds()), int(pbDate.GetNanos()), time.UTC), Precision: modelPrecision}, nil
}
// Interval is the Golang representation of a CQL Interval.
type Interval struct {
Low Value
High Value
LowInclusive bool
HighInclusive bool
// StaticType is used for the RuntimeType() of the interval when the interval contains
// only runtime nulls (meaning the runtime type cannot be reliably inferred).
StaticType *types.Interval // Field not exported.
}
// Equal returns true if this Interval matches the provided one, otherwise false.
func (i Interval) Equal(v Interval) bool {
if !i.StaticType.Equal(v.StaticType) {
return false
}
if !i.Low.Equal(v.Low) || !i.High.Equal(v.High) || i.LowInclusive != v.LowInclusive || i.HighInclusive != v.HighInclusive || !i.StaticType.Equal(v.StaticType) {
return false
}
return true
}
// Proto converts Interval to a proto.
func (i Interval) Proto() (*crpb.Interval, error) {
typepb, err := i.StaticType.Proto()
if err != nil {
return nil, err
}
pbInterval := &crpb.Interval{StaticType: typepb}
pbInterval.Low, err = i.Low.Proto()
if err != nil {
return nil, err
}
pbInterval.High, err = i.High.Proto()
if err != nil {
return nil, err
}
pbInterval.LowInclusive = proto.Bool(i.LowInclusive)
pbInterval.HighInclusive = proto.Bool(i.HighInclusive)
return pbInterval, nil
}
// IntervalFromProto converts a proto to an Interval.
func IntervalFromProto(pb *crpb.Interval) (Interval, error) {
typ, err := types.IntervalFromProto(pb.GetStaticType())
if err != nil {
return Interval{}, err
}
low, err := NewFromProto(pb.Low)
if err != nil {
return Interval{}, err
}
high, err := NewFromProto(pb.High)
if err != nil {
return Interval{}, err
}
return Interval{Low: low, High: high, LowInclusive: pb.GetLowInclusive(), HighInclusive: pb.GetHighInclusive(), StaticType: typ}, nil
}
func inferIntervalType(i Interval) types.IType {
if !IsNull(i.Low) {
return &types.Interval{PointType: i.Low.RuntimeType()}
}
if !IsNull(i.High) {
return &types.Interval{PointType: i.High.RuntimeType()}
}
// Fallback to static type
return i.StaticType
}
func (i Interval) marshalJSON(t json.RawMessage) ([]byte, error) {
low, err := i.Low.MarshalJSON()
if err != nil {
return nil, err
}
high, err := i.High.MarshalJSON()
if err != nil {
return nil, err
}
return json.Marshal(struct {
Type json.RawMessage `json:"@type"`
Low json.RawMessage `json:"low"`
High json.RawMessage `json:"high"`
LowInclusive bool `json:"lowClosed"`
HighInclusive bool `json:"highClosed"`
}{
Type: t,
Low: low,
High: high,
LowInclusive: i.LowInclusive,
HighInclusive: i.HighInclusive,
})
}
// List is the Golang representation of a CQL List.
type List struct {
Value []Value
// StaticType is used for the RuntimeType() of the list when the list is empty.
StaticType *types.List
}
// Proto converts List to a proto.
func (l List) Proto() (*crpb.List, error) {
typepb, err := l.StaticType.Proto()
if err != nil {
return nil, err
}
pbList := &crpb.List{StaticType: typepb}
for _, v := range l.Value {
pb, err := v.Proto()
if err != nil {
return nil, err
}
pbList.Value = append(pbList.Value, pb)
}
return pbList, nil
}
// ListFromProto converts a proto to a List.
func ListFromProto(pb *crpb.List) (List, error) {
l := List{Value: make([]Value, 0, len(pb.Value))}
typ, err := types.ListFromProto(pb.GetStaticType())
if err != nil {
return List{}, err
}
l.StaticType = typ
for _, pbv := range pb.Value {
v, err := NewFromProto(pbv)
if err != nil {
return List{}, err
}
l.Value = append(l.Value, v)
}
return l, nil
}
// Equal returns true if this List matches the provided one, otherwise false.
func (l List) Equal(v List) bool {
if !l.StaticType.Equal(v.StaticType) {
return false
}
if len(l.Value) != len(v.Value) {
return false
}
for idx, obj := range l.Value {
if !obj.Equal(v.Value[idx]) {
return false
}
}
return true
}
func inferListType(l []Value, staticType types.IType) types.IType {
// The parser should have already done type inference and conversions according to
// https://cql.hl7.org/03-developersguide.html#literals-and-selectors, if necessary for a List
// literal without a type specifier.
//
// There are a few cases to inferring the list type:
// 1. If the list is empty, we fall back to the static type.
// 2. We return the first non-null element from the list so that we can support lists that contain
// nulls. Mixed lists are still not fully supported.
// 3. If the list contains only nulls, return the runtime type of the first null.
// TODO(b/326277425): support mixed lists that may have a choice result type.
if len(l) == 0 {
// Because we fall back to a static type, this might be a choice type, even though mixed lists
// are not fully supported yet.
return staticType
}
for _, v := range l {
t := v.RuntimeType()
if t != types.Any {
return &types.List{ElementType: t}
}
}
return &types.List{ElementType: l[0].RuntimeType()}
}
// Named is the Golang representation fo a CQL Class (aka a CQL Named Structured Value). This could
// be any type defined in the Data Model like a FHIR.Encounter.
type Named struct {
Value proto.Message
// RuntimeType is the runtime type of this proto message value. Often times this is just the
// same as the static named type, but in some cases (e.g. Choice types) the caller should resolve
// this to the specific runtime type.
RuntimeType *types.Named
}
// Proto converts Named to a proto.
func (n Named) Proto() (*crpb.Named, error) {
a, err := anypb.New(n.Value)
if err != nil {
return nil, err
}
typepb, err := n.RuntimeType.Proto()
if err != nil {
return nil, err
}
return &crpb.Named{
Value: a,
RuntimeType: typepb,
}, nil
}
// NamedFromProto converts a proto to a Named.
func NamedFromProto(pb *crpb.Named) (Named, error) {
return Named{}, errors.New("currently do not support converting a proto named type back into a golang value")
}