This repository has been archived by the owner on Jan 18, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathclient_test.go
1599 lines (1301 loc) · 54.2 KB
/
client_test.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 orient_test
import (
"fmt"
"log"
"math/rand"
"os"
"os/exec"
"runtime"
"runtime/debug"
"sort"
"strings"
"sync"
"testing"
"time"
"gopkg.in/istreamdata/orientgo.v2"
)
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
func catch(t testing.TB) {
if r := recover(); r != nil {
t.Fatalf("panic recovery: %v\nTrace:\n%s\n", r, debug.Stack())
}
}
func notShort(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
}
func TestFDLeak(t *testing.T) {
if runtime.GOOS != "linux" {
t.SkipNow()
}
openedFDs := func() int {
out, err := exec.Command("lsof", "-p", fmt.Sprint(os.Getpid())).Output()
if err != nil {
t.Fatal(err)
}
return strings.Count(string(out), "\n") - 1
}
addr, rm := SpinOrientServer(t)
defer rm()
leak := func() {
client, err := orient.Dial(addr)
if err != nil {
t.Fatal(err)
}
defer func() {
if err := client.Close(); err != nil {
t.Fatal(err)
}
}()
dbName := "leak_test"
admin, err := client.Auth(srvUser, srvPass)
if err != nil {
t.Fatal(err)
}
if ok, _ := admin.DatabaseExists(dbName, orient.Persistent); !ok {
err = admin.CreateDatabase(dbName, orient.GraphDB, orient.Persistent)
if err != nil {
t.Fatal(err)
}
}
db, err := client.Open(dbName, orient.GraphDB, dbUser, dbPass)
if err != nil {
t.Fatal(err)
}
// Closing Database session pool
defer func() {
if err := db.Close(); err != nil {
t.Fatal(err)
}
}()
}
fds := openedFDs()
for i := 0; i < 1; i++ {
leak()
}
time.Sleep(time.Second)
if n := openedFDs(); n != fds {
t.Fatalf("leaked fd: %d != %d", n, fds)
}
}
func TestInitialize(t *testing.T) {
notShort(t)
dbc, closer := SpinOrient(t)
defer closer()
defer catch(t)
sess, err := dbc.Auth(srvUser, srvPass)
Nil(t, err)
// True(t, dbc.GetSessionId() >= int32(0), "sessionid")
// True(t, dbc.GetCurrDB() == nil, "currDB should be nil")
mapDBs, err := sess.ListDatabases()
Nil(t, err)
gratefulTestPath, ok := mapDBs["default"]
True(t, ok, "default not in DB list")
True(t, strings.HasPrefix(gratefulTestPath, "plocal"), "plocal prefix for db path")
dbexists, err := sess.DatabaseExists(dbDocumentName, orient.Persistent)
Nil(t, err)
True(t, !dbexists)
// err = dbc.CreateDatabase(dbc, dbDocumentName, constants.DocumentDbType, constants.Volatile)
err = sess.CreateDatabase(dbDocumentName, orient.DocumentDB, orient.Persistent)
Nil(t, err)
dbexists, err = sess.DatabaseExists(dbDocumentName, orient.Persistent)
Nil(t, err)
True(t, dbexists, dbDocumentName+" should now exists after creating it")
db, err := dbc.Open(dbDocumentName, orient.DocumentDB, "admin", "admin")
Nil(t, err)
SeedDB(t, db)
if orientVersion >= "2.1" { // error: Database 'plocal:/opt/orient/databases/ogonoriTest' is closed
mapDBs, err = sess.ListDatabases()
Nil(t, err)
ogonoriTestPath, ok := mapDBs[dbDocumentName]
True(t, ok, dbDocumentName+" not in DB list")
True(t, strings.HasPrefix(ogonoriTestPath, "plocal"), "plocal prefix for db path")
}
}
/*
// ---[ Use Go database/sql API on Document DB ]---
// conxStr := "admin@admin:localhost/" + dbDocumentName
// databaseSQLAPI(conxStr)
// databaseSQLPreparedStmtAPI(conxStr)
// ---[ Graph DB ]---
// graph database tests
// graphCommandsNativeAPI(dbc, testType != "dataOnly")
// graphConxStr := "admin@admin:localhost/" + dbGraphName
// graphCommandsSQLAPI(graphConxStr)
*/
func TestRecordsNativeAPIStructs(t *testing.T) {
notShort(t)
db, closer := SpinOrientAndOpenDB(t, false)
defer closer()
defer catch(t)
SeedDB(t, db)
type Cat struct {
Name string `mapstructure:"name"`
CareTaker string `mapstructure:"caretaker"`
Age int32 `mapstructure:"age"`
}
catWinston := Cat{
Name: "Winston",
CareTaker: "Churchill",
Age: 7,
}
// ---[ creation ]---
winston := orient.NewDocument("Cat")
err := winston.From(catWinston)
Nil(t, err)
Equals(t, -1, int(winston.RID.ClusterID))
Equals(t, -1, int(winston.RID.ClusterPos))
Equals(t, -1, int(winston.Vers))
err = db.CreateRecord(winston)
Nil(t, err)
True(t, int(winston.RID.ClusterID) > -1, "RID should be filled in")
True(t, int(winston.RID.ClusterPos) > -1, "RID should be filled in")
True(t, int(winston.Vers) > -1, "Version should be filled in")
// ---[ update STRING and INTEGER field ]---
versionBefore := winston.Vers
catWinston.CareTaker = "Lolly"
catWinston.Age = 8
err = winston.From(catWinston) // this updates the fields locally
Nil(t, err)
err = db.UpdateRecord(winston) // update the field in the remote DB
Nil(t, err)
True(t, versionBefore < winston.Vers, "version should have incremented")
var cats []Cat
err = db.Command(orient.NewSQLQuery("select * from Cat where @rid=" + winston.RID.String())).All(&cats)
Nil(t, err)
Equals(t, 1, len(cats))
winstonFromQuery := cats[0]
Equals(t, catWinston, winstonFromQuery)
// ---[ next creation ]---
catDaemon := Cat{Name: "Daemon", CareTaker: "Matt", Age: 4}
daemon := orient.NewDocument("Cat")
err = daemon.From(catDaemon)
Nil(t, err)
err = db.CreateRecord(daemon)
Nil(t, err)
catIndy := Cat{Name: "Indy", Age: 6}
indy := orient.NewDocument("Cat")
err = indy.From(catIndy)
Nil(t, err)
err = db.CreateRecord(indy)
Nil(t, err)
sql := fmt.Sprintf("select from Cat where @rid=%s or @rid=%s or @rid=%s ORDER BY name",
winston.RID, daemon.RID, indy.RID)
cats = nil
err = db.Command(orient.NewSQLQuery(sql)).All(&cats)
Nil(t, err)
Equals(t, 3, len(cats))
Equals(t, catDaemon, cats[0])
Equals(t, catIndy, cats[1])
Equals(t, catWinston, cats[2])
sql = fmt.Sprintf("DELETE FROM [%s, %s, %s]", winston.RID, daemon.RID, indy.RID)
err = db.Command(orient.NewSQLCommand(sql)).Err()
Nil(t, err)
}
func TestRecordsNativeAPI(t *testing.T) {
notShort(t)
db, closer := SpinOrientAndOpenDB(t, false)
defer closer()
defer catch(t)
SeedDB(t, db)
// ---[ creation ]---
winston := orient.NewDocument("Cat")
winston.SetField("name", "Winston").
SetField("caretaker", "Churchill").
SetFieldWithType("age", 7, orient.INTEGER)
Equals(t, -1, int(winston.RID.ClusterID))
Equals(t, -1, int(winston.RID.ClusterPos))
Equals(t, -1, int(winston.Vers))
err := db.CreateRecord(winston)
Nil(t, err)
True(t, int(winston.RID.ClusterID) > -1, "RID should be filled in")
True(t, int(winston.RID.ClusterPos) > -1, "RID should be filled in")
True(t, int(winston.Vers) > -1, "Version should be filled in")
// ---[ update STRING and INTEGER field ]---
versionBefore := winston.Vers
winston.SetField("caretaker", "Lolly") // this updates the field locally
winston.SetField("age", 8) // this updates the field locally
err = db.UpdateRecord(winston) // update the field in the remote DB
Nil(t, err)
True(t, versionBefore < winston.Vers, "version should have incremented")
var docs []*orient.Document
err = db.Command(orient.NewSQLQuery("select * from Cat where @rid=" + winston.RID.String())).All(&docs)
Nil(t, err)
Equals(t, 1, len(docs))
winstonFromQuery := docs[0]
Equals(t, "Winston", winstonFromQuery.GetField("name").Value)
Equals(t, 8, toInt(winstonFromQuery.GetField("age").Value))
Equals(t, "Lolly", winstonFromQuery.GetField("caretaker").Value)
// ---[ next creation ]---
daemon := orient.NewDocument("Cat")
daemon.SetField("name", "Daemon").SetField("caretaker", "Matt").SetField("age", 4)
err = db.CreateRecord(daemon)
Nil(t, err)
indy := orient.NewDocument("Cat")
indy.SetField("name", "Indy").SetField("age", 6)
err = db.CreateRecord(indy)
Nil(t, err)
sql := fmt.Sprintf("select from Cat where @rid=%s or @rid=%s or @rid=%s ORDER BY name",
winston.RID, daemon.RID, indy.RID)
docs = nil
err = db.Command(orient.NewSQLQuery(sql)).All(&docs)
Nil(t, err)
Equals(t, 3, len(docs))
Equals(t, daemon.RID, docs[0].RID)
Equals(t, indy.RID, docs[1].RID)
Equals(t, winston.RID, docs[2].RID)
Equals(t, indy.Vers, docs[1].Vers)
Equals(t, "Matt", docs[0].GetField("caretaker").Value)
sql = fmt.Sprintf("DELETE FROM [%s, %s, %s]", winston.RID, daemon.RID, indy.RID)
err = db.Command(orient.NewSQLCommand(sql)).Err()
Nil(t, err)
// ---[ Test Boolean, Byte and Short Serialization ]---
//createAndUpdateRecordsWithBooleanByteAndShort(dbc)
// ---[ Test Int, Long, Float and Double Serialization ]---
//createAndUpdateRecordsWithIntLongFloatAndDouble(dbc)
// ---[ Test BINARY Serialization ]---
//createAndUpdateRecordsWithBINARYType(dbc)
// ---[ Test EMBEDDEDRECORD Serialization ]---
//createAndUpdateRecordsWithEmbeddedRecords(dbc)
// ---[ Test EMBEDDEDLIST, EMBEDDEDSET Serialization ]---
//createAndUpdateRecordsWithEmbeddedLists(dbc, orient.EMBEDDEDLIST)
//createAndUpdateRecordsWithEmbeddedLists(dbc, orient.EMBEDDEDSET)
// ---[ Test Link Serialization ]---
//createAndUpdateRecordsWithLinks(dbc)
// ---[ Test LinkList/LinkSet Serialization ]---
//createAndUpdateRecordsWithLinkLists(dbc, orient.LINKLIST)
// createAndUpdateRecordsWithLinkLists(dbc, orient.LINKSET) // TODO: get this working
// ---[ Test LinkMap Serialization ]---
//createAndUpdateRecordsWithLinkMap(dbc)
}
func TestRecordsWithDate(t *testing.T) {
notShort(t)
db, closer := SpinOrientAndOpenDB(t, false)
defer closer()
defer catch(t)
SeedDB(t, db)
err := db.Command(orient.NewSQLCommand("CREATE PROPERTY Cat.bday DATE")).Err()
Nil(t, err)
const dtTemplate = "Jan 2, 2006 at 3:04pm (MST)"
bdayTm, err := time.Parse(dtTemplate, "Feb 3, 1932 at 7:54pm (EST)")
Nil(t, err)
jj := orient.NewDocument("Cat")
jj.SetField("name", "JJ").
SetField("age", 2).
SetFieldWithType("bday", bdayTm, orient.DATE)
err = db.CreateRecord(jj)
Nil(t, err)
True(t, jj.RID.ClusterID > 0, "ClusterID should be set")
True(t, jj.RID.ClusterPos >= 0, "ClusterID should be set")
jjbdayAfterCreate := jj.GetField("bday").Value.(time.Time)
Equals(t, 0, jjbdayAfterCreate.Hour())
Equals(t, 0, jjbdayAfterCreate.Minute())
Equals(t, 0, jjbdayAfterCreate.Second())
var docs []*orient.Document
err = db.Command(orient.NewSQLQuery("select from Cat where @rid=" + jj.RID.String())).All(&docs)
Equals(t, 1, len(docs))
jjFromQuery := docs[0]
Equals(t, jj.RID, jjFromQuery.RID)
Equals(t, 1932, jjFromQuery.GetField("bday").Value.(time.Time).Year())
// ---[ update ]---
versionBefore := jj.Vers
oneYearLater := bdayTm.AddDate(1, 0, 0)
jj.SetFieldWithType("bday", oneYearLater, orient.DATE) // updates the field locally
err = db.UpdateRecord(jj) // update the field in the remote DB
Nil(t, err)
True(t, versionBefore < jj.Vers, "version should have incremented")
docs = nil
err = db.Command(orient.NewSQLQuery("select from Cat where @rid=" + jj.RID.String())).All(&docs)
Nil(t, err)
Equals(t, 1, len(docs))
jjFromQuery = docs[0]
Equals(t, 1933, jjFromQuery.GetField("bday").Value.(time.Time).Year())
}
func TestRecordsWithDatetime(t *testing.T) {
notShort(t)
db, closer := SpinOrientAndOpenDB(t, false)
defer closer()
defer catch(t)
SeedDB(t, db)
err := db.Command(orient.NewSQLCommand("CREATE PROPERTY Cat.ddd DATETIME")).Err()
Nil(t, err)
// ---[ creation ]---
now := time.Now()
now = time.Unix(now.Unix(), int64((now.Nanosecond()/1e6))*1e6)
simba := orient.NewDocument("Cat")
simba.SetField("name", "Simba").
SetField("age", 11).
SetFieldWithType("ddd", now, orient.DATETIME)
err = db.CreateRecord(simba)
Nil(t, err)
True(t, simba.RID.ClusterID > 0, "ClusterID should be set")
True(t, simba.RID.ClusterPos >= 0, "ClusterID should be set")
var docs []*orient.Document
err = db.Command(orient.NewSQLQuery("select from Cat where @rid=" + simba.RID.String())).All(&docs)
Nil(t, err)
Equals(t, 1, len(docs))
simbaFromQuery := docs[0]
Equals(t, simba.RID, simbaFromQuery.RID)
Equals(t, simba.GetField("ddd").Value, simbaFromQuery.GetField("ddd").Value)
// ---[ update ]---
versionBefore := simba.Vers
twoDaysAgo := now.AddDate(0, 0, -2)
simba.SetFieldWithType("ddd", twoDaysAgo, orient.DATETIME) // updates the field locally
err = db.UpdateRecord(simba) // update the field in the remote DB
Nil(t, err)
True(t, versionBefore < simba.Vers, "version should have incremented")
docs = nil
err = db.Command(orient.NewSQLQuery("select from Cat where @rid=" + simba.RID.String())).All(&docs)
Nil(t, err)
Equals(t, 1, len(docs))
simbaFromQuery = docs[0]
Equals(t, twoDaysAgo.Unix(), simbaFromQuery.GetField("ddd").Value.(time.Time).Unix())
}
func TestRecordsMismatchedTypes(t *testing.T) {
notShort(t)
db, closer := SpinOrientAndOpenDB(t, false)
defer closer()
defer catch(t)
SeedDB(t, db)
c1 := orient.NewDocument("Cat")
c1.SetField("name", "fluffy1").
SetField("age", 22).
SetFieldWithType("ddd", "not a datetime", orient.DATETIME)
err := db.CreateRecord(c1)
True(t, err != nil, "Should have returned error")
// _, ok := oerror.ExtractCause(err).(oerror.ErrDataTypeMismatch)
// True(t, ok, "should be DataTypeMismatch error")
c2 := orient.NewDocument("Cat")
c2.SetField("name", "fluffy1").
SetField("age", 22).
SetFieldWithType("ddd", float32(33244.2), orient.DATE)
err = db.CreateRecord(c2)
True(t, err != nil, "Should have returned error")
// _, ok = oerror.ExtractCause(err).(oerror.ErrDataTypeMismatch)
// True(t, ok, "should be DataTypeMismatch error")
// no fluffy1 should be in the database
var docs []*orient.Document
err = db.Command(orient.NewSQLQuery("select from Cat where name = 'fluffy1'")).All(&docs)
Nil(t, err)
Equals(t, 0, len(docs))
}
func TestRecordsBasicTypes(t *testing.T) {
notShort(t)
db, closer := SpinOrientAndOpenDB(t, false)
defer closer()
defer catch(t)
SeedDB(t, db)
for _, cmd := range []string{
"CREATE PROPERTY Cat.x BOOLEAN",
"CREATE PROPERTY Cat.y BYTE",
"CREATE PROPERTY Cat.z SHORT",
} {
err := db.Command(orient.NewSQLCommand(cmd)).Err()
Nil(t, err)
}
cat := orient.NewDocument("Cat")
cat.SetField("name", "kitteh").
SetField("age", 4).
SetField("x", false).
SetField("y", byte(55)).
SetField("z", int16(5123))
err := db.CreateRecord(cat)
Nil(t, err)
True(t, cat.RID.ClusterID > 0, "RID should be filled in")
var docs []*orient.Document
err = db.Command(orient.NewSQLQuery("select from Cat where y = 55")).All(&docs)
Nil(t, err)
Equals(t, 1, len(docs))
catFromQuery := docs[0]
Equals(t, cat.GetField("x").Value.(bool), catFromQuery.GetField("x").Value.(bool))
Equals(t, cat.GetField("y").Value.(byte), catFromQuery.GetField("y").Value.(byte))
Equals(t, cat.GetField("z").Value.(int16), catFromQuery.GetField("z").Value.(int16))
// try with explicit types
cat2 := orient.NewDocument("Cat")
cat2.SetField("name", "cat2").
SetField("age", 14).
SetFieldWithType("x", true, orient.BOOLEAN).
SetFieldWithType("y", byte(44), orient.BYTE).
SetFieldWithType("z", int16(16000), orient.SHORT)
err = db.CreateRecord(cat2)
Nil(t, err)
True(t, cat2.RID.ClusterID > 0, "RID should be filled in")
docs = nil
err = db.Command(orient.NewSQLQuery("select from Cat where x = true")).All(&docs)
Nil(t, err)
Equals(t, 1, len(docs))
cat2FromQuery := docs[0]
Equals(t, cat2.GetField("x").Value.(bool), cat2FromQuery.GetField("x").Value.(bool))
Equals(t, cat2.GetField("y").Value.(byte), cat2FromQuery.GetField("y").Value.(byte))
Equals(t, cat2.GetField("z").Value.(int16), cat2FromQuery.GetField("z").Value.(int16))
// ---[ update ]---
versionBefore := cat.Vers
cat.SetField("x", true)
cat.SetField("y", byte(19))
cat.SetField("z", int16(6789))
err = db.UpdateRecord(cat) // update the field in the remote DB
Nil(t, err)
True(t, versionBefore < cat.Vers, "version should have incremented")
docs = nil
err = db.Command(orient.NewSQLQuery("select from Cat where @rid=" + cat.RID.String())).All(&docs)
Nil(t, err)
Equals(t, 1, len(docs))
catFromQuery = docs[0]
Equals(t, true, catFromQuery.GetField("x").Value)
Equals(t, byte(19), catFromQuery.GetField("y").Value)
Equals(t, int16(6789), catFromQuery.GetField("z").Value)
}
func TestRecordsBinaryField(t *testing.T) {
notShort(t)
db, closer := SpinOrientAndOpenDB(t, false)
defer closer()
defer catch(t)
SeedDB(t, db)
err := db.Command(orient.NewSQLCommand("CREATE PROPERTY Cat.bin BINARY")).Err()
Nil(t, err)
// ---[ FieldWithType ]---
str := "four, five, six, pick up sticks"
bindata := []byte(str)
cat := orient.NewDocument("Cat")
cat.SetField("name", "little-jimmy").
SetField("age", 1).
SetFieldWithType("bin", bindata, orient.BINARY)
err = db.CreateRecord(cat)
Nil(t, err)
True(t, cat.RID.ClusterID > 0, "RID should be filled in")
var docs []*orient.Document
err = db.Command(orient.NewSQLQuery("select from Cat where @rid = ?", cat.RID)).All(&docs)
Nil(t, err)
Equals(t, 1, len(docs))
catFromQuery := docs[0]
Equals(t, cat.GetField("bin").Value, catFromQuery.GetField("bin").Value)
Equals(t, str, string(catFromQuery.GetField("bin").Value.([]byte)))
// ---[ Field No Type Specified ]---
binN := 10 * 1024 * 1024
bindata2 := make([]byte, binN)
for i := 0; i < binN; i++ {
bindata2[i] = byte(i)
}
cat2 := orient.NewDocument("Cat")
cat2.SetField("name", "Sauron").
SetField("age", 1111).
SetField("bin", bindata2)
True(t, cat2.RID.ClusterID <= 0, "RID should NOT be filled in")
err = db.CreateRecord(cat2)
Nil(t, err)
True(t, cat2.RID.ClusterID > 0, "RID should be filled in")
docs = nil
err = db.Command(orient.NewSQLQuery("select from Cat where @rid = ?", cat2.RID)).All(&docs)
Nil(t, err)
Equals(t, 1, len(docs))
cat2FromQuery := docs[0]
Equals(t, bindata2, cat2FromQuery.GetField("bin").Value.([]byte))
// ---[ update ]---
versionBefore := cat.Vers
newbindata := []byte("Now Gluten Free!")
cat.SetFieldWithType("bin", newbindata, orient.BINARY)
err = db.UpdateRecord(cat) // update the field in the remote DB
Nil(t, err)
True(t, versionBefore < cat.Vers, "version should have incremented")
docs = nil
err = db.Command(orient.NewSQLQuery("select from Cat where @rid=" + cat.RID.String())).All(&docs)
Nil(t, err)
Equals(t, 1, len(docs))
catFromQuery = docs[0]
Equals(t, newbindata, catFromQuery.GetField("bin").Value)
}
func recordAsDocument(t *testing.T, rec orient.ORecord) *orient.Document {
doc, ok := rec.(*orient.Document)
if !ok {
t.Fatalf("expected document, got: %T", rec)
}
return doc
}
func TestRecordBytes(t *testing.T) {
notShort(t)
db, closer := SpinOrientAndOpenDB(t, false)
defer closer()
defer catch(t)
rec := orient.NewBytesRecord()
// ---[ FieldWithType ]---
str := "four, five, six, pick up sticks"
bindata := []byte(str)
rec.Data = bindata
err := db.CreateRecord(rec)
Nil(t, err)
True(t, rec.RID.ClusterID > 0, "RID should be filled in")
rrec, err := db.GetRecordByRID(rec.RID, "", true)
Nil(t, err)
recFromQuery := rrec.(*orient.BytesRecord)
Equals(t, rec.Data, recFromQuery.Data)
Equals(t, str, string(recFromQuery.Data))
// ---[ Field No Type Specified ]---
binN := 10 * 1024 * 1024
bindata2 := make([]byte, binN)
for i := 0; i < binN; i++ {
bindata2[i] = byte(i)
}
rec2 := orient.NewBytesRecord()
rec2.Data = bindata2
True(t, rec2.RID.ClusterID <= 0, "RID should NOT be filled in")
err = db.CreateRecord(rec2)
Nil(t, err)
True(t, rec2.RID.ClusterID > 0, "RID should be filled in")
rrec, err = db.GetRecordByRID(rec2.RID, "", true)
Nil(t, err)
rec2FromQuery := rrec.(*orient.BytesRecord)
Equals(t, bindata2, rec2FromQuery.Data)
// ---[ update ]---
versionBefore := rec.Vers
newbindata := []byte("Now Gluten Free!")
rec.Data = newbindata
err = db.UpdateRecord(rec) // update the field in the remote DB
Nil(t, err)
True(t, versionBefore < rec.Vers, "version should have incremented")
rrec, err = db.GetRecordByRID(rec.RID, "", true)
Nil(t, err)
recFromQuery = rrec.(*orient.BytesRecord)
Equals(t, newbindata, recFromQuery.Data)
}
func TestCommandsNativeAPI(t *testing.T) {
notShort(t)
db, closer := SpinOrientAndOpenDB(t, false)
defer closer()
defer catch(t)
SeedDB(t, db)
var (
rec orient.ORecord
doc *orient.Document
err error
retint int
docs []*orient.Document
)
resetVars := func() {
docs = nil
retint = 0
}
sqlCommand := func(sql string, params ...interface{}) {
err := db.Command(orient.NewSQLCommand(sql, params...)).Err()
Nil(t, err)
}
sqlCommandAll := func(sql string, out interface{}, params ...interface{}) {
resetVars()
err := db.Command(orient.NewSQLCommand(sql, params...)).All(out)
Nil(t, err)
}
sqlCommandErr := func(sql string, params ...interface{}) {
err := db.Command(orient.NewSQLCommand(sql, params...)).Err()
True(t, err != nil, "should be error: ", sql)
switch err.(type) {
case orient.OServerException:
default:
t.Fatal(fmt.Errorf("error should have been a oerror.OServerException but was: %T: %v", err, err))
}
}
sqlQueryAll := func(sql string, out interface{}, params ...interface{}) {
resetVars()
err := db.Command(orient.NewSQLQuery(sql, params...)).All(out)
Nil(t, err)
}
sqlQueryPlanAll := func(sql string, plan orient.FetchPlan, out interface{}, params ...interface{}) {
resetVars()
err := db.Command(orient.NewSQLQuery(sql, params...).FetchPlan(plan)).All(out)
Nil(t, err)
}
// ---[ query from the ogonoriTest database ]---
sqlQueryAll("select from Cat where name = ?", &docs, "Linus")
linusDocRID := docs[0].RID
True(t, linusDocRID.IsValid(), "linusDocRID should not be nil")
True(t, docs[0].Vers > 0, fmt.Sprintf("Version is: %d", docs[0].Vers))
Equals(t, 3, len(docs[0].FieldNames()))
Equals(t, "Cat", docs[0].ClassName())
nameField := docs[0].GetField("name")
True(t, nameField != nil, "should be a 'name' field")
ageField := docs[0].GetField("age")
True(t, ageField != nil, "should be a 'age' field")
caretakerField := docs[0].GetField("caretaker")
True(t, caretakerField != nil, "should be a 'caretaker' field")
Equals(t, orient.STRING, nameField.Type)
Equals(t, orient.STRING, caretakerField.Type)
Equals(t, orient.INTEGER, ageField.Type)
Equals(t, "Linus", nameField.Value)
Equals(t, int32(15), ageField.Value)
Equals(t, "Michael", caretakerField.Value)
// ---[ get by RID ]---
rec, err = db.GetRecordByRID(linusDocRID, "", true)
Nil(t, err)
doc = recordAsDocument(t, rec)
docByRID := doc
Equals(t, linusDocRID, docByRID.RID)
True(t, docByRID.Vers > 0, fmt.Sprintf("Version is: %d", docByRID.Vers))
Equals(t, 3, len(docByRID.FieldNames()))
Equals(t, "Cat", docByRID.ClassName())
nameField = docByRID.GetField("name")
True(t, nameField != nil, "should be a 'name' field")
ageField = docByRID.GetField("age")
True(t, ageField != nil, "should be a 'age' field")
caretakerField = docByRID.GetField("caretaker")
True(t, caretakerField != nil, "should be a 'caretaker' field")
Equals(t, orient.STRING, nameField.Type)
Equals(t, orient.INTEGER, ageField.Type)
Equals(t, orient.STRING, caretakerField.Type)
Equals(t, "Linus", nameField.Value)
Equals(t, int32(15), ageField.Value)
Equals(t, "Michael", caretakerField.Value)
// ---[ cluster data range ]---
// begin, end, err := db.FetchClusterDataRange("cat")
// Nil(t, err)
// glog.Infof("begin = %v; end = %v\n", begin, end)
sqlCommand(`insert into Cat (name, age, caretaker) values("Zed", 3, "Shaw")`)
// ---[ query after inserting record(s) ]---
sqlQueryAll("select * from Cat order by name asc", &docs)
Equals(t, 3, len(docs))
Equals(t, 3, len(docs[0].FieldNames()))
Equals(t, "Cat", docs[0].ClassName())
Equals(t, 3, len(docs[1].FieldNames()))
Equals(t, "Cat", docs[1].ClassName())
Equals(t, 3, len(docs[2].FieldNames()))
Equals(t, "Cat", docs[2].ClassName())
keiko := docs[0]
Equals(t, "Keiko", keiko.GetField("name").Value)
Equals(t, int32(10), keiko.GetField("age").Value)
Equals(t, "Anna", keiko.GetField("caretaker").Value)
Equals(t, orient.STRING, keiko.GetField("caretaker").Type)
True(t, keiko.Vers > 0, "Version should be greater than zero")
True(t, keiko.RID.IsValid(), "RID should be filled in")
linus := docs[1]
Equals(t, "Linus", linus.GetField("name").Value)
Equals(t, int32(15), linus.GetField("age").Value)
Equals(t, "Michael", linus.GetField("caretaker").Value)
zed := docs[2]
Equals(t, "Zed", zed.GetField("name").Value)
Equals(t, int32(3), zed.GetField("age").Value)
Equals(t, "Shaw", zed.GetField("caretaker").Value)
Equals(t, orient.STRING, zed.GetField("caretaker").Type)
Equals(t, orient.INTEGER, zed.GetField("age").Type)
True(t, zed.Vers > 0, "Version should be greater than zero")
True(t, zed.RID.IsValid(), "RID should be filled in")
sqlQueryAll("select name, caretaker from Cat order by caretaker", &docs)
Equals(t, 3, len(docs))
Equals(t, 2, len(docs[0].FieldNames()))
Equals(t, "", docs[0].ClassName()) // property queries do not come back with Classname set
Equals(t, 2, len(docs[1].FieldNames()))
Equals(t, "", docs[1].ClassName())
Equals(t, 2, len(docs[2].FieldNames()))
Equals(t, "Anna", docs[0].GetField("caretaker").Value)
Equals(t, "Michael", docs[1].GetField("caretaker").Value)
Equals(t, "Shaw", docs[2].GetField("caretaker").Value)
Equals(t, "Keiko", docs[0].GetField("name").Value)
Equals(t, "Linus", docs[1].GetField("name").Value)
Equals(t, "Zed", docs[2].GetField("name").Value)
Equals(t, "name", docs[0].GetField("name").Name)
// ---[ delete newly added record(s) ]---
err = db.DeleteRecordByRID(zed.RID, zed.Vers)
Nil(t, err)
// glog.Infoln("Deleting (Async) record #11:4")
// err = dbc.DeleteRecordByRIDAsync(dbc, "11:4", 1)
// if err != nil {
// Fatal(err)
// }
sqlCommand("insert into Cat (name, age, caretaker) values(?, ?, ?)", "June", 8, "Cleaver")
sqlQueryAll("select name, age from Cat where caretaker = ?", &docs, "Cleaver")
Equals(t, 1, len(docs))
Equals(t, 2, len(docs[0].FieldNames()))
Equals(t, "", docs[0].ClassName()) // property queries do not come back with Classname set
Equals(t, "June", docs[0].GetField("name").Value)
Equals(t, int32(8), docs[0].GetField("age").Value)
sqlCommandAll("select caretaker, name, age from Cat where age > ? order by age desc", &docs, 9)
Equals(t, 2, len(docs))
Equals(t, 3, len(docs[0].FieldNames()))
Equals(t, "", docs[0].ClassName()) // property queries do not come back with Classname set
Equals(t, "Linus", docs[0].GetField("name").Value)
Equals(t, int32(15), docs[0].GetField("age").Value)
Equals(t, "Keiko", docs[1].GetField("name").Value)
Equals(t, int32(10), docs[1].GetField("age").Value)
Equals(t, "Anna", docs[1].GetField("caretaker").Value)
sqlCommand("delete from Cat where name = ?")
// START: Basic DDL
sqlCommand("DROP CLASS Patient")
//Equals(t, true, retbool)
// ------
retint = 0
sqlCommandAll("CREATE CLASS Patient", &retint)
True(t, retint > 10, "classnum should be greater than 10 but was: ", retint)
defer func() {
err = db.Command(orient.NewSQLCommand("DROP CLASS Patient")).Err()
if err != nil {
log.Printf("WARN: clean up error: %v\n", err)
return
}
// TRUNCATE after drop should return an OServerException type
err = db.Command(orient.NewSQLCommand("TRUNCATE CLASS Patient")).Err()
True(t, err != nil, "Error from TRUNCATE should not be null")
switch err.(type) {
case orient.OServerException:
default:
t.Fatal(fmt.Errorf("TRUNCATE error cause should have been a oerror.OServerException but was: %T: %v", err, err))
}
}()
// ------
sqlCommand("Create property Patient.name string")
sqlCommand("alter property Patient.name min 3")
sqlCommand("Create property Patient.married boolean")
err = db.ReloadSchema()
Nil(t, err)
sqlCommand("INSERT INTO Patient (name, married) VALUES ('Hank', 'true')")
sqlCommand("TRUNCATE CLASS Patient")
sqlCommand("INSERT INTO Patient (name, married) VALUES ('Hank', 'true'), ('Martha', 'false')")
sqlQueryAll("SELECT count(*) from Patient", &docs)
Equals(t, 1, len(docs))
fldCount := docs[0].GetField("count")
Equals(t, int64(2), fldCount.Value)
sqlCommand("CREATE PROPERTY Patient.gender STRING")
sqlCommand("ALTER PROPERTY Patient.gender REGEXP [M|F]")
sqlCommand("INSERT INTO Patient (name, married, gender) VALUES ('Larry', 'true', 'M'), ('Shirley', 'false', 'F')")
sqlCommandErr("INSERT INTO Patient (name, married, gender) VALUES ('Lt. Dan', 'true', 'T'), ('Sally', 'false', 'F')")
sqlQueryAll("SELECT FROM Patient ORDER BY @rid desc", &docs)
Equals(t, 4, len(docs))
Equals(t, "Shirley", docs[0].GetField("name").Value)
sqlCommand("ALTER PROPERTY Patient.gender NAME sex")
err = db.ReloadSchema()
Nil(t, err)
sqlCommand("DROP PROPERTY Patient.sex")
sqlQueryAll("select from Patient order by RID", &docs)
Equals(t, 4, len(docs))
Equals(t, 2, len(docs[0].Fields())) // has name and married
Equals(t, "Hank", docs[0].Fields()["name"].Value)
Equals(t, 4, len(docs[3].Fields())) // has name, married, sex and for some reason still has `gender`
Equals(t, "Shirley", docs[3].Fields()["name"].Value)
Equals(t, "F", docs[3].Fields()["gender"].Value)
sqlCommand("TRUNCATE CLASS Patient")
// ---[ Attempt to create, insert and read back EMBEDDEDLIST types ]---
sqlCommandAll("CREATE PROPERTY Patient.tags EMBEDDEDLIST STRING", &retint)
True(t, retint >= 0, "retval from PROPERTY creation should be a positive number")
sqlCommandAll(`insert into Patient (name, married, tags) values ("George", "false", ["diabetic", "osteoarthritis"])`, &docs)
Equals(t, 1, len(docs))
Equals(t, 3, len(docs[0].FieldNames()))
sqlQueryAll(`SELECT from Patient where name = ?`, &docs, "George")
Equals(t, 1, len(docs))
Equals(t, 3, len(docs[0].FieldNames()))
embListTagsField := docs[0].GetField("tags")
embListTags := embListTagsField.Value.([]interface{})
Equals(t, 2, len(embListTags))
Equals(t, "diabetic", embListTags[0].(string))
Equals(t, "osteoarthritis", embListTags[1].(string))
// ---[ try JSON content insertion notation ]---
sqlCommandAll(`insert into Patient content {"name": "Freddy", "married":false}`, &docs)
Equals(t, 1, len(docs))
Equals(t, "Freddy", docs[0].GetField("name").Value)
Equals(t, false, docs[0].GetField("married").Value)
// ---[ Try LINKs ! ]---
sqlQueryAll(`select from Cat WHERE name = 'Linus' OR name='Keiko' ORDER BY @rid`, &docs)
Equals(t, 2, len(docs))
linusRID := docs[0].RID
keikoRID := docs[1].RID
sqlCommandAll(`CREATE PROPERTY Cat.buddy LINK`, &retint)