-
Notifications
You must be signed in to change notification settings - Fork 12
/
fts1.c
3345 lines (3018 loc) · 99.5 KB
/
fts1.c
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
/* fts1 has a design flaw which can lead to database corruption (see
** below). It is recommended not to use it any longer, instead use
** fts3 (or higher). If you believe that your use of fts1 is safe,
** add -DSQLITE_ENABLE_BROKEN_FTS1=1 to your CFLAGS.
*/
#if (!defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1)) \
&& !defined(SQLITE_ENABLE_BROKEN_FTS1)
#error fts1 has a design flaw and has been deprecated.
#endif
/* The flaw is that fts1 uses the content table's unaliased rowid as
** the unique docid. fts1 embeds the rowid in the index it builds,
** and expects the rowid to not change. The SQLite VACUUM operation
** will renumber such rowids, thereby breaking fts1. If you are using
** fts1 in a system which has disabled VACUUM, then you can continue
** to use it safely. Note that PRAGMA auto_vacuum does NOT disable
** VACUUM, though systems using auto_vacuum are unlikely to invoke
** VACUUM.
**
** fts1 should be safe even across VACUUM if you only insert documents
** and never delete.
*/
/* The author disclaims copyright to this source code.
*
* This is an SQLite module implementing full-text search.
*/
/*
** The code in this file is only compiled if:
**
** * The FTS1 module is being built as an extension
** (in which case SQLITE_CORE is not defined), or
**
** * The FTS1 module is being built into the core of
** SQLite (in which case SQLITE_ENABLE_FTS1 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1)
#if defined(SQLITE_ENABLE_FTS1) && !defined(SQLITE_CORE)
# define SQLITE_CORE 1
#endif
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "fts1.h"
#include "fts1_hash.h"
#include "fts1_tokenizer.h"
#include "sqlite3.h"
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1
#if 0
# define TRACE(A) printf A; fflush(stdout)
#else
# define TRACE(A)
#endif
/* utility functions */
typedef struct StringBuffer {
int len; /* length, not including null terminator */
int alloced; /* Space allocated for s[] */
char *s; /* Content of the string */
} StringBuffer;
static void initStringBuffer(StringBuffer *sb){
sb->len = 0;
sb->alloced = 100;
sb->s = malloc(100);
sb->s[0] = '\0';
}
static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
if( sb->len + nFrom >= sb->alloced ){
sb->alloced = sb->len + nFrom + 100;
sb->s = realloc(sb->s, sb->alloced+1);
if( sb->s==0 ){
initStringBuffer(sb);
return;
}
}
memcpy(sb->s + sb->len, zFrom, nFrom);
sb->len += nFrom;
sb->s[sb->len] = 0;
}
static void append(StringBuffer *sb, const char *zFrom){
nappend(sb, zFrom, strlen(zFrom));
}
/* We encode variable-length integers in little-endian order using seven bits
* per byte as follows:
**
** KEY:
** A = 0xxxxxxx 7 bits of data and one flag bit
** B = 1xxxxxxx 7 bits of data and one flag bit
**
** 7 bits - A
** 14 bits - BA
** 21 bits - BBA
** and so on.
*/
/* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
#define VARINT_MAX 10
/* Write a 64-bit variable-length integer to memory starting at p[0].
* The length of data written will be between 1 and VARINT_MAX bytes.
* The number of bytes written is returned. */
static int putVarint(char *p, sqlite_int64 v){
unsigned char *q = (unsigned char *) p;
sqlite_uint64 vu = v;
do{
*q++ = (unsigned char) ((vu & 0x7f) | 0x80);
vu >>= 7;
}while( vu!=0 );
q[-1] &= 0x7f; /* turn off high bit in final byte */
assert( q - (unsigned char *)p <= VARINT_MAX );
return (int) (q - (unsigned char *)p);
}
/* Read a 64-bit variable-length integer from memory starting at p[0].
* Return the number of bytes read, or 0 on error.
* The value is stored in *v. */
static int getVarint(const char *p, sqlite_int64 *v){
const unsigned char *q = (const unsigned char *) p;
sqlite_uint64 x = 0, y = 1;
while( (*q & 0x80) == 0x80 ){
x += y * (*q++ & 0x7f);
y <<= 7;
if( q - (unsigned char *)p >= VARINT_MAX ){ /* bad data */
assert( 0 );
return 0;
}
}
x += y * (*q++);
*v = (sqlite_int64) x;
return (int) (q - (unsigned char *)p);
}
static int getVarint32(const char *p, int *pi){
sqlite_int64 i;
int ret = getVarint(p, &i);
*pi = (int) i;
assert( *pi==i );
return ret;
}
/*** Document lists ***
*
* A document list holds a sorted list of varint-encoded document IDs.
*
* A doclist with type DL_POSITIONS_OFFSETS is stored like this:
*
* array {
* varint docid;
* array {
* varint position; (delta from previous position plus POS_BASE)
* varint startOffset; (delta from previous startOffset)
* varint endOffset; (delta from startOffset)
* }
* }
*
* Here, array { X } means zero or more occurrences of X, adjacent in memory.
*
* A position list may hold positions for text in multiple columns. A position
* POS_COLUMN is followed by a varint containing the index of the column for
* following positions in the list. Any positions appearing before any
* occurrences of POS_COLUMN are for column 0.
*
* A doclist with type DL_POSITIONS is like the above, but holds only docids
* and positions without offset information.
*
* A doclist with type DL_DOCIDS is like the above, but holds only docids
* without positions or offset information.
*
* On disk, every document list has positions and offsets, so we don't bother
* to serialize a doclist's type.
*
* We don't yet delta-encode document IDs; doing so will probably be a
* modest win.
*
* NOTE(shess) I've thought of a slightly (1%) better offset encoding.
* After the first offset, estimate the next offset by using the
* current token position and the previous token position and offset,
* offset to handle some variance. So the estimate would be
* (iPosition*w->iStartOffset/w->iPosition-64), which is delta-encoded
* as normal. Offsets more than 64 chars from the estimate are
* encoded as the delta to the previous start offset + 128. An
* additional tiny increment can be gained by using the end offset of
* the previous token to make the estimate a tiny bit more precise.
*/
/* It is not safe to call isspace(), tolower(), or isalnum() on
** hi-bit-set characters. This is the same solution used in the
** tokenizer.
*/
/* TODO(shess) The snippet-generation code should be using the
** tokenizer-generated tokens rather than doing its own local
** tokenization.
*/
/* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
static int safe_isspace(char c){
return (c&0x80)==0 ? isspace(c) : 0;
}
static int safe_tolower(char c){
return (c&0x80)==0 ? tolower(c) : c;
}
static int safe_isalnum(char c){
return (c&0x80)==0 ? isalnum(c) : 0;
}
typedef enum DocListType {
DL_DOCIDS, /* docids only */
DL_POSITIONS, /* docids + positions */
DL_POSITIONS_OFFSETS /* docids + positions + offsets */
} DocListType;
/*
** By default, only positions and not offsets are stored in the doclists.
** To change this so that offsets are stored too, compile with
**
** -DDL_DEFAULT=DL_POSITIONS_OFFSETS
**
*/
#ifndef DL_DEFAULT
# define DL_DEFAULT DL_POSITIONS
#endif
typedef struct DocList {
char *pData;
int nData;
DocListType iType;
int iLastColumn; /* the last column written */
int iLastPos; /* the last position written */
int iLastOffset; /* the last start offset written */
} DocList;
enum {
POS_END = 0, /* end of this position list */
POS_COLUMN, /* followed by new column number */
POS_BASE
};
/* Initialize a new DocList to hold the given data. */
static void docListInit(DocList *d, DocListType iType,
const char *pData, int nData){
d->nData = nData;
if( nData>0 ){
d->pData = malloc(nData);
memcpy(d->pData, pData, nData);
} else {
d->pData = NULL;
}
d->iType = iType;
d->iLastColumn = 0;
d->iLastPos = d->iLastOffset = 0;
}
/* Create a new dynamically-allocated DocList. */
static DocList *docListNew(DocListType iType){
DocList *d = (DocList *) malloc(sizeof(DocList));
docListInit(d, iType, 0, 0);
return d;
}
static void docListDestroy(DocList *d){
free(d->pData);
#ifndef NDEBUG
memset(d, 0x55, sizeof(*d));
#endif
}
static void docListDelete(DocList *d){
docListDestroy(d);
free(d);
}
static char *docListEnd(DocList *d){
return d->pData + d->nData;
}
/* Append a varint to a DocList's data. */
static void appendVarint(DocList *d, sqlite_int64 i){
char c[VARINT_MAX];
int n = putVarint(c, i);
d->pData = realloc(d->pData, d->nData + n);
memcpy(d->pData + d->nData, c, n);
d->nData += n;
}
static void docListAddDocid(DocList *d, sqlite_int64 iDocid){
appendVarint(d, iDocid);
if( d->iType>=DL_POSITIONS ){
appendVarint(d, POS_END); /* initially empty position list */
d->iLastColumn = 0;
d->iLastPos = d->iLastOffset = 0;
}
}
/* helper function for docListAddPos and docListAddPosOffset */
static void addPos(DocList *d, int iColumn, int iPos){
assert( d->nData>0 );
--d->nData; /* remove previous terminator */
if( iColumn!=d->iLastColumn ){
assert( iColumn>d->iLastColumn );
appendVarint(d, POS_COLUMN);
appendVarint(d, iColumn);
d->iLastColumn = iColumn;
d->iLastPos = d->iLastOffset = 0;
}
assert( iPos>=d->iLastPos );
appendVarint(d, iPos-d->iLastPos+POS_BASE);
d->iLastPos = iPos;
}
/* Add a position to the last position list in a doclist. */
static void docListAddPos(DocList *d, int iColumn, int iPos){
assert( d->iType==DL_POSITIONS );
addPos(d, iColumn, iPos);
appendVarint(d, POS_END); /* add new terminator */
}
/*
** Add a position and starting and ending offsets to a doclist.
**
** If the doclist is setup to handle only positions, then insert
** the position only and ignore the offsets.
*/
static void docListAddPosOffset(
DocList *d, /* Doclist under construction */
int iColumn, /* Column the inserted term is part of */
int iPos, /* Position of the inserted term */
int iStartOffset, /* Starting offset of inserted term */
int iEndOffset /* Ending offset of inserted term */
){
assert( d->iType>=DL_POSITIONS );
addPos(d, iColumn, iPos);
if( d->iType==DL_POSITIONS_OFFSETS ){
assert( iStartOffset>=d->iLastOffset );
appendVarint(d, iStartOffset-d->iLastOffset);
d->iLastOffset = iStartOffset;
assert( iEndOffset>=iStartOffset );
appendVarint(d, iEndOffset-iStartOffset);
}
appendVarint(d, POS_END); /* add new terminator */
}
/*
** A DocListReader object is a cursor into a doclist. Initialize
** the cursor to the beginning of the doclist by calling readerInit().
** Then use routines
**
** peekDocid()
** readDocid()
** readPosition()
** skipPositionList()
** and so forth...
**
** to read information out of the doclist. When we reach the end
** of the doclist, atEnd() returns TRUE.
*/
typedef struct DocListReader {
DocList *pDoclist; /* The document list we are stepping through */
char *p; /* Pointer to next unread byte in the doclist */
int iLastColumn;
int iLastPos; /* the last position read, or -1 when not in a position list */
} DocListReader;
/*
** Initialize the DocListReader r to point to the beginning of pDoclist.
*/
static void readerInit(DocListReader *r, DocList *pDoclist){
r->pDoclist = pDoclist;
if( pDoclist!=NULL ){
r->p = pDoclist->pData;
}
r->iLastColumn = -1;
r->iLastPos = -1;
}
/*
** Return TRUE if we have reached then end of pReader and there is
** nothing else left to read.
*/
static int atEnd(DocListReader *pReader){
return pReader->pDoclist==0 || (pReader->p >= docListEnd(pReader->pDoclist));
}
/* Peek at the next docid without advancing the read pointer.
*/
static sqlite_int64 peekDocid(DocListReader *pReader){
sqlite_int64 ret;
assert( !atEnd(pReader) );
assert( pReader->iLastPos==-1 );
getVarint(pReader->p, &ret);
return ret;
}
/* Read the next docid. See also nextDocid().
*/
static sqlite_int64 readDocid(DocListReader *pReader){
sqlite_int64 ret;
assert( !atEnd(pReader) );
assert( pReader->iLastPos==-1 );
pReader->p += getVarint(pReader->p, &ret);
if( pReader->pDoclist->iType>=DL_POSITIONS ){
pReader->iLastColumn = 0;
pReader->iLastPos = 0;
}
return ret;
}
/* Read the next position and column index from a position list.
* Returns the position, or -1 at the end of the list. */
static int readPosition(DocListReader *pReader, int *iColumn){
int i;
int iType = pReader->pDoclist->iType;
if( pReader->iLastPos==-1 ){
return -1;
}
assert( !atEnd(pReader) );
if( iType<DL_POSITIONS ){
return -1;
}
pReader->p += getVarint32(pReader->p, &i);
if( i==POS_END ){
pReader->iLastColumn = pReader->iLastPos = -1;
*iColumn = -1;
return -1;
}
if( i==POS_COLUMN ){
pReader->p += getVarint32(pReader->p, &pReader->iLastColumn);
pReader->iLastPos = 0;
pReader->p += getVarint32(pReader->p, &i);
assert( i>=POS_BASE );
}
pReader->iLastPos += ((int) i)-POS_BASE;
if( iType>=DL_POSITIONS_OFFSETS ){
/* Skip over offsets, ignoring them for now. */
int iStart, iEnd;
pReader->p += getVarint32(pReader->p, &iStart);
pReader->p += getVarint32(pReader->p, &iEnd);
}
*iColumn = pReader->iLastColumn;
return pReader->iLastPos;
}
/* Skip past the end of a position list. */
static void skipPositionList(DocListReader *pReader){
DocList *p = pReader->pDoclist;
if( p && p->iType>=DL_POSITIONS ){
int iColumn;
while( readPosition(pReader, &iColumn)!=-1 ){}
}
}
/* Skip over a docid, including its position list if the doclist has
* positions. */
static void skipDocument(DocListReader *pReader){
readDocid(pReader);
skipPositionList(pReader);
}
/* Skip past all docids which are less than [iDocid]. Returns 1 if a docid
* matching [iDocid] was found. */
static int skipToDocid(DocListReader *pReader, sqlite_int64 iDocid){
sqlite_int64 d = 0;
while( !atEnd(pReader) && (d=peekDocid(pReader))<iDocid ){
skipDocument(pReader);
}
return !atEnd(pReader) && d==iDocid;
}
/* Return the first document in a document list.
*/
static sqlite_int64 firstDocid(DocList *d){
DocListReader r;
readerInit(&r, d);
return readDocid(&r);
}
#ifdef SQLITE_DEBUG
/*
** This routine is used for debugging purpose only.
**
** Write the content of a doclist to standard output.
*/
static void printDoclist(DocList *p){
DocListReader r;
const char *zSep = "";
readerInit(&r, p);
while( !atEnd(&r) ){
sqlite_int64 docid = readDocid(&r);
if( docid==0 ){
skipPositionList(&r);
continue;
}
printf("%s%lld", zSep, docid);
zSep = ",";
if( p->iType>=DL_POSITIONS ){
int iPos, iCol;
const char *zDiv = "";
printf("(");
while( (iPos = readPosition(&r, &iCol))>=0 ){
printf("%s%d:%d", zDiv, iCol, iPos);
zDiv = ":";
}
printf(")");
}
}
printf("\n");
fflush(stdout);
}
#endif /* SQLITE_DEBUG */
/* Trim the given doclist to contain only positions in column
* [iRestrictColumn]. */
static void docListRestrictColumn(DocList *in, int iRestrictColumn){
DocListReader r;
DocList out;
assert( in->iType>=DL_POSITIONS );
readerInit(&r, in);
docListInit(&out, DL_POSITIONS, NULL, 0);
while( !atEnd(&r) ){
sqlite_int64 iDocid = readDocid(&r);
int iPos, iColumn;
docListAddDocid(&out, iDocid);
while( (iPos = readPosition(&r, &iColumn)) != -1 ){
if( iColumn==iRestrictColumn ){
docListAddPos(&out, iColumn, iPos);
}
}
}
docListDestroy(in);
*in = out;
}
/* Trim the given doclist by discarding any docids without any remaining
* positions. */
static void docListDiscardEmpty(DocList *in) {
DocListReader r;
DocList out;
/* TODO: It would be nice to implement this operation in place; that
* could save a significant amount of memory in queries with long doclists. */
assert( in->iType>=DL_POSITIONS );
readerInit(&r, in);
docListInit(&out, DL_POSITIONS, NULL, 0);
while( !atEnd(&r) ){
sqlite_int64 iDocid = readDocid(&r);
int match = 0;
int iPos, iColumn;
while( (iPos = readPosition(&r, &iColumn)) != -1 ){
if( !match ){
docListAddDocid(&out, iDocid);
match = 1;
}
docListAddPos(&out, iColumn, iPos);
}
}
docListDestroy(in);
*in = out;
}
/* Helper function for docListUpdate() and docListAccumulate().
** Splices a doclist element into the doclist represented by r,
** leaving r pointing after the newly spliced element.
*/
static void docListSpliceElement(DocListReader *r, sqlite_int64 iDocid,
const char *pSource, int nSource){
DocList *d = r->pDoclist;
char *pTarget;
int nTarget, found;
found = skipToDocid(r, iDocid);
/* Describe slice in d to place pSource/nSource. */
pTarget = r->p;
if( found ){
skipDocument(r);
nTarget = r->p-pTarget;
}else{
nTarget = 0;
}
/* The sense of the following is that there are three possibilities.
** If nTarget==nSource, we should not move any memory nor realloc.
** If nTarget>nSource, trim target and realloc.
** If nTarget<nSource, realloc then expand target.
*/
if( nTarget>nSource ){
memmove(pTarget+nSource, pTarget+nTarget, docListEnd(d)-(pTarget+nTarget));
}
if( nTarget!=nSource ){
int iDoclist = pTarget-d->pData;
d->pData = realloc(d->pData, d->nData+nSource-nTarget);
pTarget = d->pData+iDoclist;
}
if( nTarget<nSource ){
memmove(pTarget+nSource, pTarget+nTarget, docListEnd(d)-(pTarget+nTarget));
}
memcpy(pTarget, pSource, nSource);
d->nData += nSource-nTarget;
r->p = pTarget+nSource;
}
/* Insert/update pUpdate into the doclist. */
static void docListUpdate(DocList *d, DocList *pUpdate){
DocListReader reader;
assert( d!=NULL && pUpdate!=NULL );
assert( d->iType==pUpdate->iType);
readerInit(&reader, d);
docListSpliceElement(&reader, firstDocid(pUpdate),
pUpdate->pData, pUpdate->nData);
}
/* Propagate elements from pUpdate to pAcc, overwriting elements with
** matching docids.
*/
static void docListAccumulate(DocList *pAcc, DocList *pUpdate){
DocListReader accReader, updateReader;
/* Handle edge cases where one doclist is empty. */
assert( pAcc!=NULL );
if( pUpdate==NULL || pUpdate->nData==0 ) return;
if( pAcc->nData==0 ){
pAcc->pData = malloc(pUpdate->nData);
memcpy(pAcc->pData, pUpdate->pData, pUpdate->nData);
pAcc->nData = pUpdate->nData;
return;
}
readerInit(&accReader, pAcc);
readerInit(&updateReader, pUpdate);
while( !atEnd(&updateReader) ){
char *pSource = updateReader.p;
sqlite_int64 iDocid = readDocid(&updateReader);
skipPositionList(&updateReader);
docListSpliceElement(&accReader, iDocid, pSource, updateReader.p-pSource);
}
}
/*
** Read the next docid off of pIn. Return 0 if we reach the end.
*
* TODO: This assumes that docids are never 0, but they may actually be 0 since
* users can choose docids when inserting into a full-text table. Fix this.
*/
static sqlite_int64 nextDocid(DocListReader *pIn){
skipPositionList(pIn);
return atEnd(pIn) ? 0 : readDocid(pIn);
}
/*
** pLeft and pRight are two DocListReaders that are pointing to
** positions lists of the same document: iDocid.
**
** If there are no instances in pLeft or pRight where the position
** of pLeft is one less than the position of pRight, then this
** routine adds nothing to pOut.
**
** If there are one or more instances where positions from pLeft
** are exactly one less than positions from pRight, then add a new
** document record to pOut. If pOut wants to hold positions, then
** include the positions from pRight that are one more than a
** position in pLeft. In other words: pRight.iPos==pLeft.iPos+1.
**
** pLeft and pRight are left pointing at the next document record.
*/
static void mergePosList(
DocListReader *pLeft, /* Left position list */
DocListReader *pRight, /* Right position list */
sqlite_int64 iDocid, /* The docid from pLeft and pRight */
DocList *pOut /* Write the merged document record here */
){
int iLeftCol, iLeftPos = readPosition(pLeft, &iLeftCol);
int iRightCol, iRightPos = readPosition(pRight, &iRightCol);
int match = 0;
/* Loop until we've reached the end of both position lists. */
while( iLeftPos!=-1 && iRightPos!=-1 ){
if( iLeftCol==iRightCol && iLeftPos+1==iRightPos ){
if( !match ){
docListAddDocid(pOut, iDocid);
match = 1;
}
if( pOut->iType>=DL_POSITIONS ){
docListAddPos(pOut, iRightCol, iRightPos);
}
iLeftPos = readPosition(pLeft, &iLeftCol);
iRightPos = readPosition(pRight, &iRightCol);
}else if( iRightCol<iLeftCol ||
(iRightCol==iLeftCol && iRightPos<iLeftPos+1) ){
iRightPos = readPosition(pRight, &iRightCol);
}else{
iLeftPos = readPosition(pLeft, &iLeftCol);
}
}
if( iLeftPos>=0 ) skipPositionList(pLeft);
if( iRightPos>=0 ) skipPositionList(pRight);
}
/* We have two doclists: pLeft and pRight.
** Write the phrase intersection of these two doclists into pOut.
**
** A phrase intersection means that two documents only match
** if pLeft.iPos+1==pRight.iPos.
**
** The output pOut may or may not contain positions. If pOut
** does contain positions, they are the positions of pRight.
*/
static void docListPhraseMerge(
DocList *pLeft, /* Doclist resulting from the words on the left */
DocList *pRight, /* Doclist for the next word to the right */
DocList *pOut /* Write the combined doclist here */
){
DocListReader left, right;
sqlite_int64 docidLeft, docidRight;
readerInit(&left, pLeft);
readerInit(&right, pRight);
docidLeft = nextDocid(&left);
docidRight = nextDocid(&right);
while( docidLeft>0 && docidRight>0 ){
if( docidLeft<docidRight ){
docidLeft = nextDocid(&left);
}else if( docidRight<docidLeft ){
docidRight = nextDocid(&right);
}else{
mergePosList(&left, &right, docidLeft, pOut);
docidLeft = nextDocid(&left);
docidRight = nextDocid(&right);
}
}
}
/* We have two doclists: pLeft and pRight.
** Write the intersection of these two doclists into pOut.
** Only docids are matched. Position information is ignored.
**
** The output pOut never holds positions.
*/
static void docListAndMerge(
DocList *pLeft, /* Doclist resulting from the words on the left */
DocList *pRight, /* Doclist for the next word to the right */
DocList *pOut /* Write the combined doclist here */
){
DocListReader left, right;
sqlite_int64 docidLeft, docidRight;
assert( pOut->iType<DL_POSITIONS );
readerInit(&left, pLeft);
readerInit(&right, pRight);
docidLeft = nextDocid(&left);
docidRight = nextDocid(&right);
while( docidLeft>0 && docidRight>0 ){
if( docidLeft<docidRight ){
docidLeft = nextDocid(&left);
}else if( docidRight<docidLeft ){
docidRight = nextDocid(&right);
}else{
docListAddDocid(pOut, docidLeft);
docidLeft = nextDocid(&left);
docidRight = nextDocid(&right);
}
}
}
/* We have two doclists: pLeft and pRight.
** Write the union of these two doclists into pOut.
** Only docids are matched. Position information is ignored.
**
** The output pOut never holds positions.
*/
static void docListOrMerge(
DocList *pLeft, /* Doclist resulting from the words on the left */
DocList *pRight, /* Doclist for the next word to the right */
DocList *pOut /* Write the combined doclist here */
){
DocListReader left, right;
sqlite_int64 docidLeft, docidRight, priorLeft;
readerInit(&left, pLeft);
readerInit(&right, pRight);
docidLeft = nextDocid(&left);
docidRight = nextDocid(&right);
while( docidLeft>0 && docidRight>0 ){
if( docidLeft<=docidRight ){
docListAddDocid(pOut, docidLeft);
}else{
docListAddDocid(pOut, docidRight);
}
priorLeft = docidLeft;
if( docidLeft<=docidRight ){
docidLeft = nextDocid(&left);
}
if( docidRight>0 && docidRight<=priorLeft ){
docidRight = nextDocid(&right);
}
}
while( docidLeft>0 ){
docListAddDocid(pOut, docidLeft);
docidLeft = nextDocid(&left);
}
while( docidRight>0 ){
docListAddDocid(pOut, docidRight);
docidRight = nextDocid(&right);
}
}
/* We have two doclists: pLeft and pRight.
** Write into pOut all documents that occur in pLeft but not
** in pRight.
**
** Only docids are matched. Position information is ignored.
**
** The output pOut never holds positions.
*/
static void docListExceptMerge(
DocList *pLeft, /* Doclist resulting from the words on the left */
DocList *pRight, /* Doclist for the next word to the right */
DocList *pOut /* Write the combined doclist here */
){
DocListReader left, right;
sqlite_int64 docidLeft, docidRight, priorLeft;
readerInit(&left, pLeft);
readerInit(&right, pRight);
docidLeft = nextDocid(&left);
docidRight = nextDocid(&right);
while( docidLeft>0 && docidRight>0 ){
priorLeft = docidLeft;
if( docidLeft<docidRight ){
docListAddDocid(pOut, docidLeft);
}
if( docidLeft<=docidRight ){
docidLeft = nextDocid(&left);
}
if( docidRight>0 && docidRight<=priorLeft ){
docidRight = nextDocid(&right);
}
}
while( docidLeft>0 ){
docListAddDocid(pOut, docidLeft);
docidLeft = nextDocid(&left);
}
}
static char *string_dup_n(const char *s, int n){
char *str = malloc(n + 1);
memcpy(str, s, n);
str[n] = '\0';
return str;
}
/* Duplicate a string; the caller must free() the returned string.
* (We don't use strdup() since it is not part of the standard C library and
* may not be available everywhere.) */
static char *string_dup(const char *s){
return string_dup_n(s, strlen(s));
}
/* Format a string, replacing each occurrence of the % character with
* zDb.zName. This may be more convenient than sqlite_mprintf()
* when one string is used repeatedly in a format string.
* The caller must free() the returned string. */
static char *string_format(const char *zFormat,
const char *zDb, const char *zName){
const char *p;
size_t len = 0;
size_t nDb = strlen(zDb);
size_t nName = strlen(zName);
size_t nFullTableName = nDb+1+nName;
char *result;
char *r;
/* first compute length needed */
for(p = zFormat ; *p ; ++p){
len += (*p=='%' ? nFullTableName : 1);
}
len += 1; /* for null terminator */
r = result = malloc(len);
for(p = zFormat; *p; ++p){
if( *p=='%' ){
memcpy(r, zDb, nDb);
r += nDb;
*r++ = '.';
memcpy(r, zName, nName);
r += nName;
} else {
*r++ = *p;
}
}
*r++ = '\0';
assert( r == result + len );
return result;
}
static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
const char *zFormat){
char *zCommand = string_format(zFormat, zDb, zName);
int rc;
TRACE(("FTS1 sql: %s\n", zCommand));
rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
free(zCommand);
return rc;
}
static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
sqlite3_stmt **ppStmt, const char *zFormat){
char *zCommand = string_format(zFormat, zDb, zName);
int rc;
TRACE(("FTS1 prepare: %s\n", zCommand));
rc = sqlite3_prepare(db, zCommand, -1, ppStmt, NULL);
free(zCommand);
return rc;
}
/* end utility functions */
/* Forward reference */
typedef struct fulltext_vtab fulltext_vtab;
/* A single term in a query is represented by an instances of
** the following structure.
*/
typedef struct QueryTerm {
short int nPhrase; /* How many following terms are part of the same phrase */
short int iPhrase; /* This is the i-th term of a phrase. */
short int iColumn; /* Column of the index that must match this term */
signed char isOr; /* this term is preceded by "OR" */
signed char isNot; /* this term is preceded by "-" */
char *pTerm; /* text of the term. '\000' terminated. malloced */
int nTerm; /* Number of bytes in pTerm[] */
} QueryTerm;
/* A query string is parsed into a Query structure.
*
* We could, in theory, allow query strings to be complicated
* nested expressions with precedence determined by parentheses.
* But none of the major search engines do this. (Perhaps the
* feeling is that an parenthesized expression is two complex of
* an idea for the average user to grasp.) Taking our lead from
* the major search engines, we will allow queries to be a list
* of terms (with an implied AND operator) or phrases in double-quotes,
* with a single optional "-" before each non-phrase term to designate
* negation and an optional OR connector.
*
* OR binds more tightly than the implied AND, which is what the
* major search engines seem to do. So, for example:
*
* [one two OR three] ==> one AND (two OR three)
* [one OR two three] ==> (one OR two) AND three
*
* A "-" before a term matches all entries that lack that term.
* The "-" must occur immediately before the term with in intervening
* space. This is how the search engines do it.
*
* A NOT term cannot be the right-hand operand of an OR. If this
* occurs in the query string, the NOT is ignored:
*
* [one OR -two] ==> one OR two
*
*/
typedef struct Query {
fulltext_vtab *pFts; /* The full text index */
int nTerms; /* Number of terms in the query */
QueryTerm *pTerms; /* Array of terms. Space obtained from malloc() */
int nextIsOr; /* Set the isOr flag on the next inserted term */
int nextColumn; /* Next word parsed must be in this column */
int dfltColumn; /* The default column */
} Query;
/*