public
Description: gemified mirror of the tokyotyrant ruby interface
Homepage:
Clone URL: git://github.com/careo/tokyotyrant-ruby.git
Thu Apr 09 10:51:59 -0700 2009
careo (committer)
Mon Apr 20 20:30:40 -0700 2009
tokyotyrant-ruby / tokyotyrant.rb
100644 1325 lines (1317 sloc) 42.286 kb
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
#--
# Pure Ruby interface of Tokyo Cabinet
# Copyright (C) 2006-2008 Mikio Hirabayashi
# This file is part of Tokyo Cabinet.
# Tokyo Cabinet is free software; you can redistribute it and/or modify it under the terms of
# the GNU Lesser General Public License as published by the Free Software Foundation; either
# version 2.1 of the License or any later version. Tokyo Cabinet is distributed in the hope
# that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
# License for more details.
# You should have received a copy of the GNU Lesser General Public License along with Tokyo
# Cabinet; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
# Boston, MA 02111-1307 USA.
#++
#:include:overview.rd
 
 
require "socket"
 
 
module TokyoTyrant
  # Remote database is a set of interfaces to use an abstract database of Tokyo Cabinet, mediated by a server of Tokyo Tyrant. Before operations to store or retrieve records, it is necessary to connect the remote database object to the server. The method `open' is used to open a database connection and the method `close' is used to close the connection.%%
  class RDB
    #--------------------------------
    # constants
    #--------------------------------
    public
    # error code: success
    ESUCCESS = 0
    # error code: invalid operation
    EINVALID = 1
    # error code: host not found
    ENOHOST = 2
    # error code: connection refused
    EREFUSED = 3
    # error code: send error
    ESEND = 4
    # error code: recv error
    ERECV = 5
    # error code: existing record
    EKEEP = 6
    # error code: no record found
    ENOREC = 7
    # error code: miscellaneous error
    EMISC = 9999
    # scripting extension option: record locking
    XOLCKREC = 1 << 0
    # scripting extension option: global locking
    XOLCKGLB = 1 << 1
    # versatile function option: omission of the update log
    MONOULOG = 1 << 0
    #--------------------------------
    # public methods
    #--------------------------------
    public
    # Create a remote database object.%%
    # The return value is the new remote database object.%%
    def initialize()
      @ecode = ESUCCESS
      @enc = nil
      @sock = nil
    end
    # Get the message string corresponding to an error code.%%
    # `<i>ecode</i>' specifies the error code. If it is not defined or negative, the last happened error code is specified.%%
    # The return value is the message string of the error code.%%
    def errmsg(ecode = nil)
      ecode = @ecode if !ecode
      if ecode == ESUCCESS
        return "success"
      elsif ecode == EINVALID
        return "invalid operation"
      elsif ecode == ENOHOST
        return "host not found"
      elsif ecode == EREFUSED
        return "connection refused"
      elsif ecode == ESEND
        return "send error"
      elsif ecode == ERECV
        return "recv error"
      elsif ecode == EKEEP
        return "existing record"
      elsif ecode == ENOREC
        return "no record found"
      elsif ecode == EMISC
        return "miscellaneous error"
      end
      return "unknown"
    end
    # Get the last happened error code.%%
    # The return value is the last happened error code.%%
    # The following error code is defined: `TokyoTyrant::RDB::ESUCCESS' for success, `TokyoTyrant::RDB::EINVALID' for invalid operation, `TokyoTyrant::RDB::ENOHOST' for host not found, `TokyoTyrant::RDB::EREFUSED' for connection refused, `TokyoTyrant::RDB::ESEND' for send error, `TokyoTyrant::RDB::ERECV' for recv error, `TokyoTyrant::RDB::EKEEP' for existing record, `TokyoTyrant::RDB::ENOREC' for no record found, `TokyoTyrant::RDB::EMISC' for miscellaneous error.%%
    def ecode()
      return @ecode
    end
    # Open a remote database connection.%%
    # `<i>host</i>' specifies the name or the address of the server.%%
    # `<i>port</i>' specifies the port number. If it is not defined or not more than 0, UNIX domain socket is used and the path of the socket file is specified by the host parameter.%%
    # If successful, the return value is true, else, it is false.%%
    def open(host, port = 0)
      host = _argstr(host)
      port = _argnum(port)
      if @sock
        @ecode = EINVALID
        return false
      end
      if port > 0
        begin
          info = TCPSocket.gethostbyname(host)
        rescue Exception
          @ecode = ENOHOST
          return false
        end
        begin
          sock = TCPSocket.open(info[3], port)
        rescue Exception
          @ecode = EREFUSED
          return false
        end
        begin
          sock.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, true)
        rescue Exception
        end
      else
        begin
          sock = UNIXSocket.open(host)
        rescue Exception
          @ecode = EREFUSED
          return false
        end
      end
      if sock.respond_to?(:set_encoding)
        sock.set_encoding("ASCII-8BIT")
      end
      @sock = sock
      return true
    end
    # Close the database connection.%%
    # If successful, the return value is true, else, it is false.%%
    def close()
      if !@sock
        @ecode = EINVALID
        return false
      end
      begin
        @sock.close
      rescue Exception
        @ecode = EMISC
        @sock = nil
        return false
      end
      @sock = nil
      return true
    end
    # Store a record.%%
    # `<i>key</i>' specifies the key.%%
    # `<i>value</i>' specifies the value.%%
    # If successful, the return value is true, else, it is false.%%
    # If a record with the same key exists in the database, it is overwritten.%%
    def put(key, value)
      key = _argstr(key)
      value = _argstr(value)
      if !@sock
        @ecode = EINVALID
        return false
      end
      sbuf = [0xC8, 0x10, key.length, value.length].pack("CCNN")
      sbuf += key + value
      if !_send(sbuf)
        @ecode = ESEND
        return false
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return false
      end
      if code != 0
        @ecode = EMISC
        return false
      end
      return true
    end
    # Store a new record.%%
    # `<i>key</i>' specifies the key.%%
    # `<i>value</i>' specifies the value.%%
    # If successful, the return value is true, else, it is false.%%
    # If a record with the same key exists in the database, this method has no effect.%%
    def putkeep(key, value)
      key = _argstr(key)
      value = _argstr(value)
      if !@sock
        @ecode = EINVALID
        return false
      end
      sbuf = [0xC8, 0x11, key.length, value.length].pack("CCNN")
      sbuf += key + value
      if !_send(sbuf)
        @ecode = ESEND
        return false
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return false
      end
      if code != 0
        @ecode = EKEEP
        return false
      end
      return true
    end
    # Concatenate a value at the end of the existing record.%%
    # `<i>key</i>' specifies the key.%%
    # `<i>value</i>' specifies the value.%%
    # If successful, the return value is true, else, it is false.%%
    # If there is no corresponding record, a new record is created.%%
    def putcat(key, value)
      key = _argstr(key)
      value = _argstr(value)
      if !@sock
        @ecode = EINVALID
        return false
      end
      sbuf = [0xC8, 0x12, key.length, value.length].pack("CCNN")
      sbuf += key + value
      if !_send(sbuf)
        @ecode = ESEND
        return false
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return false
      end
      if code != 0
        @ecode = EMISC
        return false
      end
      return true
    end
    # Concatenate a value at the end of the existing record and shift it to the left.%%
    # `<i>key</i>' specifies the key.%%
    # `<i>value</i>' specifies the value.%%
    # `<i>width</i>' specifies the width of the record.%%
    # If successful, the return value is true, else, it is false.%%
    # If there is no corresponding record, a new record is created.%%
    def putshl(key, value, width = 0)
      key = _argstr(key)
      value = _argstr(value)
      width = _argnum(width)
      if !@sock
        @ecode = EINVALID
        return false
      end
      sbuf = [0xC8, 0x13, key.length, value.length, width].pack("CCNNN")
      sbuf += key + value
      if !_send(sbuf)
        @ecode = ESEND
        return false
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return false
      end
      if code != 0
        @ecode = EMISC
        return false
      end
      return true
    end
    # Store a record without response from the server.%%
    # `<i>key</i>' specifies the key.%%
    # `<i>value</i>' specifies the value.%%
    # If successful, the return value is true, else, it is false.%%
    # If a record with the same key exists in the database, it is overwritten.%%
    def putnr(key, value)
      key = _argstr(key)
      value = _argstr(value)
      if !@sock
        @ecode = EINVALID
        return false
      end
      sbuf = [0xC8, 0x18, key.length, value.length].pack("CCNN")
      sbuf += key + value
      if !_send(sbuf)
        @ecode = ESEND
        return false
      end
      return true
    end
    # Remove a record.%%
    # `<i>key</i>' specifies the key.%%
    # If successful, the return value is true, else, it is false.%%
    def out(key)
      key = _argstr(key)
      if !@sock
        @ecode = EINVALID
        return false
      end
      sbuf = [0xC8, 0x20, key.length].pack("CCN")
      sbuf += key
      if !_send(sbuf)
        @ecode = ESEND
        return false
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return false
      end
      if code != 0
        @ecode = ENOREC
        return false
      end
      return true
    end
    # Retrieve a record.%%
    # `<i>key</i>' specifies the key.%%
    # If successful, the return value is the value of the corresponding record. `nil' is returned if no record corresponds.%%
    def get(key)
      key = _argstr(key)
      sbuf = [0xC8, 0x30, key.length].pack("CCN")
      sbuf += key
      if !_send(sbuf)
        @ecode = ESEND
        return nil
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return nil
      end
      if code != 0
        @ecode = ENOREC
        return nil
      end
      vsiz = _recvint32
      if vsiz < 0
        @ecode = ERECV
        return nil
      end
      vbuf = _recv(vsiz)
      if !vbuf
        @ecode = ERECV
        return nil
      end
      return _retstr(vbuf)
    end
    # Retrieve records.%%
    # `<i>recs</i>' specifies a hash containing the retrieval keys. As a result of this method, keys existing in the database have the corresponding values and keys not existing in the database are removed.%%
    # If successful, the return value is the number of retrieved records or -1 on failure.%%
    def mget(recs)
      raise ArgumentError if !recs.is_a?(Hash)
      if !@sock
        @ecode = EINVALID
        return -1
      end
      rnum = 0
      sbuf = ""
      recs.each_pair do |key, value|
        key = _argstr(key)
        sbuf += [key.length].pack("N") + key
        rnum += 1
      end
      sbuf = [0xC8, 0x31, rnum].pack("CCN") + sbuf
      if !_send(sbuf)
        @ecode = ESEND
        return -1
      end
      code = _recvcode
      rnum = _recvint32
      if code == -1
        @ecode = ERECV
        return -1
      end
      if code != 0
        @ecode = ENOREC
        return -1
      end
      if rnum < 0
        @ecode = ERECV
        return -1
      end
      recs.clear
      for i in 1..rnum
        ksiz = _recvint32()
        vsiz = _recvint32()
        if ksiz < 0 || vsiz < 0
          @ecode = ERECV
          return -1
        end
        kbuf = _recv(ksiz)
        vbuf = _recv(vsiz)
        if !kbuf || !vbuf
          @ecode = ERECV
          return -1
        end
        recs[kbuf] = _retstr(vbuf)
      end
      return rnum
    end
    # Get the size of the value of a record.%%
    # `<i>key</i>' specifies the key.%%
    # If successful, the return value is the size of the value of the corresponding record, else, it is -1.%%
    def vsiz(key)
      key = _argstr(key)
      if !@sock
        @ecode = EINVALID
        return -1
      end
      sbuf = [0xC8, 0x38, key.length].pack("CCN")
      sbuf += key
      if !_send(sbuf)
        @ecode = ESEND
        return -1
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return -1
      end
      if code != 0
        @ecode = ENOREC
        return -1
      end
      return _recvint32
    end
    # Initialize the iterator.%%
    # If successful, the return value is true, else, it is false.%%
    # The iterator is used in order to access the key of every record stored in a database.%%
    def iterinit()
      if !@sock
        @ecode = EINVALID
        return false
      end
      sbuf = [0xC8, 0x50].pack("CC")
      if !_send(sbuf)
        @ecode = ESEND
        return false
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return false
      end
      if code != 0
        @ecode = EMISC
        return false
      end
      return true
    end
    # Get the next key of the iterator.%%
    # If successful, the return value is the next key, else, it is `nil'. `nil' is returned when no record is to be get out of the iterator.%%
    # It is possible to access every record by iteration of calling this method. It is allowed to update or remove records whose keys are fetched while the iteration. However, it is not assured if updating the database is occurred while the iteration. Besides, the order of this traversal access method is arbitrary, so it is not assured that the order of storing matches the one of the traversal access.%%
    def iternext()
      if !@sock
        @ecode = EINVALID
        return nil
      end
      sbuf = [0xC8, 0x51].pack("CC")
      if !_send(sbuf)
        @ecode = ESEND
        return nil
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return nil
      end
      if code != 0
        @ecode = ENOREC
        return nil
      end
      vsiz = _recvint32
      if vsiz < 0
        @ecode = ERECV
        return nil
      end
      vbuf = _recv(vsiz)
      if !vbuf
        @ecode = ERECV
        return nil
      end
      return _retstr(vbuf)
    end
    # Get forward matching keys.%%
    # `<i>prefix</i>' specifies the prefix of the corresponding keys.%%
    # `<i>max</i>' specifies the maximum number of keys to be fetched. If it is not defined or negative, no limit is specified.%%
    # The return value is an array of the keys of the corresponding records. This method does never fail and return an empty array even if no record corresponds.%%
    # Note that this method may be very slow because every key in the database is scanned.%%
    def fwmkeys(prefix, max = -1)
      prefix = _argstr(prefix)
      max = _argnum(max)
      if !@sock
        @ecode = EINVALID
        return Array.new
      end
      sbuf = [0xC8, 0x58, prefix.length, max].pack("CCNN")
      sbuf += prefix
      if !_send(sbuf)
        @ecode = ESEND
        return Array.new
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return Array.new
      end
      if code != 0
        @ecode = ENOREC
        return Array.new
      end
      knum = _recvint32
      if knum < 0
        @ecode = ERECV
        return Array.new
      end
      keys = Array.new
      for i in 1..knum
        ksiz = _recvint32()
        if ksiz < 0
          @ecode = ERECV
          return Array.new
        end
        kbuf = _recv(ksiz)
        if !kbuf
          @ecode = ERECV
          return Array.new
        end
        keys.push(_retstr(kbuf))
      end
      return keys
    end
    # Add an integer to a record.%%
    # `<i>key</i>' specifies the key.%%
    # `<i>num</i>' specifies the additional value. If it is not defined, 0 is specified.%%
    # If successful, the return value is the summation value, else, it is `nil'.%%
    # If the corresponding record exists, the value is treated as an integer and is added to. If no record corresponds, a new record of the additional value is stored. Because records are stored in binary format, they should be processed with the `unpack' function with the `i' operator after retrieval.%%
    def addint(key, num = 0)
      key = _argstr(key)
      num = _argnum(num)
      if !@sock
        @ecode = EINVALID
        return nil
      end
      sbuf = [0xC8, 0x60, key.length, num].pack("CCNN")
      sbuf += key
      if !_send(sbuf)
        @ecode = ESEND
        return nil
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return nil
      end
      if code != 0
        @ecode = EKEEP
        return nil
      end
      return _recvint32
    end
    # Add a real number to a record.%%
    # `<i>key</i>' specifies the key.%%
    # `<i>num</i>' specifies the additional value. If it is not defined, 0 is specified.%%
    # If successful, the return value is the summation value, else, it is `nil'.%%
    # If the corresponding record exists, the value is treated as a real number and is added to. If no record corresponds, a new record of the additional value is stored. Because records are stored in binary format, they should be processed with the `unpack' function with the `d' operator after retrieval.%%
    def adddouble(key, num)
      key = _argstr(key)
      num = _argnum(num)
      if !@sock
        @ecode = EINVALID
        return nil
      end
      integ = num.truncate
      fract = ((num - integ) * 1000000000000).truncate
      sbuf = [0xC8, 0x61, key.length].pack("CCN")
      sbuf += _packquad(integ) + _packquad(fract) + key
      if !_send(sbuf)
        @ecode = ESEND
        return nil
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return nil
      end
      if code != 0
        @ecode = EKEEP
        return nil
      end
      integ = _recvint64()
      fract = _recvint64()
      return integ + fract / 1000000000000.0
    end
    # Call a function of the script language extension.%%
    # `<i>name</i>' specifies the function name.%%
    # `<i>key</i>' specifies the key. If it is not defined, an empty string is specified.%%
    # `<i>value</i>' specifies the value. If it is not defined, an empty string is specified.%%
    # `<i>opts</i>' specifies options by bitwise-or: `TokyoTyrant::RDB::XOLCKREC' for record locking, `TokyoTyrant::RDB::XOLCKGLB' for global locking. If it is not defined, no option is specified.%%
    # If successful, the return value is the value of the response or `nil' on failure.%%
    def ext(name, key = "", value = "", opts = 0)
      name = _argstr(name)
      key = _argstr(key)
      value = _argstr(value)
      opts = _argnum(opts)
      if !@sock
        @ecode = EINVALID
        return nil
      end
      sbuf = [0xC8, 0x68, name.length, opts, key.length, value.length].pack("CCNNNN")
      sbuf += name + key + value
      if !_send(sbuf)
        @ecode = ESEND
        return nil
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return nil
      end
      if code != 0
        @ecode = EMISC
        return nil
      end
      vsiz = _recvint32
      if vsiz < 0
        @ecode = ERECV
        return nil
      end
      vbuf = _recv(vsiz)
      if !vbuf
        @ecode = ERECV
        return nil
      end
      return _retstr(vbuf)
    end
    # Synchronize updated contents with the file and the device.%%
    # If successful, the return value is true, else, it is false.%%
    def sync()
      if !@sock
        @ecode = EINVALID
        return false
      end
      sbuf = [0xC8, 0x70].pack("CC")
      if !_send(sbuf)
        @ecode = ESEND
        return false
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return false
      end
      if code != 0
        @ecode = EMISC
        return false
      end
      return true
    end
    # Remove all records.%%
    # If successful, the return value is true, else, it is false.%%
    def vanish()
      if !@sock
        @ecode = EINVALID
        return false
      end
      sbuf = [0xC8, 0x71].pack("CC")
      if !_send(sbuf)
        @ecode = ESEND
        return false
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return false
      end
      if code != 0
        @ecode = EMISC
        return false
      end
      return true
    end
    # Copy the database file.%%
    # `<i>path</i>' specifies the path of the destination file. If it begins with `@', the trailing substring is executed as a command line.%%
    # If successful, the return value is true, else, it is false. False is returned if the executed command returns non-zero code.%%
    # The database file is assured to be kept synchronized and not modified while the copying or executing operation is in progress. So, this method is useful to create a backup file of the database file.%%
    def copy(path)
      path = _argstr(path)
      if !@sock
        @ecode = EINVALID
        return false
      end
      sbuf = [0xC8, 0x72, path.length].pack("CCN")
      sbuf += path
      if !_send(sbuf)
        @ecode = ESEND
        return false
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return false
      end
      if code != 0
        @ecode = EMISC
        return false
      end
      return true
    end
    # Get the number of records.%%
    # The return value is the number of records or 0 if the object does not connect to any database server.%%
    def rnum()
      if !@sock
        @ecode = EINVALID
        return 0
      end
      sbuf = [0xC8, 0x80].pack("CC")
      if !_send(sbuf)
        @ecode = ESEND
        return 0
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return 0
      end
      if code != 0
        @ecode = EMISC
        return 0
      end
      return _recvint64
    end
    # Get the size of the database.%%
    # The return value is the size of the database or 0 if the object does not connect to any database server.%%
    def size()
      if !@sock
        @ecode = EINVALID
        return 0
      end
      sbuf = [0xC8, 0x81].pack("CC")
      if !_send(sbuf)
        @ecode = ESEND
        return 0
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return 0
      end
      if code != 0
        @ecode = EMISC
        return 0
      end
      return _recvint64
    end
    # Get the status string of the database server.%%
    # The return value is the status message of the database or `nil' if the object does not connect to any database server. The message format is TSV. The first field of each line means the parameter name and the second field means the value.%%
    def stat()
      if !@sock
        @ecode = EINVALID
        return nil
      end
      sbuf = [0xC8, 0x88].pack("CC")
      if !_send(sbuf)
        @ecode = ESEND
        return nil
      end
      code = _recvcode
      if code == -1
        @ecode = ERECV
        return nil
      end
      if code != 0
        @ecode = ENOREC
        return nil
      end
      ssiz = _recvint32
      if ssiz < 0
        @ecode = ERECV
        return nil
      end
      sbuf = _recv(ssiz)
      if !sbuf
        @ecode = ERECV
        return nil
      end
      return _retstr(sbuf)
    end
    # Call a versatile function for miscellaneous operations.%%
    # `<i>name</i>' specifies the name of the function. All databases support "putlist", "outlist", and "getlist". "putlist" is to store records. It receives keys and values one after the other, and returns an empty list. "outlist" is to remove records. It receives keys, and returns an empty array. "getlist" is to retrieve records. It receives keys, and returns keys and values of corresponding records one after the other. Table database supports "setindex", "search", and "genuid".%%
    # `<i>args</i>' specifies an array containing arguments. If it is not defined, no argument is specified.%%
    # `<i>opts</i>' specifies options by bitwise-or: `TokyoTyrant::RDB::MONOULOG' for omission of the update log. If it is not defined, no option is specified.%%
    # If successful, the return value is an array of the result. `nil' is returned on failure.%%
    def misc(name, args = [], opts = 0)
      name = _argstr(name)
      args = Array.new if !args.is_a?(Array)
      opts = _argnum(opts)
      if !@sock
        @ecode = EINVALID
        return nil
      end
      sbuf = [0xC8, 0x90, name.length, opts, args.size].pack("CCNNN")
      sbuf += name
      args.each do |arg|
        arg = _argstr(arg)
        sbuf += [arg.length].pack("N") + arg
      end
      if !_send(sbuf)
        @ecode = ESEND
        return nil
      end
      code = _recvcode
      rnum = _recvint32
      if code == -1
        @ecode = ERECV
        return nil
      end
      if code != 0
        @ecode = EMISC
        return nil
      end
      res = Array.new
      for i in 1..rnum
        esiz = _recvint32
        if esiz < 0
          @ecode = ERECV
          return nil
        end
        ebuf = _recv(esiz)
        if !ebuf
          @ecode = ERECV
          return nil
        end
        res.push(_retstr(ebuf))
      end
      return res
    end
    #--------------------------------
    # aliases and iterators
    #--------------------------------
    public
    # Hash-compatible method.%%
    # Alias of `put'.%%
    def store(key, value)
      return put(key, value)
    end
    # Hash-compatible method.%%
    # Alias of `out'.%%
    def delete(key)
      return out(key)
    end
    # Hash-compatible method.%%
    # Alias of `get'.%%
    def fetch(key)
      return out(key)
    end
    # Hash-compatible method.%%
    # Check existence of a key.%%
    def has_key?(key)
      return vsiz(key) >= 0
    end
    # Hash-compatible method.%%
    # Check existence of a value.%%
    def has_value?(value)
      return nil if !iterinit
      while tkey = iternext
        tvalue = get(tkey)
        break if !tvalue
        return true if value == tvalue
      end
      return false
    end
    # Hash-compatible method.%%
    # Alias of `vanish'.%%
    def clear
      return vanish
    end
    # Hash-compatible method.%%
    # Alias of `rnum'.%%
    def length
      return rnum
    end
    # Hash-compatible method.%%
    # Alias of `rnum > 0'.%%
    def empty?
      return rnum > 0
    end
    # Hash-compatible method.%%
    # Alias of `put'.%%
    def []=(key, value)
      return put(key, value)
    end
    # Hash-compatible method.%%
    # Alias of `get'.%%
    def [](key)
      return get(key)
    end
    # Hash-compatible method.%%
    # Iterator of pairs of the key and the value.%%
    def each
      return nil if !iterinit
      while key = iternext
        value = get(key)
        break if !value
        yield(key, value)
      end
      return nil
    end
    alias each_pair each
    # Hash-compatible method.%%
    # Iterator of the keys.%%
    def each_keys
      return nil if !iterinit
      while key = iternext
        yield(key)
      end
      return nil
    end
    # Hash-compatible method.%%
    # Iterator of the values.%%
    def each_values
      return nil if !iterinit
      while key = iternext
        value = get(key)
        break if !value
        yield(value)
      end
      return nil
    end
    # Hash-compatible method.%%
    # Get an array of all keys.%%
    def keys
      tkeys = Array.new
      return tkeys if !iterinit
      while key = iternext
        tkeys.push(key)
      end
      return tkeys
    end
    # Hash-compatible method.%%
    # Get an array of all keys.%%
    def values
      tvals = Array.new
      return tvals if !iterinit
      while key = iternext
        value = get(key)
        break if !value
        tvals.push(value)
      end
      return tvals
    end
    #--------------------------------
    # private methods
    #--------------------------------
    private
    # Get a string argument.%%
    def _argstr(obj)
      case obj
      when Numeric
        obj = obj.to_s
      when Symbol
        obj = obj.to_s
      when String
      else
        raise ArgumentError
      end
      if obj.respond_to?(:force_encoding)
        obj = obj.dup
        obj.force_encoding("ASCII-8BIT")
      end
      return obj
    end
    # Get a numeric argument.%%
    def _argnum(obj)
      case obj
      when String
        obj = obj.to_i
      when Numeric
      else
        raise ArgumentError
      end
      return obj
    end
    # Get a normalized string to be returned
    def _retstr(str)
      if str.respond_to?(:force_encoding)
        if @enc
          str.force_encoding(@enc)
        elsif Encoding.default_internal
          str.force_encoding(Encoding.default_internal)
        else
          str.force_encoding("UTF-8")
        end
      end
      return str
    end
    # Send a series of data.%%
    def _send(buf)
      begin
        @sock.send(buf, 0)
      rescue Exception
        return false
      end
      return true
    end
    # Receive a series of data.%%
    def _recv(len)
      return "" if len < 1
      begin
        str = @sock.recv(len, 0)
        len -= str.length
        while len > 0
          tstr = @sock.recv(len, 0)
          len -= tstr.length
          str += tstr
        end
        return str
      rescue Exception
        return nil
      end
    end
    # Receive a byte code.%%
    def _recvcode()
      rbuf = _recv(1)
      return -1 if !rbuf
      return rbuf.unpack("C")[0]
    end
    # Receive an int32 number.%%
    def _recvint32()
      rbuf = _recv(4)
      return -1 if !rbuf
      num = rbuf.unpack("N")[0]
      return [num].pack("l").unpack("l")[0]
    end
    # Receive an int64 number.%%
    def _recvint64()
      rbuf = _recv(8)
      return -1 if !rbuf
      high, low = rbuf.unpack("NN")
      num = (high << 32) + low
      return [num].pack("q").unpack("q")[0]
    end
    # Pack an int64 value.%%
    def _packquad(num)
      high = (num / (1 << 32)).truncate
      low = num % (1 << 32)
      return [high, low].pack("NN")
    end
  end
  # This class inherits the class "TokyoTyrant::RDB". All methods are specific to servers of the table database.%%
  class RDBTBL < RDB
    #--------------------------------
    # constants
    #--------------------------------
    public
    # index type: lexical string
    ITLEXICAL = 0
    # index type: decimal string
    ITDECIMAL = 1
    # index type: optimize
    ITOPT = 9998
    # index type: void
    ITVOID = 9999
    # index type: keep existing index
    ITKEEP = 1 << 24
    #--------------------------------
    # public methods
    #--------------------------------
    public
    # Store a record.%%
    # `<i>pkey</i>' specifies the primary key.%%
    # `<i>cols</i>' specifies a hash containing columns.%%
    # If successful, the return value is true, else, it is false.%%
    # If a record with the same key exists in the database, it is overwritten.%%
    def put(pkey, cols)
      pkey = _argstr(pkey)
      raise ArgumentError if !cols.is_a?(Hash)
      args = Array.new
      args.push(pkey)
      cols.each do |ckey, cvalue|
        args.push(ckey)
        args.push(cvalue)
      end
      rv = misc("put", args, 0)
      return rv ? true : false
    end
    # Store a new record.%%
    # `<i>pkey</i>' specifies the primary key.%%
    # `<i>cols</i>' specifies a hash containing columns.%%
    # If successful, the return value is true, else, it is false.%%
    # If a record with the same key exists in the database, this method has no effect.%%
    def putkeep(pkey, cols)
      pkey = _argstr(pkey)
      raise ArgumentError if !cols.is_a?(Hash)
      args = Array.new
      args.push(pkey)
      cols.each do |ckey, cvalue|
        args.push(ckey)
        args.push(cvalue)
      end
      rv = misc("putkeep", args, 0)
      return rv ? true : false
    end
    # Concatenate columns of the existing record.%%
    # `<i>pkey</i>' specifies the primary key.%%
    # `<i>cols</i>' specifies a hash containing columns.%%
    # If successful, the return value is true, else, it is false.%%
    # If there is no corresponding record, a new record is created.%%
    def putcat(pkey, cols)
      pkey = _argstr(pkey)
      raise ArgumentError if !cols.is_a?(Hash)
      args = Array.new
      args.push(pkey)
      cols.each do |ckey, cvalue|
        args.push(ckey)
        args.push(cvalue)
      end
      rv = misc("putcat", args, 0)
      return rv ? true : false
    end
    # Remove a record.%%
    # `<i>pkey</i>' specifies the primary key.%%
    # If successful, the return value is true, else, it is false.%%
    def out(pkey)
      pkey = _argstr(pkey)
      return super(pkey)
    end
    # Retrieve a record.%%
    # `<i>pkey</i>' specifies the primary key.%%
    # If successful, the return value is a hash of the columns of the corresponding record. `nil' is returned if no record corresponds.%%
    def get(pkey)
      pkey = _argstr(pkey)
      args = Array.new
      args.push(pkey)
      rv = misc("get", args)
      return nil if !rv
      cols = Hash.new()
      cnum = rv.length
      cnum -= 1
      i = 0
      while i < cnum
        cols[rv[i]] = rv[i+1]
        i += 2
      end
      return cols
    end
    # Retrieve records.%%
    # `<i>recs</i>' specifies a hash containing the retrieval keys. As a result of this method, keys existing in the database have the corresponding columns and keys not existing in the database are removed.%%
    # If successful, the return value is the number of retrieved records or -1 on failure.%%
    # Due to the protocol restriction, this method can not handle records with binary columns including the "\0" chracter.%%
    def mget(recs)
      rv = super(recs)
      return -1 if rv < 0
      recs.each do |pkey, value|
        cols = Hash.new
        cary = value.split("\0")
        cnum = cary.size - 1
        i = 0
        while i < cnum
          cols[cary[i]] = cary[i+1]
          i += 2
        end
        recs[pkey] = cols
      end
      return rv
    end
    # Set a column index.%%
    # `<i>name</i>' specifies the name of a column. If the name of an existing index is specified, the index is rebuilt. An empty string means the primary key.%%
    # `<i>type</i>' specifies the index type: `TokyoCabinet::RDBTBL::ITLEXICAL' for lexical string, `TokyoCabinet::RDBTBL::ITDECIMAL' for decimal string. If it is `TokyoCabinet::RDBTBL::ITOPT', the index is optimized. If it is `TokyoCabinet::RDBTBL::ITVOID', the index is removed. If `TokyoCabinet::RDBTBL::ITKEEP' is added by bitwise-or and the index exists, this method merely returns failure.%%
    # If successful, the return value is true, else, it is false.%%
    def setindex(name, type)
      name = _argstr(name)
      type = _argnum(type)
      args = Array.new
      args.push(name)
      args.push(type)
      rv = misc("setindex", args, 0)
      return rv ? true : false
    end
    # Generate a unique ID number.%%
    # The return value is the new unique ID number or -1 on failure.%%
    def genuid()
      rv = misc("genuid", Array.new, 0)
      return -1 if !rv
      return rv[0]
    end
  end
  # This class is a helper for the class "TokyoTyrant::RDBTBL".%%
  class RDBQRY
    # query condition: string is equal to
    QCSTREQ = 0
    # query condition: string is included in
    QCSTRINC = 1
    # query condition: string begins with
    QCSTRBW = 2
    # query condition: string ends with
    QCSTREW = 3
    # query condition: string includes all tokens in
    QCSTRAND = 4
    # query condition: string includes at least one token in
    QCSTROR = 5
    # query condition: string is equal to at least one token in
    QCSTROREQ = 6
    # query condition: string matches regular expressions of
    QCSTRRX = 7
    # query condition: number is equal to
    QCNUMEQ = 8
    # query condition: number is greater than
    QCNUMGT = 9
    # query condition: number is greater than or equal to
    QCNUMGE = 10
    # query condition: number is less than
    QCNUMLT = 11
    # query condition: number is less than or equal to
    QCNUMLE = 12
    # query condition: number is between two tokens of
    QCNUMBT = 13
    # query condition: number is equal to at least one token in
    QCNUMOREQ = 14
    # query condition: negation flag
    QCNEGATE = 1 << 24
    # query condition: no index flag
    QCNOIDX = 1 << 25
    # order type: string ascending
    QOSTRASC = 0
    # order type: string descending
    QOSTRDESC = 1
    # order type: number ascending
    QONUMASC = 2
    # order type: number descending
    QONUMDESC = 3
    # Create a query object.%%
    # `<i>rdb</i>' specifies the remote database object.%%
    # The return value is the new query object.%%
    def initialize(rdb)
      raise ArgumentError if !rdb.is_a?(TokyoTyrant::RDBTBL)
      @rdb = rdb
      @args = Array.new
      def self.setmax(max) # for backward compatibility
        setlimit(max)
      end
    end
    # Add a narrowing condition.%%
    # `<i>name</i>' specifies the name of a column. An empty string means the primary key.%%
    # `<i>op</i>' specifies an operation type: `TokyoCabinet::RDBQRY::QCSTREQ' for string which is equal to the expression, `TokyoCabinet::RDBQRY::QCSTRINC' for string which is included in the expression, `TokyoCabinet::RDBQRY::QCSTRBW' for string which begins with the expression, `TokyoCabinet::RDBQRY::QCSTREW' for string which ends with the expression, `TokyoCabinet::RDBQRY::QCSTRAND' for string which includes all tokens in the expression, `TokyoCabinet::RDBQRY::QCSTROR' for string which includes at least one token in the expression, `TokyoCabinet::RDBQRY::QCSTROREQ' for string which is equal to at least one token in the expression, `TokyoCabinet::RDBQRY::QCSTRRX' for string which matches regular expressions of the expression, `TokyoCabinet::RDBQRY::QCNUMEQ' for number which is equal to the expression, `TokyoCabinet::RDBQRY::QCNUMGT' for number which is greater than the expression, `TokyoCabinet::RDBQRY::QCNUMGE' for number which is greater than or equal to the expression, `TokyoCabinet::RDBQRY::QCNUMLT' for number which is less than the expression, `TokyoCabinet::RDBQRY::QCNUMLE' for number which is less than or equal to the expression, `TokyoCabinet::RDBQRY::QCNUMBT' for number which is between two tokens of the expression, `TokyoCabinet::RDBQRY::QCNUMOREQ' for number which is equal to at least one token in the expression. All operations can be flagged by bitwise-or: `TokyoCabinet::RDBQRY::QCNEGATE' for negation, `TokyoCabinet::RDBQRY::QCNOIDX' for using no index.%%
    # `<i>expr</i>' specifies an operand exression.%%
    # The return value is always `nil'.%%
    def addcond(name, op, expr)
      @args.push("addcond" + "\0" + name + "\0" + op.to_s + "\0" + expr)
      return nil
    end
    # Set the order of the result.%%
    # `<i>name</i>' specifies the name of a column. An empty string means the primary key.%%
    # `<i>type</i>' specifies the order type: `TokyoCabinet::RDBQRY::QOSTRASC' for string ascending, `TokyoCabinet::RDBQRY::QOSTRDESC' for string descending, `TokyoCabinet::RDBQRY::QONUMASC' for number ascending, `TokyoCabinet::RDBQRY::QONUMDESC' for number descending.%%
    # The return value is always `nil'.%%
    def setorder(name, type)
      @args.push("setorder" + "\0" + name + "\0" + type.to_s)
      return nil
    end
    # Set the maximum number of records of the result.%%
    # `<i>max</i>' specifies the maximum number of records of the result. If it is not defined or negative, no limit is specified.%%
    # `<i>skip</i>' specifies the maximum number of records of the result. If it is not defined or not more than 0, no record is skipped.%%
    # The return value is always `nil'.%%
    def setlimit(max = -1, skip = -1)
      @args.push("setlimit" + "\0" + max.to_s + "\0" + skip.to_s)
      return nil
    end
    # Execute the search.%%
    # The return value is an array of the primary keys of the corresponding records. This method does never fail and return an empty array even if no record corresponds.%%
    def search()
      rv = @rdb.misc("search", @args, RDB::MONOULOG)
      return rv ? rv : Array.new
    end
    # Remove each corresponding record.%%
    # If successful, the return value is true, else, it is false.%%
    def searchout()
      args = Array.new(@args)
      args.push("out")
      rv = @rdb.misc("search", args, 0)
      return rv ? true : false
    end
    # Get records corresponding to the search.%%
    # `<i>names</i>' specifies an array of column names to be fetched. An empty string means the primary key. If it is not defined, every column is fetched.%%
    # The return value is an array of column hashes of the corresponding records. This method does never fail and return an empty list even if no record corresponds.%%
    # Due to the protocol restriction, this method can not handle records with binary columns including the "\0" chracter.%%
    def searchget(names = nil)
      raise ArgumentError if names && !names.is_a?(Array)
      args = Array.new(@args)
      if names
        args.push("get\0" + names.join("\0"))
      else
        args.push("get")
      end
      rv = @rdb.misc("search", args, RDB::MONOULOG)
      return Array.new if !rv
      for i in 0...rv.size
        cols = Hash.new
        cary = rv[i].split("\0")
        cnum = cary.size - 1
        j = 0
        while j < cnum
          cols[cary[j]] = cary[j+1]
          j += 2
        end
        rv[i] = cols
      end
      return rv
    end
    # Get the count of corresponding records.%%
    # The return value is the count of corresponding records or 0 on failure.%%
    def searchcount()
      args = Array.new(@args)
      args.push("count")
      rv = @rdb.misc("search", args, RDB::MONOULOG)
      return rv ? rv[0].to_i : 0
    end
  end
end
 
 
 
# END OF FILE