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
|
/*
** 2015-11-16
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file implements a virtual table for SQLite3 around the LSM
** storage engine from SQLite4.
**
** USAGE
**
** CREATE VIRTUAL TABLE demo USING lsm1(filename,key,keytype,value1,...);
**
** The filename parameter is the name of the LSM database file, which is
** separate and distinct from the SQLite3 database file.
**
** The keytype must be one of: UINT, TEXT, BLOB. All keys must be of that
** one type. "UINT" means unsigned integer. The values may be of any
** SQLite datatype: BLOB, TEXT, INTEGER, FLOAT, or NULL.
**
** The virtual table contains read-only hidden columns:
**
** lsm1_key A BLOB which is the raw LSM key. If the "keytype"
** is BLOB or TEXT then this column is exactly the
** same as the key. For the UINT keytype, this column
** will be a variable-length integer encoding of the key.
**
** lsm1_value A BLOB which is the raw LSM value. All of the value
** columns are packed into this BLOB using the encoding
** described below.
**
** Attempts to write values into the lsm1_key and lsm1_value columns are
** silently ignored.
**
** EXAMPLE
**
** The virtual table declared this way:
**
** CREATE VIRTUAL TABLE demo2 USING lsm1('x.lsm',id,UINT,a,b,c,d);
**
** Results in a new virtual table named "demo2" that acts as if it has
** the following schema:
**
** CREATE TABLE demo2(
** id UINT PRIMARY KEY ON CONFLICT REPLACE,
** a ANY,
** b ANY,
** c ANY,
** d ANY,
** lsm1_key BLOB HIDDEN,
** lsm1_value BLOB HIDDEN
** ) WITHOUT ROWID;
**
**
**
** INTERNALS
**
** The key encoding for BLOB and TEXT is just a copy of the blob or text.
** UTF-8 is used for text. The key encoding for UINT is the variable-length
** integer format at https://sqlite.org/src4/doc/trunk/www/varint.wiki.
**
** The values are encoded as a single blob (since that is what lsm stores as
** its content). There is a "type integer" followed by "content" for each
** value, alternating back and forth. The content might be empty.
**
** TYPE1 CONTENT1 TYPE2 CONTENT2 TYPE3 CONTENT3 ....
**
** Each "type integer" is encoded as a variable-length integer in the
** format of the link above. Let the type integer be T. The actual
** datatype is an integer 0-5 equal to T%6. Values 1 through 5 correspond
** to SQLITE_INTEGER through SQLITE_NULL. The size of the content in bytes
** is T/6. Type value 0 means that the value is an integer whose actual
** values is T/6 and there is no content. The type-value-0 integer format
** only works for integers in the range of 0 through 40.
**
** There is no content for NULL or type-0 integers. For BLOB and TEXT
** values, the content is the blob data or the UTF-8 text data. For
** non-negative integers X, the content is a variable-length integer X*2.
** For negative integers Y, the content is varaible-length integer (1-Y)*2+1.
** For FLOAT values, the content is the IEEE754 floating point value in
** native byte-order. This means that FLOAT values will be corrupted when
** database file is moved between big-endian and little-endian machines.
*/
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1
#include "lsm.h"
#include <assert.h>
#include <string.h>
/* Forward declaration of subclasses of virtual table objects */
typedef struct lsm1_vtab lsm1_vtab;
typedef struct lsm1_cursor lsm1_cursor;
typedef struct lsm1_vblob lsm1_vblob;
/* Primitive types */
typedef unsigned char u8;
typedef unsigned int u32;
typedef sqlite3_uint64 u64;
/* An open connection to an LSM table */
struct lsm1_vtab {
sqlite3_vtab base; /* Base class - must be first */
lsm_db *pDb; /* Open connection to the LSM table */
u8 keyType; /* SQLITE_BLOB, _TEXT, or _INTEGER */
u32 nVal; /* Number of value columns */
};
/* lsm1_cursor is a subclass of sqlite3_vtab_cursor which will
** serve as the underlying representation of a cursor that scans
** over rows of the result
*/
struct lsm1_cursor {
sqlite3_vtab_cursor base; /* Base class - must be first */
lsm_cursor *pLsmCur; /* The LSM cursor */
u8 isDesc; /* 0: scan forward. 1: scan reverse */
u8 atEof; /* True if the scan is complete */
u8 bUnique; /* True if no more than one row of output */
u8 *zData; /* Content of the current row */
u32 nData; /* Number of bytes in the current row */
u8 *aeType; /* Types for all column values */
u32 *aiOfst; /* Offsets to the various fields */
u32 *aiLen; /* Length of each field */
u8 *pKey2; /* Loop termination key, or NULL */
u32 nKey2; /* Length of the loop termination key */
};
/* An extensible buffer object.
**
** Content can be appended. Space to hold new content is automatically
** allocated.
*/
struct lsm1_vblob {
u8 *a; /* Space to hold content, from sqlite3_malloc64() */
u64 n; /* Bytes of space used */
u64 nAlloc; /* Bytes of space allocated */
u8 errNoMem; /* True if a memory allocation error has been seen */
};
#if defined(__GNUC__)
# define LSM1_NOINLINE __attribute__((noinline))
#elif defined(_MSC_VER) && _MSC_VER>=1310
# define LSM1_NOINLINE __declspec(noinline)
#else
# define LSM1_NOINLINE
#endif
/* Increase the available space in the vblob object so that it can hold
** at least N more bytes. Return the number of errors.
*/
static int lsm1VblobEnlarge(lsm1_vblob *p, u32 N){
if( p->n+N>p->nAlloc ){
if( p->errNoMem ) return 1;
p->nAlloc += N + (p->nAlloc ? p->nAlloc : N);
p->a = sqlite3_realloc64(p->a, p->nAlloc);
if( p->a==0 ){
p->n = 0;
p->nAlloc = 0;
p->errNoMem = 1;
return 1;
}
p->nAlloc = sqlite3_msize(p->a);
}
return 0;
}
/* Append N bytes to a vblob after first enlarging it */
static LSM1_NOINLINE void lsm1VblobEnlargeAndAppend(
lsm1_vblob *p,
const u8 *pData,
u32 N
){
if( p->n+N>p->nAlloc && lsm1VblobEnlarge(p, N) ) return;
memcpy(p->a+p->n, pData, N);
p->n += N;
}
/* Append N bytes to a vblob */
static void lsm1VblobAppend(lsm1_vblob *p, const u8 *pData, u32 N){
sqlite3_int64 n = p->n;
if( n+N>p->nAlloc ){
lsm1VblobEnlargeAndAppend(p, pData, N);
}else{
p->n += N;
memcpy(p->a+n, pData, N);
}
}
/* append text to a vblob */
static void lsm1VblobAppendText(lsm1_vblob *p, const char *z){
lsm1VblobAppend(p, (u8*)z, (u32)strlen(z));
}
/* Dequote the string */
static void lsm1Dequote(char *z){
int j;
char cQuote = z[0];
size_t i, n;
if( cQuote!='\'' && cQuote!='"' ) return;
n = strlen(z);
if( n<2 || z[n-1]!=z[0] ) return;
for(i=1, j=0; i<n-1; i++){
if( z[i]==cQuote && z[i+1]==cQuote ) i++;
z[j++] = z[i];
}
z[j] = 0;
}
/*
** The lsm1Connect() method is invoked to create a new
** lsm1_vtab that describes the virtual table.
*/
static int lsm1Connect(
sqlite3 *db,
void *pAux,
int argc, const char *const*argv,
sqlite3_vtab **ppVtab,
char **pzErr
){
lsm1_vtab *pNew;
int rc;
char *zFilename;
u8 keyType = 0;
int i;
lsm1_vblob sql;
static const char *azTypes[] = { "UINT", "TEXT", "BLOB" };
static const u8 aeTypes[] = { SQLITE_INTEGER, SQLITE_TEXT, SQLITE_BLOB };
static const char *azArgName[] = {"filename", "key", "key type", "value1" };
for(i=0; i<sizeof(azArgName)/sizeof(azArgName[0]); i++){
if( argc<i+4 || argv[i+3]==0 || argv[i+3][0]==0 ){
*pzErr = sqlite3_mprintf("%s (%r) argument missing",
azArgName[i], i+1);
return SQLITE_ERROR;
}
}
for(i=0; i<sizeof(azTypes)/sizeof(azTypes[0]); i++){
if( sqlite3_stricmp(azTypes[i],argv[5])==0 ){
keyType = aeTypes[i];
break;
}
}
if( keyType==0 ){
*pzErr = sqlite3_mprintf("key type should be INT, TEXT, or BLOB");
return SQLITE_ERROR;
}
*ppVtab = sqlite3_malloc( sizeof(*pNew) );
pNew = (lsm1_vtab*)*ppVtab;
if( pNew==0 ){
return SQLITE_NOMEM;
}
memset(pNew, 0, sizeof(*pNew));
pNew->keyType = keyType;
rc = lsm_new(0, &pNew->pDb);
if( rc ){
*pzErr = sqlite3_mprintf("lsm_new failed with error code %d", rc);
rc = SQLITE_ERROR;
goto connect_failed;
}
zFilename = sqlite3_mprintf("%s", argv[3]);
lsm1Dequote(zFilename);
rc = lsm_open(pNew->pDb, zFilename);
sqlite3_free(zFilename);
if( rc ){
*pzErr = sqlite3_mprintf("lsm_open failed with %d", rc);
rc = SQLITE_ERROR;
goto connect_failed;
}
memset(&sql, 0, sizeof(sql));
lsm1VblobAppendText(&sql, "CREATE TABLE x(");
lsm1VblobAppendText(&sql, argv[4]);
lsm1VblobAppendText(&sql, " ");
lsm1VblobAppendText(&sql, argv[5]);
lsm1VblobAppendText(&sql, " PRIMARY KEY");
for(i=6; i<argc; i++){
lsm1VblobAppendText(&sql, ", ");
lsm1VblobAppendText(&sql, argv[i]);
pNew->nVal++;
}
lsm1VblobAppendText(&sql,
", lsm1_command HIDDEN"
", lsm1_key HIDDEN"
", lsm1_value HIDDEN) WITHOUT ROWID");
lsm1VblobAppend(&sql, (u8*)"", 1);
if( sql.errNoMem ){
rc = SQLITE_NOMEM;
goto connect_failed;
}
rc = sqlite3_declare_vtab(db, (const char*)sql.a);
sqlite3_free(sql.a);
connect_failed:
if( rc!=SQLITE_OK ){
if( pNew ){
if( pNew->pDb ) lsm_close(pNew->pDb);
sqlite3_free(pNew);
}
*ppVtab = 0;
}
return rc;
}
/*
** This method is the destructor for lsm1_cursor objects.
*/
static int lsm1Disconnect(sqlite3_vtab *pVtab){
lsm1_vtab *p = (lsm1_vtab*)pVtab;
lsm_close(p->pDb);
sqlite3_free(p);
return SQLITE_OK;
}
/*
** Constructor for a new lsm1_cursor object.
*/
static int lsm1Open(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
lsm1_vtab *p = (lsm1_vtab*)pVtab;
lsm1_cursor *pCur;
int rc;
pCur = sqlite3_malloc64( sizeof(*pCur)
+ p->nVal*(sizeof(pCur->aiOfst)+sizeof(pCur->aiLen)+1) );
if( pCur==0 ) return SQLITE_NOMEM;
memset(pCur, 0, sizeof(*pCur));
pCur->aiOfst = (u32*)&pCur[1];
pCur->aiLen = &pCur->aiOfst[p->nVal];
pCur->aeType = (u8*)&pCur->aiLen[p->nVal];
*ppCursor = &pCur->base;
rc = lsm_csr_open(p->pDb, &pCur->pLsmCur);
if( rc==LSM_OK ){
rc = SQLITE_OK;
}else{
sqlite3_free(pCur);
*ppCursor = 0;
rc = SQLITE_ERROR;
}
return rc;
}
/*
** Destructor for a lsm1_cursor.
*/
static int lsm1Close(sqlite3_vtab_cursor *cur){
lsm1_cursor *pCur = (lsm1_cursor*)cur;
sqlite3_free(pCur->pKey2);
lsm_csr_close(pCur->pLsmCur);
sqlite3_free(pCur);
return SQLITE_OK;
}
/*
** Advance a lsm1_cursor to its next row of output.
*/
static int lsm1Next(sqlite3_vtab_cursor *cur){
lsm1_cursor *pCur = (lsm1_cursor*)cur;
int rc = LSM_OK;
if( pCur->bUnique ){
pCur->atEof = 1;
}else{
if( pCur->isDesc ){
rc = lsm_csr_prev(pCur->pLsmCur);
}else{
rc = lsm_csr_next(pCur->pLsmCur);
}
if( rc==LSM_OK && lsm_csr_valid(pCur->pLsmCur)==0 ){
pCur->atEof = 1;
}
if( pCur->pKey2 && pCur->atEof==0 ){
const u8 *pVal;
u32 nVal;
assert( pCur->isDesc==0 );
rc = lsm_csr_key(pCur->pLsmCur, (const void**)&pVal, (int*)&nVal);
if( rc==LSM_OK ){
u32 len = pCur->nKey2;
int c;
if( len>nVal ) len = nVal;
c = memcmp(pVal, pCur->pKey2, len);
if( c==0 ) c = nVal - pCur->nKey2;
if( c>0 ) pCur->atEof = 1;
}
}
pCur->zData = 0;
}
return rc==LSM_OK ? SQLITE_OK : SQLITE_ERROR;
}
/*
** Return TRUE if the cursor has been moved off of the last
** row of output.
*/
static int lsm1Eof(sqlite3_vtab_cursor *cur){
lsm1_cursor *pCur = (lsm1_cursor*)cur;
return pCur->atEof;
}
/*
** Rowids are not supported by the underlying virtual table. So always
** return 0 for the rowid.
*/
static int lsm1Rowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
*pRowid = 0;
return SQLITE_OK;
}
/*
** Type prefixes on LSM keys
*/
#define LSM1_TYPE_NEGATIVE 0
#define LSM1_TYPE_POSITIVE 1
#define LSM1_TYPE_TEXT 2
#define LSM1_TYPE_BLOB 3
/*
** Write a 32-bit unsigned integer as 4 big-endian bytes.
*/
static void varintWrite32(unsigned char *z, unsigned int y){
z[0] = (unsigned char)(y>>24);
z[1] = (unsigned char)(y>>16);
z[2] = (unsigned char)(y>>8);
z[3] = (unsigned char)(y);
}
/*
** Write a varint into z[]. The buffer z[] must be at least 9 characters
** long to accommodate the largest possible varint. Return the number of
** bytes of z[] used.
*/
static int lsm1PutVarint64(unsigned char *z, sqlite3_uint64 x){
unsigned int w, y;
if( x<=240 ){
z[0] = (unsigned char)x;
return 1;
}
if( x<=2287 ){
y = (unsigned int)(x - 240);
z[0] = (unsigned char)(y/256 + 241);
z[1] = (unsigned char)(y%256);
return 2;
}
if( x<=67823 ){
y = (unsigned int)(x - 2288);
z[0] = 249;
z[1] = (unsigned char)(y/256);
z[2] = (unsigned char)(y%256);
return 3;
}
y = (unsigned int)x;
w = (unsigned int)(x>>32);
if( w==0 ){
if( y<=16777215 ){
z[0] = 250;
z[1] = (unsigned char)(y>>16);
z[2] = (unsigned char)(y>>8);
z[3] = (unsigned char)(y);
return 4;
}
z[0] = 251;
varintWrite32(z+1, y);
return 5;
}
if( w<=255 ){
z[0] = 252;
z[1] = (unsigned char)w;
varintWrite32(z+2, y);
return 6;
}
if( w<=65535 ){
z[0] = 253;
z[1] = (unsigned char)(w>>8);
z[2] = (unsigned char)w;
varintWrite32(z+3, y);
return 7;
}
if( w<=16777215 ){
z[0] = 254;
z[1] = (unsigned char)(w>>16);
z[2] = (unsigned char)(w>>8);
z[3] = (unsigned char)w;
varintWrite32(z+4, y);
return 8;
}
z[0] = 255;
varintWrite32(z+1, w);
varintWrite32(z+5, y);
return 9;
}
/* Append non-negative integer x as a variable-length integer.
*/
static void lsm1VblobAppendVarint(lsm1_vblob *p, sqlite3_uint64 x){
sqlite3_int64 n = p->n;
if( n+9>p->nAlloc && lsm1VblobEnlarge(p, 9) ) return;
p->n += lsm1PutVarint64(p->a+p->n, x);
}
/*
** Decode the varint in the first n bytes z[]. Write the integer value
** into *pResult and return the number of bytes in the varint.
**
** If the decode fails because there are not enough bytes in z[] then
** return 0;
*/
static int lsm1GetVarint64(
const unsigned char *z,
int n,
sqlite3_uint64 *pResult
){
unsigned int x;
if( n<1 ) return 0;
if( z[0]<=240 ){
*pResult = z[0];
return 1;
}
if( z[0]<=248 ){
if( n<2 ) return 0;
*pResult = (z[0]-241)*256 + z[1] + 240;
return 2;
}
if( n<z[0]-246 ) return 0;
if( z[0]==249 ){
*pResult = 2288 + 256*z[1] + z[2];
return 3;
}
if( z[0]==250 ){
*pResult = (z[1]<<16) + (z[2]<<8) + z[3];
return 4;
}
x = (z[1]<<24) + (z[2]<<16) + (z[3]<<8) + z[4];
if( z[0]==251 ){
*pResult = x;
return 5;
}
if( z[0]==252 ){
*pResult = (((sqlite3_uint64)x)<<8) + z[5];
return 6;
}
if( z[0]==253 ){
*pResult = (((sqlite3_uint64)x)<<16) + (z[5]<<8) + z[6];
return 7;
}
if( z[0]==254 ){
*pResult = (((sqlite3_uint64)x)<<24) + (z[5]<<16) + (z[6]<<8) + z[7];
return 8;
}
*pResult = (((sqlite3_uint64)x)<<32) +
(0xffffffff & ((z[5]<<24) + (z[6]<<16) + (z[7]<<8) + z[8]));
return 9;
}
/* Encoded a signed integer as a varint. Numbers close to zero uses fewer
** bytes than numbers far away from zero. However, the result is not in
** lexicographical order.
**
** Encoding: Non-negative integer X is encoding as an unsigned
** varint X*2. Negative integer Y is encoding as an unsigned
** varint (1-Y)*2 + 1.
*/
static int lsm1PutSignedVarint64(u8 *z, sqlite3_int64 v){
sqlite3_uint64 u;
if( v>=0 ){
u = (sqlite3_uint64)v;
return lsm1PutVarint64(z, u*2);
}else{
u = (sqlite3_uint64)(-1-v);
return lsm1PutVarint64(z, u*2+1);
}
}
/* Decoded a signed varint. */
static int lsm1GetSignedVarint64(
const unsigned char *z,
int n,
sqlite3_int64 *pResult
){
sqlite3_uint64 u = 0;
n = lsm1GetVarint64(z, n, &u);
if( u&1 ){
*pResult = -1 - (sqlite3_int64)(u>>1);
}else{
*pResult = (sqlite3_int64)(u>>1);
}
return n;
}
/*
** Read the value part of the key-value pair and decode it into columns.
*/
static int lsm1DecodeValues(lsm1_cursor *pCur){
lsm1_vtab *pTab = (lsm1_vtab*)(pCur->base.pVtab);
int i, n;
int rc;
u8 eType;
sqlite3_uint64 v;
if( pCur->zData ) return 1;
rc = lsm_csr_value(pCur->pLsmCur, (const void**)&pCur->zData,
(int*)&pCur->nData);
if( rc ) return 0;
for(i=n=0; i<pTab->nVal; i++){
v = 0;
n += lsm1GetVarint64(pCur->zData+n, pCur->nData-n, &v);
pCur->aeType[i] = eType = (u8)(v%6);
if( eType==0 ){
pCur->aiOfst[i] = (u32)(v/6);
pCur->aiLen[i] = 0;
}else{
pCur->aiOfst[i] = n;
n += (pCur->aiLen[i] = (u32)(v/6));
}
if( n>pCur->nData ) break;
}
if( i<pTab->nVal ){
pCur->zData = 0;
return 0;
}
return 1;
}
/*
** Return values of columns for the row at which the lsm1_cursor
** is currently pointing.
*/
static int lsm1Column(
sqlite3_vtab_cursor *cur, /* The cursor */
sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
int i /* Which column to return */
){
lsm1_cursor *pCur = (lsm1_cursor*)cur;
lsm1_vtab *pTab = (lsm1_vtab*)(cur->pVtab);
if( i==0 ){
/* The key column */
const void *pVal;
int nVal;
if( lsm_csr_key(pCur->pLsmCur, &pVal, &nVal)==LSM_OK ){
if( pTab->keyType==SQLITE_BLOB ){
sqlite3_result_blob(ctx, pVal, nVal, SQLITE_TRANSIENT);
}else if( pTab->keyType==SQLITE_TEXT ){
sqlite3_result_text(ctx,(const char*)pVal, nVal, SQLITE_TRANSIENT);
}else{
const unsigned char *z = (const unsigned char*)pVal;
sqlite3_uint64 v1;
lsm1GetVarint64(z, nVal, &v1);
sqlite3_result_int64(ctx, (sqlite3_int64)v1);
}
}
}else if( i>pTab->nVal ){
if( i==pTab->nVal+2 ){ /* lsm1_key */
const void *pVal;
int nVal;
if( lsm_csr_key(pCur->pLsmCur, &pVal, &nVal)==LSM_OK ){
sqlite3_result_blob(ctx, pVal, nVal, SQLITE_TRANSIENT);
}
}else if( i==pTab->nVal+3 ){ /* lsm1_value */
const void *pVal;
int nVal;
if( lsm_csr_value(pCur->pLsmCur, &pVal, &nVal)==LSM_OK ){
sqlite3_result_blob(ctx, pVal, nVal, SQLITE_TRANSIENT);
}
}
}else if( lsm1DecodeValues(pCur) ){
/* The i-th value column (where leftmost is 1) */
const u8 *zData;
u32 nData;
i--;
zData = pCur->zData + pCur->aiOfst[i];
nData = pCur->aiLen[i];
switch( pCur->aeType[i] ){
case 0: { /* in-line integer */
sqlite3_result_int(ctx, pCur->aiOfst[i]);
break;
}
case SQLITE_INTEGER: {
sqlite3_int64 v;
lsm1GetSignedVarint64(zData, nData, &v);
sqlite3_result_int64(ctx, v);
break;
}
case SQLITE_FLOAT: {
double v;
if( nData==sizeof(v) ){
memcpy(&v, zData, sizeof(v));
sqlite3_result_double(ctx, v);
}
break;
}
case SQLITE_TEXT: {
sqlite3_result_text(ctx, (const char*)zData, nData, SQLITE_TRANSIENT);
break;
}
case SQLITE_BLOB: {
sqlite3_result_blob(ctx, zData, nData, SQLITE_TRANSIENT);
break;
}
default: {
/* A NULL. Do nothing */
}
}
}
return SQLITE_OK;
}
/* Parameter "pValue" contains an SQL value that is to be used as
** a key in an LSM table. The type of the key is determined by
** "keyType". Extract the raw bytes used for the key in LSM1.
*/
static void lsm1KeyFromValue(
int keyType, /* The key type */
sqlite3_value *pValue, /* The key value */
u8 *pBuf, /* Storage space for a generated key */
const u8 **ppKey, /* OUT: the bytes of the key */
int *pnKey /* OUT: size of the key */
){
if( keyType==SQLITE_BLOB ){
*ppKey = (const u8*)sqlite3_value_blob(pValue);
*pnKey = sqlite3_value_bytes(pValue);
}else if( keyType==SQLITE_TEXT ){
*ppKey = (const u8*)sqlite3_value_text(pValue);
*pnKey = sqlite3_value_bytes(pValue);
}else{
sqlite3_int64 v = sqlite3_value_int64(pValue);
if( v<0 ) v = 0;
*pnKey = lsm1PutVarint64(pBuf, v);
*ppKey = pBuf;
}
}
/* Move to the first row to return.
*/
static int lsm1Filter(
sqlite3_vtab_cursor *pVtabCursor,
int idxNum, const char *idxStr,
int argc, sqlite3_value **argv
){
lsm1_cursor *pCur = (lsm1_cursor *)pVtabCursor;
lsm1_vtab *pTab = (lsm1_vtab*)(pCur->base.pVtab);
int rc = LSM_OK;
int seekType = -1;
const u8 *pVal = 0;
int nVal;
u8 keyType = pTab->keyType;
u8 aKey1[16];
pCur->atEof = 1;
sqlite3_free(pCur->pKey2);
pCur->pKey2 = 0;
if( idxNum<99 ){
lsm1KeyFromValue(keyType, argv[0], aKey1, &pVal, &nVal);
}
switch( idxNum ){
case 0: { /* key==argv[0] */
assert( argc==1 );
seekType = LSM_SEEK_EQ;
pCur->isDesc = 0;
pCur->bUnique = 1;
break;
}
case 1: { /* key>=argv[0] AND key<=argv[1] */
u8 aKey[12];
seekType = LSM_SEEK_GE;
pCur->isDesc = 0;
pCur->bUnique = 0;
if( keyType==SQLITE_INTEGER ){
sqlite3_int64 v = sqlite3_value_int64(argv[1]);
if( v<0 ) v = 0;
pCur->nKey2 = lsm1PutVarint64(aKey, (sqlite3_uint64)v);
pCur->pKey2 = sqlite3_malloc( pCur->nKey2 );
if( pCur->pKey2==0 ) return SQLITE_NOMEM;
memcpy(pCur->pKey2, aKey, pCur->nKey2);
}else{
pCur->nKey2 = sqlite3_value_bytes(argv[1]);
pCur->pKey2 = sqlite3_malloc( pCur->nKey2 );
if( pCur->pKey2==0 ) return SQLITE_NOMEM;
if( keyType==SQLITE_BLOB ){
memcpy(pCur->pKey2, sqlite3_value_blob(argv[1]), pCur->nKey2);
}else{
memcpy(pCur->pKey2, sqlite3_value_text(argv[1]), pCur->nKey2);
}
}
break;
}
case 2: { /* key>=argv[0] */
seekType = LSM_SEEK_GE;
pCur->isDesc = 0;
pCur->bUnique = 0;
break;
}
case 3: { /* key<=argv[0] */
seekType = LSM_SEEK_LE;
pCur->isDesc = 1;
pCur->bUnique = 0;
break;
}
default: { /* full table scan */
pCur->isDesc = 0;
pCur->bUnique = 0;
break;
}
}
if( pVal ){
rc = lsm_csr_seek(pCur->pLsmCur, pVal, nVal, seekType);
}else{
rc = lsm_csr_first(pCur->pLsmCur);
}
if( rc==LSM_OK && lsm_csr_valid(pCur->pLsmCur)!=0 ){
pCur->atEof = 0;
}
return rc==LSM_OK ? SQLITE_OK : SQLITE_ERROR;
}
/*
** Only comparisons against the key are allowed. The idxNum defines
** which comparisons are available:
**
** 0 key==?1
** 1 key>=?1 AND key<=?2
** 2 key>?1 or key>=?1
** 3 key<?1 or key<=?1
** 99 Full table scan only
*/
static int lsm1BestIndex(
sqlite3_vtab *tab,
sqlite3_index_info *pIdxInfo
){
int i; /* Loop over constraints */
int idxNum = 99; /* The query plan */
int nArg = 0; /* Number of arguments to xFilter */
int argIdx = -1; /* Index of the key== constraint, or -1 if none */
int iIdx2 = -1; /* The index of the second key */
int omit1 = 0;
int omit2 = 0;
const struct sqlite3_index_constraint *pConstraint;
pConstraint = pIdxInfo->aConstraint;
for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
if( pConstraint->usable==0 ) continue;
if( pConstraint->iColumn!=0 ) continue;
switch( pConstraint->op ){
case SQLITE_INDEX_CONSTRAINT_EQ: {
if( idxNum>0 ){
argIdx = i;
iIdx2 = -1;
idxNum = 0;
omit1 = 1;
}
break;
}
case SQLITE_INDEX_CONSTRAINT_GE:
case SQLITE_INDEX_CONSTRAINT_GT: {
if( idxNum==99 ){
argIdx = i;
idxNum = 2;
omit1 = pConstraint->op==SQLITE_INDEX_CONSTRAINT_GE;
}else if( idxNum==3 ){
iIdx2 = idxNum;
omit2 = omit1;
argIdx = i;
idxNum = 1;
omit1 = pConstraint->op==SQLITE_INDEX_CONSTRAINT_GE;
}
break;
}
case SQLITE_INDEX_CONSTRAINT_LE:
case SQLITE_INDEX_CONSTRAINT_LT: {
if( idxNum==99 ){
argIdx = i;
idxNum = 3;
omit1 = pConstraint->op==SQLITE_INDEX_CONSTRAINT_LE;
}else if( idxNum==2 ){
iIdx2 = i;
idxNum = 1;
omit1 = pConstraint->op==SQLITE_INDEX_CONSTRAINT_LE;
}
break;
}
}
}
if( argIdx>=0 ){
pIdxInfo->aConstraintUsage[argIdx].argvIndex = ++nArg;
pIdxInfo->aConstraintUsage[argIdx].omit = omit1;
}
if( iIdx2>=0 ){
pIdxInfo->aConstraintUsage[iIdx2].argvIndex = ++nArg;
pIdxInfo->aConstraintUsage[iIdx2].omit = omit2;
}
if( idxNum==0 ){
pIdxInfo->estimatedCost = (double)1;
pIdxInfo->estimatedRows = 1;
pIdxInfo->orderByConsumed = 1;
}else if( idxNum==1 ){
pIdxInfo->estimatedCost = (double)100;
pIdxInfo->estimatedRows = 100;
}else if( idxNum<99 ){
pIdxInfo->estimatedCost = (double)5000;
pIdxInfo->estimatedRows = 5000;
}else{
/* Full table scan */
pIdxInfo->estimatedCost = (double)2147483647;
pIdxInfo->estimatedRows = 2147483647;
}
pIdxInfo->idxNum = idxNum;
return SQLITE_OK;
}
/*
** The xUpdate method is normally used for INSERT, REPLACE, UPDATE, and
** DELETE. But this virtual table only supports INSERT and REPLACE.
** DELETE is accomplished by inserting a record with a value of NULL.
** UPDATE is achieved by using REPLACE.
*/
int lsm1Update(
sqlite3_vtab *pVTab,
int argc,
sqlite3_value **argv,
sqlite_int64 *pRowid
){
lsm1_vtab *p = (lsm1_vtab*)pVTab;
int nKey, nKey2;
int i;
int rc = LSM_OK;
const u8 *pKey, *pKey2;
unsigned char aKey[16];
unsigned char pSpace[16];
lsm1_vblob val;
if( argc==1 ){
/* DELETE the record whose key is argv[0] */
lsm1KeyFromValue(p->keyType, argv[0], aKey, &pKey, &nKey);
lsm_delete(p->pDb, pKey, nKey);
return SQLITE_OK;
}
if( sqlite3_value_type(argv[0])!=SQLITE_NULL ){
/* An UPDATE */
lsm1KeyFromValue(p->keyType, argv[0], aKey, &pKey, &nKey);
lsm1KeyFromValue(p->keyType, argv[1], pSpace, &pKey2, &nKey2);
if( nKey!=nKey2 || memcmp(pKey, pKey2, nKey)!=0 ){
/* The UPDATE changes the PRIMARY KEY value. DELETE the old key */
lsm_delete(p->pDb, pKey, nKey);
}
/* Fall through into the INSERT case to complete the UPDATE */
}
/* "INSERT INTO tab(lsm1_command) VALUES('....')" is used to implement
** special commands.
*/
if( sqlite3_value_type(argv[3+p->nVal])!=SQLITE_NULL ){
return SQLITE_OK;
}
lsm1KeyFromValue(p->keyType, argv[2], aKey, &pKey, &nKey);
memset(&val, 0, sizeof(val));
for(i=0; i<p->nVal; i++){
sqlite3_value *pArg = argv[3+i];
u8 eType = sqlite3_value_type(pArg);
switch( eType ){
case SQLITE_NULL: {
lsm1VblobAppendVarint(&val, SQLITE_NULL);
break;
}
case SQLITE_INTEGER: {
sqlite3_int64 v = sqlite3_value_int64(pArg);
if( v>=0 && v<=240/6 ){
lsm1VblobAppendVarint(&val, v*6);
}else{
int n = lsm1PutSignedVarint64(pSpace, v);
lsm1VblobAppendVarint(&val, SQLITE_INTEGER + n*6);
lsm1VblobAppend(&val, pSpace, n);
}
break;
}
case SQLITE_FLOAT: {
double r = sqlite3_value_double(pArg);
lsm1VblobAppendVarint(&val, SQLITE_FLOAT + 8*6);
lsm1VblobAppend(&val, (u8*)&r, sizeof(r));
break;
}
case SQLITE_BLOB: {
int n = sqlite3_value_bytes(pArg);
lsm1VblobAppendVarint(&val, n*6 + SQLITE_BLOB);
lsm1VblobAppend(&val, sqlite3_value_blob(pArg), n);
break;
}
case SQLITE_TEXT: {
int n = sqlite3_value_bytes(pArg);
lsm1VblobAppendVarint(&val, n*6 + SQLITE_TEXT);
lsm1VblobAppend(&val, sqlite3_value_text(pArg), n);
break;
}
}
}
if( val.errNoMem ){
return SQLITE_NOMEM;
}
rc = lsm_insert(p->pDb, pKey, nKey, val.a, val.n);
sqlite3_free(val.a);
return rc==LSM_OK ? SQLITE_OK : SQLITE_ERROR;
}
/* Begin a transaction
*/
static int lsm1Begin(sqlite3_vtab *pVtab){
lsm1_vtab *p = (lsm1_vtab*)pVtab;
int rc = lsm_begin(p->pDb, 1);
return rc==LSM_OK ? SQLITE_OK : SQLITE_ERROR;
}
/* Phase 1 of a transaction commit.
*/
static int lsm1Sync(sqlite3_vtab *pVtab){
return SQLITE_OK;
}
/* Commit a transaction
*/
static int lsm1Commit(sqlite3_vtab *pVtab){
lsm1_vtab *p = (lsm1_vtab*)pVtab;
int rc = lsm_commit(p->pDb, 0);
return rc==LSM_OK ? SQLITE_OK : SQLITE_ERROR;
}
/* Rollback a transaction
*/
static int lsm1Rollback(sqlite3_vtab *pVtab){
lsm1_vtab *p = (lsm1_vtab*)pVtab;
int rc = lsm_rollback(p->pDb, 0);
return rc==LSM_OK ? SQLITE_OK : SQLITE_ERROR;
}
/*
** This following structure defines all the methods for the
** generate_lsm1 virtual table.
*/
static sqlite3_module lsm1Module = {
0, /* iVersion */
lsm1Connect, /* xCreate */
lsm1Connect, /* xConnect */
lsm1BestIndex, /* xBestIndex */
lsm1Disconnect, /* xDisconnect */
lsm1Disconnect, /* xDestroy */
lsm1Open, /* xOpen - open a cursor */
lsm1Close, /* xClose - close a cursor */
lsm1Filter, /* xFilter - configure scan constraints */
lsm1Next, /* xNext - advance a cursor */
lsm1Eof, /* xEof - check for end of scan */
lsm1Column, /* xColumn - read data */
lsm1Rowid, /* xRowid - read data */
lsm1Update, /* xUpdate */
lsm1Begin, /* xBegin */
lsm1Sync, /* xSync */
lsm1Commit, /* xCommit */
lsm1Rollback, /* xRollback */
0, /* xFindMethod */
0, /* xRename */
0, /* xSavepoint */
0, /* xRelease */
0, /* xRollbackTo */
0, /* xShadowName */
0 /* xIntegrity */
};
#ifdef _WIN32
__declspec(dllexport)
#endif
int sqlite3_lsm_init(
sqlite3 *db,
char **pzErrMsg,
const sqlite3_api_routines *pApi
){
int rc = SQLITE_OK;
SQLITE_EXTENSION_INIT2(pApi);
rc = sqlite3_create_module(db, "lsm1", &lsm1Module, 0);
return rc;
}
|