-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgrngo.go
1455 lines (1383 loc) · 44.8 KB
/
grngo.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
// Another Groonga binding for Go language.
package grngo
// #cgo pkg-config: groonga
// #include "grngo.h"
import "C"
import (
"bytes"
"fmt"
"reflect"
"strings"
"unsafe"
)
// -- Errors --
func rcString(rc C.grn_rc) string {
switch rc {
case C.GRN_SUCCESS:
return fmt.Sprintf("GRN_SUCCESS (%d)", rc)
case C.GRN_END_OF_DATA:
return fmt.Sprintf("GRN_END_OF_DATA (%d)", rc)
case C.GRN_UNKNOWN_ERROR:
return fmt.Sprintf("GRN_UNKNOWN_ERROR (%d)", rc)
case C.GRN_OPERATION_NOT_PERMITTED:
return fmt.Sprintf("GRN_OPERATION_NOT_PERMITTED (%d)", rc)
case C.GRN_NO_SUCH_FILE_OR_DIRECTORY:
return fmt.Sprintf("GRN_NO_SUCH_FILE_OR_DIRECTORY (%d)", rc)
case C.GRN_NO_SUCH_PROCESS:
return fmt.Sprintf("GRN_NO_SUCH_PROCESS (%d)", rc)
case C.GRN_INTERRUPTED_FUNCTION_CALL:
return fmt.Sprintf("GRN_INTERRUPTED_FUNCTION_CALL (%d)", rc)
case C.GRN_INPUT_OUTPUT_ERROR:
return fmt.Sprintf("GRN_INPUT_OUTPUT_ERROR (%d)", rc)
case C.GRN_NO_SUCH_DEVICE_OR_ADDRESS:
return fmt.Sprintf("GRN_NO_SUCH_DEVICE_OR_ADDRESS (%d)", rc)
case C.GRN_ARG_LIST_TOO_LONG:
return fmt.Sprintf("GRN_ARG_LIST_TOO_LONG (%d)", rc)
case C.GRN_EXEC_FORMAT_ERROR:
return fmt.Sprintf("GRN_EXEC_FORMAT_ERROR (%d)", rc)
case C.GRN_BAD_FILE_DESCRIPTOR:
return fmt.Sprintf("GRN_BAD_FILE_DESCRIPTOR (%d)", rc)
case C.GRN_NO_CHILD_PROCESSES:
return fmt.Sprintf("GRN_NO_CHILD_PROCESSES (%d)", rc)
case C.GRN_RESOURCE_TEMPORARILY_UNAVAILABLE:
return fmt.Sprintf("GRN_RESOURCE_TEMPORARILY_UNAVAILABLE (%d)", rc)
case C.GRN_NOT_ENOUGH_SPACE:
return fmt.Sprintf("GRN_NOT_ENOUGH_SPACE (%d)", rc)
case C.GRN_PERMISSION_DENIED:
return fmt.Sprintf("GRN_PERMISSION_DENIED (%d)", rc)
case C.GRN_BAD_ADDRESS:
return fmt.Sprintf("GRN_BAD_ADDRESS (%d)", rc)
case C.GRN_RESOURCE_BUSY:
return fmt.Sprintf("GRN_RESOURCE_BUSY (%d)", rc)
case C.GRN_FILE_EXISTS:
return fmt.Sprintf("GRN_FILE_EXISTS (%d)", rc)
case C.GRN_IMPROPER_LINK:
return fmt.Sprintf("GRN_IMPROPER_LINK (%d)", rc)
case C.GRN_NO_SUCH_DEVICE:
return fmt.Sprintf("GRN_NO_SUCH_DEVICE (%d)", rc)
case C.GRN_NOT_A_DIRECTORY:
return fmt.Sprintf("GRN_NOT_A_DIRECTORY (%d)", rc)
case C.GRN_IS_A_DIRECTORY:
return fmt.Sprintf("GRN_IS_A_DIRECTORY (%d)", rc)
case C.GRN_INVALID_ARGUMENT:
return fmt.Sprintf("GRN_INVALID_ARGUMENT (%d)", rc)
case C.GRN_TOO_MANY_OPEN_FILES_IN_SYSTEM:
return fmt.Sprintf("GRN_TOO_MANY_OPEN_FILES_IN_SYSTEM (%d)", rc)
case C.GRN_TOO_MANY_OPEN_FILES:
return fmt.Sprintf("GRN_TOO_MANY_OPEN_FILES (%d)", rc)
case C.GRN_INAPPROPRIATE_I_O_CONTROL_OPERATION:
return fmt.Sprintf("GRN_INAPPROPRIATE_I_O_CONTROL_OPERATION (%d)", rc)
case C.GRN_FILE_TOO_LARGE:
return fmt.Sprintf("GRN_FILE_TOO_LARGE (%d)", rc)
case C.GRN_NO_SPACE_LEFT_ON_DEVICE:
return fmt.Sprintf("GRN_NO_SPACE_LEFT_ON_DEVICE (%d)", rc)
case C.GRN_INVALID_SEEK:
return fmt.Sprintf("GRN_INVALID_SEEK (%d)", rc)
case C.GRN_READ_ONLY_FILE_SYSTEM:
return fmt.Sprintf("GRN_READ_ONLY_FILE_SYSTEM (%d)", rc)
case C.GRN_TOO_MANY_LINKS:
return fmt.Sprintf("GRN_TOO_MANY_LINKS (%d)", rc)
case C.GRN_BROKEN_PIPE:
return fmt.Sprintf("GRN_BROKEN_PIPE (%d)", rc)
case C.GRN_DOMAIN_ERROR:
return fmt.Sprintf("GRN_DOMAIN_ERROR (%d)", rc)
case C.GRN_RESULT_TOO_LARGE:
return fmt.Sprintf("GRN_RESULT_TOO_LARGE (%d)", rc)
case C.GRN_RESOURCE_DEADLOCK_AVOIDED:
return fmt.Sprintf("GRN_RESOURCE_DEADLOCK_AVOIDED (%d)", rc)
case C.GRN_NO_MEMORY_AVAILABLE:
return fmt.Sprintf("GRN_NO_MEMORY_AVAILABLE (%d)", rc)
case C.GRN_FILENAME_TOO_LONG:
return fmt.Sprintf("GRN_FILENAME_TOO_LONG (%d)", rc)
case C.GRN_NO_LOCKS_AVAILABLE:
return fmt.Sprintf("GRN_NO_LOCKS_AVAILABLE (%d)", rc)
case C.GRN_FUNCTION_NOT_IMPLEMENTED:
return fmt.Sprintf("GRN_FUNCTION_NOT_IMPLEMENTED (%d)", rc)
case C.GRN_DIRECTORY_NOT_EMPTY:
return fmt.Sprintf("GRN_DIRECTORY_NOT_EMPTY (%d)", rc)
case C.GRN_ILLEGAL_BYTE_SEQUENCE:
return fmt.Sprintf("GRN_ILLEGAL_BYTE_SEQUENCE (%d)", rc)
case C.GRN_SOCKET_NOT_INITIALIZED:
return fmt.Sprintf("GRN_SOCKET_NOT_INITIALIZED (%d)", rc)
case C.GRN_OPERATION_WOULD_BLOCK:
return fmt.Sprintf("GRN_OPERATION_WOULD_BLOCK (%d)", rc)
case C.GRN_ADDRESS_IS_NOT_AVAILABLE:
return fmt.Sprintf("GRN_ADDRESS_IS_NOT_AVAILABLE (%d)", rc)
case C.GRN_NETWORK_IS_DOWN:
return fmt.Sprintf("GRN_NETWORK_IS_DOWN (%d)", rc)
case C.GRN_NO_BUFFER:
return fmt.Sprintf("GRN_NO_BUFFER (%d)", rc)
case C.GRN_SOCKET_IS_ALREADY_CONNECTED:
return fmt.Sprintf("GRN_SOCKET_IS_ALREADY_CONNECTED (%d)", rc)
case C.GRN_SOCKET_IS_NOT_CONNECTED:
return fmt.Sprintf("GRN_SOCKET_IS_NOT_CONNECTED (%d)", rc)
case C.GRN_SOCKET_IS_ALREADY_SHUTDOWNED:
return fmt.Sprintf("GRN_SOCKET_IS_ALREADY_SHUTDOWNED (%d)", rc)
case C.GRN_OPERATION_TIMEOUT:
return fmt.Sprintf("GRN_OPERATION_TIMEOUT (%d)", rc)
case C.GRN_CONNECTION_REFUSED:
return fmt.Sprintf("GRN_CONNECTION_REFUSED (%d)", rc)
case C.GRN_RANGE_ERROR:
return fmt.Sprintf("GRN_RANGE_ERROR (%d)", rc)
case C.GRN_TOKENIZER_ERROR:
return fmt.Sprintf("GRN_TOKENIZER_ERROR (%d)", rc)
case C.GRN_FILE_CORRUPT:
return fmt.Sprintf("GRN_FILE_CORRUPT (%d)", rc)
case C.GRN_INVALID_FORMAT:
return fmt.Sprintf("GRN_INVALID_FORMAT (%d)", rc)
case C.GRN_OBJECT_CORRUPT:
return fmt.Sprintf("GRN_OBJECT_CORRUPT (%d)", rc)
case C.GRN_TOO_MANY_SYMBOLIC_LINKS:
return fmt.Sprintf("GRN_TOO_MANY_SYMBOLIC_LINKS (%d)", rc)
case C.GRN_NOT_SOCKET:
return fmt.Sprintf("GRN_NOT_SOCKET (%d)", rc)
case C.GRN_OPERATION_NOT_SUPPORTED:
return fmt.Sprintf("GRN_OPERATION_NOT_SUPPORTED (%d)", rc)
case C.GRN_ADDRESS_IS_IN_USE:
return fmt.Sprintf("GRN_ADDRESS_IS_IN_USE (%d)", rc)
case C.GRN_ZLIB_ERROR:
return fmt.Sprintf("GRN_ZLIB_ERROR (%d)", rc)
case C.GRN_LZ4_ERROR:
return fmt.Sprintf("GRN_LZ4_ERROR (%d)", rc)
case C.GRN_STACK_OVER_FLOW:
return fmt.Sprintf("GRN_STACK_OVER_FLOW (%d)", rc)
case C.GRN_SYNTAX_ERROR:
return fmt.Sprintf("GRN_SYNTAX_ERROR (%d)", rc)
case C.GRN_RETRY_MAX:
return fmt.Sprintf("GRN_RETRY_MAX (%d)", rc)
case C.GRN_INCOMPATIBLE_FILE_FORMAT:
return fmt.Sprintf("GRN_INCOMPATIBLE_FILE_FORMAT (%d)", rc)
case C.GRN_UPDATE_NOT_ALLOWED:
return fmt.Sprintf("GRN_UPDATE_NOT_ALLOWED (%d)", rc)
case C.GRN_TOO_SMALL_OFFSET:
return fmt.Sprintf("GRN_TOO_SMALL_OFFSET (%d)", rc)
case C.GRN_TOO_LARGE_OFFSET:
return fmt.Sprintf("GRN_TOO_LARGE_OFFSET (%d)", rc)
case C.GRN_TOO_SMALL_LIMIT:
return fmt.Sprintf("GRN_TOO_SMALL_LIMIT (%d)", rc)
case C.GRN_CAS_ERROR:
return fmt.Sprintf("GRN_CAS_ERROR (%d)", rc)
case C.GRN_UNSUPPORTED_COMMAND_VERSION:
return fmt.Sprintf("GRN_UNSUPPORTED_COMMAND_VERSION (%d)", rc)
case C.GRN_NORMALIZER_ERROR:
return fmt.Sprintf("GRN_NORMALIZER_ERROR (%d)", rc)
case C.GRN_TOKEN_FILTER_ERROR:
return fmt.Sprintf("GRN_TOKEN_FILTER_ERROR (%d)", rc)
case C.GRN_COMMAND_ERROR:
return fmt.Sprintf("GRN_COMMAND_ERROR (%d)", rc)
case C.GRN_PLUGIN_ERROR:
return fmt.Sprintf("GRN_PLUGIN_ERROR (%d)", rc)
case C.GRN_SCORER_ERROR:
return fmt.Sprintf("GRN_SCORER_ERROR (%d)", rc)
default:
return fmt.Sprintf("GRN_UNDEFINED_ERROR (%d)", rc)
}
}
// newCError returns an error related to a Groonga or Grngo operation.
func newCError(opName string, rc C.grn_rc, db *DB) error {
if db == nil {
return fmt.Errorf("%s failed: rc = %s", opName, rcString(rc))
}
ctx := db.c.ctx
if ctx.errbuf[0] == 0 {
return fmt.Errorf("%s failed: rc = %s, ctx.rc = %s",
opName, rcString(rc), rcString(ctx.rc))
}
return fmt.Errorf("%s failed: rc = %s, ctx.rc = %s, ctx.errbuf = %s",
opName, rcString(rc), rcString(ctx.rc), C.GoString(&ctx.errbuf[0]))
}
// -- Data types --
// GeoPoint represents a coordinate of latitude and longitude.
type GeoPoint struct {
Latitude int32 // Latitude in milliseconds.
Longitude int32 // Longitude in milliseconds.
}
// NilID is an invalid record ID.
// Some functions return NilID if operations failed.
const NilID = uint32(C.GRN_ID_NIL)
// DataType is an enumeration of Groonga built-in data types.
//
// See http://groonga.org/docs/reference/types.html for details.
type DataType int
// Time (int64) represents the number of microseconds elapsed since the Unix
// epoch.
//
// See http://groonga.org/docs/reference/types.html for details.
const (
Void = DataType(C.GRN_DB_VOID) // N/A.
Bool = DataType(C.GRN_DB_BOOL) // bool.
Int8 = DataType(C.GRN_DB_INT8) // int64.
Int16 = DataType(C.GRN_DB_INT16) // int64.
Int32 = DataType(C.GRN_DB_INT32) // int64.
Int64 = DataType(C.GRN_DB_INT64) // int64.
UInt8 = DataType(C.GRN_DB_UINT8) // int64.
UInt16 = DataType(C.GRN_DB_UINT16) // int64.
UInt32 = DataType(C.GRN_DB_UINT32) // int64.
UInt64 = DataType(C.GRN_DB_UINT64) // int64.
Float = DataType(C.GRN_DB_FLOAT) // float64.
Time = DataType(C.GRN_DB_TIME) // int64.
ShortText = DataType(C.GRN_DB_SHORT_TEXT) // []byte.
Text = DataType(C.GRN_DB_TEXT) // []byte.
LongText = DataType(C.GRN_DB_LONG_TEXT) // []byte.
TokyoGeoPoint = DataType(C.GRN_DB_TOKYO_GEO_POINT) // GeoPoint.
WGS84GeoPoint = DataType(C.GRN_DB_WGS84_GEO_POINT) // GeoPoint.
LazyInt = DataType(-iota - 1) // int64.
LazyGeoPoint // GeoPoint.
)
func (dataType DataType) String() string {
switch dataType {
case Void:
return "Void"
case Bool:
return "Bool"
case Int8:
return "Int8"
case Int16:
return "Int16"
case Int32:
return "Int32"
case Int64:
return "Int64"
case UInt8:
return "UInt8"
case UInt16:
return "UInt16"
case UInt32:
return "UInt32"
case UInt64:
return "UInt64"
case Float:
return "Float"
case Time:
return "Time"
case ShortText:
return "ShortText"
case Text:
return "Text"
case LongText:
return "LongText"
case TokyoGeoPoint:
return "TokyoGeoPoint"
case WGS84GeoPoint:
return "WGS84GeoPoint"
case LazyInt:
return "Int"
case LazyGeoPoint:
return "GeoPoint"
default:
return fmt.Sprintf("DataType(%d)", dataType)
}
}
// -- TableOptions --
// Flags of TableOptions accepts a combination of these constants.
//
// See http://groonga.org/docs/reference/commands/table_create.html#flags for details.
const (
TableTypeMask = C.GRN_OBJ_TABLE_TYPE_MASK // TableNoKey | TablePatKey | TableDatKey | TableHashKey.
TableNoKey = C.GRN_OBJ_TABLE_NO_KEY // TableNoKey is associated with TABLE_NO_KEY.
TablePatKey = C.GRN_OBJ_TABLE_PAT_KEY // TablePatKey is associated with TABLE_PAT_KEY.
TableDatKey = C.GRN_OBJ_TABLE_DAT_KEY // TableDatKey is associated with TABLE_DAT_KEY.
TableHashKey = C.GRN_OBJ_TABLE_HASH_KEY // TableHashKey is associated with TABLE_HASH_KEY.
KeyWithSIS = C.GRN_OBJ_KEY_WITH_SIS // KeyWithSIS is associated with KEY_WITH_SIS.
)
// TableOptions is a set of options for CreateTable.
// Flags is TableHashKey by default.
//
// See http://groonga.org/docs/reference/commands/table_create.html#parameters for details.
type TableOptions struct {
Flags int // Flags is associated with flags.
KeyType string // KeyType is associated with key_type.
ValueType string // ValueType is associated with value_type.
DefaultTokenizer string // DefaultTokenizer is associated with default_tokenizer.
Normalizer string // Normalizer is associated with normalizer.
TokenFilters []string // TokenFilters is associated with token_filters.
}
// NewTableOptions returns a new TableOptions with the default settings.
func NewTableOptions() *TableOptions {
options := new(TableOptions)
options.Flags = TableHashKey
return options
}
// -- ColumnOptions --
// Flags of ColumnOptions accepts a combination of these constants.
//
// See http://groonga.org/docs/reference/commands/column_create.html#parameters for details.
const (
CompressMask = C.GRN_OBJ_COMPRESS_MASK // CompressZlib | CompressLZ4.
CompressNone = C.GRN_OBJ_COMPRESS_NONE // CompressNone is 0.
CompressZlib = C.GRN_OBJ_COMPRESS_ZLIB // CompressZlib is associated with COMPRESS_ZLIB.
CompressLZ4 = C.GRN_OBJ_COMPRESS_LZ4 // CompressLZ4 is associated with COMPRESS_LZ4.
WithSection = C.GRN_OBJ_WITH_SECTION // WithSection is associated with WITH_SECTION.
WithWeight = C.GRN_OBJ_WITH_WEIGHT // WithWeight is associated with WITH_WEIGHT.
WithPosition = C.GRN_OBJ_WITH_POSITION // WithPosition is associated with WITH_POSITION.
)
// ColumnOptions is a set of options for CreateColumn.
// Flags is CompressNone by default.
//
// See http://groonga.org/docs/reference/commands/column_create.html#parameters for details.
type ColumnOptions struct {
Flags int
}
// NewColumnOptions returns a new ColumnOptions with the default settings.
func NewColumnOptions() *ColumnOptions {
options := new(ColumnOptions)
options.Flags = CompressNone
return options
}
// -- Groonga --
// grnInitFinDisabled shows whther C.grn_init and C.grn_fin are disabled.
var grnInitFinDisabled = false
// grnInitCount is an internal counter used in GrnInit and GrnFin.
var grnInitCount = 0
// DisableGrnInitFin disables calls of C.grn_init and C.grn_fin in GrnInit()
// and GrnFin().
// DisableGrnInitFin should be used if you manually or another library
// initialize and finalize Groonga.
func DisableGrnInitFin() {
grnInitFinDisabled = true
}
// GrnInit increments an internal counter grnInitCount and if it changes from
// 0 to 1, calls C.grn_init to initialize Groonga.
//
// Note that CreateDB and OpenDB call GrnInit, so you should not manually call
// GrnInit if not needed.
func GrnInit() error {
if grnInitCount == 0 {
if !grnInitFinDisabled {
if rc := C.grn_init(); rc != C.GRN_SUCCESS {
return newCError("grn_init()", rc, nil)
}
}
}
grnInitCount++
return nil
}
// GrnFin decrements an internal counter grnInitCount and if it changes from
// 1 to 0, calls C.grn_fin to finalize Groonga.
//
// Note that DB.Close calls GrnFin, so you should not manually call GrnFin if
// not needed.
func GrnFin() error {
switch grnInitCount {
case 0:
return fmt.Errorf("Groonga is not initialized yet")
case 1:
if !grnInitFinDisabled {
if rc := C.grn_fin(); rc != C.GRN_SUCCESS {
return newCError("grn_fin()", rc, nil)
}
}
}
grnInitCount--
return nil
}
// -- DB --
// DB is associated with a Groonga database with its context.
type DB struct {
c *C.grngo_db // The associated C object.
tables map[string]*Table // A cache to find tables by name.
}
// newDB returns a new DB.
func newDB(c *C.grngo_db) *DB {
db := new(DB)
db.c = c
db.tables = make(map[string]*Table)
return db
}
// CreateDB creates a Groonga database and returns a new DB associated with it.
// If path is empty, CreateDB creates a temporary database.
//
// Note that CreateDB initializes Groonga if the new DB will be the only one
// and implicit initialization is not disabled.
func CreateDB(path string) (*DB, error) {
if err := GrnInit(); err != nil {
return nil, err
}
pathBytes := []byte(path)
var cPath *C.char
if len(pathBytes) != 0 {
cPath = (*C.char)(unsafe.Pointer(&pathBytes[0]))
}
var c *C.grngo_db
rc := C.grngo_create_db(cPath, C.size_t(len(pathBytes)), &c)
if rc != C.GRN_SUCCESS {
GrnFin()
return nil, newCError("grngo_create_db()", rc, nil)
}
return newDB(c), nil
}
// OpenDB opens an existing Groonga database and returns a new DB associated
// with it.
//
// Note that CreateDB initializes Groonga if the new DB will be the only one
// and implicit initialization is not disabled.
func OpenDB(path string) (*DB, error) {
if err := GrnInit(); err != nil {
return nil, err
}
pathBytes := []byte(path)
var cPath *C.char
if len(pathBytes) != 0 {
cPath = (*C.char)(unsafe.Pointer(&pathBytes[0]))
}
var c *C.grngo_db
rc := C.grngo_open_db(cPath, C.size_t(len(pathBytes)), &c)
if rc != C.GRN_SUCCESS {
GrnFin()
return nil, newCError("grngo_open_db()", rc, nil)
}
return newDB(c), nil
}
// Close finalizes a DB.
func (db *DB) Close() error {
C.grngo_close_db(db.c)
return GrnFin()
}
// Refresh clears maps for Table and Column name resolution.
//
// If a table or column is renamed or removed, old maps can cause a name
// resolution error. In such a case, you should use Refresh or reopen the
// Groonga database to resolve it.
func (db *DB) Refresh() error {
for _, table := range db.tables {
for _, column := range table.columns {
C.grngo_close_column(column.c)
}
table.columns = make(map[string]*Column)
C.grngo_close_table(table.c)
}
db.tables = make(map[string]*Table)
return nil
}
// Send executes a Groonga command.
// The command must be well-formed.
//
// See http://groonga.org/docs/reference/command.html for details.
func (db *DB) Send(command string) error {
command = strings.TrimSpace(command)
if strings.HasPrefix(command, "table_remove") ||
strings.HasPrefix(command, "table_rename") ||
strings.HasPrefix(command, "column_remove") ||
strings.HasPrefix(command, "column_rename") {
db.Refresh()
}
commandBytes := []byte(command)
var cCommand *C.char
if len(commandBytes) != 0 {
cCommand = (*C.char)(unsafe.Pointer(&commandBytes[0]))
}
rc := C.grngo_send(db.c, cCommand, C.size_t(len(commandBytes)))
if rc != C.GRN_SUCCESS {
return newCError("grngo_send()", rc, db)
}
return nil
}
// SendEx executes a Groonga command with separated options.
//
// See http://groonga.org/docs/reference/command.html for details.
func (db *DB) SendEx(name string, options map[string]string) error {
if name == "" {
return fmt.Errorf("invalid command: name = <%s>", name)
}
for _, r := range name {
if (r != '_') && (r < 'a') && (r > 'z') {
return fmt.Errorf("invalid command: name = <%s>", name)
}
}
commandParts := []string{name}
for key, value := range options {
if key == "" {
return fmt.Errorf("invalid option: key = <%s>", key)
}
for _, r := range key {
if (r != '_') && (r < 'a') && (r > 'z') {
return fmt.Errorf("invalid option: key = <%s>", key)
}
}
value = strings.Replace(value, "\\", "\\\\", -1)
value = strings.Replace(value, "'", "\\'", -1)
commandParts = append(commandParts, fmt.Sprintf("--%s '%s'", key, value))
}
return db.Send(strings.Join(commandParts, " "))
}
// Recv returns the result of Groonga commands executed by Send and SendEx.
//
// See http://groonga.org/docs/reference/command.html for details.
func (db *DB) Recv() ([]byte, error) {
var res *C.char
var resLen C.uint
rc := C.grngo_recv(db.c, &res, &resLen)
if rc != C.GRN_SUCCESS {
return nil, newCError("grngo_recv()", rc, db)
}
return C.GoBytes(unsafe.Pointer(res), C.int(resLen)), nil
}
// Query executes a Groonga command and returns the result.
//
// See http://groonga.org/docs/reference/command.html for details.
func (db *DB) Query(command string) ([]byte, error) {
if err := db.Send(command); err != nil {
result, _ := db.Recv()
return result, err
}
return db.Recv()
}
// Query executes a Groonga command with separated options and returns the
// result.
//
// See http://groonga.org/docs/reference/command.html for details.
func (db *DB) QueryEx(name string, options map[string]string) (
[]byte, error) {
if err := db.SendEx(name, options); err != nil {
result, _ := db.Recv()
return result, err
}
return db.Recv()
}
// createTableOptionsMap creates an options map for table_create.
//
// See http://groonga.org/docs/reference/commands/table_create.html#parameters for details.
func (db *DB) createTableOptionsMap(name string, options *TableOptions) (map[string]string, error) {
optionsMap := make(map[string]string)
// http://groonga.org/docs/reference/commands/table_create.html#name
optionsMap["name"] = name
// http://groonga.org/docs/reference/commands/table_create.html#flags
if options.KeyType == "" {
optionsMap["flags"] = "TABLE_NO_KEY"
} else {
switch options.Flags & TableTypeMask {
case TableNoKey:
optionsMap["flags"] = "TABLE_NO_KEY"
case TableHashKey:
optionsMap["flags"] = "TABLE_HASH_KEY"
case TablePatKey:
optionsMap["flags"] = "TABLE_PAT_KEY"
case TableDatKey:
optionsMap["flags"] = "TABLE_DAT_KEY"
default:
return nil, fmt.Errorf("undefined table type: options = %+v", options)
}
}
if (options.Flags & KeyWithSIS) == KeyWithSIS {
optionsMap["flags"] += "|KEY_WITH_SIS"
}
// http://groonga.org/docs/reference/commands/table_create.html#key-type
switch options.KeyType {
case "":
case "Bool", "Int8", "Int16", "Int32", "Int64", "UInt8", "UInt16",
"UInt32", "UInt64", "Float", "Time", "ShortText", "TokyoGeoPoint",
"WGS84GeoPoint":
optionsMap["key_type"] = options.KeyType
default:
if _, err := db.FindTable(options.KeyType); err != nil {
return nil, fmt.Errorf("invalid key type: options = %+v", options)
}
optionsMap["key_type"] = options.KeyType
}
// http://groonga.org/docs/reference/commands/table_create.html#value-type
switch options.ValueType {
case "":
case "Bool", "Int8", "Int16", "Int32", "Int64", "UInt8", "UInt16",
"UInt32", "UInt64", "Float", "Time", "TokyoGeoPoint", "WGS84GeoPoint":
optionsMap["value_type"] = options.ValueType
default:
if _, err := db.FindTable(options.ValueType); err != nil {
return nil, fmt.Errorf("invalid value type: options = %+v", options)
}
optionsMap["value_type"] = options.ValueType
}
// http://groonga.org/docs/reference/commands/table_create.html#default-tokenizer
if options.DefaultTokenizer != "" {
optionsMap["default_tokenizer"] = options.DefaultTokenizer
}
// http://groonga.org/docs/reference/commands/table_create.html#normalizer
if options.Normalizer != "" {
optionsMap["normalizer"] = options.Normalizer
}
// http://groonga.org/docs/reference/commands/table_create.html#token-filters
if len(options.TokenFilters) != 0 {
optionsMap["token_filters"] = strings.Join(options.TokenFilters, ",")
}
return optionsMap, nil
}
// CreateTable creates a Groonga table and returns a new Table associated with
// it.
//
// If options is nil, the default parameters are used.
//
// See http://groonga.org/docs/reference/commands/table_create.html for details.
func (db *DB) CreateTable(name string, options *TableOptions) (*Table, error) {
if options == nil {
options = NewTableOptions()
}
optionsMap, err := db.createTableOptionsMap(name, options)
if err != nil {
return nil, err
}
bytes, err := db.QueryEx("table_create", optionsMap)
if err != nil {
return nil, err
}
if string(bytes) != "true" {
return nil, fmt.Errorf("table_create failed: name = <%s>", name)
}
return db.FindTable(name)
}
// FindTable finds a table.
func (db *DB) FindTable(name string) (*Table, error) {
if table, ok := db.tables[name]; ok {
return table, nil
}
nameBytes := []byte(name)
var cName *C.char
if len(nameBytes) != 0 {
cName = (*C.char)(unsafe.Pointer(&nameBytes[0]))
}
var c *C.grngo_table
rc := C.grngo_open_table(db.c, cName, C.size_t(len(nameBytes)), &c)
if rc != C.GRN_SUCCESS {
return nil, newCError("grngo_find_table()", rc, db)
}
table := newTable(db, c, name)
db.tables[name] = table
return table, nil
}
type LoadOptions struct {
IfExists string
}
// NewLoadOptions returns a new LoadOptions with the default settings.
func NewLoadOptions() *LoadOptions {
options := new(LoadOptions)
return options
}
// (Experimental) Load loads values.
func (db *DB) Load(tableName string, values interface{}, options *LoadOptions) ([]byte, error) {
table, err := db.FindTable(tableName)
if err != nil {
return nil, err
}
return table.Load(values, options)
}
// InsertRow finds or inserts a row.
func (db *DB) InsertRow(tableName string, key interface{}) (inserted bool, id uint32, err error) {
table, err := db.FindTable(tableName)
if err != nil {
return false, NilID, err
}
return table.InsertRow(key)
}
// CreateColumn creates a Groonga column and returns a new Column associated
// with it.
//
// If valueType starts with "[]", COLUMN_VECTOR is enabled and the rest is used
// as the type parameter.
// If valueType contains a dot ('.'), COLUMN_INDEX is enabled and valueType is
// split by the first dot. Then, the former part is used as the type parameter
// and the latter part is used as the source parameter.
// Otherwise, COLUMN_SCALAR is enabled and valueType is used as the type
// parameter.
//
// If options is nil, the default parameters are used.
//
// See http://groonga.org/docs/reference/commands/column_create.html for details.
func (db *DB) CreateColumn(tableName, columnName string, valueType string, options *ColumnOptions) (*Column, error) {
table, err := db.FindTable(tableName)
if err != nil {
return nil, err
}
return table.CreateColumn(columnName, valueType, options)
}
// FindColumn finds a column.
func (db *DB) FindColumn(tableName, columnName string) (*Column, error) {
table, err := db.FindTable(tableName)
if err != nil {
return nil, err
}
return table.FindColumn(columnName)
}
// SetValue assigns a value.
func (db *DB) SetValue(tableName, columnName string, id uint32, value interface{}) error {
table, err := db.FindTable(tableName)
if err != nil {
return err
}
return table.SetValue(columnName, id, value)
}
// GetValue gets a value.
func (db *DB) GetValue(tableName, columnName string, id uint32) (interface{}, error) {
table, err := db.FindTable(tableName)
if err != nil {
return nil, err
}
return table.GetValue(columnName, id)
}
// -- Table --
// Table is associated with a Groonga table.
type Table struct {
db *DB // The owner DB.
c *C.grngo_table // The associated C object.
name string // The table name.
columns map[string]*Column // A cache to find columns by name.
}
// newTable returns a new Table.
func newTable(db *DB, c *C.grngo_table, name string) *Table {
var table Table
table.db = db
table.c = c
table.name = name
table.columns = make(map[string]*Column)
return &table
}
// genLoadHead generates the head line of a load command.
func (table *Table) genLoadHead(options *LoadOptions) (string, error) {
line := fmt.Sprintf("load --table %s", table.name)
if options.IfExists != "" {
value := strings.Replace(options.IfExists, "\\", "\\\\", -1)
value = strings.Replace(value, "\"", "\\\"", -1)
line += fmt.Sprintf(" --ifexists '%s'", value)
}
return line, nil
}
// writeLoadColumns writes columns of a load command.
func (table *Table) writeLoadColumns(buf *bytes.Buffer, valueType reflect.Type) error {
if err := buf.WriteByte('['); err != nil {
return err
}
needsDelimiter := false
for i := 0; i < valueType.NumField(); i++ {
field := valueType.Field(i)
columnName := field.Tag.Get("grngo")
if columnName == "" {
continue
}
if needsDelimiter {
if err := buf.WriteByte(','); err != nil {
return err
}
} else {
needsDelimiter = true
}
if _, err := fmt.Fprintf(buf, "\"%s\"", columnName); err != nil {
return err
}
}
if err := buf.WriteByte(']'); err != nil {
return err
}
return nil
}
// writeLoadValue writes a value of a load command.
func (table *Table) writeLoadValue(buf *bytes.Buffer, value *reflect.Value) error {
if err := buf.WriteByte('['); err != nil {
return err
}
valueType := value.Type()
needsDelimiter := false
for i := 0; i < valueType.NumField(); i++ {
field := valueType.Field(i)
tag := field.Tag.Get("grngo")
if tag == "" {
continue
}
if needsDelimiter {
if err := buf.WriteByte(','); err != nil {
return err
}
} else {
needsDelimiter = true
}
fieldValue := value.Field(i)
switch fieldValue.Kind() {
case reflect.Bool:
if _, err := fmt.Fprint(buf, fieldValue.Bool()); err != nil {
return err
}
case reflect.Int64:
if _, err := fmt.Fprint(buf, fieldValue.Int()); err != nil {
return err
}
case reflect.Float64:
if _, err := fmt.Fprint(buf, fieldValue.Float()); err != nil {
return err
}
case reflect.String:
str := fieldValue.String()
str = strings.Replace(str, "\\", "\\\\", -1)
str = strings.Replace(str, "\"", "\\\"", -1)
if _, err := fmt.Fprintf(buf, "\"%s\"", str); err != nil {
return err
}
case reflect.Slice:
switch field.Type.Elem().Kind() {
case reflect.Uint8:
str := string(fieldValue.Bytes())
str = strings.Replace(str, "\\", "\\\\", -1)
str = strings.Replace(str, "\"", "\\\"", -1)
if _, err := fmt.Fprintf(buf, "\"%s\"", str); err != nil {
return err
}
default:
// TODO: Support other types!
return fmt.Errorf("unsupported data kind")
}
default:
// TODO: Support other types!
return fmt.Errorf("unsupported data kind")
}
}
if err := buf.WriteByte(']'); err != nil {
return err
}
return nil
}
// genLoadBody generates the body line of a load command.
func (table *Table) genLoadBody(values interface{}) (string, error) {
buf := new(bytes.Buffer)
if err := buf.WriteByte('['); err != nil {
return "", err
}
value := reflect.ValueOf(values)
switch value.Kind() {
case reflect.Struct:
case reflect.Ptr:
value := value.Elem()
if value.Kind() != reflect.Struct {
return "", fmt.Errorf("invalid values")
}
if err := table.writeLoadColumns(buf, value.Type()); err != nil {
return "", err
}
if err := table.writeLoadValue(buf, &value); err != nil {
return "", err
}
case reflect.Slice:
if value.Len() == 0 {
return "", fmt.Errorf("invalid values")
}
valueType := value.Type().Elem()
if valueType.Kind() != reflect.Struct {
return "", fmt.Errorf("invalid values")
}
if err := table.writeLoadColumns(buf, valueType); err != nil {
return "", err
}
for i := 0; i < value.Len(); i++ {
if err := buf.WriteByte(','); err != nil {
return "", err
}
v := value.Index(i)
if err := table.writeLoadValue(buf, &v); err != nil {
return "", err
}
}
}
if err := buf.WriteByte(']'); err != nil {
return "", err
}
return buf.String(), nil
}
// (Experimental) Load loads values.
//
// Implicit conversion for Time is not supported.
// GeoPoint is not supported.
// Vector types are not supported.
func (table *Table) Load(values interface{}, options *LoadOptions) ([]byte, error) {
if options == nil {
options = NewLoadOptions()
}
headLine, err := table.genLoadHead(options)
if err != nil {
return nil, err
}
bodyLine, err := table.genLoadBody(values)
if err != nil {
return nil, err
}
lines := []string{ headLine, bodyLine }
for _, line := range lines {
if err := table.db.Send(line); err != nil {
result, _ := table.db.Recv()
return result, err
}
}
return table.db.Recv()
}
// InsertRow finds or inserts a row.
func (table *Table) InsertRow(key interface{}) (inserted bool, id uint32, err error) {
var rc C.grn_rc
var cInserted C.grn_bool
var cID C.grn_id
switch key := key.(type) {
case nil:
rc = C.grngo_insert_void(table.c, &cInserted, &cID)
case bool:
cKey := C.grn_bool(C.GRN_FALSE)
if key {
cKey = C.grn_bool(C.GRN_TRUE)
}
rc = C.grngo_insert_bool(table.c, cKey, &cInserted, &cID)
case int64:
cKey := C.int64_t(key)
rc = C.grngo_insert_int(table.c, cKey, &cInserted, &cID)
case float64:
cKey := C.double(key)
rc = C.grngo_insert_float(table.c, cKey, &cInserted, &cID)
case []byte:
var cKey C.grngo_text
if len(key) != 0 {
cKey.ptr = (*C.char)(unsafe.Pointer(&key[0]))
cKey.size = C.size_t(len(key))
}
rc = C.grngo_insert_text(table.c, cKey, &cInserted, &cID)
case GeoPoint:
cKey := C.grn_geo_point{C.int(key.Latitude), C.int(key.Longitude)}
rc = C.grngo_insert_geo_point(table.c, cKey, &cInserted, &cID)
default:
return false, NilID, fmt.Errorf(
"unsupported key type: typeName = <%s>", reflect.TypeOf(key).Name())
}
if rc != C.GRN_SUCCESS {
return false, NilID, newCError("grngo_insert_*()", rc, table.db)
}
return cInserted == C.GRN_TRUE, uint32(cID), nil
}