forked from godror/godror
-
Notifications
You must be signed in to change notification settings - Fork 1
/
obj.go
1268 lines (1171 loc) · 34 KB
/
obj.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 2017, 2022 The Godror Authors
//
//
// SPDX-License-Identifier: UPL-1.0 OR Apache-2.0
package godror
/*
#include <stdlib.h>
#include "dpiImpl.h"
*/
import "C"
import (
"bufio"
"bytes"
"context"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"io"
"reflect"
"runtime"
"sort"
"strings"
"sync"
"unsafe"
"github.com/godror/godror/slog"
)
const (
warnMissingObjectClose = true
closeObjectWithFinalizer = false
)
var _ = fmt.Printf
// Object represents a dpiObject.
type Object struct {
dpiObject *C.dpiObject
*ObjectType
}
// ErrNoSuchKey is the error for missing key in lookup.
var ErrNoSuchKey = errors.New("no such key")
// GetAttribute gets the i-th attribute into data.
func (O *Object) GetAttribute(data *Data, name string) error {
if O == nil {
panic("nil Object")
}
attr, ok := O.Attributes[name]
if !ok {
return fmt.Errorf("get %s[%s]: %w (have: %q)", O.Name, name, ErrNoSuchKey, O.AttributeNames())
}
data.reset()
data.NativeTypeNum = attr.NativeTypeNum
data.ObjectType = attr.ObjectType
data.implicitObj = true
if O.dpiObject == nil {
data.SetNull()
return nil
}
// the maximum length of that buffer must be supplied
// in the value.asBytes.length attribute before calling this function.
if attr.NativeTypeNum == C.DPI_NATIVE_TYPE_BYTES && attr.OracleTypeNum == C.DPI_ORACLE_TYPE_NUMBER {
var a [39]byte
C.dpiData_setBytes(&data.dpiData, (*C.char)(unsafe.Pointer(&a[0])), C.uint32_t(len(a)))
}
//fmt.Printf("getAttributeValue(%p, %p, %d, %+v)\n", O.dpiObject, attr.dpiObjectAttr, data.NativeTypeNum, data.dpiData)
if err := O.drv.checkExec(func() C.int {
return C.dpiObject_getAttributeValue(O.dpiObject, attr.dpiObjectAttr, data.NativeTypeNum, &data.dpiData)
}); err != nil {
return fmt.Errorf("getAttributeValue(%q, obj=%s, attr=%+v, typ=%d): %w", name, O.Name, attr.dpiObjectAttr, data.NativeTypeNum, err)
}
if logger := getLogger(context.TODO()); logger != nil && logger.Enabled(context.TODO(), slog.LevelDebug) {
logger.Debug("getAttributeValue", "dpiObject", fmt.Sprintf("%p", O.dpiObject),
attr.Name, fmt.Sprintf("%p", attr.dpiObjectAttr),
"nativeType", data.NativeTypeNum, "oracleType", attr.OracleTypeNum,
"p", fmt.Sprintf("%p", data))
}
return nil
}
// SetAttribute sets the named attribute with data.
func (O *Object) SetAttribute(name string, data *Data) error {
if !strings.Contains(name, `"`) {
name = strings.ToUpper(name)
}
attr, ok := O.Attributes[name]
if !ok {
return fmt.Errorf("set %s[%s]: %w (have: %q)", O, name, ErrNoSuchKey, O.AttributeNames())
}
if data.NativeTypeNum == 0 {
if logger := getLogger(context.TODO()); logger != nil && logger.Enabled(context.TODO(), slog.LevelWarn) {
logger.Warn("WARN setAttributeValue", "attr.NativeTypeNum", attr.NativeTypeNum, "data.NativeTypeNum", data.NativeTypeNum)
}
data.NativeTypeNum = attr.NativeTypeNum
data.ObjectType = attr.ObjectType
data.dpiData.isNull = 1
}
if err := O.drv.checkExec(func() C.int {
return C.dpiObject_setAttributeValue(O.dpiObject, attr.dpiObjectAttr, data.NativeTypeNum, &data.dpiData)
}); err != nil {
return fmt.Errorf("dpiObject_setAttributeValue NativeTypeNum=%d ObjectType=%v: %w", data.NativeTypeNum, data.ObjectType, err)
}
return nil
}
// Set is a convenience function to set the named attribute with the given value.
func (O *Object) Set(name string, v interface{}) error {
if data, ok := v.(*Data); ok {
return O.SetAttribute(name, data)
}
d := scratch.Get()
defer scratch.Put(d)
if err := d.Set(v); err != nil {
return err
}
return O.SetAttribute(name, d)
}
// ResetAttributes prepare all attributes for use the object as IN parameter
func (O *Object) ResetAttributes() error {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
data := scratch.Get()
defer scratch.Put(data)
for _, attr := range O.Attributes {
data.reset()
data.NativeTypeNum = attr.NativeTypeNum
data.ObjectType = attr.ObjectType
if attr.NativeTypeNum == C.DPI_NATIVE_TYPE_BYTES && attr.OracleTypeNum == C.DPI_ORACLE_TYPE_NUMBER {
a := make([]byte, attr.Precision)
C.dpiData_setBytes(&data.dpiData, (*C.char)(unsafe.Pointer(&a[0])), C.uint32_t(attr.Precision))
}
if C.dpiObject_setAttributeValue(O.dpiObject, attr.dpiObjectAttr, data.NativeTypeNum, &data.dpiData) == C.DPI_FAILURE {
return O.drv.getError()
}
}
return nil
}
// Get scans the named attribute into dest, and returns it.
func (O *Object) Get(name string) (interface{}, error) {
d := scratch.Get()
defer scratch.Put(d)
if err := O.GetAttribute(d, name); err != nil {
return nil, err
}
isObject := d.IsObject()
ot := O.Attributes[name].ObjectType
if isObject {
d.ObjectType = ot
}
v := d.Get()
if !isObject {
return maybeString(v, ot), nil
}
sub := v.(*Object)
if sub != nil && sub.ObjectType.CollectionOf != nil {
return &ObjectCollection{Object: sub}, nil
}
return sub, nil
}
func maybeString(v interface{}, ot *ObjectType) interface{} {
switch ot.OracleTypeNum {
case C.DPI_ORACLE_TYPE_VARCHAR, C.DPI_ORACLE_TYPE_NVARCHAR,
C.DPI_ORACLE_TYPE_CHAR, C.DPI_ORACLE_TYPE_NCHAR,
C.DPI_ORACLE_TYPE_NUMBER,
C.DPI_ORACLE_TYPE_CLOB, C.DPI_ORACLE_TYPE_NCLOB,
C.DPI_ORACLE_TYPE_LONG_VARCHAR, C.DPI_ORACLE_TYPE_LONG_NVARCHAR:
if b, ok := v.([]byte); ok {
return string(b)
}
}
return v
}
// ObjectRef implements userType interface.
func (O *Object) ObjectRef() *Object {
return O
}
// Collection returns &ObjectCollection{Object: O} iff the Object is a collection.
// Otherwise it returns nil.
func (O *Object) Collection() ObjectCollection {
if O.ObjectType.CollectionOf == nil {
return ObjectCollection{}
}
return ObjectCollection{Object: O}
}
// Close releases a reference to the object.
func (O *Object) Close() error {
if O == nil {
return nil
}
obj := O.dpiObject
O.dpiObject = nil
if obj == nil {
return nil
}
logger := getLogger(context.TODO())
if logger != nil && logger.Enabled(context.TODO(), slog.LevelDebug) {
logger.Debug("Object.Close", "object", fmt.Sprintf("%p", obj))
}
// Close sub-objects first
for _, a := range O.Attributes {
if !a.IsObject() {
continue
}
if err := func() error {
data := scratch.Get()
defer scratch.Put(data)
if err := O.GetAttribute(data, a.Name); err != nil {
return fmt.Errorf("get attribute %q: %w", a.Name, err)
}
obj := data.GetObject()
if obj == nil {
return nil
}
if logger != nil && logger.Enabled(context.TODO(), slog.LevelInfo) {
logger.Info("Object.Close close sub-object", "attribute", a.Name, "object", fmt.Sprintf("%p", obj))
}
return obj.Close()
}(); err != nil && logger != nil {
logger.Error("Close sub-object", "name", a.Name, "error", err)
}
}
// Reset all attributes
O.ResetAttributes()
if err := O.drv.checkExec(func() C.int { return C.dpiObject_release(obj) }); err != nil {
return fmt.Errorf("error on close object: %w", err)
}
return nil
}
// AsMap is a convenience function that returns the object's attributes as a map[string]interface{}.
// It allocates, so use it as a guide how to implement your own converter function.
//
// If recursive is true, then the embedded objects are converted, too, recursively.
func (O *Object) AsMap(recursive bool) (map[string]interface{}, error) {
if O == nil || O.dpiObject == nil {
return nil, nil
}
logger := getLogger(context.TODO())
m := make(map[string]interface{}, len(O.ObjectType.Attributes))
data := scratch.Get()
defer scratch.Put(data)
for a, ot := range O.ObjectType.Attributes {
if err := O.GetAttribute(data, a); err != nil {
return m, fmt.Errorf("%q: %w", a, err)
}
d := data.Get()
if d == nil {
continue
}
if !data.IsObject() {
d = maybeString(d, ot.ObjectType)
}
m[a] = d
if logger != nil && logger.Enabled(context.TODO(), slog.LevelDebug) {
logger.Debug("AsMap", "attribute", a, "data", fmt.Sprintf("%#v", d), "type", fmt.Sprintf("%T", d), "recursive", recursive)
}
if !recursive {
continue
}
if sub, ok := d.(*Object); ok && sub != nil && sub.ObjectType != nil {
var err error
if sub.ObjectType.CollectionOf == nil {
if m[a], err = sub.AsMap(recursive); err != nil {
return m, fmt.Errorf("%q.AsMap: %w", a, err)
}
continue
}
if sub.ObjectType.CollectionOf.Attributes == nil {
if m[a], err = sub.Collection().AsSlice(nil); err != nil {
return m, fmt.Errorf("%q.AsSlice: %w", a, err)
}
} else if m[a], err = sub.Collection().AsMapSlice(recursive); err != nil {
return m, fmt.Errorf("%q.AsMapSlice: %w", a, err)
}
}
}
return m, nil
}
// ToJSON writes the Object as JSON into the io.Writer.
func (O *Object) ToJSON(w io.Writer) error {
if O == nil || O.ObjectType == nil {
_, err := io.WriteString(w, "nil")
return err
}
if O.ObjectType.CollectionOf != nil {
return O.Collection().ToJSON(w)
}
bw := bufio.NewWriter(w)
defer bw.Flush()
if err := bw.WriteByte('{'); err != nil {
return err
}
data := scratch.Get()
defer scratch.Put(data)
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
keys := make([]string, 0, len(O.ObjectType.Attributes))
for a := range O.ObjectType.Attributes {
keys = append(keys, a)
}
sort.Strings(keys)
for i, a := range keys {
if err := O.GetAttribute(data, a); err != nil {
return fmt.Errorf("%q: %w", a, err)
}
if i != 0 {
if err := bw.WriteByte(','); err != nil {
return err
}
}
fmt.Fprintf(bw, "%q:", a)
d := data.Get()
if data.IsObject() {
if err := d.(*Object).ToJSON(bw); err != nil {
return fmt.Errorf("%q: %w", a, err)
}
continue
}
d = maybeString(d, O.ObjectType.Attributes[a].ObjectType)
buf.Reset()
if err := enc.Encode(d); err != nil {
return fmt.Errorf("%q: %#v: %w", a, d, err)
}
if _, err := bw.Write(bytes.TrimSpace(buf.Bytes())); err != nil {
return fmt.Errorf("%q: %w", a, err)
}
}
return bw.WriteByte('}')
}
func (O *Object) String() string {
if O == nil {
return ""
}
var buf strings.Builder
_, _ = buf.WriteString(O.ObjectType.String())
_ = O.ToJSON(&buf)
return buf.String()
}
// ObjectCollection represents a Collection of Objects - itself an Object, too.
type ObjectCollection struct {
*Object
}
// ErrNotCollection is returned when the Object is not a collection.
var ErrNotCollection = errors.New("not collection")
// ErrNotExist is returned when the collection's requested element does not exist.
var ErrNotExist = errors.New("not exist")
// AsMapSlice retrieves the collection into a []map[string]interface{}.
// If recursive is true, then all subsequent Objects/ObjectsCollections are translated.
//
// This is horrendously inefficient, use it only as a guide!
func (O ObjectCollection) AsMapSlice(recursive bool) ([]map[string]interface{}, error) {
length, err := O.Len()
if err != nil {
return nil, fmt.Errorf("Len: %w", err)
}
m := make([]map[string]interface{}, 0, length)
for curr, err := O.First(); err == nil; curr, err = O.Next(curr) {
if v, err := O.Get(curr); err != nil {
return m, fmt.Errorf("Get(%v): %w", curr, err)
} else if v == nil {
m = append(m, nil)
} else if o, ok := v.(*Object); ok {
r, err := o.AsMap(recursive)
if err != nil {
return m, fmt.Errorf("[%d](%v).AsMap: %w", curr, v, err)
}
m = append(m, r)
}
}
return m, nil
}
// FromSlice read from a slice of primitives.
func (O ObjectCollection) FromSlice(v []interface{}) error {
if O.dpiObject == nil {
return nil
}
logger := getLogger(context.TODO())
data := scratch.Get()
for i, o := range v {
if logger != nil {
logger.Debug("FromSlice", "index", i)
}
if err := data.Set(o); err != nil {
return err
}
if err := O.AppendData(data); err != nil {
return err
}
}
return nil
}
// FromMap populates the Object starting from a map, according to the Object's Attributes.
func (O *Object) FromMap(recursive bool, m map[string]interface{}) error {
if O == nil || O.dpiObject == nil {
return nil
}
logger := getLogger(context.TODO())
for a, ot := range O.ObjectType.Attributes {
v := m[a]
if v == nil {
continue
}
if logger != nil && logger.Enabled(context.TODO(), slog.LevelDebug) {
logger.Debug("FromMap", "attribute", a, "value", v, "type", fmt.Sprintf("%T", v), "recursive", recursive, "ot", ot.ObjectType)
}
if ot.ObjectType.CollectionOf != nil { // Collection case
if err := func() error {
coll, err := ot.NewCollection()
if err != nil {
return fmt.Errorf("%q.FromMap: %w", a, err)
}
defer coll.Close()
switch v := v.(type) {
case []map[string]interface{}:
if err := coll.FromMapSlice(recursive, v); err != nil {
return fmt.Errorf("%q.FromMapSlice: %w", a, err)
}
case []interface{}:
if ot.IsObject() {
m := make([]map[string]interface{}, 0, len(v))
for _, e := range v {
m = append(m, e.(map[string]interface{}))
}
if err := coll.FromMapSlice(recursive, m); err != nil {
return fmt.Errorf("%q.FromMapSlice: %w", a, err)
}
} else {
data := scratch.Get()
defer scratch.Put(data)
for _, e := range v {
if err := data.Set(e); err != nil {
return err
}
if err := coll.AppendData(data); err != nil {
return err
}
}
}
default:
return fmt.Errorf("%q is a collection, needs []interface{} or []map[string]interface{}, got %T", a, v)
}
if err = O.Set(a, coll); err != nil {
return fmt.Errorf("%q.Set(%v): %w", a, coll, err)
}
return nil
}(); err != nil {
return err
}
} else if ot.ObjectType.Attributes != nil { // Object case
newO, err := ot.NewObject()
if err != nil {
return fmt.Errorf("%q.FromMap: %w", a, err)
}
if err := newO.FromMap(recursive, v.(map[string]interface{})); err != nil {
newO.Close()
return fmt.Errorf("%q.FromMap: %w", a, err)
}
err = O.Set(a, newO)
newO.Close()
if err != nil {
return fmt.Errorf("%q.Set(%v): %w", a, newO.ObjectType, err)
}
} else if err := O.Set(a, v); err != nil { // Plain type case
return err
}
}
return nil
}
func (O *Object) FromJSON(dec *json.Decoder) error {
tok, err := dec.Token()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
wantDelim := tok == json.Delim('{')
logger := getLogger(context.TODO())
first := true
for {
if first && wantDelim || !first {
first = false
if tok, err = dec.Token(); err != nil {
if err == io.EOF {
break
}
return err
}
}
k, ok := tok.(string)
if !ok {
return fmt.Errorf("wanted key (string), got %v (%T)", tok, tok)
}
k = strings.ToUpper(k)
a, ok := O.ObjectType.Attributes[k]
if logger != nil && logger.Enabled(context.TODO(), slog.LevelDebug) {
logger.Debug("attribute", "k", k, "a", a)
}
if !ok {
return fmt.Errorf("key %q not found", k)
}
var v interface{}
var C func() error
if a.ObjectType.CollectionOf != nil {
coll, err := a.ObjectType.NewCollection()
if err != nil {
return fmt.Errorf("%q.%s.NewCollection: %w", k, a.ObjectType, err)
}
if err = coll.FromJSON(dec); err != nil {
return fmt.Errorf("%q.FromJSON: %w", k, err)
}
v = coll
C = coll.Close
} else if a.ObjectType.IsObject() {
obj, err := a.ObjectType.NewObject()
if err != nil {
return fmt.Errorf("%q.%s.NewObject: %w", k, a.ObjectType, err)
}
if err = obj.FromJSON(dec); err != nil {
return fmt.Errorf("%q.FromJSON: %w", k, err)
}
v = obj
C = obj.Close
} else {
if tok, err = dec.Token(); err != nil {
return err
}
v = tok
}
err = O.Set(k, v)
if C != nil {
if closeErr := C(); err == nil {
err = closeErr
}
}
if err != nil {
return fmt.Errorf("%q.Set(%v): %w", k, v, err)
}
if !dec.More() {
break
}
}
if wantDelim {
_, err = dec.Token()
}
return err
}
// FromMapSlice populates the ObjectCollection starting from a slice of map, according to the Collections's Attributes.
func (O ObjectCollection) FromMapSlice(recursive bool, m []map[string]interface{}) error {
if O.dpiObject == nil {
return nil
}
logger := getLogger(context.TODO())
for i, o := range m {
if logger != nil && logger.Enabled(context.TODO(), slog.LevelDebug) {
logger.Debug("FromMapSlice", "index", i, "recursive", recursive)
}
elt, err := O.ObjectType.CollectionOf.NewObject()
if err != nil {
return fmt.Errorf("%d.FromMapSlice: %w", i, err)
}
if err := elt.FromMap(recursive, o); err != nil {
elt.Close()
return fmt.Errorf("%d.FromMapSlice: %w", i, err)
}
err = O.Append(elt)
elt.Close()
if err != nil {
return err
}
}
return nil
}
func (O ObjectCollection) FromJSON(dec *json.Decoder) error {
tok, err := dec.Token()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
wantDelim := tok == json.Delim('[')
for {
elt, err := O.ObjectType.CollectionOf.NewObject()
if err != nil {
return err
}
err = elt.FromJSON(dec)
if err != nil {
elt.Close()
return err
}
err = O.Append(elt)
elt.Close()
if err != nil {
return err
}
if !dec.More() {
break
}
}
if wantDelim {
_, err = dec.Token()
}
return err
}
// AsSlice retrieves the collection into a slice.
func (O ObjectCollection) AsSlice(dest interface{}) (interface{}, error) {
var dr reflect.Value
needsInit := dest == nil
if !needsInit {
dr = reflect.ValueOf(dest)
}
d := scratch.Get()
defer scratch.Put(d)
for i, err := O.First(); err == nil; i, err = O.Next(i) {
if O.CollectionOf.IsObject() {
d.ObjectType = O.CollectionOf
}
if err = O.GetItem(d, i); err != nil {
return dest, err
}
v := d.Get()
if !d.IsObject() {
v = maybeString(v, O.CollectionOf)
}
vr := reflect.ValueOf(v)
if needsInit {
needsInit = false
length, lengthErr := O.Len()
if lengthErr != nil {
return dr.Interface(), lengthErr
}
dr = reflect.MakeSlice(reflect.SliceOf(vr.Type()), 0, length)
}
dr = reflect.Append(dr, vr)
}
if !dr.IsValid() {
return nil, nil
}
return dr.Interface(), nil
}
// ToJSON writes the ObjectCollection as JSON to the io.Writer.
func (O ObjectCollection) ToJSON(w io.Writer) error {
var notFirst bool
bw := bufio.NewWriter(w)
defer bw.Flush()
if err := bw.WriteByte('['); err != nil {
return err
}
for curr, err := O.First(); err == nil; curr, err = O.Next(curr) {
if notFirst {
if err = bw.WriteByte(','); err != nil {
return err
}
} else {
notFirst = true
}
if v, err := O.Get(curr); err != nil {
return fmt.Errorf("Get(%v): %w", curr, err)
} else if v == nil {
if _, err = bw.WriteString("nil"); err != nil {
return err
}
} else if o, ok := v.(*Object); ok {
if err = o.ToJSON(bw); err != nil {
return err
}
}
}
return bw.WriteByte(']')
}
func (O ObjectCollection) String() string {
if O.Object == nil {
return ""
}
var buf strings.Builder
_, _ = buf.WriteString(O.Object.ObjectType.String())
_ = O.ToJSON(&buf)
return buf.String()
}
// AppendData to the collection.
func (O ObjectCollection) AppendData(data *Data) error {
if err := O.drv.checkExec(func() C.int {
return C.dpiObject_appendElement(O.dpiObject, data.NativeTypeNum, &data.dpiData)
}); err != nil {
return fmt.Errorf("append(%d): %w", data.NativeTypeNum, err)
}
return nil
}
// Append v to the collection.
func (O ObjectCollection) Append(v interface{}) error {
if data, ok := v.(*Data); ok {
return O.AppendData(data)
}
d := scratch.Get()
defer scratch.Put(d)
if err := d.Set(v); err != nil {
return err
}
return O.AppendData(d)
}
// AppendObject adds an Object to the collection.
func (O ObjectCollection) AppendObject(obj *Object) error {
d := scratch.Get()
defer scratch.Put(d)
d.ObjectType = obj.ObjectType
d.NativeTypeNum = C.DPI_NATIVE_TYPE_OBJECT
d.SetObject(obj)
return O.Append(d)
}
// Delete i-th element of the collection.
func (O ObjectCollection) Delete(i int) error {
if err := O.drv.checkExec(func() C.int {
return C.dpiObject_deleteElementByIndex(O.dpiObject, C.int32_t(i))
}); err != nil {
return fmt.Errorf("delete(%d): %w", i, err)
}
return nil
}
// GetItem gets the i-th element of the collection into data.
func (O ObjectCollection) GetItem(data *Data, i int) error {
if data == nil {
panic("data cannot be nil")
}
runtime.LockOSThread()
defer runtime.UnlockOSThread()
idx := C.int32_t(i)
var exists C.int
if C.dpiObject_getElementExistsByIndex(O.dpiObject, idx, &exists) == C.DPI_FAILURE {
return fmt.Errorf("exists(%d): %w", idx, O.drv.getError())
}
if exists == 0 {
return ErrNotExist
}
data.reset()
data.ObjectType = O.CollectionOf
if O.CollectionOf != nil {
data.NativeTypeNum = O.CollectionOf.NativeTypeNum
data.implicitObj = true
}
if C.dpiObject_getElementValueByIndex(O.dpiObject, idx, data.NativeTypeNum, &data.dpiData) == C.DPI_FAILURE {
return fmt.Errorf("get(%d[%d]): %w", idx, data.NativeTypeNum, O.drv.getError())
}
return nil
}
// Get the i-th element of the collection.
func (O ObjectCollection) Get(i int) (interface{}, error) {
data := scratch.Get()
defer scratch.Put(data)
err := O.GetItem(data, i)
return data.Get(), err
}
// SetItem sets the i-th element of the collection with data.
func (O ObjectCollection) SetItem(i int, data *Data) error {
if err := O.drv.checkExec(func() C.int {
return C.dpiObject_setElementValueByIndex(O.dpiObject, C.int32_t(i), data.NativeTypeNum, &data.dpiData)
}); err != nil {
return fmt.Errorf("set(%d[%d]): %w", i, data.NativeTypeNum, err)
}
return nil
}
// Set the i-th element of the collection with value.
func (O ObjectCollection) Set(i int, v interface{}) error {
if data, ok := v.(*Data); ok {
return O.SetItem(i, data)
}
d := scratch.Get()
defer scratch.Put(d)
if err := d.Set(v); err != nil {
return err
}
return O.SetItem(i, d)
}
// First returns the first element's index of the collection.
func (O ObjectCollection) First() (int, error) {
var exists C.int
var idx C.int32_t
if err := O.drv.checkExec(func() C.int {
return C.dpiObject_getFirstIndex(O.dpiObject, &idx, &exists)
}); err != nil {
return 0, fmt.Errorf("first: %w", err)
}
if exists == 1 {
return int(idx), nil
}
return 0, ErrNotExist
}
// Last returns the index of the last element.
func (O ObjectCollection) Last() (int, error) {
var exists C.int
var idx C.int32_t
if err := O.drv.checkExec(func() C.int {
return C.dpiObject_getLastIndex(O.dpiObject, &idx, &exists)
}); err != nil {
return 0, fmt.Errorf("last: %w", err)
}
if exists == 1 {
return int(idx), nil
}
return 0, ErrNotExist
}
// Next returns the succeeding index of i.
func (O ObjectCollection) Next(i int) (int, error) {
var exists C.int
var idx C.int32_t
if err := O.drv.checkExec(func() C.int {
return C.dpiObject_getNextIndex(O.dpiObject, C.int32_t(i), &idx, &exists)
}); err != nil {
return 0, fmt.Errorf("next(%d): %w", i, err)
}
if exists == 1 {
return int(idx), nil
}
return 0, ErrNotExist
}
// Len returns the length of the collection.
func (O ObjectCollection) Len() (int, error) {
var size C.int32_t
if err := O.drv.checkExec(func() C.int { return C.dpiObject_getSize(O.dpiObject, &size) }); err != nil {
return 0, fmt.Errorf("len: %w", err)
}
return int(size), nil
}
// Trim the collection to n.
func (O ObjectCollection) Trim(n int) error {
return O.drv.checkExec(func() C.int { return C.dpiObject_trim(O.dpiObject, C.uint32_t(n)) })
}
// ObjectType holds type info of an Object.
type ObjectType struct {
CollectionOf *ObjectType
Attributes map[string]ObjectAttribute
drv *drv
dpiObjectType *C.dpiObjectType
Schema, Name, PackageName string
Annotations []Annotation
DBSize, ClientSizeInBytes, CharSize int
mu sync.RWMutex
OracleTypeNum C.dpiOracleTypeNum
NativeTypeNum C.dpiNativeTypeNum
DomainAnnotation
Precision int16
Scale int8
FsPrecision uint8
}
// AttributeNames returns the Attributes' names ordered as on the database (by ObjectAttribute.Sequence).
func (t *ObjectType) AttributeNames() []string {
if t == nil {
return nil
}
names := make([]string, len(t.Attributes))
for k, v := range t.Attributes {
names[v.Sequence] = k
}
return names
}
func (t *ObjectType) String() string {
if t == nil {
return ""
}
if t.Schema == "" {
return t.Name
}
return t.Schema + "." + t.Name
}
func (t *ObjectType) IsObject() bool { return t != nil && t.NativeTypeNum == C.DPI_NATIVE_TYPE_OBJECT }
// FullName returns the object's name with the schame prepended.
func (t *ObjectType) FullName() string {
if t == nil {
return ""
}
if t.Schema == "" {
return t.Name
}
return t.Schema + "." + t.Name
}
// GetObjectType returns the ObjectType of a name.
//
// The name is uppercased! Because here Oracle seems to be case-sensitive.
// To leave it as is, enclose it in "-s!
func (c *conn) GetObjectType(name string) (*ObjectType, error) {
if !strings.Contains(name, "\"") {
name = strings.ToUpper(name)
}
if name == "" {
return nil, errors.New("empty name")
}
c.mu.RLock()
defer c.mu.RUnlock()
if c.dpiConn == nil {
return nil, driver.ErrBadConn
}
if t := c.objTypes[name]; t != nil {
if t.drv != nil {
//fmt.Println("GetObjectType CACHED", name)
return t, nil
}
//fmt.Printf("GetObjectType(%q) %p is CLOSED on %p\n", name, t, c)
// t is closed
delete(c.objTypes, name)
delete(c.objTypes, t.FullName())
}
objType := (*C.dpiObjectType)(C.malloc(C.sizeof_void))
cName := C.CString(name)
err := c.checkExec(func() C.int {
return C.dpiConn_getObjectType(c.dpiConn, cName, C.uint32_t(len(name)), &objType)
})
C.free(unsafe.Pointer(cName))
if err != nil {
C.free(unsafe.Pointer(objType))
if strings.Contains(err.Error(), "DPI-1062: unexpected OCI return value 1041 in function dpiConn_getObjectType") {
err = fmt.Errorf("getObjectType(%q) conn=%p: %+v: %w", name, c.dpiConn, err, driver.ErrBadConn)
_ = c.closeNotLocking()
return nil, err
}
return nil, fmt.Errorf("getObjectType(%q) conn=%p: %w", name, c.dpiConn, err)
}
t := &ObjectType{drv: c.drv, dpiObjectType: objType}
if err = t.init(c.objTypes); err != nil {
return t, err
}
if name != t.FullName() {
c.objTypes[name] = t
}
//fmt.Printf("GetObjectType(%q/%q) NEW: %p\n", name, t.FullName(), t)
return t, nil
}
var errNilObjectType = errors.New("ObjectType is nil")
// NewObject returns a new Object with ObjectType type.
//
// As with all Objects, you MUST call Close on it when not needed anymore!
func (t *ObjectType) NewObject() (*Object, error) {
if t == nil {
return nil, errNilObjectType
}