xref: /sqlite-3.40.0/ext/fts3/fts3.c (revision c9099d2d)
1 /*
2 ** 2006 Oct 10
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 ******************************************************************************
12 **
13 ** This is an SQLite module implementing full-text search.
14 */
15 
16 /*
17 ** The code in this file is only compiled if:
18 **
19 **     * The FTS3 module is being built as an extension
20 **       (in which case SQLITE_CORE is not defined), or
21 **
22 **     * The FTS3 module is being built into the core of
23 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
24 */
25 
26 /* The full-text index is stored in a series of b+tree (-like)
27 ** structures called segments which map terms to doclists.  The
28 ** structures are like b+trees in layout, but are constructed from the
29 ** bottom up in optimal fashion and are not updatable.  Since trees
30 ** are built from the bottom up, things will be described from the
31 ** bottom up.
32 **
33 **
34 **** Varints ****
35 ** The basic unit of encoding is a variable-length integer called a
36 ** varint.  We encode variable-length integers in little-endian order
37 ** using seven bits * per byte as follows:
38 **
39 ** KEY:
40 **         A = 0xxxxxxx    7 bits of data and one flag bit
41 **         B = 1xxxxxxx    7 bits of data and one flag bit
42 **
43 **  7 bits - A
44 ** 14 bits - BA
45 ** 21 bits - BBA
46 ** and so on.
47 **
48 ** This is similar in concept to how sqlite encodes "varints" but
49 ** the encoding is not the same.  SQLite varints are big-endian
50 ** are are limited to 9 bytes in length whereas FTS3 varints are
51 ** little-endian and can be up to 10 bytes in length (in theory).
52 **
53 ** Example encodings:
54 **
55 **     1:    0x01
56 **   127:    0x7f
57 **   128:    0x81 0x00
58 **
59 **
60 **** Document lists ****
61 ** A doclist (document list) holds a docid-sorted list of hits for a
62 ** given term.  Doclists hold docids and associated token positions.
63 ** A docid is the unique integer identifier for a single document.
64 ** A position is the index of a word within the document.  The first
65 ** word of the document has a position of 0.
66 **
67 ** FTS3 used to optionally store character offsets using a compile-time
68 ** option.  But that functionality is no longer supported.
69 **
70 ** A doclist is stored like this:
71 **
72 ** array {
73 **   varint docid;          (delta from previous doclist)
74 **   array {                (position list for column 0)
75 **     varint position;     (2 more than the delta from previous position)
76 **   }
77 **   array {
78 **     varint POS_COLUMN;   (marks start of position list for new column)
79 **     varint column;       (index of new column)
80 **     array {
81 **       varint position;   (2 more than the delta from previous position)
82 **     }
83 **   }
84 **   varint POS_END;        (marks end of positions for this document.
85 ** }
86 **
87 ** Here, array { X } means zero or more occurrences of X, adjacent in
88 ** memory.  A "position" is an index of a token in the token stream
89 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
90 ** in the same logical place as the position element, and act as sentinals
91 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
92 ** The positions numbers are not stored literally but rather as two more
93 ** than the difference from the prior position, or the just the position plus
94 ** 2 for the first position.  Example:
95 **
96 **   label:       A B C D E  F  G H   I  J K
97 **   value:     123 5 9 1 1 14 35 0 234 72 0
98 **
99 ** The 123 value is the first docid.  For column zero in this document
100 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
101 ** at D signals the start of a new column; the 1 at E indicates that the
102 ** new column is column number 1.  There are two positions at 12 and 45
103 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
104 ** 234 at I is the delta to next docid (357).  It has one position 70
105 ** (72-2) and then terminates with the 0 at K.
106 **
107 ** A "position-list" is the list of positions for multiple columns for
108 ** a single docid.  A "column-list" is the set of positions for a single
109 ** column.  Hence, a position-list consists of one or more column-lists,
110 ** a document record consists of a docid followed by a position-list and
111 ** a doclist consists of one or more document records.
112 **
113 ** A bare doclist omits the position information, becoming an
114 ** array of varint-encoded docids.
115 **
116 **** Segment leaf nodes ****
117 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
118 ** nodes are written using LeafWriter, and read using LeafReader (to
119 ** iterate through a single leaf node's data) and LeavesReader (to
120 ** iterate through a segment's entire leaf layer).  Leaf nodes have
121 ** the format:
122 **
123 ** varint iHeight;             (height from leaf level, always 0)
124 ** varint nTerm;               (length of first term)
125 ** char pTerm[nTerm];          (content of first term)
126 ** varint nDoclist;            (length of term's associated doclist)
127 ** char pDoclist[nDoclist];    (content of doclist)
128 ** array {
129 **                             (further terms are delta-encoded)
130 **   varint nPrefix;           (length of prefix shared with previous term)
131 **   varint nSuffix;           (length of unshared suffix)
132 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
133 **   varint nDoclist;          (length of term's associated doclist)
134 **   char pDoclist[nDoclist];  (content of doclist)
135 ** }
136 **
137 ** Here, array { X } means zero or more occurrences of X, adjacent in
138 ** memory.
139 **
140 ** Leaf nodes are broken into blocks which are stored contiguously in
141 ** the %_segments table in sorted order.  This means that when the end
142 ** of a node is reached, the next term is in the node with the next
143 ** greater node id.
144 **
145 ** New data is spilled to a new leaf node when the current node
146 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
147 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
148 ** node (a leaf node with a single term and doclist).  The goal of
149 ** these settings is to pack together groups of small doclists while
150 ** making it efficient to directly access large doclists.  The
151 ** assumption is that large doclists represent terms which are more
152 ** likely to be query targets.
153 **
154 ** TODO(shess) It may be useful for blocking decisions to be more
155 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
156 ** node rather than splitting into 2k and .5k nodes.  My intuition is
157 ** that this might extend through 2x or 4x the pagesize.
158 **
159 **
160 **** Segment interior nodes ****
161 ** Segment interior nodes store blockids for subtree nodes and terms
162 ** to describe what data is stored by the each subtree.  Interior
163 ** nodes are written using InteriorWriter, and read using
164 ** InteriorReader.  InteriorWriters are created as needed when
165 ** SegmentWriter creates new leaf nodes, or when an interior node
166 ** itself grows too big and must be split.  The format of interior
167 ** nodes:
168 **
169 ** varint iHeight;           (height from leaf level, always >0)
170 ** varint iBlockid;          (block id of node's leftmost subtree)
171 ** optional {
172 **   varint nTerm;           (length of first term)
173 **   char pTerm[nTerm];      (content of first term)
174 **   array {
175 **                                (further terms are delta-encoded)
176 **     varint nPrefix;            (length of shared prefix with previous term)
177 **     varint nSuffix;            (length of unshared suffix)
178 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
179 **   }
180 ** }
181 **
182 ** Here, optional { X } means an optional element, while array { X }
183 ** means zero or more occurrences of X, adjacent in memory.
184 **
185 ** An interior node encodes n terms separating n+1 subtrees.  The
186 ** subtree blocks are contiguous, so only the first subtree's blockid
187 ** is encoded.  The subtree at iBlockid will contain all terms less
188 ** than the first term encoded (or all terms if no term is encoded).
189 ** Otherwise, for terms greater than or equal to pTerm[i] but less
190 ** than pTerm[i+1], the subtree for that term will be rooted at
191 ** iBlockid+i.  Interior nodes only store enough term data to
192 ** distinguish adjacent children (if the rightmost term of the left
193 ** child is "something", and the leftmost term of the right child is
194 ** "wicked", only "w" is stored).
195 **
196 ** New data is spilled to a new interior node at the same height when
197 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
198 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
199 ** interior nodes and making the tree too skinny.  The interior nodes
200 ** at a given height are naturally tracked by interior nodes at
201 ** height+1, and so on.
202 **
203 **
204 **** Segment directory ****
205 ** The segment directory in table %_segdir stores meta-information for
206 ** merging and deleting segments, and also the root node of the
207 ** segment's tree.
208 **
209 ** The root node is the top node of the segment's tree after encoding
210 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
211 ** This could be either a leaf node or an interior node.  If the top
212 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
213 ** and a new root interior node is generated (which should always fit
214 ** within ROOT_MAX because it only needs space for 2 varints, the
215 ** height and the blockid of the previous root).
216 **
217 ** The meta-information in the segment directory is:
218 **   level               - segment level (see below)
219 **   idx                 - index within level
220 **                       - (level,idx uniquely identify a segment)
221 **   start_block         - first leaf node
222 **   leaves_end_block    - last leaf node
223 **   end_block           - last block (including interior nodes)
224 **   root                - contents of root node
225 **
226 ** If the root node is a leaf node, then start_block,
227 ** leaves_end_block, and end_block are all 0.
228 **
229 **
230 **** Segment merging ****
231 ** To amortize update costs, segments are grouped into levels and
232 ** merged in batches.  Each increase in level represents exponentially
233 ** more documents.
234 **
235 ** New documents (actually, document updates) are tokenized and
236 ** written individually (using LeafWriter) to a level 0 segment, with
237 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
238 ** level 0 segments are merged into a single level 1 segment.  Level 1
239 ** is populated like level 0, and eventually MERGE_COUNT level 1
240 ** segments are merged to a single level 2 segment (representing
241 ** MERGE_COUNT^2 updates), and so on.
242 **
243 ** A segment merge traverses all segments at a given level in
244 ** parallel, performing a straightforward sorted merge.  Since segment
245 ** leaf nodes are written in to the %_segments table in order, this
246 ** merge traverses the underlying sqlite disk structures efficiently.
247 ** After the merge, all segment blocks from the merged level are
248 ** deleted.
249 **
250 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
251 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
252 ** very similar performance numbers to 16 on insertion, though they're
253 ** a tiny bit slower (perhaps due to more overhead in merge-time
254 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
255 ** 16, 2 about 66% slower than 16.
256 **
257 ** At query time, high MERGE_COUNT increases the number of segments
258 ** which need to be scanned and merged.  For instance, with 100k docs
259 ** inserted:
260 **
261 **    MERGE_COUNT   segments
262 **       16           25
263 **        8           12
264 **        4           10
265 **        2            6
266 **
267 ** This appears to have only a moderate impact on queries for very
268 ** frequent terms (which are somewhat dominated by segment merge
269 ** costs), and infrequent and non-existent terms still seem to be fast
270 ** even with many segments.
271 **
272 ** TODO(shess) That said, it would be nice to have a better query-side
273 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
274 ** optimizations to things like doclist merging will swing the sweet
275 ** spot around.
276 **
277 **
278 **
279 **** Handling of deletions and updates ****
280 ** Since we're using a segmented structure, with no docid-oriented
281 ** index into the term index, we clearly cannot simply update the term
282 ** index when a document is deleted or updated.  For deletions, we
283 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
284 ** we simply write the new doclist.  Segment merges overwrite older
285 ** data for a particular docid with newer data, so deletes or updates
286 ** will eventually overtake the earlier data and knock it out.  The
287 ** query logic likewise merges doclists so that newer data knocks out
288 ** older data.
289 */
290 
291 #include "fts3Int.h"
292 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
293 
294 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
295 # define SQLITE_CORE 1
296 #endif
297 
298 #include <assert.h>
299 #include <stdlib.h>
300 #include <stddef.h>
301 #include <stdio.h>
302 #include <string.h>
303 #include <stdarg.h>
304 
305 #include "fts3.h"
306 #ifndef SQLITE_CORE
307 # include "sqlite3ext.h"
308   SQLITE_EXTENSION_INIT1
309 #endif
310 
311 typedef struct Fts3HashWrapper Fts3HashWrapper;
312 struct Fts3HashWrapper {
313   Fts3Hash hash;                  /* Hash table */
314   int nRef;                       /* Number of pointers to this object */
315 };
316 
317 static int fts3EvalNext(Fts3Cursor *pCsr);
318 static int fts3EvalStart(Fts3Cursor *pCsr);
319 static int fts3TermSegReaderCursor(
320     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
321 
322 /*
323 ** This variable is set to false when running tests for which the on disk
324 ** structures should not be corrupt. Otherwise, true. If it is false, extra
325 ** assert() conditions in the fts3 code are activated - conditions that are
326 ** only true if it is guaranteed that the fts3 database is not corrupt.
327 */
328 #ifdef SQLITE_DEBUG
329 int sqlite3_fts3_may_be_corrupt = 1;
330 #endif
331 
332 /*
333 ** Write a 64-bit variable-length integer to memory starting at p[0].
334 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
335 ** The number of bytes written is returned.
336 */
sqlite3Fts3PutVarint(char * p,sqlite_int64 v)337 int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
338   unsigned char *q = (unsigned char *) p;
339   sqlite_uint64 vu = v;
340   do{
341     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
342     vu >>= 7;
343   }while( vu!=0 );
344   q[-1] &= 0x7f;  /* turn off high bit in final byte */
345   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
346   return (int) (q - (unsigned char *)p);
347 }
348 
349 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
350   v = (v & mask1) | ( (*(const unsigned char*)(ptr++)) << shift );  \
351   if( (v & mask2)==0 ){ var = v; return ret; }
352 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
353   v = (*ptr++);                                               \
354   if( (v & mask2)==0 ){ var = v; return ret; }
355 
sqlite3Fts3GetVarintU(const char * pBuf,sqlite_uint64 * v)356 int sqlite3Fts3GetVarintU(const char *pBuf, sqlite_uint64 *v){
357   const unsigned char *p = (const unsigned char*)pBuf;
358   const unsigned char *pStart = p;
359   u32 a;
360   u64 b;
361   int shift;
362 
363   GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
364   GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
365   GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
366   GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
367   b = (a & 0x0FFFFFFF );
368 
369   for(shift=28; shift<=63; shift+=7){
370     u64 c = *p++;
371     b += (c&0x7F) << shift;
372     if( (c & 0x80)==0 ) break;
373   }
374   *v = b;
375   return (int)(p - pStart);
376 }
377 
378 /*
379 ** Read a 64-bit variable-length integer from memory starting at p[0].
380 ** Return the number of bytes read, or 0 on error.
381 ** The value is stored in *v.
382 */
sqlite3Fts3GetVarint(const char * pBuf,sqlite_int64 * v)383 int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
384   return sqlite3Fts3GetVarintU(pBuf, (sqlite3_uint64*)v);
385 }
386 
387 /*
388 ** Read a 64-bit variable-length integer from memory starting at p[0] and
389 ** not extending past pEnd[-1].
390 ** Return the number of bytes read, or 0 on error.
391 ** The value is stored in *v.
392 */
sqlite3Fts3GetVarintBounded(const char * pBuf,const char * pEnd,sqlite_int64 * v)393 int sqlite3Fts3GetVarintBounded(
394   const char *pBuf,
395   const char *pEnd,
396   sqlite_int64 *v
397 ){
398   const unsigned char *p = (const unsigned char*)pBuf;
399   const unsigned char *pStart = p;
400   const unsigned char *pX = (const unsigned char*)pEnd;
401   u64 b = 0;
402   int shift;
403   for(shift=0; shift<=63; shift+=7){
404     u64 c = p<pX ? *p : 0;
405     p++;
406     b += (c&0x7F) << shift;
407     if( (c & 0x80)==0 ) break;
408   }
409   *v = b;
410   return (int)(p - pStart);
411 }
412 
413 /*
414 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
415 ** a non-negative 32-bit integer before it is returned.
416 */
sqlite3Fts3GetVarint32(const char * p,int * pi)417 int sqlite3Fts3GetVarint32(const char *p, int *pi){
418   const unsigned char *ptr = (const unsigned char*)p;
419   u32 a;
420 
421 #ifndef fts3GetVarint32
422   GETVARINT_INIT(a, ptr, 0,  0x00,     0x80, *pi, 1);
423 #else
424   a = (*ptr++);
425   assert( a & 0x80 );
426 #endif
427 
428   GETVARINT_STEP(a, ptr, 7,  0x7F,     0x4000, *pi, 2);
429   GETVARINT_STEP(a, ptr, 14, 0x3FFF,   0x200000, *pi, 3);
430   GETVARINT_STEP(a, ptr, 21, 0x1FFFFF, 0x10000000, *pi, 4);
431   a = (a & 0x0FFFFFFF );
432   *pi = (int)(a | ((u32)(*ptr & 0x07) << 28));
433   assert( 0==(a & 0x80000000) );
434   assert( *pi>=0 );
435   return 5;
436 }
437 
438 /*
439 ** Return the number of bytes required to encode v as a varint
440 */
sqlite3Fts3VarintLen(sqlite3_uint64 v)441 int sqlite3Fts3VarintLen(sqlite3_uint64 v){
442   int i = 0;
443   do{
444     i++;
445     v >>= 7;
446   }while( v!=0 );
447   return i;
448 }
449 
450 /*
451 ** Convert an SQL-style quoted string into a normal string by removing
452 ** the quote characters.  The conversion is done in-place.  If the
453 ** input does not begin with a quote character, then this routine
454 ** is a no-op.
455 **
456 ** Examples:
457 **
458 **     "abc"   becomes   abc
459 **     'xyz'   becomes   xyz
460 **     [pqr]   becomes   pqr
461 **     `mno`   becomes   mno
462 **
463 */
sqlite3Fts3Dequote(char * z)464 void sqlite3Fts3Dequote(char *z){
465   char quote;                     /* Quote character (if any ) */
466 
467   quote = z[0];
468   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
469     int iIn = 1;                  /* Index of next byte to read from input */
470     int iOut = 0;                 /* Index of next byte to write to output */
471 
472     /* If the first byte was a '[', then the close-quote character is a ']' */
473     if( quote=='[' ) quote = ']';
474 
475     while( z[iIn] ){
476       if( z[iIn]==quote ){
477         if( z[iIn+1]!=quote ) break;
478         z[iOut++] = quote;
479         iIn += 2;
480       }else{
481         z[iOut++] = z[iIn++];
482       }
483     }
484     z[iOut] = '\0';
485   }
486 }
487 
488 /*
489 ** Read a single varint from the doclist at *pp and advance *pp to point
490 ** to the first byte past the end of the varint.  Add the value of the varint
491 ** to *pVal.
492 */
fts3GetDeltaVarint(char ** pp,sqlite3_int64 * pVal)493 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
494   sqlite3_int64 iVal;
495   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
496   *pVal += iVal;
497 }
498 
499 /*
500 ** When this function is called, *pp points to the first byte following a
501 ** varint that is part of a doclist (or position-list, or any other list
502 ** of varints). This function moves *pp to point to the start of that varint,
503 ** and sets *pVal by the varint value.
504 **
505 ** Argument pStart points to the first byte of the doclist that the
506 ** varint is part of.
507 */
fts3GetReverseVarint(char ** pp,char * pStart,sqlite3_int64 * pVal)508 static void fts3GetReverseVarint(
509   char **pp,
510   char *pStart,
511   sqlite3_int64 *pVal
512 ){
513   sqlite3_int64 iVal;
514   char *p;
515 
516   /* Pointer p now points at the first byte past the varint we are
517   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
518   ** clear on character p[-1]. */
519   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
520   p++;
521   *pp = p;
522 
523   sqlite3Fts3GetVarint(p, &iVal);
524   *pVal = iVal;
525 }
526 
527 /*
528 ** The xDisconnect() virtual table method.
529 */
fts3DisconnectMethod(sqlite3_vtab * pVtab)530 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
531   Fts3Table *p = (Fts3Table *)pVtab;
532   int i;
533 
534   assert( p->nPendingData==0 );
535   assert( p->pSegments==0 );
536 
537   /* Free any prepared statements held */
538   sqlite3_finalize(p->pSeekStmt);
539   for(i=0; i<SizeofArray(p->aStmt); i++){
540     sqlite3_finalize(p->aStmt[i]);
541   }
542   sqlite3_free(p->zSegmentsTbl);
543   sqlite3_free(p->zReadExprlist);
544   sqlite3_free(p->zWriteExprlist);
545   sqlite3_free(p->zContentTbl);
546   sqlite3_free(p->zLanguageid);
547 
548   /* Invoke the tokenizer destructor to free the tokenizer. */
549   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
550 
551   sqlite3_free(p);
552   return SQLITE_OK;
553 }
554 
555 /*
556 ** Write an error message into *pzErr
557 */
sqlite3Fts3ErrMsg(char ** pzErr,const char * zFormat,...)558 void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
559   va_list ap;
560   sqlite3_free(*pzErr);
561   va_start(ap, zFormat);
562   *pzErr = sqlite3_vmprintf(zFormat, ap);
563   va_end(ap);
564 }
565 
566 /*
567 ** Construct one or more SQL statements from the format string given
568 ** and then evaluate those statements. The success code is written
569 ** into *pRc.
570 **
571 ** If *pRc is initially non-zero then this routine is a no-op.
572 */
fts3DbExec(int * pRc,sqlite3 * db,const char * zFormat,...)573 static void fts3DbExec(
574   int *pRc,              /* Success code */
575   sqlite3 *db,           /* Database in which to run SQL */
576   const char *zFormat,   /* Format string for SQL */
577   ...                    /* Arguments to the format string */
578 ){
579   va_list ap;
580   char *zSql;
581   if( *pRc ) return;
582   va_start(ap, zFormat);
583   zSql = sqlite3_vmprintf(zFormat, ap);
584   va_end(ap);
585   if( zSql==0 ){
586     *pRc = SQLITE_NOMEM;
587   }else{
588     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
589     sqlite3_free(zSql);
590   }
591 }
592 
593 /*
594 ** The xDestroy() virtual table method.
595 */
fts3DestroyMethod(sqlite3_vtab * pVtab)596 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
597   Fts3Table *p = (Fts3Table *)pVtab;
598   int rc = SQLITE_OK;              /* Return code */
599   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
600   sqlite3 *db = p->db;             /* Database handle */
601 
602   /* Drop the shadow tables */
603   fts3DbExec(&rc, db,
604     "DROP TABLE IF EXISTS %Q.'%q_segments';"
605     "DROP TABLE IF EXISTS %Q.'%q_segdir';"
606     "DROP TABLE IF EXISTS %Q.'%q_docsize';"
607     "DROP TABLE IF EXISTS %Q.'%q_stat';"
608     "%s DROP TABLE IF EXISTS %Q.'%q_content';",
609     zDb, p->zName,
610     zDb, p->zName,
611     zDb, p->zName,
612     zDb, p->zName,
613     (p->zContentTbl ? "--" : ""), zDb,p->zName
614   );
615 
616   /* If everything has worked, invoke fts3DisconnectMethod() to free the
617   ** memory associated with the Fts3Table structure and return SQLITE_OK.
618   ** Otherwise, return an SQLite error code.
619   */
620   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
621 }
622 
623 
624 /*
625 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
626 ** passed as the first argument. This is done as part of the xConnect()
627 ** and xCreate() methods.
628 **
629 ** If *pRc is non-zero when this function is called, it is a no-op.
630 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
631 ** before returning.
632 */
fts3DeclareVtab(int * pRc,Fts3Table * p)633 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
634   if( *pRc==SQLITE_OK ){
635     int i;                        /* Iterator variable */
636     int rc;                       /* Return code */
637     char *zSql;                   /* SQL statement passed to declare_vtab() */
638     char *zCols;                  /* List of user defined columns */
639     const char *zLanguageid;
640 
641     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
642     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
643 
644     /* Create a list of user columns for the virtual table */
645     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
646     for(i=1; zCols && i<p->nColumn; i++){
647       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
648     }
649 
650     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
651     zSql = sqlite3_mprintf(
652         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
653         zCols, p->zName, zLanguageid
654     );
655     if( !zCols || !zSql ){
656       rc = SQLITE_NOMEM;
657     }else{
658       rc = sqlite3_declare_vtab(p->db, zSql);
659     }
660 
661     sqlite3_free(zSql);
662     sqlite3_free(zCols);
663     *pRc = rc;
664   }
665 }
666 
667 /*
668 ** Create the %_stat table if it does not already exist.
669 */
sqlite3Fts3CreateStatTable(int * pRc,Fts3Table * p)670 void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
671   fts3DbExec(pRc, p->db,
672       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
673           "(id INTEGER PRIMARY KEY, value BLOB);",
674       p->zDb, p->zName
675   );
676   if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
677 }
678 
679 /*
680 ** Create the backing store tables (%_content, %_segments and %_segdir)
681 ** required by the FTS3 table passed as the only argument. This is done
682 ** as part of the vtab xCreate() method.
683 **
684 ** If the p->bHasDocsize boolean is true (indicating that this is an
685 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
686 ** %_stat tables required by FTS4.
687 */
fts3CreateTables(Fts3Table * p)688 static int fts3CreateTables(Fts3Table *p){
689   int rc = SQLITE_OK;             /* Return code */
690   int i;                          /* Iterator variable */
691   sqlite3 *db = p->db;            /* The database connection */
692 
693   if( p->zContentTbl==0 ){
694     const char *zLanguageid = p->zLanguageid;
695     char *zContentCols;           /* Columns of %_content table */
696 
697     /* Create a list of user columns for the content table */
698     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
699     for(i=0; zContentCols && i<p->nColumn; i++){
700       char *z = p->azColumn[i];
701       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
702     }
703     if( zLanguageid && zContentCols ){
704       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
705     }
706     if( zContentCols==0 ) rc = SQLITE_NOMEM;
707 
708     /* Create the content table */
709     fts3DbExec(&rc, db,
710        "CREATE TABLE %Q.'%q_content'(%s)",
711        p->zDb, p->zName, zContentCols
712     );
713     sqlite3_free(zContentCols);
714   }
715 
716   /* Create other tables */
717   fts3DbExec(&rc, db,
718       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
719       p->zDb, p->zName
720   );
721   fts3DbExec(&rc, db,
722       "CREATE TABLE %Q.'%q_segdir'("
723         "level INTEGER,"
724         "idx INTEGER,"
725         "start_block INTEGER,"
726         "leaves_end_block INTEGER,"
727         "end_block INTEGER,"
728         "root BLOB,"
729         "PRIMARY KEY(level, idx)"
730       ");",
731       p->zDb, p->zName
732   );
733   if( p->bHasDocsize ){
734     fts3DbExec(&rc, db,
735         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
736         p->zDb, p->zName
737     );
738   }
739   assert( p->bHasStat==p->bFts4 );
740   if( p->bHasStat ){
741     sqlite3Fts3CreateStatTable(&rc, p);
742   }
743   return rc;
744 }
745 
746 /*
747 ** Store the current database page-size in bytes in p->nPgsz.
748 **
749 ** If *pRc is non-zero when this function is called, it is a no-op.
750 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
751 ** before returning.
752 */
fts3DatabasePageSize(int * pRc,Fts3Table * p)753 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
754   if( *pRc==SQLITE_OK ){
755     int rc;                       /* Return code */
756     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
757     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
758 
759     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
760     if( !zSql ){
761       rc = SQLITE_NOMEM;
762     }else{
763       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
764       if( rc==SQLITE_OK ){
765         sqlite3_step(pStmt);
766         p->nPgsz = sqlite3_column_int(pStmt, 0);
767         rc = sqlite3_finalize(pStmt);
768       }else if( rc==SQLITE_AUTH ){
769         p->nPgsz = 1024;
770         rc = SQLITE_OK;
771       }
772     }
773     assert( p->nPgsz>0 || rc!=SQLITE_OK );
774     sqlite3_free(zSql);
775     *pRc = rc;
776   }
777 }
778 
779 /*
780 ** "Special" FTS4 arguments are column specifications of the following form:
781 **
782 **   <key> = <value>
783 **
784 ** There may not be whitespace surrounding the "=" character. The <value>
785 ** term may be quoted, but the <key> may not.
786 */
fts3IsSpecialColumn(const char * z,int * pnKey,char ** pzValue)787 static int fts3IsSpecialColumn(
788   const char *z,
789   int *pnKey,
790   char **pzValue
791 ){
792   char *zValue;
793   const char *zCsr = z;
794 
795   while( *zCsr!='=' ){
796     if( *zCsr=='\0' ) return 0;
797     zCsr++;
798   }
799 
800   *pnKey = (int)(zCsr-z);
801   zValue = sqlite3_mprintf("%s", &zCsr[1]);
802   if( zValue ){
803     sqlite3Fts3Dequote(zValue);
804   }
805   *pzValue = zValue;
806   return 1;
807 }
808 
809 /*
810 ** Append the output of a printf() style formatting to an existing string.
811 */
fts3Appendf(int * pRc,char ** pz,const char * zFormat,...)812 static void fts3Appendf(
813   int *pRc,                       /* IN/OUT: Error code */
814   char **pz,                      /* IN/OUT: Pointer to string buffer */
815   const char *zFormat,            /* Printf format string to append */
816   ...                             /* Arguments for printf format string */
817 ){
818   if( *pRc==SQLITE_OK ){
819     va_list ap;
820     char *z;
821     va_start(ap, zFormat);
822     z = sqlite3_vmprintf(zFormat, ap);
823     va_end(ap);
824     if( z && *pz ){
825       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
826       sqlite3_free(z);
827       z = z2;
828     }
829     if( z==0 ) *pRc = SQLITE_NOMEM;
830     sqlite3_free(*pz);
831     *pz = z;
832   }
833 }
834 
835 /*
836 ** Return a copy of input string zInput enclosed in double-quotes (") and
837 ** with all double quote characters escaped. For example:
838 **
839 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
840 **
841 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
842 ** is the callers responsibility to call sqlite3_free() to release this
843 ** memory.
844 */
fts3QuoteId(char const * zInput)845 static char *fts3QuoteId(char const *zInput){
846   sqlite3_int64 nRet;
847   char *zRet;
848   nRet = 2 + (int)strlen(zInput)*2 + 1;
849   zRet = sqlite3_malloc64(nRet);
850   if( zRet ){
851     int i;
852     char *z = zRet;
853     *(z++) = '"';
854     for(i=0; zInput[i]; i++){
855       if( zInput[i]=='"' ) *(z++) = '"';
856       *(z++) = zInput[i];
857     }
858     *(z++) = '"';
859     *(z++) = '\0';
860   }
861   return zRet;
862 }
863 
864 /*
865 ** Return a list of comma separated SQL expressions and a FROM clause that
866 ** could be used in a SELECT statement such as the following:
867 **
868 **     SELECT <list of expressions> FROM %_content AS x ...
869 **
870 ** to return the docid, followed by each column of text data in order
871 ** from left to write. If parameter zFunc is not NULL, then instead of
872 ** being returned directly each column of text data is passed to an SQL
873 ** function named zFunc first. For example, if zFunc is "unzip" and the
874 ** table has the three user-defined columns "a", "b", and "c", the following
875 ** string is returned:
876 **
877 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
878 **
879 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
880 ** is the responsibility of the caller to eventually free it.
881 **
882 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
883 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
884 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
885 ** no error occurs, *pRc is left unmodified.
886 */
fts3ReadExprList(Fts3Table * p,const char * zFunc,int * pRc)887 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
888   char *zRet = 0;
889   char *zFree = 0;
890   char *zFunction;
891   int i;
892 
893   if( p->zContentTbl==0 ){
894     if( !zFunc ){
895       zFunction = "";
896     }else{
897       zFree = zFunction = fts3QuoteId(zFunc);
898     }
899     fts3Appendf(pRc, &zRet, "docid");
900     for(i=0; i<p->nColumn; i++){
901       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
902     }
903     if( p->zLanguageid ){
904       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
905     }
906     sqlite3_free(zFree);
907   }else{
908     fts3Appendf(pRc, &zRet, "rowid");
909     for(i=0; i<p->nColumn; i++){
910       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
911     }
912     if( p->zLanguageid ){
913       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
914     }
915   }
916   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
917       p->zDb,
918       (p->zContentTbl ? p->zContentTbl : p->zName),
919       (p->zContentTbl ? "" : "_content")
920   );
921   return zRet;
922 }
923 
924 /*
925 ** Return a list of N comma separated question marks, where N is the number
926 ** of columns in the %_content table (one for the docid plus one for each
927 ** user-defined text column).
928 **
929 ** If argument zFunc is not NULL, then all but the first question mark
930 ** is preceded by zFunc and an open bracket, and followed by a closed
931 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
932 ** user-defined text columns, the following string is returned:
933 **
934 **     "?, zip(?), zip(?), zip(?)"
935 **
936 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
937 ** is the responsibility of the caller to eventually free it.
938 **
939 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
940 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
941 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
942 ** no error occurs, *pRc is left unmodified.
943 */
fts3WriteExprList(Fts3Table * p,const char * zFunc,int * pRc)944 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
945   char *zRet = 0;
946   char *zFree = 0;
947   char *zFunction;
948   int i;
949 
950   if( !zFunc ){
951     zFunction = "";
952   }else{
953     zFree = zFunction = fts3QuoteId(zFunc);
954   }
955   fts3Appendf(pRc, &zRet, "?");
956   for(i=0; i<p->nColumn; i++){
957     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
958   }
959   if( p->zLanguageid ){
960     fts3Appendf(pRc, &zRet, ", ?");
961   }
962   sqlite3_free(zFree);
963   return zRet;
964 }
965 
966 /*
967 ** Buffer z contains a positive integer value encoded as utf-8 text.
968 ** Decode this value and store it in *pnOut, returning the number of bytes
969 ** consumed. If an overflow error occurs return a negative value.
970 */
sqlite3Fts3ReadInt(const char * z,int * pnOut)971 int sqlite3Fts3ReadInt(const char *z, int *pnOut){
972   u64 iVal = 0;
973   int i;
974   for(i=0; z[i]>='0' && z[i]<='9'; i++){
975     iVal = iVal*10 + (z[i] - '0');
976     if( iVal>0x7FFFFFFF ) return -1;
977   }
978   *pnOut = (int)iVal;
979   return i;
980 }
981 
982 /*
983 ** This function interprets the string at (*pp) as a non-negative integer
984 ** value. It reads the integer and sets *pnOut to the value read, then
985 ** sets *pp to point to the byte immediately following the last byte of
986 ** the integer value.
987 **
988 ** Only decimal digits ('0'..'9') may be part of an integer value.
989 **
990 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
991 ** the output value undefined. Otherwise SQLITE_OK is returned.
992 **
993 ** This function is used when parsing the "prefix=" FTS4 parameter.
994 */
fts3GobbleInt(const char ** pp,int * pnOut)995 static int fts3GobbleInt(const char **pp, int *pnOut){
996   const int MAX_NPREFIX = 10000000;
997   int nInt = 0;                   /* Output value */
998   int nByte;
999   nByte = sqlite3Fts3ReadInt(*pp, &nInt);
1000   if( nInt>MAX_NPREFIX ){
1001     nInt = 0;
1002   }
1003   if( nByte==0 ){
1004     return SQLITE_ERROR;
1005   }
1006   *pnOut = nInt;
1007   *pp += nByte;
1008   return SQLITE_OK;
1009 }
1010 
1011 /*
1012 ** This function is called to allocate an array of Fts3Index structures
1013 ** representing the indexes maintained by the current FTS table. FTS tables
1014 ** always maintain the main "terms" index, but may also maintain one or
1015 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
1016 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
1017 **
1018 ** Argument zParam is passed the value of the "prefix=" option if one was
1019 ** specified, or NULL otherwise.
1020 **
1021 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
1022 ** the allocated array. *pnIndex is set to the number of elements in the
1023 ** array. If an error does occur, an SQLite error code is returned.
1024 **
1025 ** Regardless of whether or not an error is returned, it is the responsibility
1026 ** of the caller to call sqlite3_free() on the output array to free it.
1027 */
fts3PrefixParameter(const char * zParam,int * pnIndex,struct Fts3Index ** apIndex)1028 static int fts3PrefixParameter(
1029   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
1030   int *pnIndex,                   /* OUT: size of *apIndex[] array */
1031   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
1032 ){
1033   struct Fts3Index *aIndex;       /* Allocated array */
1034   int nIndex = 1;                 /* Number of entries in array */
1035 
1036   if( zParam && zParam[0] ){
1037     const char *p;
1038     nIndex++;
1039     for(p=zParam; *p; p++){
1040       if( *p==',' ) nIndex++;
1041     }
1042   }
1043 
1044   aIndex = sqlite3_malloc64(sizeof(struct Fts3Index) * nIndex);
1045   *apIndex = aIndex;
1046   if( !aIndex ){
1047     return SQLITE_NOMEM;
1048   }
1049 
1050   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
1051   if( zParam ){
1052     const char *p = zParam;
1053     int i;
1054     for(i=1; i<nIndex; i++){
1055       int nPrefix = 0;
1056       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
1057       assert( nPrefix>=0 );
1058       if( nPrefix==0 ){
1059         nIndex--;
1060         i--;
1061       }else{
1062         aIndex[i].nPrefix = nPrefix;
1063       }
1064       p++;
1065     }
1066   }
1067 
1068   *pnIndex = nIndex;
1069   return SQLITE_OK;
1070 }
1071 
1072 /*
1073 ** This function is called when initializing an FTS4 table that uses the
1074 ** content=xxx option. It determines the number of and names of the columns
1075 ** of the new FTS4 table.
1076 **
1077 ** The third argument passed to this function is the value passed to the
1078 ** config=xxx option (i.e. "xxx"). This function queries the database for
1079 ** a table of that name. If found, the output variables are populated
1080 ** as follows:
1081 **
1082 **   *pnCol:   Set to the number of columns table xxx has,
1083 **
1084 **   *pnStr:   Set to the total amount of space required to store a copy
1085 **             of each columns name, including the nul-terminator.
1086 **
1087 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
1088 **             the name of the corresponding column in table xxx. The array
1089 **             and its contents are allocated using a single allocation. It
1090 **             is the responsibility of the caller to free this allocation
1091 **             by eventually passing the *pazCol value to sqlite3_free().
1092 **
1093 ** If the table cannot be found, an error code is returned and the output
1094 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
1095 ** returned (and the output variables are undefined).
1096 */
fts3ContentColumns(sqlite3 * db,const char * zDb,const char * zTbl,const char *** pazCol,int * pnCol,int * pnStr,char ** pzErr)1097 static int fts3ContentColumns(
1098   sqlite3 *db,                    /* Database handle */
1099   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
1100   const char *zTbl,               /* Name of content table */
1101   const char ***pazCol,           /* OUT: Malloc'd array of column names */
1102   int *pnCol,                     /* OUT: Size of array *pazCol */
1103   int *pnStr,                     /* OUT: Bytes of string content */
1104   char **pzErr                    /* OUT: error message */
1105 ){
1106   int rc = SQLITE_OK;             /* Return code */
1107   char *zSql;                     /* "SELECT *" statement on zTbl */
1108   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
1109 
1110   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
1111   if( !zSql ){
1112     rc = SQLITE_NOMEM;
1113   }else{
1114     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1115     if( rc!=SQLITE_OK ){
1116       sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
1117     }
1118   }
1119   sqlite3_free(zSql);
1120 
1121   if( rc==SQLITE_OK ){
1122     const char **azCol;           /* Output array */
1123     sqlite3_int64 nStr = 0;       /* Size of all column names (incl. 0x00) */
1124     int nCol;                     /* Number of table columns */
1125     int i;                        /* Used to iterate through columns */
1126 
1127     /* Loop through the returned columns. Set nStr to the number of bytes of
1128     ** space required to store a copy of each column name, including the
1129     ** nul-terminator byte.  */
1130     nCol = sqlite3_column_count(pStmt);
1131     for(i=0; i<nCol; i++){
1132       const char *zCol = sqlite3_column_name(pStmt, i);
1133       nStr += strlen(zCol) + 1;
1134     }
1135 
1136     /* Allocate and populate the array to return. */
1137     azCol = (const char **)sqlite3_malloc64(sizeof(char *) * nCol + nStr);
1138     if( azCol==0 ){
1139       rc = SQLITE_NOMEM;
1140     }else{
1141       char *p = (char *)&azCol[nCol];
1142       for(i=0; i<nCol; i++){
1143         const char *zCol = sqlite3_column_name(pStmt, i);
1144         int n = (int)strlen(zCol)+1;
1145         memcpy(p, zCol, n);
1146         azCol[i] = p;
1147         p += n;
1148       }
1149     }
1150     sqlite3_finalize(pStmt);
1151 
1152     /* Set the output variables. */
1153     *pnCol = nCol;
1154     *pnStr = nStr;
1155     *pazCol = azCol;
1156   }
1157 
1158   return rc;
1159 }
1160 
1161 /*
1162 ** This function is the implementation of both the xConnect and xCreate
1163 ** methods of the FTS3 virtual table.
1164 **
1165 ** The argv[] array contains the following:
1166 **
1167 **   argv[0]   -> module name  ("fts3" or "fts4")
1168 **   argv[1]   -> database name
1169 **   argv[2]   -> table name
1170 **   argv[...] -> "column name" and other module argument fields.
1171 */
fts3InitVtab(int isCreate,sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVTab,char ** pzErr)1172 static int fts3InitVtab(
1173   int isCreate,                   /* True for xCreate, false for xConnect */
1174   sqlite3 *db,                    /* The SQLite database connection */
1175   void *pAux,                     /* Hash table containing tokenizers */
1176   int argc,                       /* Number of elements in argv array */
1177   const char * const *argv,       /* xCreate/xConnect argument array */
1178   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
1179   char **pzErr                    /* Write any error message here */
1180 ){
1181   Fts3Hash *pHash = &((Fts3HashWrapper*)pAux)->hash;
1182   Fts3Table *p = 0;               /* Pointer to allocated vtab */
1183   int rc = SQLITE_OK;             /* Return code */
1184   int i;                          /* Iterator variable */
1185   sqlite3_int64 nByte;            /* Size of allocation used for *p */
1186   int iCol;                       /* Column index */
1187   int nString = 0;                /* Bytes required to hold all column names */
1188   int nCol = 0;                   /* Number of columns in the FTS table */
1189   char *zCsr;                     /* Space for holding column names */
1190   int nDb;                        /* Bytes required to hold database name */
1191   int nName;                      /* Bytes required to hold table name */
1192   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
1193   const char **aCol;              /* Array of column names */
1194   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
1195 
1196   int nIndex = 0;                 /* Size of aIndex[] array */
1197   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
1198 
1199   /* The results of parsing supported FTS4 key=value options: */
1200   int bNoDocsize = 0;             /* True to omit %_docsize table */
1201   int bDescIdx = 0;               /* True to store descending indexes */
1202   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
1203   char *zCompress = 0;            /* compress=? parameter (or NULL) */
1204   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
1205   char *zContent = 0;             /* content=? parameter (or NULL) */
1206   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
1207   char **azNotindexed = 0;        /* The set of notindexed= columns */
1208   int nNotindexed = 0;            /* Size of azNotindexed[] array */
1209 
1210   assert( strlen(argv[0])==4 );
1211   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
1212        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
1213   );
1214 
1215   nDb = (int)strlen(argv[1]) + 1;
1216   nName = (int)strlen(argv[2]) + 1;
1217 
1218   nByte = sizeof(const char *) * (argc-2);
1219   aCol = (const char **)sqlite3_malloc64(nByte);
1220   if( aCol ){
1221     memset((void*)aCol, 0, nByte);
1222     azNotindexed = (char **)sqlite3_malloc64(nByte);
1223   }
1224   if( azNotindexed ){
1225     memset(azNotindexed, 0, nByte);
1226   }
1227   if( !aCol || !azNotindexed ){
1228     rc = SQLITE_NOMEM;
1229     goto fts3_init_out;
1230   }
1231 
1232   /* Loop through all of the arguments passed by the user to the FTS3/4
1233   ** module (i.e. all the column names and special arguments). This loop
1234   ** does the following:
1235   **
1236   **   + Figures out the number of columns the FTSX table will have, and
1237   **     the number of bytes of space that must be allocated to store copies
1238   **     of the column names.
1239   **
1240   **   + If there is a tokenizer specification included in the arguments,
1241   **     initializes the tokenizer pTokenizer.
1242   */
1243   for(i=3; rc==SQLITE_OK && i<argc; i++){
1244     char const *z = argv[i];
1245     int nKey;
1246     char *zVal;
1247 
1248     /* Check if this is a tokenizer specification */
1249     if( !pTokenizer
1250      && strlen(z)>8
1251      && 0==sqlite3_strnicmp(z, "tokenize", 8)
1252      && 0==sqlite3Fts3IsIdChar(z[8])
1253     ){
1254       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
1255     }
1256 
1257     /* Check if it is an FTS4 special argument. */
1258     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
1259       struct Fts4Option {
1260         const char *zOpt;
1261         int nOpt;
1262       } aFts4Opt[] = {
1263         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
1264         { "prefix",      6 },     /* 1 -> PREFIX */
1265         { "compress",    8 },     /* 2 -> COMPRESS */
1266         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
1267         { "order",       5 },     /* 4 -> ORDER */
1268         { "content",     7 },     /* 5 -> CONTENT */
1269         { "languageid", 10 },     /* 6 -> LANGUAGEID */
1270         { "notindexed", 10 }      /* 7 -> NOTINDEXED */
1271       };
1272 
1273       int iOpt;
1274       if( !zVal ){
1275         rc = SQLITE_NOMEM;
1276       }else{
1277         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
1278           struct Fts4Option *pOp = &aFts4Opt[iOpt];
1279           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
1280             break;
1281           }
1282         }
1283         switch( iOpt ){
1284           case 0:               /* MATCHINFO */
1285             if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
1286               sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
1287               rc = SQLITE_ERROR;
1288             }
1289             bNoDocsize = 1;
1290             break;
1291 
1292           case 1:               /* PREFIX */
1293             sqlite3_free(zPrefix);
1294             zPrefix = zVal;
1295             zVal = 0;
1296             break;
1297 
1298           case 2:               /* COMPRESS */
1299             sqlite3_free(zCompress);
1300             zCompress = zVal;
1301             zVal = 0;
1302             break;
1303 
1304           case 3:               /* UNCOMPRESS */
1305             sqlite3_free(zUncompress);
1306             zUncompress = zVal;
1307             zVal = 0;
1308             break;
1309 
1310           case 4:               /* ORDER */
1311             if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
1312              && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
1313             ){
1314               sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
1315               rc = SQLITE_ERROR;
1316             }
1317             bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
1318             break;
1319 
1320           case 5:              /* CONTENT */
1321             sqlite3_free(zContent);
1322             zContent = zVal;
1323             zVal = 0;
1324             break;
1325 
1326           case 6:              /* LANGUAGEID */
1327             assert( iOpt==6 );
1328             sqlite3_free(zLanguageid);
1329             zLanguageid = zVal;
1330             zVal = 0;
1331             break;
1332 
1333           case 7:              /* NOTINDEXED */
1334             azNotindexed[nNotindexed++] = zVal;
1335             zVal = 0;
1336             break;
1337 
1338           default:
1339             assert( iOpt==SizeofArray(aFts4Opt) );
1340             sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
1341             rc = SQLITE_ERROR;
1342             break;
1343         }
1344         sqlite3_free(zVal);
1345       }
1346     }
1347 
1348     /* Otherwise, the argument is a column name. */
1349     else {
1350       nString += (int)(strlen(z) + 1);
1351       aCol[nCol++] = z;
1352     }
1353   }
1354 
1355   /* If a content=xxx option was specified, the following:
1356   **
1357   **   1. Ignore any compress= and uncompress= options.
1358   **
1359   **   2. If no column names were specified as part of the CREATE VIRTUAL
1360   **      TABLE statement, use all columns from the content table.
1361   */
1362   if( rc==SQLITE_OK && zContent ){
1363     sqlite3_free(zCompress);
1364     sqlite3_free(zUncompress);
1365     zCompress = 0;
1366     zUncompress = 0;
1367     if( nCol==0 ){
1368       sqlite3_free((void*)aCol);
1369       aCol = 0;
1370       rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
1371 
1372       /* If a languageid= option was specified, remove the language id
1373       ** column from the aCol[] array. */
1374       if( rc==SQLITE_OK && zLanguageid ){
1375         int j;
1376         for(j=0; j<nCol; j++){
1377           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
1378             int k;
1379             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
1380             nCol--;
1381             break;
1382           }
1383         }
1384       }
1385     }
1386   }
1387   if( rc!=SQLITE_OK ) goto fts3_init_out;
1388 
1389   if( nCol==0 ){
1390     assert( nString==0 );
1391     aCol[0] = "content";
1392     nString = 8;
1393     nCol = 1;
1394   }
1395 
1396   if( pTokenizer==0 ){
1397     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
1398     if( rc!=SQLITE_OK ) goto fts3_init_out;
1399   }
1400   assert( pTokenizer );
1401 
1402   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
1403   if( rc==SQLITE_ERROR ){
1404     assert( zPrefix );
1405     sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
1406   }
1407   if( rc!=SQLITE_OK ) goto fts3_init_out;
1408 
1409   /* Allocate and populate the Fts3Table structure. */
1410   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
1411           nCol * sizeof(char *) +              /* azColumn */
1412           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
1413           nCol * sizeof(u8) +                  /* abNotindexed */
1414           nName +                              /* zName */
1415           nDb +                                /* zDb */
1416           nString;                             /* Space for azColumn strings */
1417   p = (Fts3Table*)sqlite3_malloc64(nByte);
1418   if( p==0 ){
1419     rc = SQLITE_NOMEM;
1420     goto fts3_init_out;
1421   }
1422   memset(p, 0, nByte);
1423   p->db = db;
1424   p->nColumn = nCol;
1425   p->nPendingData = 0;
1426   p->azColumn = (char **)&p[1];
1427   p->pTokenizer = pTokenizer;
1428   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
1429   p->bHasDocsize = (isFts4 && bNoDocsize==0);
1430   p->bHasStat = (u8)isFts4;
1431   p->bFts4 = (u8)isFts4;
1432   p->bDescIdx = (u8)bDescIdx;
1433   p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
1434   p->zContentTbl = zContent;
1435   p->zLanguageid = zLanguageid;
1436   zContent = 0;
1437   zLanguageid = 0;
1438   TESTONLY( p->inTransaction = -1 );
1439   TESTONLY( p->mxSavepoint = -1 );
1440 
1441   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
1442   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
1443   p->nIndex = nIndex;
1444   for(i=0; i<nIndex; i++){
1445     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
1446   }
1447   p->abNotindexed = (u8 *)&p->aIndex[nIndex];
1448 
1449   /* Fill in the zName and zDb fields of the vtab structure. */
1450   zCsr = (char *)&p->abNotindexed[nCol];
1451   p->zName = zCsr;
1452   memcpy(zCsr, argv[2], nName);
1453   zCsr += nName;
1454   p->zDb = zCsr;
1455   memcpy(zCsr, argv[1], nDb);
1456   zCsr += nDb;
1457 
1458   /* Fill in the azColumn array */
1459   for(iCol=0; iCol<nCol; iCol++){
1460     char *z;
1461     int n = 0;
1462     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
1463     if( n>0 ){
1464       memcpy(zCsr, z, n);
1465     }
1466     zCsr[n] = '\0';
1467     sqlite3Fts3Dequote(zCsr);
1468     p->azColumn[iCol] = zCsr;
1469     zCsr += n+1;
1470     assert( zCsr <= &((char *)p)[nByte] );
1471   }
1472 
1473   /* Fill in the abNotindexed array */
1474   for(iCol=0; iCol<nCol; iCol++){
1475     int n = (int)strlen(p->azColumn[iCol]);
1476     for(i=0; i<nNotindexed; i++){
1477       char *zNot = azNotindexed[i];
1478       if( zNot && n==(int)strlen(zNot)
1479        && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
1480       ){
1481         p->abNotindexed[iCol] = 1;
1482         sqlite3_free(zNot);
1483         azNotindexed[i] = 0;
1484       }
1485     }
1486   }
1487   for(i=0; i<nNotindexed; i++){
1488     if( azNotindexed[i] ){
1489       sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
1490       rc = SQLITE_ERROR;
1491     }
1492   }
1493 
1494   if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
1495     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
1496     rc = SQLITE_ERROR;
1497     sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
1498   }
1499   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
1500   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
1501   if( rc!=SQLITE_OK ) goto fts3_init_out;
1502 
1503   /* If this is an xCreate call, create the underlying tables in the
1504   ** database. TODO: For xConnect(), it could verify that said tables exist.
1505   */
1506   if( isCreate ){
1507     rc = fts3CreateTables(p);
1508   }
1509 
1510   /* Check to see if a legacy fts3 table has been "upgraded" by the
1511   ** addition of a %_stat table so that it can use incremental merge.
1512   */
1513   if( !isFts4 && !isCreate ){
1514     p->bHasStat = 2;
1515   }
1516 
1517   /* Figure out the page-size for the database. This is required in order to
1518   ** estimate the cost of loading large doclists from the database.  */
1519   fts3DatabasePageSize(&rc, p);
1520   p->nNodeSize = p->nPgsz-35;
1521 
1522 #if defined(SQLITE_DEBUG)||defined(SQLITE_TEST)
1523   p->nMergeCount = FTS3_MERGE_COUNT;
1524 #endif
1525 
1526   /* Declare the table schema to SQLite. */
1527   fts3DeclareVtab(&rc, p);
1528 
1529 fts3_init_out:
1530   sqlite3_free(zPrefix);
1531   sqlite3_free(aIndex);
1532   sqlite3_free(zCompress);
1533   sqlite3_free(zUncompress);
1534   sqlite3_free(zContent);
1535   sqlite3_free(zLanguageid);
1536   for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
1537   sqlite3_free((void *)aCol);
1538   sqlite3_free((void *)azNotindexed);
1539   if( rc!=SQLITE_OK ){
1540     if( p ){
1541       fts3DisconnectMethod((sqlite3_vtab *)p);
1542     }else if( pTokenizer ){
1543       pTokenizer->pModule->xDestroy(pTokenizer);
1544     }
1545   }else{
1546     assert( p->pSegments==0 );
1547     *ppVTab = &p->base;
1548   }
1549   return rc;
1550 }
1551 
1552 /*
1553 ** The xConnect() and xCreate() methods for the virtual table. All the
1554 ** work is done in function fts3InitVtab().
1555 */
fts3ConnectMethod(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)1556 static int fts3ConnectMethod(
1557   sqlite3 *db,                    /* Database connection */
1558   void *pAux,                     /* Pointer to tokenizer hash table */
1559   int argc,                       /* Number of elements in argv array */
1560   const char * const *argv,       /* xCreate/xConnect argument array */
1561   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
1562   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
1563 ){
1564   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
1565 }
fts3CreateMethod(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)1566 static int fts3CreateMethod(
1567   sqlite3 *db,                    /* Database connection */
1568   void *pAux,                     /* Pointer to tokenizer hash table */
1569   int argc,                       /* Number of elements in argv array */
1570   const char * const *argv,       /* xCreate/xConnect argument array */
1571   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
1572   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
1573 ){
1574   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
1575 }
1576 
1577 /*
1578 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
1579 ** extension is currently being used by a version of SQLite too old to
1580 ** support estimatedRows. In that case this function is a no-op.
1581 */
fts3SetEstimatedRows(sqlite3_index_info * pIdxInfo,i64 nRow)1582 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
1583 #if SQLITE_VERSION_NUMBER>=3008002
1584   if( sqlite3_libversion_number()>=3008002 ){
1585     pIdxInfo->estimatedRows = nRow;
1586   }
1587 #endif
1588 }
1589 
1590 /*
1591 ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
1592 ** extension is currently being used by a version of SQLite too old to
1593 ** support index-info flags. In that case this function is a no-op.
1594 */
fts3SetUniqueFlag(sqlite3_index_info * pIdxInfo)1595 static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
1596 #if SQLITE_VERSION_NUMBER>=3008012
1597   if( sqlite3_libversion_number()>=3008012 ){
1598     pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
1599   }
1600 #endif
1601 }
1602 
1603 /*
1604 ** Implementation of the xBestIndex method for FTS3 tables. There
1605 ** are three possible strategies, in order of preference:
1606 **
1607 **   1. Direct lookup by rowid or docid.
1608 **   2. Full-text search using a MATCH operator on a non-docid column.
1609 **   3. Linear scan of %_content table.
1610 */
fts3BestIndexMethod(sqlite3_vtab * pVTab,sqlite3_index_info * pInfo)1611 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
1612   Fts3Table *p = (Fts3Table *)pVTab;
1613   int i;                          /* Iterator variable */
1614   int iCons = -1;                 /* Index of constraint to use */
1615 
1616   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
1617   int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
1618   int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
1619   int iIdx;
1620 
1621   if( p->bLock ){
1622     return SQLITE_ERROR;
1623   }
1624 
1625   /* By default use a full table scan. This is an expensive option,
1626   ** so search through the constraints to see if a more efficient
1627   ** strategy is possible.
1628   */
1629   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
1630   pInfo->estimatedCost = 5000000;
1631   for(i=0; i<pInfo->nConstraint; i++){
1632     int bDocid;                 /* True if this constraint is on docid */
1633     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
1634     if( pCons->usable==0 ){
1635       if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
1636         /* There exists an unusable MATCH constraint. This means that if
1637         ** the planner does elect to use the results of this call as part
1638         ** of the overall query plan the user will see an "unable to use
1639         ** function MATCH in the requested context" error. To discourage
1640         ** this, return a very high cost here.  */
1641         pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
1642         pInfo->estimatedCost = 1e50;
1643         fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
1644         return SQLITE_OK;
1645       }
1646       continue;
1647     }
1648 
1649     bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
1650 
1651     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
1652     if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
1653       pInfo->idxNum = FTS3_DOCID_SEARCH;
1654       pInfo->estimatedCost = 1.0;
1655       iCons = i;
1656     }
1657 
1658     /* A MATCH constraint. Use a full-text search.
1659     **
1660     ** If there is more than one MATCH constraint available, use the first
1661     ** one encountered. If there is both a MATCH constraint and a direct
1662     ** rowid/docid lookup, prefer the MATCH strategy. This is done even
1663     ** though the rowid/docid lookup is faster than a MATCH query, selecting
1664     ** it would lead to an "unable to use function MATCH in the requested
1665     ** context" error.
1666     */
1667     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
1668      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
1669     ){
1670       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
1671       pInfo->estimatedCost = 2.0;
1672       iCons = i;
1673     }
1674 
1675     /* Equality constraint on the langid column */
1676     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
1677      && pCons->iColumn==p->nColumn + 2
1678     ){
1679       iLangidCons = i;
1680     }
1681 
1682     if( bDocid ){
1683       switch( pCons->op ){
1684         case SQLITE_INDEX_CONSTRAINT_GE:
1685         case SQLITE_INDEX_CONSTRAINT_GT:
1686           iDocidGe = i;
1687           break;
1688 
1689         case SQLITE_INDEX_CONSTRAINT_LE:
1690         case SQLITE_INDEX_CONSTRAINT_LT:
1691           iDocidLe = i;
1692           break;
1693       }
1694     }
1695   }
1696 
1697   /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
1698   if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
1699 
1700   iIdx = 1;
1701   if( iCons>=0 ){
1702     pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
1703     pInfo->aConstraintUsage[iCons].omit = 1;
1704   }
1705   if( iLangidCons>=0 ){
1706     pInfo->idxNum |= FTS3_HAVE_LANGID;
1707     pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
1708   }
1709   if( iDocidGe>=0 ){
1710     pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
1711     pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
1712   }
1713   if( iDocidLe>=0 ){
1714     pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
1715     pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
1716   }
1717 
1718   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
1719   ** docid) order. Both ascending and descending are possible.
1720   */
1721   if( pInfo->nOrderBy==1 ){
1722     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
1723     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
1724       if( pOrder->desc ){
1725         pInfo->idxStr = "DESC";
1726       }else{
1727         pInfo->idxStr = "ASC";
1728       }
1729       pInfo->orderByConsumed = 1;
1730     }
1731   }
1732 
1733   assert( p->pSegments==0 );
1734   return SQLITE_OK;
1735 }
1736 
1737 /*
1738 ** Implementation of xOpen method.
1739 */
fts3OpenMethod(sqlite3_vtab * pVTab,sqlite3_vtab_cursor ** ppCsr)1740 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
1741   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
1742 
1743   UNUSED_PARAMETER(pVTab);
1744 
1745   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
1746   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
1747   ** if the allocation fails, return SQLITE_NOMEM.
1748   */
1749   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
1750   if( !pCsr ){
1751     return SQLITE_NOMEM;
1752   }
1753   memset(pCsr, 0, sizeof(Fts3Cursor));
1754   return SQLITE_OK;
1755 }
1756 
1757 /*
1758 ** Finalize the statement handle at pCsr->pStmt.
1759 **
1760 ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
1761 ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
1762 ** pointer there instead of finalizing it.
1763 */
fts3CursorFinalizeStmt(Fts3Cursor * pCsr)1764 static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
1765   if( pCsr->bSeekStmt ){
1766     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
1767     if( p->pSeekStmt==0 ){
1768       p->pSeekStmt = pCsr->pStmt;
1769       sqlite3_reset(pCsr->pStmt);
1770       pCsr->pStmt = 0;
1771     }
1772     pCsr->bSeekStmt = 0;
1773   }
1774   sqlite3_finalize(pCsr->pStmt);
1775 }
1776 
1777 /*
1778 ** Free all resources currently held by the cursor passed as the only
1779 ** argument.
1780 */
fts3ClearCursor(Fts3Cursor * pCsr)1781 static void fts3ClearCursor(Fts3Cursor *pCsr){
1782   fts3CursorFinalizeStmt(pCsr);
1783   sqlite3Fts3FreeDeferredTokens(pCsr);
1784   sqlite3_free(pCsr->aDoclist);
1785   sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
1786   sqlite3Fts3ExprFree(pCsr->pExpr);
1787   memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
1788 }
1789 
1790 /*
1791 ** Close the cursor.  For additional information see the documentation
1792 ** on the xClose method of the virtual table interface.
1793 */
fts3CloseMethod(sqlite3_vtab_cursor * pCursor)1794 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
1795   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
1796   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
1797   fts3ClearCursor(pCsr);
1798   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
1799   sqlite3_free(pCsr);
1800   return SQLITE_OK;
1801 }
1802 
1803 /*
1804 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
1805 ** compose and prepare an SQL statement of the form:
1806 **
1807 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
1808 **
1809 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
1810 ** it. If an error occurs, return an SQLite error code.
1811 */
fts3CursorSeekStmt(Fts3Cursor * pCsr)1812 static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
1813   int rc = SQLITE_OK;
1814   if( pCsr->pStmt==0 ){
1815     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
1816     char *zSql;
1817     if( p->pSeekStmt ){
1818       pCsr->pStmt = p->pSeekStmt;
1819       p->pSeekStmt = 0;
1820     }else{
1821       zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
1822       if( !zSql ) return SQLITE_NOMEM;
1823       p->bLock++;
1824       rc = sqlite3_prepare_v3(
1825           p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0
1826       );
1827       p->bLock--;
1828       sqlite3_free(zSql);
1829     }
1830     if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
1831   }
1832   return rc;
1833 }
1834 
1835 /*
1836 ** Position the pCsr->pStmt statement so that it is on the row
1837 ** of the %_content table that contains the last match.  Return
1838 ** SQLITE_OK on success.
1839 */
fts3CursorSeek(sqlite3_context * pContext,Fts3Cursor * pCsr)1840 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
1841   int rc = SQLITE_OK;
1842   if( pCsr->isRequireSeek ){
1843     rc = fts3CursorSeekStmt(pCsr);
1844     if( rc==SQLITE_OK ){
1845       Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab;
1846       pTab->bLock++;
1847       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
1848       pCsr->isRequireSeek = 0;
1849       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
1850         pTab->bLock--;
1851         return SQLITE_OK;
1852       }else{
1853         pTab->bLock--;
1854         rc = sqlite3_reset(pCsr->pStmt);
1855         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
1856           /* If no row was found and no error has occurred, then the %_content
1857           ** table is missing a row that is present in the full-text index.
1858           ** The data structures are corrupt.  */
1859           rc = FTS_CORRUPT_VTAB;
1860           pCsr->isEof = 1;
1861         }
1862       }
1863     }
1864   }
1865 
1866   if( rc!=SQLITE_OK && pContext ){
1867     sqlite3_result_error_code(pContext, rc);
1868   }
1869   return rc;
1870 }
1871 
1872 /*
1873 ** This function is used to process a single interior node when searching
1874 ** a b-tree for a term or term prefix. The node data is passed to this
1875 ** function via the zNode/nNode parameters. The term to search for is
1876 ** passed in zTerm/nTerm.
1877 **
1878 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
1879 ** of the child node that heads the sub-tree that may contain the term.
1880 **
1881 ** If piLast is not NULL, then *piLast is set to the right-most child node
1882 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
1883 ** a prefix.
1884 **
1885 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
1886 */
fts3ScanInteriorNode(const char * zTerm,int nTerm,const char * zNode,int nNode,sqlite3_int64 * piFirst,sqlite3_int64 * piLast)1887 static int fts3ScanInteriorNode(
1888   const char *zTerm,              /* Term to select leaves for */
1889   int nTerm,                      /* Size of term zTerm in bytes */
1890   const char *zNode,              /* Buffer containing segment interior node */
1891   int nNode,                      /* Size of buffer at zNode */
1892   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
1893   sqlite3_int64 *piLast           /* OUT: Selected child node */
1894 ){
1895   int rc = SQLITE_OK;             /* Return code */
1896   const char *zCsr = zNode;       /* Cursor to iterate through node */
1897   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
1898   char *zBuffer = 0;              /* Buffer to load terms into */
1899   i64 nAlloc = 0;                 /* Size of allocated buffer */
1900   int isFirstTerm = 1;            /* True when processing first term on page */
1901   u64 iChild;                     /* Block id of child node to descend to */
1902   int nBuffer = 0;                /* Total term size */
1903 
1904   /* Skip over the 'height' varint that occurs at the start of every
1905   ** interior node. Then load the blockid of the left-child of the b-tree
1906   ** node into variable iChild.
1907   **
1908   ** Even if the data structure on disk is corrupted, this (reading two
1909   ** varints from the buffer) does not risk an overread. If zNode is a
1910   ** root node, then the buffer comes from a SELECT statement. SQLite does
1911   ** not make this guarantee explicitly, but in practice there are always
1912   ** either more than 20 bytes of allocated space following the nNode bytes of
1913   ** contents, or two zero bytes. Or, if the node is read from the %_segments
1914   ** table, then there are always 20 bytes of zeroed padding following the
1915   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
1916   */
1917   zCsr += sqlite3Fts3GetVarintU(zCsr, &iChild);
1918   zCsr += sqlite3Fts3GetVarintU(zCsr, &iChild);
1919   if( zCsr>zEnd ){
1920     return FTS_CORRUPT_VTAB;
1921   }
1922 
1923   while( zCsr<zEnd && (piFirst || piLast) ){
1924     int cmp;                      /* memcmp() result */
1925     int nSuffix;                  /* Size of term suffix */
1926     int nPrefix = 0;              /* Size of term prefix */
1927 
1928     /* Load the next term on the node into zBuffer. Use realloc() to expand
1929     ** the size of zBuffer if required.  */
1930     if( !isFirstTerm ){
1931       zCsr += fts3GetVarint32(zCsr, &nPrefix);
1932       if( nPrefix>nBuffer ){
1933         rc = FTS_CORRUPT_VTAB;
1934         goto finish_scan;
1935       }
1936     }
1937     isFirstTerm = 0;
1938     zCsr += fts3GetVarint32(zCsr, &nSuffix);
1939 
1940     assert( nPrefix>=0 && nSuffix>=0 );
1941     if( nPrefix>zCsr-zNode || nSuffix>zEnd-zCsr || nSuffix==0 ){
1942       rc = FTS_CORRUPT_VTAB;
1943       goto finish_scan;
1944     }
1945     if( (i64)nPrefix+nSuffix>nAlloc ){
1946       char *zNew;
1947       nAlloc = ((i64)nPrefix+nSuffix) * 2;
1948       zNew = (char *)sqlite3_realloc64(zBuffer, nAlloc);
1949       if( !zNew ){
1950         rc = SQLITE_NOMEM;
1951         goto finish_scan;
1952       }
1953       zBuffer = zNew;
1954     }
1955     assert( zBuffer );
1956     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
1957     nBuffer = nPrefix + nSuffix;
1958     zCsr += nSuffix;
1959 
1960     /* Compare the term we are searching for with the term just loaded from
1961     ** the interior node. If the specified term is greater than or equal
1962     ** to the term from the interior node, then all terms on the sub-tree
1963     ** headed by node iChild are smaller than zTerm. No need to search
1964     ** iChild.
1965     **
1966     ** If the interior node term is larger than the specified term, then
1967     ** the tree headed by iChild may contain the specified term.
1968     */
1969     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
1970     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
1971       *piFirst = (i64)iChild;
1972       piFirst = 0;
1973     }
1974 
1975     if( piLast && cmp<0 ){
1976       *piLast = (i64)iChild;
1977       piLast = 0;
1978     }
1979 
1980     iChild++;
1981   };
1982 
1983   if( piFirst ) *piFirst = (i64)iChild;
1984   if( piLast ) *piLast = (i64)iChild;
1985 
1986  finish_scan:
1987   sqlite3_free(zBuffer);
1988   return rc;
1989 }
1990 
1991 
1992 /*
1993 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
1994 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
1995 ** contains a term. This function searches the sub-tree headed by the zNode
1996 ** node for the range of leaf nodes that may contain the specified term
1997 ** or terms for which the specified term is a prefix.
1998 **
1999 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
2000 ** left-most leaf node in the tree that may contain the specified term.
2001 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
2002 ** right-most leaf node that may contain a term for which the specified
2003 ** term is a prefix.
2004 **
2005 ** It is possible that the range of returned leaf nodes does not contain
2006 ** the specified term or any terms for which it is a prefix. However, if the
2007 ** segment does contain any such terms, they are stored within the identified
2008 ** range. Because this function only inspects interior segment nodes (and
2009 ** never loads leaf nodes into memory), it is not possible to be sure.
2010 **
2011 ** If an error occurs, an error code other than SQLITE_OK is returned.
2012 */
fts3SelectLeaf(Fts3Table * p,const char * zTerm,int nTerm,const char * zNode,int nNode,sqlite3_int64 * piLeaf,sqlite3_int64 * piLeaf2)2013 static int fts3SelectLeaf(
2014   Fts3Table *p,                   /* Virtual table handle */
2015   const char *zTerm,              /* Term to select leaves for */
2016   int nTerm,                      /* Size of term zTerm in bytes */
2017   const char *zNode,              /* Buffer containing segment interior node */
2018   int nNode,                      /* Size of buffer at zNode */
2019   sqlite3_int64 *piLeaf,          /* Selected leaf node */
2020   sqlite3_int64 *piLeaf2          /* Selected leaf node */
2021 ){
2022   int rc = SQLITE_OK;             /* Return code */
2023   int iHeight;                    /* Height of this node in tree */
2024 
2025   assert( piLeaf || piLeaf2 );
2026 
2027   fts3GetVarint32(zNode, &iHeight);
2028   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
2029   assert_fts3_nc( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
2030 
2031   if( rc==SQLITE_OK && iHeight>1 ){
2032     char *zBlob = 0;              /* Blob read from %_segments table */
2033     int nBlob = 0;                /* Size of zBlob in bytes */
2034 
2035     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
2036       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
2037       if( rc==SQLITE_OK ){
2038         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
2039       }
2040       sqlite3_free(zBlob);
2041       piLeaf = 0;
2042       zBlob = 0;
2043     }
2044 
2045     if( rc==SQLITE_OK ){
2046       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
2047     }
2048     if( rc==SQLITE_OK ){
2049       int iNewHeight = 0;
2050       fts3GetVarint32(zBlob, &iNewHeight);
2051       if( iNewHeight>=iHeight ){
2052         rc = FTS_CORRUPT_VTAB;
2053       }else{
2054         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
2055       }
2056     }
2057     sqlite3_free(zBlob);
2058   }
2059 
2060   return rc;
2061 }
2062 
2063 /*
2064 ** This function is used to create delta-encoded serialized lists of FTS3
2065 ** varints. Each call to this function appends a single varint to a list.
2066 */
fts3PutDeltaVarint(char ** pp,sqlite3_int64 * piPrev,sqlite3_int64 iVal)2067 static void fts3PutDeltaVarint(
2068   char **pp,                      /* IN/OUT: Output pointer */
2069   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
2070   sqlite3_int64 iVal              /* Write this value to the list */
2071 ){
2072   assert_fts3_nc( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
2073   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
2074   *piPrev = iVal;
2075 }
2076 
2077 /*
2078 ** When this function is called, *ppPoslist is assumed to point to the
2079 ** start of a position-list. After it returns, *ppPoslist points to the
2080 ** first byte after the position-list.
2081 **
2082 ** A position list is list of positions (delta encoded) and columns for
2083 ** a single document record of a doclist.  So, in other words, this
2084 ** routine advances *ppPoslist so that it points to the next docid in
2085 ** the doclist, or to the first byte past the end of the doclist.
2086 **
2087 ** If pp is not NULL, then the contents of the position list are copied
2088 ** to *pp. *pp is set to point to the first byte past the last byte copied
2089 ** before this function returns.
2090 */
fts3PoslistCopy(char ** pp,char ** ppPoslist)2091 static void fts3PoslistCopy(char **pp, char **ppPoslist){
2092   char *pEnd = *ppPoslist;
2093   char c = 0;
2094 
2095   /* The end of a position list is marked by a zero encoded as an FTS3
2096   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
2097   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
2098   ** of some other, multi-byte, value.
2099   **
2100   ** The following while-loop moves pEnd to point to the first byte that is not
2101   ** immediately preceded by a byte with the 0x80 bit set. Then increments
2102   ** pEnd once more so that it points to the byte immediately following the
2103   ** last byte in the position-list.
2104   */
2105   while( *pEnd | c ){
2106     c = *pEnd++ & 0x80;
2107     testcase( c!=0 && (*pEnd)==0 );
2108   }
2109   pEnd++;  /* Advance past the POS_END terminator byte */
2110 
2111   if( pp ){
2112     int n = (int)(pEnd - *ppPoslist);
2113     char *p = *pp;
2114     memcpy(p, *ppPoslist, n);
2115     p += n;
2116     *pp = p;
2117   }
2118   *ppPoslist = pEnd;
2119 }
2120 
2121 /*
2122 ** When this function is called, *ppPoslist is assumed to point to the
2123 ** start of a column-list. After it returns, *ppPoslist points to the
2124 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
2125 **
2126 ** A column-list is list of delta-encoded positions for a single column
2127 ** within a single document within a doclist.
2128 **
2129 ** The column-list is terminated either by a POS_COLUMN varint (1) or
2130 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
2131 ** the POS_COLUMN or POS_END that terminates the column-list.
2132 **
2133 ** If pp is not NULL, then the contents of the column-list are copied
2134 ** to *pp. *pp is set to point to the first byte past the last byte copied
2135 ** before this function returns.  The POS_COLUMN or POS_END terminator
2136 ** is not copied into *pp.
2137 */
fts3ColumnlistCopy(char ** pp,char ** ppPoslist)2138 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
2139   char *pEnd = *ppPoslist;
2140   char c = 0;
2141 
2142   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
2143   ** not part of a multi-byte varint.
2144   */
2145   while( 0xFE & (*pEnd | c) ){
2146     c = *pEnd++ & 0x80;
2147     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
2148   }
2149   if( pp ){
2150     int n = (int)(pEnd - *ppPoslist);
2151     char *p = *pp;
2152     memcpy(p, *ppPoslist, n);
2153     p += n;
2154     *pp = p;
2155   }
2156   *ppPoslist = pEnd;
2157 }
2158 
2159 /*
2160 ** Value used to signify the end of an position-list. This must be
2161 ** as large or larger than any value that might appear on the
2162 ** position-list, even a position list that has been corrupted.
2163 */
2164 #define POSITION_LIST_END LARGEST_INT64
2165 
2166 /*
2167 ** This function is used to help parse position-lists. When this function is
2168 ** called, *pp may point to the start of the next varint in the position-list
2169 ** being parsed, or it may point to 1 byte past the end of the position-list
2170 ** (in which case **pp will be a terminator bytes POS_END (0) or
2171 ** (1)).
2172 **
2173 ** If *pp points past the end of the current position-list, set *pi to
2174 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
2175 ** increment the current value of *pi by the value read, and set *pp to
2176 ** point to the next value before returning.
2177 **
2178 ** Before calling this routine *pi must be initialized to the value of
2179 ** the previous position, or zero if we are reading the first position
2180 ** in the position-list.  Because positions are delta-encoded, the value
2181 ** of the previous position is needed in order to compute the value of
2182 ** the next position.
2183 */
fts3ReadNextPos(char ** pp,sqlite3_int64 * pi)2184 static void fts3ReadNextPos(
2185   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
2186   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
2187 ){
2188   if( (**pp)&0xFE ){
2189     int iVal;
2190     *pp += fts3GetVarint32((*pp), &iVal);
2191     *pi += iVal;
2192     *pi -= 2;
2193   }else{
2194     *pi = POSITION_LIST_END;
2195   }
2196 }
2197 
2198 /*
2199 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
2200 ** the value of iCol encoded as a varint to *pp.   This will start a new
2201 ** column list.
2202 **
2203 ** Set *pp to point to the byte just after the last byte written before
2204 ** returning (do not modify it if iCol==0). Return the total number of bytes
2205 ** written (0 if iCol==0).
2206 */
fts3PutColNumber(char ** pp,int iCol)2207 static int fts3PutColNumber(char **pp, int iCol){
2208   int n = 0;                      /* Number of bytes written */
2209   if( iCol ){
2210     char *p = *pp;                /* Output pointer */
2211     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
2212     *p = 0x01;
2213     *pp = &p[n];
2214   }
2215   return n;
2216 }
2217 
2218 /*
2219 ** Compute the union of two position lists.  The output written
2220 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
2221 ** order and with any duplicates removed.  All pointers are
2222 ** updated appropriately.   The caller is responsible for insuring
2223 ** that there is enough space in *pp to hold the complete output.
2224 */
fts3PoslistMerge(char ** pp,char ** pp1,char ** pp2)2225 static int fts3PoslistMerge(
2226   char **pp,                      /* Output buffer */
2227   char **pp1,                     /* Left input list */
2228   char **pp2                      /* Right input list */
2229 ){
2230   char *p = *pp;
2231   char *p1 = *pp1;
2232   char *p2 = *pp2;
2233 
2234   while( *p1 || *p2 ){
2235     int iCol1;         /* The current column index in pp1 */
2236     int iCol2;         /* The current column index in pp2 */
2237 
2238     if( *p1==POS_COLUMN ){
2239       fts3GetVarint32(&p1[1], &iCol1);
2240       if( iCol1==0 ) return FTS_CORRUPT_VTAB;
2241     }
2242     else if( *p1==POS_END ) iCol1 = 0x7fffffff;
2243     else iCol1 = 0;
2244 
2245     if( *p2==POS_COLUMN ){
2246       fts3GetVarint32(&p2[1], &iCol2);
2247       if( iCol2==0 ) return FTS_CORRUPT_VTAB;
2248     }
2249     else if( *p2==POS_END ) iCol2 = 0x7fffffff;
2250     else iCol2 = 0;
2251 
2252     if( iCol1==iCol2 ){
2253       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
2254       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
2255       sqlite3_int64 iPrev = 0;
2256       int n = fts3PutColNumber(&p, iCol1);
2257       p1 += n;
2258       p2 += n;
2259 
2260       /* At this point, both p1 and p2 point to the start of column-lists
2261       ** for the same column (the column with index iCol1 and iCol2).
2262       ** A column-list is a list of non-negative delta-encoded varints, each
2263       ** incremented by 2 before being stored. Each list is terminated by a
2264       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
2265       ** and writes the results to buffer p. p is left pointing to the byte
2266       ** after the list written. No terminator (POS_END or POS_COLUMN) is
2267       ** written to the output.
2268       */
2269       fts3GetDeltaVarint(&p1, &i1);
2270       fts3GetDeltaVarint(&p2, &i2);
2271       if( i1<2 || i2<2 ){
2272         break;
2273       }
2274       do {
2275         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
2276         iPrev -= 2;
2277         if( i1==i2 ){
2278           fts3ReadNextPos(&p1, &i1);
2279           fts3ReadNextPos(&p2, &i2);
2280         }else if( i1<i2 ){
2281           fts3ReadNextPos(&p1, &i1);
2282         }else{
2283           fts3ReadNextPos(&p2, &i2);
2284         }
2285       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
2286     }else if( iCol1<iCol2 ){
2287       p1 += fts3PutColNumber(&p, iCol1);
2288       fts3ColumnlistCopy(&p, &p1);
2289     }else{
2290       p2 += fts3PutColNumber(&p, iCol2);
2291       fts3ColumnlistCopy(&p, &p2);
2292     }
2293   }
2294 
2295   *p++ = POS_END;
2296   *pp = p;
2297   *pp1 = p1 + 1;
2298   *pp2 = p2 + 1;
2299   return SQLITE_OK;
2300 }
2301 
2302 /*
2303 ** This function is used to merge two position lists into one. When it is
2304 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
2305 ** the part of a doclist that follows each document id. For example, if a row
2306 ** contains:
2307 **
2308 **     'a b c'|'x y z'|'a b b a'
2309 **
2310 ** Then the position list for this row for token 'b' would consist of:
2311 **
2312 **     0x02 0x01 0x02 0x03 0x03 0x00
2313 **
2314 ** When this function returns, both *pp1 and *pp2 are left pointing to the
2315 ** byte following the 0x00 terminator of their respective position lists.
2316 **
2317 ** If isSaveLeft is 0, an entry is added to the output position list for
2318 ** each position in *pp2 for which there exists one or more positions in
2319 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
2320 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
2321 ** slots before it.
2322 **
2323 ** e.g. nToken==1 searches for adjacent positions.
2324 */
fts3PoslistPhraseMerge(char ** pp,int nToken,int isSaveLeft,int isExact,char ** pp1,char ** pp2)2325 static int fts3PoslistPhraseMerge(
2326   char **pp,                      /* IN/OUT: Preallocated output buffer */
2327   int nToken,                     /* Maximum difference in token positions */
2328   int isSaveLeft,                 /* Save the left position */
2329   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
2330   char **pp1,                     /* IN/OUT: Left input list */
2331   char **pp2                      /* IN/OUT: Right input list */
2332 ){
2333   char *p = *pp;
2334   char *p1 = *pp1;
2335   char *p2 = *pp2;
2336   int iCol1 = 0;
2337   int iCol2 = 0;
2338 
2339   /* Never set both isSaveLeft and isExact for the same invocation. */
2340   assert( isSaveLeft==0 || isExact==0 );
2341 
2342   assert_fts3_nc( p!=0 && *p1!=0 && *p2!=0 );
2343   if( *p1==POS_COLUMN ){
2344     p1++;
2345     p1 += fts3GetVarint32(p1, &iCol1);
2346   }
2347   if( *p2==POS_COLUMN ){
2348     p2++;
2349     p2 += fts3GetVarint32(p2, &iCol2);
2350   }
2351 
2352   while( 1 ){
2353     if( iCol1==iCol2 ){
2354       char *pSave = p;
2355       sqlite3_int64 iPrev = 0;
2356       sqlite3_int64 iPos1 = 0;
2357       sqlite3_int64 iPos2 = 0;
2358 
2359       if( iCol1 ){
2360         *p++ = POS_COLUMN;
2361         p += sqlite3Fts3PutVarint(p, iCol1);
2362       }
2363 
2364       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
2365       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
2366       if( iPos1<0 || iPos2<0 ) break;
2367 
2368       while( 1 ){
2369         if( iPos2==iPos1+nToken
2370          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
2371         ){
2372           sqlite3_int64 iSave;
2373           iSave = isSaveLeft ? iPos1 : iPos2;
2374           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
2375           pSave = 0;
2376           assert( p );
2377         }
2378         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
2379           if( (*p2&0xFE)==0 ) break;
2380           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
2381         }else{
2382           if( (*p1&0xFE)==0 ) break;
2383           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
2384         }
2385       }
2386 
2387       if( pSave ){
2388         assert( pp && p );
2389         p = pSave;
2390       }
2391 
2392       fts3ColumnlistCopy(0, &p1);
2393       fts3ColumnlistCopy(0, &p2);
2394       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
2395       if( 0==*p1 || 0==*p2 ) break;
2396 
2397       p1++;
2398       p1 += fts3GetVarint32(p1, &iCol1);
2399       p2++;
2400       p2 += fts3GetVarint32(p2, &iCol2);
2401     }
2402 
2403     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
2404     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
2405     ** end of the position list, or the 0x01 that precedes the next
2406     ** column-number in the position list.
2407     */
2408     else if( iCol1<iCol2 ){
2409       fts3ColumnlistCopy(0, &p1);
2410       if( 0==*p1 ) break;
2411       p1++;
2412       p1 += fts3GetVarint32(p1, &iCol1);
2413     }else{
2414       fts3ColumnlistCopy(0, &p2);
2415       if( 0==*p2 ) break;
2416       p2++;
2417       p2 += fts3GetVarint32(p2, &iCol2);
2418     }
2419   }
2420 
2421   fts3PoslistCopy(0, &p2);
2422   fts3PoslistCopy(0, &p1);
2423   *pp1 = p1;
2424   *pp2 = p2;
2425   if( *pp==p ){
2426     return 0;
2427   }
2428   *p++ = 0x00;
2429   *pp = p;
2430   return 1;
2431 }
2432 
2433 /*
2434 ** Merge two position-lists as required by the NEAR operator. The argument
2435 ** position lists correspond to the left and right phrases of an expression
2436 ** like:
2437 **
2438 **     "phrase 1" NEAR "phrase number 2"
2439 **
2440 ** Position list *pp1 corresponds to the left-hand side of the NEAR
2441 ** expression and *pp2 to the right. As usual, the indexes in the position
2442 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
2443 ** in the example above).
2444 **
2445 ** The output position list - written to *pp - is a copy of *pp2 with those
2446 ** entries that are not sufficiently NEAR entries in *pp1 removed.
2447 */
fts3PoslistNearMerge(char ** pp,char * aTmp,int nRight,int nLeft,char ** pp1,char ** pp2)2448 static int fts3PoslistNearMerge(
2449   char **pp,                      /* Output buffer */
2450   char *aTmp,                     /* Temporary buffer space */
2451   int nRight,                     /* Maximum difference in token positions */
2452   int nLeft,                      /* Maximum difference in token positions */
2453   char **pp1,                     /* IN/OUT: Left input list */
2454   char **pp2                      /* IN/OUT: Right input list */
2455 ){
2456   char *p1 = *pp1;
2457   char *p2 = *pp2;
2458 
2459   char *pTmp1 = aTmp;
2460   char *pTmp2;
2461   char *aTmp2;
2462   int res = 1;
2463 
2464   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
2465   aTmp2 = pTmp2 = pTmp1;
2466   *pp1 = p1;
2467   *pp2 = p2;
2468   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
2469   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
2470     fts3PoslistMerge(pp, &aTmp, &aTmp2);
2471   }else if( pTmp1!=aTmp ){
2472     fts3PoslistCopy(pp, &aTmp);
2473   }else if( pTmp2!=aTmp2 ){
2474     fts3PoslistCopy(pp, &aTmp2);
2475   }else{
2476     res = 0;
2477   }
2478 
2479   return res;
2480 }
2481 
2482 /*
2483 ** An instance of this function is used to merge together the (potentially
2484 ** large number of) doclists for each term that matches a prefix query.
2485 ** See function fts3TermSelectMerge() for details.
2486 */
2487 typedef struct TermSelect TermSelect;
2488 struct TermSelect {
2489   char *aaOutput[16];             /* Malloc'd output buffers */
2490   int anOutput[16];               /* Size each output buffer in bytes */
2491 };
2492 
2493 /*
2494 ** This function is used to read a single varint from a buffer. Parameter
2495 ** pEnd points 1 byte past the end of the buffer. When this function is
2496 ** called, if *pp points to pEnd or greater, then the end of the buffer
2497 ** has been reached. In this case *pp is set to 0 and the function returns.
2498 **
2499 ** If *pp does not point to or past pEnd, then a single varint is read
2500 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
2501 **
2502 ** If bDescIdx is false, the value read is added to *pVal before returning.
2503 ** If it is true, the value read is subtracted from *pVal before this
2504 ** function returns.
2505 */
fts3GetDeltaVarint3(char ** pp,char * pEnd,int bDescIdx,sqlite3_int64 * pVal)2506 static void fts3GetDeltaVarint3(
2507   char **pp,                      /* IN/OUT: Point to read varint from */
2508   char *pEnd,                     /* End of buffer */
2509   int bDescIdx,                   /* True if docids are descending */
2510   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
2511 ){
2512   if( *pp>=pEnd ){
2513     *pp = 0;
2514   }else{
2515     u64 iVal;
2516     *pp += sqlite3Fts3GetVarintU(*pp, &iVal);
2517     if( bDescIdx ){
2518       *pVal = (i64)((u64)*pVal - iVal);
2519     }else{
2520       *pVal = (i64)((u64)*pVal + iVal);
2521     }
2522   }
2523 }
2524 
2525 /*
2526 ** This function is used to write a single varint to a buffer. The varint
2527 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
2528 ** end of the value written.
2529 **
2530 ** If *pbFirst is zero when this function is called, the value written to
2531 ** the buffer is that of parameter iVal.
2532 **
2533 ** If *pbFirst is non-zero when this function is called, then the value
2534 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
2535 ** (if bDescIdx is non-zero).
2536 **
2537 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
2538 ** to the value of parameter iVal.
2539 */
fts3PutDeltaVarint3(char ** pp,int bDescIdx,sqlite3_int64 * piPrev,int * pbFirst,sqlite3_int64 iVal)2540 static void fts3PutDeltaVarint3(
2541   char **pp,                      /* IN/OUT: Output pointer */
2542   int bDescIdx,                   /* True for descending docids */
2543   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
2544   int *pbFirst,                   /* IN/OUT: True after first int written */
2545   sqlite3_int64 iVal              /* Write this value to the list */
2546 ){
2547   sqlite3_uint64 iWrite;
2548   if( bDescIdx==0 || *pbFirst==0 ){
2549     assert_fts3_nc( *pbFirst==0 || iVal>=*piPrev );
2550     iWrite = (u64)iVal - (u64)*piPrev;
2551   }else{
2552     assert_fts3_nc( *piPrev>=iVal );
2553     iWrite = (u64)*piPrev - (u64)iVal;
2554   }
2555   assert( *pbFirst || *piPrev==0 );
2556   assert_fts3_nc( *pbFirst==0 || iWrite>0 );
2557   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
2558   *piPrev = iVal;
2559   *pbFirst = 1;
2560 }
2561 
2562 
2563 /*
2564 ** This macro is used by various functions that merge doclists. The two
2565 ** arguments are 64-bit docid values. If the value of the stack variable
2566 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
2567 ** Otherwise, (i2-i1).
2568 **
2569 ** Using this makes it easier to write code that can merge doclists that are
2570 ** sorted in either ascending or descending order.
2571 */
2572 /* #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i64)((u64)i1-i2)) */
2573 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1>i2?1:((i1==i2)?0:-1)))
2574 
2575 /*
2576 ** This function does an "OR" merge of two doclists (output contains all
2577 ** positions contained in either argument doclist). If the docids in the
2578 ** input doclists are sorted in ascending order, parameter bDescDoclist
2579 ** should be false. If they are sorted in ascending order, it should be
2580 ** passed a non-zero value.
2581 **
2582 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
2583 ** containing the output doclist and SQLITE_OK is returned. In this case
2584 ** *pnOut is set to the number of bytes in the output doclist.
2585 **
2586 ** If an error occurs, an SQLite error code is returned. The output values
2587 ** are undefined in this case.
2588 */
fts3DoclistOrMerge(int bDescDoclist,char * a1,int n1,char * a2,int n2,char ** paOut,int * pnOut)2589 static int fts3DoclistOrMerge(
2590   int bDescDoclist,               /* True if arguments are desc */
2591   char *a1, int n1,               /* First doclist */
2592   char *a2, int n2,               /* Second doclist */
2593   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
2594 ){
2595   int rc = SQLITE_OK;
2596   sqlite3_int64 i1 = 0;
2597   sqlite3_int64 i2 = 0;
2598   sqlite3_int64 iPrev = 0;
2599   char *pEnd1 = &a1[n1];
2600   char *pEnd2 = &a2[n2];
2601   char *p1 = a1;
2602   char *p2 = a2;
2603   char *p;
2604   char *aOut;
2605   int bFirstOut = 0;
2606 
2607   *paOut = 0;
2608   *pnOut = 0;
2609 
2610   /* Allocate space for the output. Both the input and output doclists
2611   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
2612   ** then the first docid in each list is simply encoded as a varint. For
2613   ** each subsequent docid, the varint stored is the difference between the
2614   ** current and previous docid (a positive number - since the list is in
2615   ** ascending order).
2616   **
2617   ** The first docid written to the output is therefore encoded using the
2618   ** same number of bytes as it is in whichever of the input lists it is
2619   ** read from. And each subsequent docid read from the same input list
2620   ** consumes either the same or less bytes as it did in the input (since
2621   ** the difference between it and the previous value in the output must
2622   ** be a positive value less than or equal to the delta value read from
2623   ** the input list). The same argument applies to all but the first docid
2624   ** read from the 'other' list. And to the contents of all position lists
2625   ** that will be copied and merged from the input to the output.
2626   **
2627   ** However, if the first docid copied to the output is a negative number,
2628   ** then the encoding of the first docid from the 'other' input list may
2629   ** be larger in the output than it was in the input (since the delta value
2630   ** may be a larger positive integer than the actual docid).
2631   **
2632   ** The space required to store the output is therefore the sum of the
2633   ** sizes of the two inputs, plus enough space for exactly one of the input
2634   ** docids to grow.
2635   **
2636   ** A symetric argument may be made if the doclists are in descending
2637   ** order.
2638   */
2639   aOut = sqlite3_malloc64((i64)n1+n2+FTS3_VARINT_MAX-1+FTS3_BUFFER_PADDING);
2640   if( !aOut ) return SQLITE_NOMEM;
2641 
2642   p = aOut;
2643   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
2644   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
2645   while( p1 || p2 ){
2646     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
2647 
2648     if( p2 && p1 && iDiff==0 ){
2649       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
2650       rc = fts3PoslistMerge(&p, &p1, &p2);
2651       if( rc ) break;
2652       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
2653       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
2654     }else if( !p2 || (p1 && iDiff<0) ){
2655       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
2656       fts3PoslistCopy(&p, &p1);
2657       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
2658     }else{
2659       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
2660       fts3PoslistCopy(&p, &p2);
2661       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
2662     }
2663 
2664     assert( (p-aOut)<=((p1?(p1-a1):n1)+(p2?(p2-a2):n2)+FTS3_VARINT_MAX-1) );
2665   }
2666 
2667   if( rc!=SQLITE_OK ){
2668     sqlite3_free(aOut);
2669     p = aOut = 0;
2670   }else{
2671     assert( (p-aOut)<=n1+n2+FTS3_VARINT_MAX-1 );
2672     memset(&aOut[(p-aOut)], 0, FTS3_BUFFER_PADDING);
2673   }
2674   *paOut = aOut;
2675   *pnOut = (int)(p-aOut);
2676   return rc;
2677 }
2678 
2679 /*
2680 ** This function does a "phrase" merge of two doclists. In a phrase merge,
2681 ** the output contains a copy of each position from the right-hand input
2682 ** doclist for which there is a position in the left-hand input doclist
2683 ** exactly nDist tokens before it.
2684 **
2685 ** If the docids in the input doclists are sorted in ascending order,
2686 ** parameter bDescDoclist should be false. If they are sorted in ascending
2687 ** order, it should be passed a non-zero value.
2688 **
2689 ** The right-hand input doclist is overwritten by this function.
2690 */
fts3DoclistPhraseMerge(int bDescDoclist,int nDist,char * aLeft,int nLeft,char ** paRight,int * pnRight)2691 static int fts3DoclistPhraseMerge(
2692   int bDescDoclist,               /* True if arguments are desc */
2693   int nDist,                      /* Distance from left to right (1=adjacent) */
2694   char *aLeft, int nLeft,         /* Left doclist */
2695   char **paRight, int *pnRight    /* IN/OUT: Right/output doclist */
2696 ){
2697   sqlite3_int64 i1 = 0;
2698   sqlite3_int64 i2 = 0;
2699   sqlite3_int64 iPrev = 0;
2700   char *aRight = *paRight;
2701   char *pEnd1 = &aLeft[nLeft];
2702   char *pEnd2 = &aRight[*pnRight];
2703   char *p1 = aLeft;
2704   char *p2 = aRight;
2705   char *p;
2706   int bFirstOut = 0;
2707   char *aOut;
2708 
2709   assert( nDist>0 );
2710   if( bDescDoclist ){
2711     aOut = sqlite3_malloc64((sqlite3_int64)*pnRight + FTS3_VARINT_MAX);
2712     if( aOut==0 ) return SQLITE_NOMEM;
2713   }else{
2714     aOut = aRight;
2715   }
2716   p = aOut;
2717 
2718   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
2719   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
2720 
2721   while( p1 && p2 ){
2722     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
2723     if( iDiff==0 ){
2724       char *pSave = p;
2725       sqlite3_int64 iPrevSave = iPrev;
2726       int bFirstOutSave = bFirstOut;
2727 
2728       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
2729       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
2730         p = pSave;
2731         iPrev = iPrevSave;
2732         bFirstOut = bFirstOutSave;
2733       }
2734       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
2735       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
2736     }else if( iDiff<0 ){
2737       fts3PoslistCopy(0, &p1);
2738       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
2739     }else{
2740       fts3PoslistCopy(0, &p2);
2741       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
2742     }
2743   }
2744 
2745   *pnRight = (int)(p - aOut);
2746   if( bDescDoclist ){
2747     sqlite3_free(aRight);
2748     *paRight = aOut;
2749   }
2750 
2751   return SQLITE_OK;
2752 }
2753 
2754 /*
2755 ** Argument pList points to a position list nList bytes in size. This
2756 ** function checks to see if the position list contains any entries for
2757 ** a token in position 0 (of any column). If so, it writes argument iDelta
2758 ** to the output buffer pOut, followed by a position list consisting only
2759 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
2760 ** The value returned is the number of bytes written to pOut (if any).
2761 */
sqlite3Fts3FirstFilter(sqlite3_int64 iDelta,char * pList,int nList,char * pOut)2762 int sqlite3Fts3FirstFilter(
2763   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
2764   char *pList,                    /* Position list (no 0x00 term) */
2765   int nList,                      /* Size of pList in bytes */
2766   char *pOut                      /* Write output here */
2767 ){
2768   int nOut = 0;
2769   int bWritten = 0;               /* True once iDelta has been written */
2770   char *p = pList;
2771   char *pEnd = &pList[nList];
2772 
2773   if( *p!=0x01 ){
2774     if( *p==0x02 ){
2775       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
2776       pOut[nOut++] = 0x02;
2777       bWritten = 1;
2778     }
2779     fts3ColumnlistCopy(0, &p);
2780   }
2781 
2782   while( p<pEnd ){
2783     sqlite3_int64 iCol;
2784     p++;
2785     p += sqlite3Fts3GetVarint(p, &iCol);
2786     if( *p==0x02 ){
2787       if( bWritten==0 ){
2788         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
2789         bWritten = 1;
2790       }
2791       pOut[nOut++] = 0x01;
2792       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
2793       pOut[nOut++] = 0x02;
2794     }
2795     fts3ColumnlistCopy(0, &p);
2796   }
2797   if( bWritten ){
2798     pOut[nOut++] = 0x00;
2799   }
2800 
2801   return nOut;
2802 }
2803 
2804 
2805 /*
2806 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
2807 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
2808 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
2809 **
2810 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
2811 ** the responsibility of the caller to free any doclists left in the
2812 ** TermSelect.aaOutput[] array.
2813 */
fts3TermSelectFinishMerge(Fts3Table * p,TermSelect * pTS)2814 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
2815   char *aOut = 0;
2816   int nOut = 0;
2817   int i;
2818 
2819   /* Loop through the doclists in the aaOutput[] array. Merge them all
2820   ** into a single doclist.
2821   */
2822   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
2823     if( pTS->aaOutput[i] ){
2824       if( !aOut ){
2825         aOut = pTS->aaOutput[i];
2826         nOut = pTS->anOutput[i];
2827         pTS->aaOutput[i] = 0;
2828       }else{
2829         int nNew;
2830         char *aNew;
2831 
2832         int rc = fts3DoclistOrMerge(p->bDescIdx,
2833             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
2834         );
2835         if( rc!=SQLITE_OK ){
2836           sqlite3_free(aOut);
2837           return rc;
2838         }
2839 
2840         sqlite3_free(pTS->aaOutput[i]);
2841         sqlite3_free(aOut);
2842         pTS->aaOutput[i] = 0;
2843         aOut = aNew;
2844         nOut = nNew;
2845       }
2846     }
2847   }
2848 
2849   pTS->aaOutput[0] = aOut;
2850   pTS->anOutput[0] = nOut;
2851   return SQLITE_OK;
2852 }
2853 
2854 /*
2855 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
2856 ** as the first argument. The merge is an "OR" merge (see function
2857 ** fts3DoclistOrMerge() for details).
2858 **
2859 ** This function is called with the doclist for each term that matches
2860 ** a queried prefix. It merges all these doclists into one, the doclist
2861 ** for the specified prefix. Since there can be a very large number of
2862 ** doclists to merge, the merging is done pair-wise using the TermSelect
2863 ** object.
2864 **
2865 ** This function returns SQLITE_OK if the merge is successful, or an
2866 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
2867 */
fts3TermSelectMerge(Fts3Table * p,TermSelect * pTS,char * aDoclist,int nDoclist)2868 static int fts3TermSelectMerge(
2869   Fts3Table *p,                   /* FTS table handle */
2870   TermSelect *pTS,                /* TermSelect object to merge into */
2871   char *aDoclist,                 /* Pointer to doclist */
2872   int nDoclist                    /* Size of aDoclist in bytes */
2873 ){
2874   if( pTS->aaOutput[0]==0 ){
2875     /* If this is the first term selected, copy the doclist to the output
2876     ** buffer using memcpy().
2877     **
2878     ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
2879     ** allocation. This is so as to ensure that the buffer is big enough
2880     ** to hold the current doclist AND'd with any other doclist. If the
2881     ** doclists are stored in order=ASC order, this padding would not be
2882     ** required (since the size of [doclistA AND doclistB] is always less
2883     ** than or equal to the size of [doclistA] in that case). But this is
2884     ** not true for order=DESC. For example, a doclist containing (1, -1)
2885     ** may be smaller than (-1), as in the first example the -1 may be stored
2886     ** as a single-byte delta, whereas in the second it must be stored as a
2887     ** FTS3_VARINT_MAX byte varint.
2888     **
2889     ** Similar padding is added in the fts3DoclistOrMerge() function.
2890     */
2891     pTS->aaOutput[0] = sqlite3_malloc64((i64)nDoclist + FTS3_VARINT_MAX + 1);
2892     pTS->anOutput[0] = nDoclist;
2893     if( pTS->aaOutput[0] ){
2894       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
2895       memset(&pTS->aaOutput[0][nDoclist], 0, FTS3_VARINT_MAX);
2896     }else{
2897       return SQLITE_NOMEM;
2898     }
2899   }else{
2900     char *aMerge = aDoclist;
2901     int nMerge = nDoclist;
2902     int iOut;
2903 
2904     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
2905       if( pTS->aaOutput[iOut]==0 ){
2906         assert( iOut>0 );
2907         pTS->aaOutput[iOut] = aMerge;
2908         pTS->anOutput[iOut] = nMerge;
2909         break;
2910       }else{
2911         char *aNew;
2912         int nNew;
2913 
2914         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
2915             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
2916         );
2917         if( rc!=SQLITE_OK ){
2918           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
2919           return rc;
2920         }
2921 
2922         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
2923         sqlite3_free(pTS->aaOutput[iOut]);
2924         pTS->aaOutput[iOut] = 0;
2925 
2926         aMerge = aNew;
2927         nMerge = nNew;
2928         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
2929           pTS->aaOutput[iOut] = aMerge;
2930           pTS->anOutput[iOut] = nMerge;
2931         }
2932       }
2933     }
2934   }
2935   return SQLITE_OK;
2936 }
2937 
2938 /*
2939 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
2940 */
fts3SegReaderCursorAppend(Fts3MultiSegReader * pCsr,Fts3SegReader * pNew)2941 static int fts3SegReaderCursorAppend(
2942   Fts3MultiSegReader *pCsr,
2943   Fts3SegReader *pNew
2944 ){
2945   if( (pCsr->nSegment%16)==0 ){
2946     Fts3SegReader **apNew;
2947     sqlite3_int64 nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
2948     apNew = (Fts3SegReader **)sqlite3_realloc64(pCsr->apSegment, nByte);
2949     if( !apNew ){
2950       sqlite3Fts3SegReaderFree(pNew);
2951       return SQLITE_NOMEM;
2952     }
2953     pCsr->apSegment = apNew;
2954   }
2955   pCsr->apSegment[pCsr->nSegment++] = pNew;
2956   return SQLITE_OK;
2957 }
2958 
2959 /*
2960 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
2961 ** 8th argument.
2962 **
2963 ** This function returns SQLITE_OK if successful, or an SQLite error code
2964 ** otherwise.
2965 */
fts3SegReaderCursor(Fts3Table * p,int iLangid,int iIndex,int iLevel,const char * zTerm,int nTerm,int isPrefix,int isScan,Fts3MultiSegReader * pCsr)2966 static int fts3SegReaderCursor(
2967   Fts3Table *p,                   /* FTS3 table handle */
2968   int iLangid,                    /* Language id */
2969   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
2970   int iLevel,                     /* Level of segments to scan */
2971   const char *zTerm,              /* Term to query for */
2972   int nTerm,                      /* Size of zTerm in bytes */
2973   int isPrefix,                   /* True for a prefix search */
2974   int isScan,                     /* True to scan from zTerm to EOF */
2975   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
2976 ){
2977   int rc = SQLITE_OK;             /* Error code */
2978   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
2979   int rc2;                        /* Result of sqlite3_reset() */
2980 
2981   /* If iLevel is less than 0 and this is not a scan, include a seg-reader
2982   ** for the pending-terms. If this is a scan, then this call must be being
2983   ** made by an fts4aux module, not an FTS table. In this case calling
2984   ** Fts3SegReaderPending might segfault, as the data structures used by
2985   ** fts4aux are not completely populated. So it's easiest to filter these
2986   ** calls out here.  */
2987   if( iLevel<0 && p->aIndex && p->iPrevLangid==iLangid ){
2988     Fts3SegReader *pSeg = 0;
2989     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
2990     if( rc==SQLITE_OK && pSeg ){
2991       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
2992     }
2993   }
2994 
2995   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
2996     if( rc==SQLITE_OK ){
2997       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
2998     }
2999 
3000     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
3001       Fts3SegReader *pSeg = 0;
3002 
3003       /* Read the values returned by the SELECT into local variables. */
3004       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
3005       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
3006       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
3007       int nRoot = sqlite3_column_bytes(pStmt, 4);
3008       char const *zRoot = sqlite3_column_blob(pStmt, 4);
3009 
3010       /* If zTerm is not NULL, and this segment is not stored entirely on its
3011       ** root node, the range of leaves scanned can be reduced. Do this. */
3012       if( iStartBlock && zTerm && zRoot ){
3013         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
3014         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
3015         if( rc!=SQLITE_OK ) goto finished;
3016         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
3017       }
3018 
3019       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
3020           (isPrefix==0 && isScan==0),
3021           iStartBlock, iLeavesEndBlock,
3022           iEndBlock, zRoot, nRoot, &pSeg
3023       );
3024       if( rc!=SQLITE_OK ) goto finished;
3025       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
3026     }
3027   }
3028 
3029  finished:
3030   rc2 = sqlite3_reset(pStmt);
3031   if( rc==SQLITE_DONE ) rc = rc2;
3032 
3033   return rc;
3034 }
3035 
3036 /*
3037 ** Set up a cursor object for iterating through a full-text index or a
3038 ** single level therein.
3039 */
sqlite3Fts3SegReaderCursor(Fts3Table * p,int iLangid,int iIndex,int iLevel,const char * zTerm,int nTerm,int isPrefix,int isScan,Fts3MultiSegReader * pCsr)3040 int sqlite3Fts3SegReaderCursor(
3041   Fts3Table *p,                   /* FTS3 table handle */
3042   int iLangid,                    /* Language-id to search */
3043   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
3044   int iLevel,                     /* Level of segments to scan */
3045   const char *zTerm,              /* Term to query for */
3046   int nTerm,                      /* Size of zTerm in bytes */
3047   int isPrefix,                   /* True for a prefix search */
3048   int isScan,                     /* True to scan from zTerm to EOF */
3049   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
3050 ){
3051   assert( iIndex>=0 && iIndex<p->nIndex );
3052   assert( iLevel==FTS3_SEGCURSOR_ALL
3053       ||  iLevel==FTS3_SEGCURSOR_PENDING
3054       ||  iLevel>=0
3055   );
3056   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
3057   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
3058   assert( isPrefix==0 || isScan==0 );
3059 
3060   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
3061   return fts3SegReaderCursor(
3062       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
3063   );
3064 }
3065 
3066 /*
3067 ** In addition to its current configuration, have the Fts3MultiSegReader
3068 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
3069 **
3070 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
3071 */
fts3SegReaderCursorAddZero(Fts3Table * p,int iLangid,const char * zTerm,int nTerm,Fts3MultiSegReader * pCsr)3072 static int fts3SegReaderCursorAddZero(
3073   Fts3Table *p,                   /* FTS virtual table handle */
3074   int iLangid,
3075   const char *zTerm,              /* Term to scan doclist of */
3076   int nTerm,                      /* Number of bytes in zTerm */
3077   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
3078 ){
3079   return fts3SegReaderCursor(p,
3080       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
3081   );
3082 }
3083 
3084 /*
3085 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
3086 ** if isPrefix is true, to scan the doclist for all terms for which
3087 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
3088 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
3089 ** an SQLite error code.
3090 **
3091 ** It is the responsibility of the caller to free this object by eventually
3092 ** passing it to fts3SegReaderCursorFree()
3093 **
3094 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
3095 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
3096 */
fts3TermSegReaderCursor(Fts3Cursor * pCsr,const char * zTerm,int nTerm,int isPrefix,Fts3MultiSegReader ** ppSegcsr)3097 static int fts3TermSegReaderCursor(
3098   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
3099   const char *zTerm,              /* Term to query for */
3100   int nTerm,                      /* Size of zTerm in bytes */
3101   int isPrefix,                   /* True for a prefix search */
3102   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
3103 ){
3104   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
3105   int rc = SQLITE_NOMEM;          /* Return code */
3106 
3107   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
3108   if( pSegcsr ){
3109     int i;
3110     int bFound = 0;               /* True once an index has been found */
3111     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
3112 
3113     if( isPrefix ){
3114       for(i=1; bFound==0 && i<p->nIndex; i++){
3115         if( p->aIndex[i].nPrefix==nTerm ){
3116           bFound = 1;
3117           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
3118               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
3119           );
3120           pSegcsr->bLookup = 1;
3121         }
3122       }
3123 
3124       for(i=1; bFound==0 && i<p->nIndex; i++){
3125         if( p->aIndex[i].nPrefix==nTerm+1 ){
3126           bFound = 1;
3127           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
3128               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
3129           );
3130           if( rc==SQLITE_OK ){
3131             rc = fts3SegReaderCursorAddZero(
3132                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
3133             );
3134           }
3135         }
3136       }
3137     }
3138 
3139     if( bFound==0 ){
3140       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
3141           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
3142       );
3143       pSegcsr->bLookup = !isPrefix;
3144     }
3145   }
3146 
3147   *ppSegcsr = pSegcsr;
3148   return rc;
3149 }
3150 
3151 /*
3152 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
3153 */
fts3SegReaderCursorFree(Fts3MultiSegReader * pSegcsr)3154 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
3155   sqlite3Fts3SegReaderFinish(pSegcsr);
3156   sqlite3_free(pSegcsr);
3157 }
3158 
3159 /*
3160 ** This function retrieves the doclist for the specified term (or term
3161 ** prefix) from the database.
3162 */
fts3TermSelect(Fts3Table * p,Fts3PhraseToken * pTok,int iColumn,int * pnOut,char ** ppOut)3163 static int fts3TermSelect(
3164   Fts3Table *p,                   /* Virtual table handle */
3165   Fts3PhraseToken *pTok,          /* Token to query for */
3166   int iColumn,                    /* Column to query (or -ve for all columns) */
3167   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
3168   char **ppOut                    /* OUT: Malloced result buffer */
3169 ){
3170   int rc;                         /* Return code */
3171   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
3172   TermSelect tsc;                 /* Object for pair-wise doclist merging */
3173   Fts3SegFilter filter;           /* Segment term filter configuration */
3174 
3175   pSegcsr = pTok->pSegcsr;
3176   memset(&tsc, 0, sizeof(TermSelect));
3177 
3178   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
3179         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
3180         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
3181         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
3182   filter.iCol = iColumn;
3183   filter.zTerm = pTok->z;
3184   filter.nTerm = pTok->n;
3185 
3186   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
3187   while( SQLITE_OK==rc
3188       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
3189   ){
3190     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
3191   }
3192 
3193   if( rc==SQLITE_OK ){
3194     rc = fts3TermSelectFinishMerge(p, &tsc);
3195   }
3196   if( rc==SQLITE_OK ){
3197     *ppOut = tsc.aaOutput[0];
3198     *pnOut = tsc.anOutput[0];
3199   }else{
3200     int i;
3201     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
3202       sqlite3_free(tsc.aaOutput[i]);
3203     }
3204   }
3205 
3206   fts3SegReaderCursorFree(pSegcsr);
3207   pTok->pSegcsr = 0;
3208   return rc;
3209 }
3210 
3211 /*
3212 ** This function counts the total number of docids in the doclist stored
3213 ** in buffer aList[], size nList bytes.
3214 **
3215 ** If the isPoslist argument is true, then it is assumed that the doclist
3216 ** contains a position-list following each docid. Otherwise, it is assumed
3217 ** that the doclist is simply a list of docids stored as delta encoded
3218 ** varints.
3219 */
fts3DoclistCountDocids(char * aList,int nList)3220 static int fts3DoclistCountDocids(char *aList, int nList){
3221   int nDoc = 0;                   /* Return value */
3222   if( aList ){
3223     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
3224     char *p = aList;              /* Cursor */
3225     while( p<aEnd ){
3226       nDoc++;
3227       while( (*p++)&0x80 );     /* Skip docid varint */
3228       fts3PoslistCopy(0, &p);   /* Skip over position list */
3229     }
3230   }
3231 
3232   return nDoc;
3233 }
3234 
3235 /*
3236 ** Advance the cursor to the next row in the %_content table that
3237 ** matches the search criteria.  For a MATCH search, this will be
3238 ** the next row that matches. For a full-table scan, this will be
3239 ** simply the next row in the %_content table.  For a docid lookup,
3240 ** this routine simply sets the EOF flag.
3241 **
3242 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
3243 ** even if we reach end-of-file.  The fts3EofMethod() will be called
3244 ** subsequently to determine whether or not an EOF was hit.
3245 */
fts3NextMethod(sqlite3_vtab_cursor * pCursor)3246 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
3247   int rc;
3248   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
3249   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
3250     Fts3Table *pTab = (Fts3Table*)pCursor->pVtab;
3251     pTab->bLock++;
3252     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
3253       pCsr->isEof = 1;
3254       rc = sqlite3_reset(pCsr->pStmt);
3255     }else{
3256       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
3257       rc = SQLITE_OK;
3258     }
3259     pTab->bLock--;
3260   }else{
3261     rc = fts3EvalNext((Fts3Cursor *)pCursor);
3262   }
3263   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
3264   return rc;
3265 }
3266 
3267 /*
3268 ** If the numeric type of argument pVal is "integer", then return it
3269 ** converted to a 64-bit signed integer. Otherwise, return a copy of
3270 ** the second parameter, iDefault.
3271 */
fts3DocidRange(sqlite3_value * pVal,i64 iDefault)3272 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
3273   if( pVal ){
3274     int eType = sqlite3_value_numeric_type(pVal);
3275     if( eType==SQLITE_INTEGER ){
3276       return sqlite3_value_int64(pVal);
3277     }
3278   }
3279   return iDefault;
3280 }
3281 
3282 /*
3283 ** This is the xFilter interface for the virtual table.  See
3284 ** the virtual table xFilter method documentation for additional
3285 ** information.
3286 **
3287 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
3288 ** the %_content table.
3289 **
3290 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
3291 ** in the %_content table.
3292 **
3293 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
3294 ** column on the left-hand side of the MATCH operator is column
3295 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
3296 ** side of the MATCH operator.
3297 */
fts3FilterMethod(sqlite3_vtab_cursor * pCursor,int idxNum,const char * idxStr,int nVal,sqlite3_value ** apVal)3298 static int fts3FilterMethod(
3299   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
3300   int idxNum,                     /* Strategy index */
3301   const char *idxStr,             /* Unused */
3302   int nVal,                       /* Number of elements in apVal */
3303   sqlite3_value **apVal           /* Arguments for the indexing scheme */
3304 ){
3305   int rc = SQLITE_OK;
3306   char *zSql;                     /* SQL statement used to access %_content */
3307   int eSearch;
3308   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
3309   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
3310 
3311   sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
3312   sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
3313   sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
3314   sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
3315   int iIdx;
3316 
3317   UNUSED_PARAMETER(idxStr);
3318   UNUSED_PARAMETER(nVal);
3319 
3320   if( p->bLock ){
3321     return SQLITE_ERROR;
3322   }
3323 
3324   eSearch = (idxNum & 0x0000FFFF);
3325   assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
3326   assert( p->pSegments==0 );
3327 
3328   /* Collect arguments into local variables */
3329   iIdx = 0;
3330   if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
3331   if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
3332   if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
3333   if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
3334   assert( iIdx==nVal );
3335 
3336   /* In case the cursor has been used before, clear it now. */
3337   fts3ClearCursor(pCsr);
3338 
3339   /* Set the lower and upper bounds on docids to return */
3340   pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
3341   pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
3342 
3343   if( idxStr ){
3344     pCsr->bDesc = (idxStr[0]=='D');
3345   }else{
3346     pCsr->bDesc = p->bDescIdx;
3347   }
3348   pCsr->eSearch = (i16)eSearch;
3349 
3350   if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
3351     int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
3352     const char *zQuery = (const char *)sqlite3_value_text(pCons);
3353 
3354     if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
3355       return SQLITE_NOMEM;
3356     }
3357 
3358     pCsr->iLangid = 0;
3359     if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
3360 
3361     assert( p->base.zErrMsg==0 );
3362     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
3363         p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
3364         &p->base.zErrMsg
3365     );
3366     if( rc!=SQLITE_OK ){
3367       return rc;
3368     }
3369 
3370     rc = fts3EvalStart(pCsr);
3371     sqlite3Fts3SegmentsClose(p);
3372     if( rc!=SQLITE_OK ) return rc;
3373     pCsr->pNextId = pCsr->aDoclist;
3374     pCsr->iPrevId = 0;
3375   }
3376 
3377   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
3378   ** statement loops through all rows of the %_content table. For a
3379   ** full-text query or docid lookup, the statement retrieves a single
3380   ** row by docid.
3381   */
3382   if( eSearch==FTS3_FULLSCAN_SEARCH ){
3383     if( pDocidGe || pDocidLe ){
3384       zSql = sqlite3_mprintf(
3385           "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
3386           p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
3387           (pCsr->bDesc ? "DESC" : "ASC")
3388       );
3389     }else{
3390       zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
3391           p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
3392       );
3393     }
3394     if( zSql ){
3395       p->bLock++;
3396       rc = sqlite3_prepare_v3(
3397           p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0
3398       );
3399       p->bLock--;
3400       sqlite3_free(zSql);
3401     }else{
3402       rc = SQLITE_NOMEM;
3403     }
3404   }else if( eSearch==FTS3_DOCID_SEARCH ){
3405     rc = fts3CursorSeekStmt(pCsr);
3406     if( rc==SQLITE_OK ){
3407       rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
3408     }
3409   }
3410   if( rc!=SQLITE_OK ) return rc;
3411 
3412   return fts3NextMethod(pCursor);
3413 }
3414 
3415 /*
3416 ** This is the xEof method of the virtual table. SQLite calls this
3417 ** routine to find out if it has reached the end of a result set.
3418 */
fts3EofMethod(sqlite3_vtab_cursor * pCursor)3419 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
3420   Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
3421   if( pCsr->isEof ){
3422     fts3ClearCursor(pCsr);
3423     pCsr->isEof = 1;
3424   }
3425   return pCsr->isEof;
3426 }
3427 
3428 /*
3429 ** This is the xRowid method. The SQLite core calls this routine to
3430 ** retrieve the rowid for the current row of the result set. fts3
3431 ** exposes %_content.docid as the rowid for the virtual table. The
3432 ** rowid should be written to *pRowid.
3433 */
fts3RowidMethod(sqlite3_vtab_cursor * pCursor,sqlite_int64 * pRowid)3434 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
3435   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
3436   *pRowid = pCsr->iPrevId;
3437   return SQLITE_OK;
3438 }
3439 
3440 /*
3441 ** This is the xColumn method, called by SQLite to request a value from
3442 ** the row that the supplied cursor currently points to.
3443 **
3444 ** If:
3445 **
3446 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
3447 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
3448 **   (iCol == p->nColumn+1) -> Docid column
3449 **   (iCol == p->nColumn+2) -> Langid column
3450 */
fts3ColumnMethod(sqlite3_vtab_cursor * pCursor,sqlite3_context * pCtx,int iCol)3451 static int fts3ColumnMethod(
3452   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
3453   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
3454   int iCol                        /* Index of column to read value from */
3455 ){
3456   int rc = SQLITE_OK;             /* Return Code */
3457   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
3458   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
3459 
3460   /* The column value supplied by SQLite must be in range. */
3461   assert( iCol>=0 && iCol<=p->nColumn+2 );
3462 
3463   switch( iCol-p->nColumn ){
3464     case 0:
3465       /* The special 'table-name' column */
3466       sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
3467       break;
3468 
3469     case 1:
3470       /* The docid column */
3471       sqlite3_result_int64(pCtx, pCsr->iPrevId);
3472       break;
3473 
3474     case 2:
3475       if( pCsr->pExpr ){
3476         sqlite3_result_int64(pCtx, pCsr->iLangid);
3477         break;
3478       }else if( p->zLanguageid==0 ){
3479         sqlite3_result_int(pCtx, 0);
3480         break;
3481       }else{
3482         iCol = p->nColumn;
3483         /* no break */ deliberate_fall_through
3484       }
3485 
3486     default:
3487       /* A user column. Or, if this is a full-table scan, possibly the
3488       ** language-id column. Seek the cursor. */
3489       rc = fts3CursorSeek(0, pCsr);
3490       if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
3491         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
3492       }
3493       break;
3494   }
3495 
3496   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
3497   return rc;
3498 }
3499 
3500 /*
3501 ** This function is the implementation of the xUpdate callback used by
3502 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
3503 ** inserted, updated or deleted.
3504 */
fts3UpdateMethod(sqlite3_vtab * pVtab,int nArg,sqlite3_value ** apVal,sqlite_int64 * pRowid)3505 static int fts3UpdateMethod(
3506   sqlite3_vtab *pVtab,            /* Virtual table handle */
3507   int nArg,                       /* Size of argument array */
3508   sqlite3_value **apVal,          /* Array of arguments */
3509   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
3510 ){
3511   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
3512 }
3513 
3514 /*
3515 ** Implementation of xSync() method. Flush the contents of the pending-terms
3516 ** hash-table to the database.
3517 */
fts3SyncMethod(sqlite3_vtab * pVtab)3518 static int fts3SyncMethod(sqlite3_vtab *pVtab){
3519 
3520   /* Following an incremental-merge operation, assuming that the input
3521   ** segments are not completely consumed (the usual case), they are updated
3522   ** in place to remove the entries that have already been merged. This
3523   ** involves updating the leaf block that contains the smallest unmerged
3524   ** entry and each block (if any) between the leaf and the root node. So
3525   ** if the height of the input segment b-trees is N, and input segments
3526   ** are merged eight at a time, updating the input segments at the end
3527   ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
3528   ** small - often between 0 and 2. So the overhead of the incremental
3529   ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
3530   ** dwarfing the actual productive work accomplished, the incremental merge
3531   ** is only attempted if it will write at least 64 leaf blocks. Hence
3532   ** nMinMerge.
3533   **
3534   ** Of course, updating the input segments also involves deleting a bunch
3535   ** of blocks from the segments table. But this is not considered overhead
3536   ** as it would also be required by a crisis-merge that used the same input
3537   ** segments.
3538   */
3539   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
3540 
3541   Fts3Table *p = (Fts3Table*)pVtab;
3542   int rc;
3543   i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
3544 
3545   rc = sqlite3Fts3PendingTermsFlush(p);
3546   if( rc==SQLITE_OK
3547    && p->nLeafAdd>(nMinMerge/16)
3548    && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
3549   ){
3550     int mxLevel = 0;              /* Maximum relative level value in db */
3551     int A;                        /* Incr-merge parameter A */
3552 
3553     rc = sqlite3Fts3MaxLevel(p, &mxLevel);
3554     assert( rc==SQLITE_OK || mxLevel==0 );
3555     A = p->nLeafAdd * mxLevel;
3556     A += (A/2);
3557     if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
3558   }
3559   sqlite3Fts3SegmentsClose(p);
3560   sqlite3_set_last_insert_rowid(p->db, iLastRowid);
3561   return rc;
3562 }
3563 
3564 /*
3565 ** If it is currently unknown whether or not the FTS table has an %_stat
3566 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
3567 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
3568 ** if an error occurs.
3569 */
fts3SetHasStat(Fts3Table * p)3570 static int fts3SetHasStat(Fts3Table *p){
3571   int rc = SQLITE_OK;
3572   if( p->bHasStat==2 ){
3573     char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
3574     if( zTbl ){
3575       int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
3576       sqlite3_free(zTbl);
3577       p->bHasStat = (res==SQLITE_OK);
3578     }else{
3579       rc = SQLITE_NOMEM;
3580     }
3581   }
3582   return rc;
3583 }
3584 
3585 /*
3586 ** Implementation of xBegin() method.
3587 */
fts3BeginMethod(sqlite3_vtab * pVtab)3588 static int fts3BeginMethod(sqlite3_vtab *pVtab){
3589   Fts3Table *p = (Fts3Table*)pVtab;
3590   int rc;
3591   UNUSED_PARAMETER(pVtab);
3592   assert( p->pSegments==0 );
3593   assert( p->nPendingData==0 );
3594   assert( p->inTransaction!=1 );
3595   p->nLeafAdd = 0;
3596   rc = fts3SetHasStat(p);
3597 #ifdef SQLITE_DEBUG
3598   if( rc==SQLITE_OK ){
3599     p->inTransaction = 1;
3600     p->mxSavepoint = -1;
3601   }
3602 #endif
3603   return rc;
3604 }
3605 
3606 /*
3607 ** Implementation of xCommit() method. This is a no-op. The contents of
3608 ** the pending-terms hash-table have already been flushed into the database
3609 ** by fts3SyncMethod().
3610 */
fts3CommitMethod(sqlite3_vtab * pVtab)3611 static int fts3CommitMethod(sqlite3_vtab *pVtab){
3612   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
3613   UNUSED_PARAMETER(pVtab);
3614   assert( p->nPendingData==0 );
3615   assert( p->inTransaction!=0 );
3616   assert( p->pSegments==0 );
3617   TESTONLY( p->inTransaction = 0 );
3618   TESTONLY( p->mxSavepoint = -1; );
3619   return SQLITE_OK;
3620 }
3621 
3622 /*
3623 ** Implementation of xRollback(). Discard the contents of the pending-terms
3624 ** hash-table. Any changes made to the database are reverted by SQLite.
3625 */
fts3RollbackMethod(sqlite3_vtab * pVtab)3626 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
3627   Fts3Table *p = (Fts3Table*)pVtab;
3628   sqlite3Fts3PendingTermsClear(p);
3629   assert( p->inTransaction!=0 );
3630   TESTONLY( p->inTransaction = 0 );
3631   TESTONLY( p->mxSavepoint = -1; );
3632   return SQLITE_OK;
3633 }
3634 
3635 /*
3636 ** When called, *ppPoslist must point to the byte immediately following the
3637 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
3638 ** moves *ppPoslist so that it instead points to the first byte of the
3639 ** same position list.
3640 */
fts3ReversePoslist(char * pStart,char ** ppPoslist)3641 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
3642   char *p = &(*ppPoslist)[-2];
3643   char c = 0;
3644 
3645   /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
3646   while( p>pStart && (c=*p--)==0 );
3647 
3648   /* Search backwards for a varint with value zero (the end of the previous
3649   ** poslist). This is an 0x00 byte preceded by some byte that does not
3650   ** have the 0x80 bit set.  */
3651   while( p>pStart && (*p & 0x80) | c ){
3652     c = *p--;
3653   }
3654   assert( p==pStart || c==0 );
3655 
3656   /* At this point p points to that preceding byte without the 0x80 bit
3657   ** set. So to find the start of the poslist, skip forward 2 bytes then
3658   ** over a varint.
3659   **
3660   ** Normally. The other case is that p==pStart and the poslist to return
3661   ** is the first in the doclist. In this case do not skip forward 2 bytes.
3662   ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
3663   ** is required for cases where the first byte of a doclist and the
3664   ** doclist is empty. For example, if the first docid is 10, a doclist
3665   ** that begins with:
3666   **
3667   **   0x0A 0x00 <next docid delta varint>
3668   */
3669   if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
3670   while( *p++&0x80 );
3671   *ppPoslist = p;
3672 }
3673 
3674 /*
3675 ** Helper function used by the implementation of the overloaded snippet(),
3676 ** offsets() and optimize() SQL functions.
3677 **
3678 ** If the value passed as the third argument is a blob of size
3679 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
3680 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
3681 ** message is written to context pContext and SQLITE_ERROR returned. The
3682 ** string passed via zFunc is used as part of the error message.
3683 */
fts3FunctionArg(sqlite3_context * pContext,const char * zFunc,sqlite3_value * pVal,Fts3Cursor ** ppCsr)3684 static int fts3FunctionArg(
3685   sqlite3_context *pContext,      /* SQL function call context */
3686   const char *zFunc,              /* Function name */
3687   sqlite3_value *pVal,            /* argv[0] passed to function */
3688   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
3689 ){
3690   int rc;
3691   *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
3692   if( (*ppCsr)!=0 ){
3693     rc = SQLITE_OK;
3694   }else{
3695     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
3696     sqlite3_result_error(pContext, zErr, -1);
3697     sqlite3_free(zErr);
3698     rc = SQLITE_ERROR;
3699   }
3700   return rc;
3701 }
3702 
3703 /*
3704 ** Implementation of the snippet() function for FTS3
3705 */
fts3SnippetFunc(sqlite3_context * pContext,int nVal,sqlite3_value ** apVal)3706 static void fts3SnippetFunc(
3707   sqlite3_context *pContext,      /* SQLite function call context */
3708   int nVal,                       /* Size of apVal[] array */
3709   sqlite3_value **apVal           /* Array of arguments */
3710 ){
3711   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
3712   const char *zStart = "<b>";
3713   const char *zEnd = "</b>";
3714   const char *zEllipsis = "<b>...</b>";
3715   int iCol = -1;
3716   int nToken = 15;                /* Default number of tokens in snippet */
3717 
3718   /* There must be at least one argument passed to this function (otherwise
3719   ** the non-overloaded version would have been called instead of this one).
3720   */
3721   assert( nVal>=1 );
3722 
3723   if( nVal>6 ){
3724     sqlite3_result_error(pContext,
3725         "wrong number of arguments to function snippet()", -1);
3726     return;
3727   }
3728   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
3729 
3730   switch( nVal ){
3731     case 6: nToken = sqlite3_value_int(apVal[5]);
3732             /* no break */ deliberate_fall_through
3733     case 5: iCol = sqlite3_value_int(apVal[4]);
3734             /* no break */ deliberate_fall_through
3735     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
3736             /* no break */ deliberate_fall_through
3737     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
3738             /* no break */ deliberate_fall_through
3739     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
3740   }
3741   if( !zEllipsis || !zEnd || !zStart ){
3742     sqlite3_result_error_nomem(pContext);
3743   }else if( nToken==0 ){
3744     sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
3745   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
3746     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
3747   }
3748 }
3749 
3750 /*
3751 ** Implementation of the offsets() function for FTS3
3752 */
fts3OffsetsFunc(sqlite3_context * pContext,int nVal,sqlite3_value ** apVal)3753 static void fts3OffsetsFunc(
3754   sqlite3_context *pContext,      /* SQLite function call context */
3755   int nVal,                       /* Size of argument array */
3756   sqlite3_value **apVal           /* Array of arguments */
3757 ){
3758   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
3759 
3760   UNUSED_PARAMETER(nVal);
3761 
3762   assert( nVal==1 );
3763   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
3764   assert( pCsr );
3765   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
3766     sqlite3Fts3Offsets(pContext, pCsr);
3767   }
3768 }
3769 
3770 /*
3771 ** Implementation of the special optimize() function for FTS3. This
3772 ** function merges all segments in the database to a single segment.
3773 ** Example usage is:
3774 **
3775 **   SELECT optimize(t) FROM t LIMIT 1;
3776 **
3777 ** where 't' is the name of an FTS3 table.
3778 */
fts3OptimizeFunc(sqlite3_context * pContext,int nVal,sqlite3_value ** apVal)3779 static void fts3OptimizeFunc(
3780   sqlite3_context *pContext,      /* SQLite function call context */
3781   int nVal,                       /* Size of argument array */
3782   sqlite3_value **apVal           /* Array of arguments */
3783 ){
3784   int rc;                         /* Return code */
3785   Fts3Table *p;                   /* Virtual table handle */
3786   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
3787 
3788   UNUSED_PARAMETER(nVal);
3789 
3790   assert( nVal==1 );
3791   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
3792   p = (Fts3Table *)pCursor->base.pVtab;
3793   assert( p );
3794 
3795   rc = sqlite3Fts3Optimize(p);
3796 
3797   switch( rc ){
3798     case SQLITE_OK:
3799       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
3800       break;
3801     case SQLITE_DONE:
3802       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
3803       break;
3804     default:
3805       sqlite3_result_error_code(pContext, rc);
3806       break;
3807   }
3808 }
3809 
3810 /*
3811 ** Implementation of the matchinfo() function for FTS3
3812 */
fts3MatchinfoFunc(sqlite3_context * pContext,int nVal,sqlite3_value ** apVal)3813 static void fts3MatchinfoFunc(
3814   sqlite3_context *pContext,      /* SQLite function call context */
3815   int nVal,                       /* Size of argument array */
3816   sqlite3_value **apVal           /* Array of arguments */
3817 ){
3818   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
3819   assert( nVal==1 || nVal==2 );
3820   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
3821     const char *zArg = 0;
3822     if( nVal>1 ){
3823       zArg = (const char *)sqlite3_value_text(apVal[1]);
3824     }
3825     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
3826   }
3827 }
3828 
3829 /*
3830 ** This routine implements the xFindFunction method for the FTS3
3831 ** virtual table.
3832 */
fts3FindFunctionMethod(sqlite3_vtab * pVtab,int nArg,const char * zName,void (** pxFunc)(sqlite3_context *,int,sqlite3_value **),void ** ppArg)3833 static int fts3FindFunctionMethod(
3834   sqlite3_vtab *pVtab,            /* Virtual table handle */
3835   int nArg,                       /* Number of SQL function arguments */
3836   const char *zName,              /* Name of SQL function */
3837   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
3838   void **ppArg                    /* Unused */
3839 ){
3840   struct Overloaded {
3841     const char *zName;
3842     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
3843   } aOverload[] = {
3844     { "snippet", fts3SnippetFunc },
3845     { "offsets", fts3OffsetsFunc },
3846     { "optimize", fts3OptimizeFunc },
3847     { "matchinfo", fts3MatchinfoFunc },
3848   };
3849   int i;                          /* Iterator variable */
3850 
3851   UNUSED_PARAMETER(pVtab);
3852   UNUSED_PARAMETER(nArg);
3853   UNUSED_PARAMETER(ppArg);
3854 
3855   for(i=0; i<SizeofArray(aOverload); i++){
3856     if( strcmp(zName, aOverload[i].zName)==0 ){
3857       *pxFunc = aOverload[i].xFunc;
3858       return 1;
3859     }
3860   }
3861 
3862   /* No function of the specified name was found. Return 0. */
3863   return 0;
3864 }
3865 
3866 /*
3867 ** Implementation of FTS3 xRename method. Rename an fts3 table.
3868 */
fts3RenameMethod(sqlite3_vtab * pVtab,const char * zName)3869 static int fts3RenameMethod(
3870   sqlite3_vtab *pVtab,            /* Virtual table handle */
3871   const char *zName               /* New name of table */
3872 ){
3873   Fts3Table *p = (Fts3Table *)pVtab;
3874   sqlite3 *db = p->db;            /* Database connection */
3875   int rc;                         /* Return Code */
3876 
3877   /* At this point it must be known if the %_stat table exists or not.
3878   ** So bHasStat may not be 2.  */
3879   rc = fts3SetHasStat(p);
3880 
3881   /* As it happens, the pending terms table is always empty here. This is
3882   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
3883   ** always opens a savepoint transaction. And the xSavepoint() method
3884   ** flushes the pending terms table. But leave the (no-op) call to
3885   ** PendingTermsFlush() in in case that changes.
3886   */
3887   assert( p->nPendingData==0 );
3888   if( rc==SQLITE_OK ){
3889     rc = sqlite3Fts3PendingTermsFlush(p);
3890   }
3891 
3892   if( p->zContentTbl==0 ){
3893     fts3DbExec(&rc, db,
3894       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
3895       p->zDb, p->zName, zName
3896     );
3897   }
3898 
3899   if( p->bHasDocsize ){
3900     fts3DbExec(&rc, db,
3901       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
3902       p->zDb, p->zName, zName
3903     );
3904   }
3905   if( p->bHasStat ){
3906     fts3DbExec(&rc, db,
3907       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
3908       p->zDb, p->zName, zName
3909     );
3910   }
3911   fts3DbExec(&rc, db,
3912     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
3913     p->zDb, p->zName, zName
3914   );
3915   fts3DbExec(&rc, db,
3916     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
3917     p->zDb, p->zName, zName
3918   );
3919   return rc;
3920 }
3921 
3922 /*
3923 ** The xSavepoint() method.
3924 **
3925 ** Flush the contents of the pending-terms table to disk.
3926 */
fts3SavepointMethod(sqlite3_vtab * pVtab,int iSavepoint)3927 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
3928   int rc = SQLITE_OK;
3929   UNUSED_PARAMETER(iSavepoint);
3930   assert( ((Fts3Table *)pVtab)->inTransaction );
3931   assert( ((Fts3Table *)pVtab)->mxSavepoint <= iSavepoint );
3932   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
3933   if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
3934     rc = fts3SyncMethod(pVtab);
3935   }
3936   return rc;
3937 }
3938 
3939 /*
3940 ** The xRelease() method.
3941 **
3942 ** This is a no-op.
3943 */
fts3ReleaseMethod(sqlite3_vtab * pVtab,int iSavepoint)3944 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
3945   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
3946   UNUSED_PARAMETER(iSavepoint);
3947   UNUSED_PARAMETER(pVtab);
3948   assert( p->inTransaction );
3949   assert( p->mxSavepoint >= iSavepoint );
3950   TESTONLY( p->mxSavepoint = iSavepoint-1 );
3951   return SQLITE_OK;
3952 }
3953 
3954 /*
3955 ** The xRollbackTo() method.
3956 **
3957 ** Discard the contents of the pending terms table.
3958 */
fts3RollbackToMethod(sqlite3_vtab * pVtab,int iSavepoint)3959 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
3960   Fts3Table *p = (Fts3Table*)pVtab;
3961   UNUSED_PARAMETER(iSavepoint);
3962   assert( p->inTransaction );
3963   TESTONLY( p->mxSavepoint = iSavepoint );
3964   sqlite3Fts3PendingTermsClear(p);
3965   return SQLITE_OK;
3966 }
3967 
3968 /*
3969 ** Return true if zName is the extension on one of the shadow tables used
3970 ** by this module.
3971 */
fts3ShadowName(const char * zName)3972 static int fts3ShadowName(const char *zName){
3973   static const char *azName[] = {
3974     "content", "docsize", "segdir", "segments", "stat",
3975   };
3976   unsigned int i;
3977   for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
3978     if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
3979   }
3980   return 0;
3981 }
3982 
3983 static const sqlite3_module fts3Module = {
3984   /* iVersion      */ 3,
3985   /* xCreate       */ fts3CreateMethod,
3986   /* xConnect      */ fts3ConnectMethod,
3987   /* xBestIndex    */ fts3BestIndexMethod,
3988   /* xDisconnect   */ fts3DisconnectMethod,
3989   /* xDestroy      */ fts3DestroyMethod,
3990   /* xOpen         */ fts3OpenMethod,
3991   /* xClose        */ fts3CloseMethod,
3992   /* xFilter       */ fts3FilterMethod,
3993   /* xNext         */ fts3NextMethod,
3994   /* xEof          */ fts3EofMethod,
3995   /* xColumn       */ fts3ColumnMethod,
3996   /* xRowid        */ fts3RowidMethod,
3997   /* xUpdate       */ fts3UpdateMethod,
3998   /* xBegin        */ fts3BeginMethod,
3999   /* xSync         */ fts3SyncMethod,
4000   /* xCommit       */ fts3CommitMethod,
4001   /* xRollback     */ fts3RollbackMethod,
4002   /* xFindFunction */ fts3FindFunctionMethod,
4003   /* xRename */       fts3RenameMethod,
4004   /* xSavepoint    */ fts3SavepointMethod,
4005   /* xRelease      */ fts3ReleaseMethod,
4006   /* xRollbackTo   */ fts3RollbackToMethod,
4007   /* xShadowName   */ fts3ShadowName,
4008 };
4009 
4010 /*
4011 ** This function is registered as the module destructor (called when an
4012 ** FTS3 enabled database connection is closed). It frees the memory
4013 ** allocated for the tokenizer hash table.
4014 */
hashDestroy(void * p)4015 static void hashDestroy(void *p){
4016   Fts3HashWrapper *pHash = (Fts3HashWrapper *)p;
4017   pHash->nRef--;
4018   if( pHash->nRef<=0 ){
4019     sqlite3Fts3HashClear(&pHash->hash);
4020     sqlite3_free(pHash);
4021   }
4022 }
4023 
4024 /*
4025 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
4026 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
4027 ** respectively. The following three forward declarations are for functions
4028 ** declared in these files used to retrieve the respective implementations.
4029 **
4030 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
4031 ** to by the argument to point to the "simple" tokenizer implementation.
4032 ** And so on.
4033 */
4034 void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
4035 void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
4036 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4037 void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
4038 #endif
4039 #ifdef SQLITE_ENABLE_ICU
4040 void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
4041 #endif
4042 
4043 /*
4044 ** Initialize the fts3 extension. If this extension is built as part
4045 ** of the sqlite library, then this function is called directly by
4046 ** SQLite. If fts3 is built as a dynamically loadable extension, this
4047 ** function is called by the sqlite3_extension_init() entry point.
4048 */
sqlite3Fts3Init(sqlite3 * db)4049 int sqlite3Fts3Init(sqlite3 *db){
4050   int rc = SQLITE_OK;
4051   Fts3HashWrapper *pHash = 0;
4052   const sqlite3_tokenizer_module *pSimple = 0;
4053   const sqlite3_tokenizer_module *pPorter = 0;
4054 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4055   const sqlite3_tokenizer_module *pUnicode = 0;
4056 #endif
4057 
4058 #ifdef SQLITE_ENABLE_ICU
4059   const sqlite3_tokenizer_module *pIcu = 0;
4060   sqlite3Fts3IcuTokenizerModule(&pIcu);
4061 #endif
4062 
4063 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4064   sqlite3Fts3UnicodeTokenizer(&pUnicode);
4065 #endif
4066 
4067 #ifdef SQLITE_TEST
4068   rc = sqlite3Fts3InitTerm(db);
4069   if( rc!=SQLITE_OK ) return rc;
4070 #endif
4071 
4072   rc = sqlite3Fts3InitAux(db);
4073   if( rc!=SQLITE_OK ) return rc;
4074 
4075   sqlite3Fts3SimpleTokenizerModule(&pSimple);
4076   sqlite3Fts3PorterTokenizerModule(&pPorter);
4077 
4078   /* Allocate and initialize the hash-table used to store tokenizers. */
4079   pHash = sqlite3_malloc(sizeof(Fts3HashWrapper));
4080   if( !pHash ){
4081     rc = SQLITE_NOMEM;
4082   }else{
4083     sqlite3Fts3HashInit(&pHash->hash, FTS3_HASH_STRING, 1);
4084     pHash->nRef = 0;
4085   }
4086 
4087   /* Load the built-in tokenizers into the hash table */
4088   if( rc==SQLITE_OK ){
4089     if( sqlite3Fts3HashInsert(&pHash->hash, "simple", 7, (void *)pSimple)
4090      || sqlite3Fts3HashInsert(&pHash->hash, "porter", 7, (void *)pPorter)
4091 
4092 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4093      || sqlite3Fts3HashInsert(&pHash->hash, "unicode61", 10, (void *)pUnicode)
4094 #endif
4095 #ifdef SQLITE_ENABLE_ICU
4096      || (pIcu && sqlite3Fts3HashInsert(&pHash->hash, "icu", 4, (void *)pIcu))
4097 #endif
4098     ){
4099       rc = SQLITE_NOMEM;
4100     }
4101   }
4102 
4103 #ifdef SQLITE_TEST
4104   if( rc==SQLITE_OK ){
4105     rc = sqlite3Fts3ExprInitTestInterface(db, &pHash->hash);
4106   }
4107 #endif
4108 
4109   /* Create the virtual table wrapper around the hash-table and overload
4110   ** the four scalar functions. If this is successful, register the
4111   ** module with sqlite.
4112   */
4113   if( SQLITE_OK==rc
4114    && SQLITE_OK==(rc=sqlite3Fts3InitHashTable(db,&pHash->hash,"fts3_tokenizer"))
4115    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
4116    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
4117    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
4118    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
4119    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
4120   ){
4121     pHash->nRef++;
4122     rc = sqlite3_create_module_v2(
4123         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
4124     );
4125     if( rc==SQLITE_OK ){
4126       pHash->nRef++;
4127       rc = sqlite3_create_module_v2(
4128           db, "fts4", &fts3Module, (void *)pHash, hashDestroy
4129       );
4130     }
4131     if( rc==SQLITE_OK ){
4132       pHash->nRef++;
4133       rc = sqlite3Fts3InitTok(db, (void *)pHash, hashDestroy);
4134     }
4135     return rc;
4136   }
4137 
4138 
4139   /* An error has occurred. Delete the hash table and return the error code. */
4140   assert( rc!=SQLITE_OK );
4141   if( pHash ){
4142     sqlite3Fts3HashClear(&pHash->hash);
4143     sqlite3_free(pHash);
4144   }
4145   return rc;
4146 }
4147 
4148 /*
4149 ** Allocate an Fts3MultiSegReader for each token in the expression headed
4150 ** by pExpr.
4151 **
4152 ** An Fts3SegReader object is a cursor that can seek or scan a range of
4153 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
4154 ** Fts3SegReader objects internally to provide an interface to seek or scan
4155 ** within the union of all segments of a b-tree. Hence the name.
4156 **
4157 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
4158 ** segment b-tree (if the term is not a prefix or it is a prefix for which
4159 ** there exists prefix b-tree of the right length) then it may be traversed
4160 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
4161 ** doclist and then traversed.
4162 */
fts3EvalAllocateReaders(Fts3Cursor * pCsr,Fts3Expr * pExpr,int * pnToken,int * pnOr,int * pRc)4163 static void fts3EvalAllocateReaders(
4164   Fts3Cursor *pCsr,               /* FTS cursor handle */
4165   Fts3Expr *pExpr,                /* Allocate readers for this expression */
4166   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
4167   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
4168   int *pRc                        /* IN/OUT: Error code */
4169 ){
4170   if( pExpr && SQLITE_OK==*pRc ){
4171     if( pExpr->eType==FTSQUERY_PHRASE ){
4172       int i;
4173       int nToken = pExpr->pPhrase->nToken;
4174       *pnToken += nToken;
4175       for(i=0; i<nToken; i++){
4176         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
4177         int rc = fts3TermSegReaderCursor(pCsr,
4178             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
4179         );
4180         if( rc!=SQLITE_OK ){
4181           *pRc = rc;
4182           return;
4183         }
4184       }
4185       assert( pExpr->pPhrase->iDoclistToken==0 );
4186       pExpr->pPhrase->iDoclistToken = -1;
4187     }else{
4188       *pnOr += (pExpr->eType==FTSQUERY_OR);
4189       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
4190       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
4191     }
4192   }
4193 }
4194 
4195 /*
4196 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
4197 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
4198 **
4199 ** This function assumes that pList points to a buffer allocated using
4200 ** sqlite3_malloc(). This function takes responsibility for eventually
4201 ** freeing the buffer.
4202 **
4203 ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
4204 */
fts3EvalPhraseMergeToken(Fts3Table * pTab,Fts3Phrase * p,int iToken,char * pList,int nList)4205 static int fts3EvalPhraseMergeToken(
4206   Fts3Table *pTab,                /* FTS Table pointer */
4207   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
4208   int iToken,                     /* Token pList/nList corresponds to */
4209   char *pList,                    /* Pointer to doclist */
4210   int nList                       /* Number of bytes in pList */
4211 ){
4212   int rc = SQLITE_OK;
4213   assert( iToken!=p->iDoclistToken );
4214 
4215   if( pList==0 ){
4216     sqlite3_free(p->doclist.aAll);
4217     p->doclist.aAll = 0;
4218     p->doclist.nAll = 0;
4219   }
4220 
4221   else if( p->iDoclistToken<0 ){
4222     p->doclist.aAll = pList;
4223     p->doclist.nAll = nList;
4224   }
4225 
4226   else if( p->doclist.aAll==0 ){
4227     sqlite3_free(pList);
4228   }
4229 
4230   else {
4231     char *pLeft;
4232     char *pRight;
4233     int nLeft;
4234     int nRight;
4235     int nDiff;
4236 
4237     if( p->iDoclistToken<iToken ){
4238       pLeft = p->doclist.aAll;
4239       nLeft = p->doclist.nAll;
4240       pRight = pList;
4241       nRight = nList;
4242       nDiff = iToken - p->iDoclistToken;
4243     }else{
4244       pRight = p->doclist.aAll;
4245       nRight = p->doclist.nAll;
4246       pLeft = pList;
4247       nLeft = nList;
4248       nDiff = p->iDoclistToken - iToken;
4249     }
4250 
4251     rc = fts3DoclistPhraseMerge(
4252         pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
4253     );
4254     sqlite3_free(pLeft);
4255     p->doclist.aAll = pRight;
4256     p->doclist.nAll = nRight;
4257   }
4258 
4259   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
4260   return rc;
4261 }
4262 
4263 /*
4264 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
4265 ** does not take deferred tokens into account.
4266 **
4267 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
4268 */
fts3EvalPhraseLoad(Fts3Cursor * pCsr,Fts3Phrase * p)4269 static int fts3EvalPhraseLoad(
4270   Fts3Cursor *pCsr,               /* FTS Cursor handle */
4271   Fts3Phrase *p                   /* Phrase object */
4272 ){
4273   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
4274   int iToken;
4275   int rc = SQLITE_OK;
4276 
4277   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
4278     Fts3PhraseToken *pToken = &p->aToken[iToken];
4279     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
4280 
4281     if( pToken->pSegcsr ){
4282       int nThis = 0;
4283       char *pThis = 0;
4284       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
4285       if( rc==SQLITE_OK ){
4286         rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
4287       }
4288     }
4289     assert( pToken->pSegcsr==0 );
4290   }
4291 
4292   return rc;
4293 }
4294 
4295 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
4296 /*
4297 ** This function is called on each phrase after the position lists for
4298 ** any deferred tokens have been loaded into memory. It updates the phrases
4299 ** current position list to include only those positions that are really
4300 ** instances of the phrase (after considering deferred tokens). If this
4301 ** means that the phrase does not appear in the current row, doclist.pList
4302 ** and doclist.nList are both zeroed.
4303 **
4304 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
4305 */
fts3EvalDeferredPhrase(Fts3Cursor * pCsr,Fts3Phrase * pPhrase)4306 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
4307   int iToken;                     /* Used to iterate through phrase tokens */
4308   char *aPoslist = 0;             /* Position list for deferred tokens */
4309   int nPoslist = 0;               /* Number of bytes in aPoslist */
4310   int iPrev = -1;                 /* Token number of previous deferred token */
4311   char *aFree = (pPhrase->doclist.bFreeList ? pPhrase->doclist.pList : 0);
4312 
4313   for(iToken=0; iToken<pPhrase->nToken; iToken++){
4314     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
4315     Fts3DeferredToken *pDeferred = pToken->pDeferred;
4316 
4317     if( pDeferred ){
4318       char *pList;
4319       int nList;
4320       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
4321       if( rc!=SQLITE_OK ) return rc;
4322 
4323       if( pList==0 ){
4324         sqlite3_free(aPoslist);
4325         sqlite3_free(aFree);
4326         pPhrase->doclist.pList = 0;
4327         pPhrase->doclist.nList = 0;
4328         return SQLITE_OK;
4329 
4330       }else if( aPoslist==0 ){
4331         aPoslist = pList;
4332         nPoslist = nList;
4333 
4334       }else{
4335         char *aOut = pList;
4336         char *p1 = aPoslist;
4337         char *p2 = aOut;
4338 
4339         assert( iPrev>=0 );
4340         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
4341         sqlite3_free(aPoslist);
4342         aPoslist = pList;
4343         nPoslist = (int)(aOut - aPoslist);
4344         if( nPoslist==0 ){
4345           sqlite3_free(aPoslist);
4346           sqlite3_free(aFree);
4347           pPhrase->doclist.pList = 0;
4348           pPhrase->doclist.nList = 0;
4349           return SQLITE_OK;
4350         }
4351       }
4352       iPrev = iToken;
4353     }
4354   }
4355 
4356   if( iPrev>=0 ){
4357     int nMaxUndeferred = pPhrase->iDoclistToken;
4358     if( nMaxUndeferred<0 ){
4359       pPhrase->doclist.pList = aPoslist;
4360       pPhrase->doclist.nList = nPoslist;
4361       pPhrase->doclist.iDocid = pCsr->iPrevId;
4362       pPhrase->doclist.bFreeList = 1;
4363     }else{
4364       int nDistance;
4365       char *p1;
4366       char *p2;
4367       char *aOut;
4368 
4369       if( nMaxUndeferred>iPrev ){
4370         p1 = aPoslist;
4371         p2 = pPhrase->doclist.pList;
4372         nDistance = nMaxUndeferred - iPrev;
4373       }else{
4374         p1 = pPhrase->doclist.pList;
4375         p2 = aPoslist;
4376         nDistance = iPrev - nMaxUndeferred;
4377       }
4378 
4379       aOut = (char *)sqlite3Fts3MallocZero(nPoslist+FTS3_BUFFER_PADDING);
4380       if( !aOut ){
4381         sqlite3_free(aPoslist);
4382         return SQLITE_NOMEM;
4383       }
4384 
4385       pPhrase->doclist.pList = aOut;
4386       assert( p1 && p2 );
4387       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
4388         pPhrase->doclist.bFreeList = 1;
4389         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
4390       }else{
4391         sqlite3_free(aOut);
4392         pPhrase->doclist.pList = 0;
4393         pPhrase->doclist.nList = 0;
4394       }
4395       sqlite3_free(aPoslist);
4396     }
4397   }
4398 
4399   if( pPhrase->doclist.pList!=aFree ) sqlite3_free(aFree);
4400   return SQLITE_OK;
4401 }
4402 #endif /* SQLITE_DISABLE_FTS4_DEFERRED */
4403 
4404 /*
4405 ** Maximum number of tokens a phrase may have to be considered for the
4406 ** incremental doclists strategy.
4407 */
4408 #define MAX_INCR_PHRASE_TOKENS 4
4409 
4410 /*
4411 ** This function is called for each Fts3Phrase in a full-text query
4412 ** expression to initialize the mechanism for returning rows. Once this
4413 ** function has been called successfully on an Fts3Phrase, it may be
4414 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
4415 **
4416 ** If parameter bOptOk is true, then the phrase may (or may not) use the
4417 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
4418 ** memory within this call.
4419 **
4420 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
4421 */
fts3EvalPhraseStart(Fts3Cursor * pCsr,int bOptOk,Fts3Phrase * p)4422 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
4423   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
4424   int rc = SQLITE_OK;             /* Error code */
4425   int i;
4426 
4427   /* Determine if doclists may be loaded from disk incrementally. This is
4428   ** possible if the bOptOk argument is true, the FTS doclists will be
4429   ** scanned in forward order, and the phrase consists of
4430   ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
4431   ** tokens or prefix tokens that cannot use a prefix-index.  */
4432   int bHaveIncr = 0;
4433   int bIncrOk = (bOptOk
4434    && pCsr->bDesc==pTab->bDescIdx
4435    && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
4436 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
4437    && pTab->bNoIncrDoclist==0
4438 #endif
4439   );
4440   for(i=0; bIncrOk==1 && i<p->nToken; i++){
4441     Fts3PhraseToken *pToken = &p->aToken[i];
4442     if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
4443       bIncrOk = 0;
4444     }
4445     if( pToken->pSegcsr ) bHaveIncr = 1;
4446   }
4447 
4448   if( bIncrOk && bHaveIncr ){
4449     /* Use the incremental approach. */
4450     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
4451     for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
4452       Fts3PhraseToken *pToken = &p->aToken[i];
4453       Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
4454       if( pSegcsr ){
4455         rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
4456       }
4457     }
4458     p->bIncr = 1;
4459   }else{
4460     /* Load the full doclist for the phrase into memory. */
4461     rc = fts3EvalPhraseLoad(pCsr, p);
4462     p->bIncr = 0;
4463   }
4464 
4465   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
4466   return rc;
4467 }
4468 
4469 /*
4470 ** This function is used to iterate backwards (from the end to start)
4471 ** through doclists. It is used by this module to iterate through phrase
4472 ** doclists in reverse and by the fts3_write.c module to iterate through
4473 ** pending-terms lists when writing to databases with "order=desc".
4474 **
4475 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
4476 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
4477 ** function iterates from the end of the doclist to the beginning.
4478 */
sqlite3Fts3DoclistPrev(int bDescIdx,char * aDoclist,int nDoclist,char ** ppIter,sqlite3_int64 * piDocid,int * pnList,u8 * pbEof)4479 void sqlite3Fts3DoclistPrev(
4480   int bDescIdx,                   /* True if the doclist is desc */
4481   char *aDoclist,                 /* Pointer to entire doclist */
4482   int nDoclist,                   /* Length of aDoclist in bytes */
4483   char **ppIter,                  /* IN/OUT: Iterator pointer */
4484   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
4485   int *pnList,                    /* OUT: List length pointer */
4486   u8 *pbEof                       /* OUT: End-of-file flag */
4487 ){
4488   char *p = *ppIter;
4489 
4490   assert( nDoclist>0 );
4491   assert( *pbEof==0 );
4492   assert_fts3_nc( p || *piDocid==0 );
4493   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
4494 
4495   if( p==0 ){
4496     sqlite3_int64 iDocid = 0;
4497     char *pNext = 0;
4498     char *pDocid = aDoclist;
4499     char *pEnd = &aDoclist[nDoclist];
4500     int iMul = 1;
4501 
4502     while( pDocid<pEnd ){
4503       sqlite3_int64 iDelta;
4504       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
4505       iDocid += (iMul * iDelta);
4506       pNext = pDocid;
4507       fts3PoslistCopy(0, &pDocid);
4508       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
4509       iMul = (bDescIdx ? -1 : 1);
4510     }
4511 
4512     *pnList = (int)(pEnd - pNext);
4513     *ppIter = pNext;
4514     *piDocid = iDocid;
4515   }else{
4516     int iMul = (bDescIdx ? -1 : 1);
4517     sqlite3_int64 iDelta;
4518     fts3GetReverseVarint(&p, aDoclist, &iDelta);
4519     *piDocid -= (iMul * iDelta);
4520 
4521     if( p==aDoclist ){
4522       *pbEof = 1;
4523     }else{
4524       char *pSave = p;
4525       fts3ReversePoslist(aDoclist, &p);
4526       *pnList = (int)(pSave - p);
4527     }
4528     *ppIter = p;
4529   }
4530 }
4531 
4532 /*
4533 ** Iterate forwards through a doclist.
4534 */
sqlite3Fts3DoclistNext(int bDescIdx,char * aDoclist,int nDoclist,char ** ppIter,sqlite3_int64 * piDocid,u8 * pbEof)4535 void sqlite3Fts3DoclistNext(
4536   int bDescIdx,                   /* True if the doclist is desc */
4537   char *aDoclist,                 /* Pointer to entire doclist */
4538   int nDoclist,                   /* Length of aDoclist in bytes */
4539   char **ppIter,                  /* IN/OUT: Iterator pointer */
4540   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
4541   u8 *pbEof                       /* OUT: End-of-file flag */
4542 ){
4543   char *p = *ppIter;
4544 
4545   assert( nDoclist>0 );
4546   assert( *pbEof==0 );
4547   assert_fts3_nc( p || *piDocid==0 );
4548   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
4549 
4550   if( p==0 ){
4551     p = aDoclist;
4552     p += sqlite3Fts3GetVarint(p, piDocid);
4553   }else{
4554     fts3PoslistCopy(0, &p);
4555     while( p<&aDoclist[nDoclist] && *p==0 ) p++;
4556     if( p>=&aDoclist[nDoclist] ){
4557       *pbEof = 1;
4558     }else{
4559       sqlite3_int64 iVar;
4560       p += sqlite3Fts3GetVarint(p, &iVar);
4561       *piDocid += ((bDescIdx ? -1 : 1) * iVar);
4562     }
4563   }
4564 
4565   *ppIter = p;
4566 }
4567 
4568 /*
4569 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
4570 ** to true if EOF is reached.
4571 */
fts3EvalDlPhraseNext(Fts3Table * pTab,Fts3Doclist * pDL,u8 * pbEof)4572 static void fts3EvalDlPhraseNext(
4573   Fts3Table *pTab,
4574   Fts3Doclist *pDL,
4575   u8 *pbEof
4576 ){
4577   char *pIter;                            /* Used to iterate through aAll */
4578   char *pEnd;                             /* 1 byte past end of aAll */
4579 
4580   if( pDL->pNextDocid ){
4581     pIter = pDL->pNextDocid;
4582     assert( pDL->aAll!=0 || pIter==0 );
4583   }else{
4584     pIter = pDL->aAll;
4585   }
4586 
4587   if( pIter==0 || pIter>=(pEnd = pDL->aAll + pDL->nAll) ){
4588     /* We have already reached the end of this doclist. EOF. */
4589     *pbEof = 1;
4590   }else{
4591     sqlite3_int64 iDelta;
4592     pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
4593     if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
4594       pDL->iDocid += iDelta;
4595     }else{
4596       pDL->iDocid -= iDelta;
4597     }
4598     pDL->pList = pIter;
4599     fts3PoslistCopy(0, &pIter);
4600     pDL->nList = (int)(pIter - pDL->pList);
4601 
4602     /* pIter now points just past the 0x00 that terminates the position-
4603     ** list for document pDL->iDocid. However, if this position-list was
4604     ** edited in place by fts3EvalNearTrim(), then pIter may not actually
4605     ** point to the start of the next docid value. The following line deals
4606     ** with this case by advancing pIter past the zero-padding added by
4607     ** fts3EvalNearTrim().  */
4608     while( pIter<pEnd && *pIter==0 ) pIter++;
4609 
4610     pDL->pNextDocid = pIter;
4611     assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
4612     *pbEof = 0;
4613   }
4614 }
4615 
4616 /*
4617 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
4618 */
4619 typedef struct TokenDoclist TokenDoclist;
4620 struct TokenDoclist {
4621   int bIgnore;
4622   sqlite3_int64 iDocid;
4623   char *pList;
4624   int nList;
4625 };
4626 
4627 /*
4628 ** Token pToken is an incrementally loaded token that is part of a
4629 ** multi-token phrase. Advance it to the next matching document in the
4630 ** database and populate output variable *p with the details of the new
4631 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
4632 **
4633 ** If an error occurs, return an SQLite error code. Otherwise, return
4634 ** SQLITE_OK.
4635 */
incrPhraseTokenNext(Fts3Table * pTab,Fts3Phrase * pPhrase,int iToken,TokenDoclist * p,u8 * pbEof)4636 static int incrPhraseTokenNext(
4637   Fts3Table *pTab,                /* Virtual table handle */
4638   Fts3Phrase *pPhrase,            /* Phrase to advance token of */
4639   int iToken,                     /* Specific token to advance */
4640   TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
4641   u8 *pbEof                       /* OUT: True if iterator is at EOF */
4642 ){
4643   int rc = SQLITE_OK;
4644 
4645   if( pPhrase->iDoclistToken==iToken ){
4646     assert( p->bIgnore==0 );
4647     assert( pPhrase->aToken[iToken].pSegcsr==0 );
4648     fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
4649     p->pList = pPhrase->doclist.pList;
4650     p->nList = pPhrase->doclist.nList;
4651     p->iDocid = pPhrase->doclist.iDocid;
4652   }else{
4653     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
4654     assert( pToken->pDeferred==0 );
4655     assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
4656     if( pToken->pSegcsr ){
4657       assert( p->bIgnore==0 );
4658       rc = sqlite3Fts3MsrIncrNext(
4659           pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
4660       );
4661       if( p->pList==0 ) *pbEof = 1;
4662     }else{
4663       p->bIgnore = 1;
4664     }
4665   }
4666 
4667   return rc;
4668 }
4669 
4670 
4671 /*
4672 ** The phrase iterator passed as the second argument:
4673 **
4674 **   * features at least one token that uses an incremental doclist, and
4675 **
4676 **   * does not contain any deferred tokens.
4677 **
4678 ** Advance it to the next matching documnent in the database and populate
4679 ** the Fts3Doclist.pList and nList fields.
4680 **
4681 ** If there is no "next" entry and no error occurs, then *pbEof is set to
4682 ** 1 before returning. Otherwise, if no error occurs and the iterator is
4683 ** successfully advanced, *pbEof is set to 0.
4684 **
4685 ** If an error occurs, return an SQLite error code. Otherwise, return
4686 ** SQLITE_OK.
4687 */
fts3EvalIncrPhraseNext(Fts3Cursor * pCsr,Fts3Phrase * p,u8 * pbEof)4688 static int fts3EvalIncrPhraseNext(
4689   Fts3Cursor *pCsr,               /* FTS Cursor handle */
4690   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
4691   u8 *pbEof                       /* OUT: Set to 1 if EOF */
4692 ){
4693   int rc = SQLITE_OK;
4694   Fts3Doclist *pDL = &p->doclist;
4695   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
4696   u8 bEof = 0;
4697 
4698   /* This is only called if it is guaranteed that the phrase has at least
4699   ** one incremental token. In which case the bIncr flag is set. */
4700   assert( p->bIncr==1 );
4701 
4702   if( p->nToken==1 ){
4703     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
4704         &pDL->iDocid, &pDL->pList, &pDL->nList
4705     );
4706     if( pDL->pList==0 ) bEof = 1;
4707   }else{
4708     int bDescDoclist = pCsr->bDesc;
4709     struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
4710 
4711     memset(a, 0, sizeof(a));
4712     assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
4713     assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
4714 
4715     while( bEof==0 ){
4716       int bMaxSet = 0;
4717       sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
4718       int i;                      /* Used to iterate through tokens */
4719 
4720       /* Advance the iterator for each token in the phrase once. */
4721       for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
4722         rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
4723         if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
4724           iMax = a[i].iDocid;
4725           bMaxSet = 1;
4726         }
4727       }
4728       assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
4729       assert( rc!=SQLITE_OK || bMaxSet );
4730 
4731       /* Keep advancing iterators until they all point to the same document */
4732       for(i=0; i<p->nToken; i++){
4733         while( rc==SQLITE_OK && bEof==0
4734             && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
4735         ){
4736           rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
4737           if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
4738             iMax = a[i].iDocid;
4739             i = 0;
4740           }
4741         }
4742       }
4743 
4744       /* Check if the current entries really are a phrase match */
4745       if( bEof==0 ){
4746         int nList = 0;
4747         int nByte = a[p->nToken-1].nList;
4748         char *aDoclist = sqlite3_malloc64((i64)nByte+FTS3_BUFFER_PADDING);
4749         if( !aDoclist ) return SQLITE_NOMEM;
4750         memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
4751         memset(&aDoclist[nByte], 0, FTS3_BUFFER_PADDING);
4752 
4753         for(i=0; i<(p->nToken-1); i++){
4754           if( a[i].bIgnore==0 ){
4755             char *pL = a[i].pList;
4756             char *pR = aDoclist;
4757             char *pOut = aDoclist;
4758             int nDist = p->nToken-1-i;
4759             int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
4760             if( res==0 ) break;
4761             nList = (int)(pOut - aDoclist);
4762           }
4763         }
4764         if( i==(p->nToken-1) ){
4765           pDL->iDocid = iMax;
4766           pDL->pList = aDoclist;
4767           pDL->nList = nList;
4768           pDL->bFreeList = 1;
4769           break;
4770         }
4771         sqlite3_free(aDoclist);
4772       }
4773     }
4774   }
4775 
4776   *pbEof = bEof;
4777   return rc;
4778 }
4779 
4780 /*
4781 ** Attempt to move the phrase iterator to point to the next matching docid.
4782 ** If an error occurs, return an SQLite error code. Otherwise, return
4783 ** SQLITE_OK.
4784 **
4785 ** If there is no "next" entry and no error occurs, then *pbEof is set to
4786 ** 1 before returning. Otherwise, if no error occurs and the iterator is
4787 ** successfully advanced, *pbEof is set to 0.
4788 */
fts3EvalPhraseNext(Fts3Cursor * pCsr,Fts3Phrase * p,u8 * pbEof)4789 static int fts3EvalPhraseNext(
4790   Fts3Cursor *pCsr,               /* FTS Cursor handle */
4791   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
4792   u8 *pbEof                       /* OUT: Set to 1 if EOF */
4793 ){
4794   int rc = SQLITE_OK;
4795   Fts3Doclist *pDL = &p->doclist;
4796   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
4797 
4798   if( p->bIncr ){
4799     rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
4800   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
4801     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
4802         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
4803     );
4804     pDL->pList = pDL->pNextDocid;
4805   }else{
4806     fts3EvalDlPhraseNext(pTab, pDL, pbEof);
4807   }
4808 
4809   return rc;
4810 }
4811 
4812 /*
4813 **
4814 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
4815 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
4816 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
4817 ** expressions for which all descendent tokens are deferred.
4818 **
4819 ** If parameter bOptOk is zero, then it is guaranteed that the
4820 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
4821 ** each phrase in the expression (subject to deferred token processing).
4822 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
4823 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
4824 **
4825 ** If an error occurs within this function, *pRc is set to an SQLite error
4826 ** code before returning.
4827 */
fts3EvalStartReaders(Fts3Cursor * pCsr,Fts3Expr * pExpr,int * pRc)4828 static void fts3EvalStartReaders(
4829   Fts3Cursor *pCsr,               /* FTS Cursor handle */
4830   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
4831   int *pRc                        /* IN/OUT: Error code */
4832 ){
4833   if( pExpr && SQLITE_OK==*pRc ){
4834     if( pExpr->eType==FTSQUERY_PHRASE ){
4835       int nToken = pExpr->pPhrase->nToken;
4836       if( nToken ){
4837         int i;
4838         for(i=0; i<nToken; i++){
4839           if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
4840         }
4841         pExpr->bDeferred = (i==nToken);
4842       }
4843       *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
4844     }else{
4845       fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
4846       fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
4847       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
4848     }
4849   }
4850 }
4851 
4852 /*
4853 ** An array of the following structures is assembled as part of the process
4854 ** of selecting tokens to defer before the query starts executing (as part
4855 ** of the xFilter() method). There is one element in the array for each
4856 ** token in the FTS expression.
4857 **
4858 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
4859 ** to phrases that are connected only by AND and NEAR operators (not OR or
4860 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
4861 ** separately. The root of a tokens AND/NEAR cluster is stored in
4862 ** Fts3TokenAndCost.pRoot.
4863 */
4864 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
4865 struct Fts3TokenAndCost {
4866   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
4867   int iToken;                     /* Position of token in phrase */
4868   Fts3PhraseToken *pToken;        /* The token itself */
4869   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
4870   int nOvfl;                      /* Number of overflow pages to load doclist */
4871   int iCol;                       /* The column the token must match */
4872 };
4873 
4874 /*
4875 ** This function is used to populate an allocated Fts3TokenAndCost array.
4876 **
4877 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
4878 ** Otherwise, if an error occurs during execution, *pRc is set to an
4879 ** SQLite error code.
4880 */
fts3EvalTokenCosts(Fts3Cursor * pCsr,Fts3Expr * pRoot,Fts3Expr * pExpr,Fts3TokenAndCost ** ppTC,Fts3Expr *** ppOr,int * pRc)4881 static void fts3EvalTokenCosts(
4882   Fts3Cursor *pCsr,               /* FTS Cursor handle */
4883   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
4884   Fts3Expr *pExpr,                /* Expression to consider */
4885   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
4886   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
4887   int *pRc                        /* IN/OUT: Error code */
4888 ){
4889   if( *pRc==SQLITE_OK ){
4890     if( pExpr->eType==FTSQUERY_PHRASE ){
4891       Fts3Phrase *pPhrase = pExpr->pPhrase;
4892       int i;
4893       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
4894         Fts3TokenAndCost *pTC = (*ppTC)++;
4895         pTC->pPhrase = pPhrase;
4896         pTC->iToken = i;
4897         pTC->pRoot = pRoot;
4898         pTC->pToken = &pPhrase->aToken[i];
4899         pTC->iCol = pPhrase->iColumn;
4900         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
4901       }
4902     }else if( pExpr->eType!=FTSQUERY_NOT ){
4903       assert( pExpr->eType==FTSQUERY_OR
4904            || pExpr->eType==FTSQUERY_AND
4905            || pExpr->eType==FTSQUERY_NEAR
4906       );
4907       assert( pExpr->pLeft && pExpr->pRight );
4908       if( pExpr->eType==FTSQUERY_OR ){
4909         pRoot = pExpr->pLeft;
4910         **ppOr = pRoot;
4911         (*ppOr)++;
4912       }
4913       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
4914       if( pExpr->eType==FTSQUERY_OR ){
4915         pRoot = pExpr->pRight;
4916         **ppOr = pRoot;
4917         (*ppOr)++;
4918       }
4919       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
4920     }
4921   }
4922 }
4923 
4924 /*
4925 ** Determine the average document (row) size in pages. If successful,
4926 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
4927 ** an SQLite error code.
4928 **
4929 ** The average document size in pages is calculated by first calculating
4930 ** determining the average size in bytes, B. If B is less than the amount
4931 ** of data that will fit on a single leaf page of an intkey table in
4932 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
4933 ** the number of overflow pages consumed by a record B bytes in size.
4934 */
fts3EvalAverageDocsize(Fts3Cursor * pCsr,int * pnPage)4935 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
4936   int rc = SQLITE_OK;
4937   if( pCsr->nRowAvg==0 ){
4938     /* The average document size, which is required to calculate the cost
4939     ** of each doclist, has not yet been determined. Read the required
4940     ** data from the %_stat table to calculate it.
4941     **
4942     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
4943     ** varints, where nCol is the number of columns in the FTS3 table.
4944     ** The first varint is the number of documents currently stored in
4945     ** the table. The following nCol varints contain the total amount of
4946     ** data stored in all rows of each column of the table, from left
4947     ** to right.
4948     */
4949     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
4950     sqlite3_stmt *pStmt;
4951     sqlite3_int64 nDoc = 0;
4952     sqlite3_int64 nByte = 0;
4953     const char *pEnd;
4954     const char *a;
4955 
4956     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
4957     if( rc!=SQLITE_OK ) return rc;
4958     a = sqlite3_column_blob(pStmt, 0);
4959     testcase( a==0 );  /* If %_stat.value set to X'' */
4960     if( a ){
4961       pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
4962       a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc);
4963       while( a<pEnd ){
4964         a += sqlite3Fts3GetVarintBounded(a, pEnd, &nByte);
4965       }
4966     }
4967     if( nDoc==0 || nByte==0 ){
4968       sqlite3_reset(pStmt);
4969       return FTS_CORRUPT_VTAB;
4970     }
4971 
4972     pCsr->nDoc = nDoc;
4973     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
4974     assert( pCsr->nRowAvg>0 );
4975     rc = sqlite3_reset(pStmt);
4976   }
4977 
4978   *pnPage = pCsr->nRowAvg;
4979   return rc;
4980 }
4981 
4982 /*
4983 ** This function is called to select the tokens (if any) that will be
4984 ** deferred. The array aTC[] has already been populated when this is
4985 ** called.
4986 **
4987 ** This function is called once for each AND/NEAR cluster in the
4988 ** expression. Each invocation determines which tokens to defer within
4989 ** the cluster with root node pRoot. See comments above the definition
4990 ** of struct Fts3TokenAndCost for more details.
4991 **
4992 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
4993 ** called on each token to defer. Otherwise, an SQLite error code is
4994 ** returned.
4995 */
fts3EvalSelectDeferred(Fts3Cursor * pCsr,Fts3Expr * pRoot,Fts3TokenAndCost * aTC,int nTC)4996 static int fts3EvalSelectDeferred(
4997   Fts3Cursor *pCsr,               /* FTS Cursor handle */
4998   Fts3Expr *pRoot,                /* Consider tokens with this root node */
4999   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
5000   int nTC                         /* Number of entries in aTC[] */
5001 ){
5002   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
5003   int nDocSize = 0;               /* Number of pages per doc loaded */
5004   int rc = SQLITE_OK;             /* Return code */
5005   int ii;                         /* Iterator variable for various purposes */
5006   int nOvfl = 0;                  /* Total overflow pages used by doclists */
5007   int nToken = 0;                 /* Total number of tokens in cluster */
5008 
5009   int nMinEst = 0;                /* The minimum count for any phrase so far. */
5010   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
5011 
5012   /* Tokens are never deferred for FTS tables created using the content=xxx
5013   ** option. The reason being that it is not guaranteed that the content
5014   ** table actually contains the same data as the index. To prevent this from
5015   ** causing any problems, the deferred token optimization is completely
5016   ** disabled for content=xxx tables. */
5017   if( pTab->zContentTbl ){
5018     return SQLITE_OK;
5019   }
5020 
5021   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
5022   ** associated with the tokens spill onto overflow pages, or if there is
5023   ** only 1 token, exit early. No tokens to defer in this case. */
5024   for(ii=0; ii<nTC; ii++){
5025     if( aTC[ii].pRoot==pRoot ){
5026       nOvfl += aTC[ii].nOvfl;
5027       nToken++;
5028     }
5029   }
5030   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
5031 
5032   /* Obtain the average docsize (in pages). */
5033   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
5034   assert( rc!=SQLITE_OK || nDocSize>0 );
5035 
5036 
5037   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
5038   ** of the number of overflow pages that will be loaded by the pager layer
5039   ** to retrieve the entire doclist for the token from the full-text index.
5040   ** Load the doclists for tokens that are either:
5041   **
5042   **   a. The cheapest token in the entire query (i.e. the one visited by the
5043   **      first iteration of this loop), or
5044   **
5045   **   b. Part of a multi-token phrase.
5046   **
5047   ** After each token doclist is loaded, merge it with the others from the
5048   ** same phrase and count the number of documents that the merged doclist
5049   ** contains. Set variable "nMinEst" to the smallest number of documents in
5050   ** any phrase doclist for which 1 or more token doclists have been loaded.
5051   ** Let nOther be the number of other phrases for which it is certain that
5052   ** one or more tokens will not be deferred.
5053   **
5054   ** Then, for each token, defer it if loading the doclist would result in
5055   ** loading N or more overflow pages into memory, where N is computed as:
5056   **
5057   **    (nMinEst + 4^nOther - 1) / (4^nOther)
5058   */
5059   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
5060     int iTC;                      /* Used to iterate through aTC[] array. */
5061     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
5062 
5063     /* Set pTC to point to the cheapest remaining token. */
5064     for(iTC=0; iTC<nTC; iTC++){
5065       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
5066        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
5067       ){
5068         pTC = &aTC[iTC];
5069       }
5070     }
5071     assert( pTC );
5072 
5073     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
5074       /* The number of overflow pages to load for this (and therefore all
5075       ** subsequent) tokens is greater than the estimated number of pages
5076       ** that will be loaded if all subsequent tokens are deferred.
5077       */
5078       Fts3PhraseToken *pToken = pTC->pToken;
5079       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
5080       fts3SegReaderCursorFree(pToken->pSegcsr);
5081       pToken->pSegcsr = 0;
5082     }else{
5083       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
5084       ** for-loop. Except, limit the value to 2^24 to prevent it from
5085       ** overflowing the 32-bit integer it is stored in. */
5086       if( ii<12 ) nLoad4 = nLoad4*4;
5087 
5088       if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
5089         /* Either this is the cheapest token in the entire query, or it is
5090         ** part of a multi-token phrase. Either way, the entire doclist will
5091         ** (eventually) be loaded into memory. It may as well be now. */
5092         Fts3PhraseToken *pToken = pTC->pToken;
5093         int nList = 0;
5094         char *pList = 0;
5095         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
5096         assert( rc==SQLITE_OK || pList==0 );
5097         if( rc==SQLITE_OK ){
5098           rc = fts3EvalPhraseMergeToken(
5099               pTab, pTC->pPhrase, pTC->iToken,pList,nList
5100           );
5101         }
5102         if( rc==SQLITE_OK ){
5103           int nCount;
5104           nCount = fts3DoclistCountDocids(
5105               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
5106           );
5107           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
5108         }
5109       }
5110     }
5111     pTC->pToken = 0;
5112   }
5113 
5114   return rc;
5115 }
5116 
5117 /*
5118 ** This function is called from within the xFilter method. It initializes
5119 ** the full-text query currently stored in pCsr->pExpr. To iterate through
5120 ** the results of a query, the caller does:
5121 **
5122 **    fts3EvalStart(pCsr);
5123 **    while( 1 ){
5124 **      fts3EvalNext(pCsr);
5125 **      if( pCsr->bEof ) break;
5126 **      ... return row pCsr->iPrevId to the caller ...
5127 **    }
5128 */
fts3EvalStart(Fts3Cursor * pCsr)5129 static int fts3EvalStart(Fts3Cursor *pCsr){
5130   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
5131   int rc = SQLITE_OK;
5132   int nToken = 0;
5133   int nOr = 0;
5134 
5135   /* Allocate a MultiSegReader for each token in the expression. */
5136   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
5137 
5138   /* Determine which, if any, tokens in the expression should be deferred. */
5139 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
5140   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
5141     Fts3TokenAndCost *aTC;
5142     aTC = (Fts3TokenAndCost *)sqlite3_malloc64(
5143         sizeof(Fts3TokenAndCost) * nToken
5144       + sizeof(Fts3Expr *) * nOr * 2
5145     );
5146 
5147     if( !aTC ){
5148       rc = SQLITE_NOMEM;
5149     }else{
5150       Fts3Expr **apOr = (Fts3Expr **)&aTC[nToken];
5151       int ii;
5152       Fts3TokenAndCost *pTC = aTC;
5153       Fts3Expr **ppOr = apOr;
5154 
5155       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
5156       nToken = (int)(pTC-aTC);
5157       nOr = (int)(ppOr-apOr);
5158 
5159       if( rc==SQLITE_OK ){
5160         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
5161         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
5162           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
5163         }
5164       }
5165 
5166       sqlite3_free(aTC);
5167     }
5168   }
5169 #endif
5170 
5171   fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
5172   return rc;
5173 }
5174 
5175 /*
5176 ** Invalidate the current position list for phrase pPhrase.
5177 */
fts3EvalInvalidatePoslist(Fts3Phrase * pPhrase)5178 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
5179   if( pPhrase->doclist.bFreeList ){
5180     sqlite3_free(pPhrase->doclist.pList);
5181   }
5182   pPhrase->doclist.pList = 0;
5183   pPhrase->doclist.nList = 0;
5184   pPhrase->doclist.bFreeList = 0;
5185 }
5186 
5187 /*
5188 ** This function is called to edit the position list associated with
5189 ** the phrase object passed as the fifth argument according to a NEAR
5190 ** condition. For example:
5191 **
5192 **     abc NEAR/5 "def ghi"
5193 **
5194 ** Parameter nNear is passed the NEAR distance of the expression (5 in
5195 ** the example above). When this function is called, *paPoslist points to
5196 ** the position list, and *pnToken is the number of phrase tokens in the
5197 ** phrase on the other side of the NEAR operator to pPhrase. For example,
5198 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
5199 ** the position list associated with phrase "abc".
5200 **
5201 ** All positions in the pPhrase position list that are not sufficiently
5202 ** close to a position in the *paPoslist position list are removed. If this
5203 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
5204 **
5205 ** Before returning, *paPoslist is set to point to the position lsit
5206 ** associated with pPhrase. And *pnToken is set to the number of tokens in
5207 ** pPhrase.
5208 */
fts3EvalNearTrim(int nNear,char * aTmp,char ** paPoslist,int * pnToken,Fts3Phrase * pPhrase)5209 static int fts3EvalNearTrim(
5210   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
5211   char *aTmp,                     /* Temporary space to use */
5212   char **paPoslist,               /* IN/OUT: Position list */
5213   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
5214   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
5215 ){
5216   int nParam1 = nNear + pPhrase->nToken;
5217   int nParam2 = nNear + *pnToken;
5218   int nNew;
5219   char *p2;
5220   char *pOut;
5221   int res;
5222 
5223   assert( pPhrase->doclist.pList );
5224 
5225   p2 = pOut = pPhrase->doclist.pList;
5226   res = fts3PoslistNearMerge(
5227     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
5228   );
5229   if( res ){
5230     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
5231     assert_fts3_nc( nNew<=pPhrase->doclist.nList && nNew>0 );
5232     if( nNew>=0 && nNew<=pPhrase->doclist.nList ){
5233       assert( pPhrase->doclist.pList[nNew]=='\0' );
5234       memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
5235       pPhrase->doclist.nList = nNew;
5236     }
5237     *paPoslist = pPhrase->doclist.pList;
5238     *pnToken = pPhrase->nToken;
5239   }
5240 
5241   return res;
5242 }
5243 
5244 /*
5245 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
5246 ** Otherwise, it advances the expression passed as the second argument to
5247 ** point to the next matching row in the database. Expressions iterate through
5248 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
5249 ** or descending if it is non-zero.
5250 **
5251 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
5252 ** successful, the following variables in pExpr are set:
5253 **
5254 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
5255 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
5256 **
5257 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
5258 ** at EOF, then the following variables are populated with the position list
5259 ** for the phrase for the visited row:
5260 **
5261 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
5262 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
5263 **
5264 ** It says above that this function advances the expression to the next
5265 ** matching row. This is usually true, but there are the following exceptions:
5266 **
5267 **   1. Deferred tokens are not taken into account. If a phrase consists
5268 **      entirely of deferred tokens, it is assumed to match every row in
5269 **      the db. In this case the position-list is not populated at all.
5270 **
5271 **      Or, if a phrase contains one or more deferred tokens and one or
5272 **      more non-deferred tokens, then the expression is advanced to the
5273 **      next possible match, considering only non-deferred tokens. In other
5274 **      words, if the phrase is "A B C", and "B" is deferred, the expression
5275 **      is advanced to the next row that contains an instance of "A * C",
5276 **      where "*" may match any single token. The position list in this case
5277 **      is populated as for "A * C" before returning.
5278 **
5279 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
5280 **      advanced to point to the next row that matches "x AND y".
5281 **
5282 ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
5283 ** really a match, taking into account deferred tokens and NEAR operators.
5284 */
fts3EvalNextRow(Fts3Cursor * pCsr,Fts3Expr * pExpr,int * pRc)5285 static void fts3EvalNextRow(
5286   Fts3Cursor *pCsr,               /* FTS Cursor handle */
5287   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
5288   int *pRc                        /* IN/OUT: Error code */
5289 ){
5290   if( *pRc==SQLITE_OK ){
5291     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
5292     assert( pExpr->bEof==0 );
5293     pExpr->bStart = 1;
5294 
5295     switch( pExpr->eType ){
5296       case FTSQUERY_NEAR:
5297       case FTSQUERY_AND: {
5298         Fts3Expr *pLeft = pExpr->pLeft;
5299         Fts3Expr *pRight = pExpr->pRight;
5300         assert( !pLeft->bDeferred || !pRight->bDeferred );
5301 
5302         if( pLeft->bDeferred ){
5303           /* LHS is entirely deferred. So we assume it matches every row.
5304           ** Advance the RHS iterator to find the next row visited. */
5305           fts3EvalNextRow(pCsr, pRight, pRc);
5306           pExpr->iDocid = pRight->iDocid;
5307           pExpr->bEof = pRight->bEof;
5308         }else if( pRight->bDeferred ){
5309           /* RHS is entirely deferred. So we assume it matches every row.
5310           ** Advance the LHS iterator to find the next row visited. */
5311           fts3EvalNextRow(pCsr, pLeft, pRc);
5312           pExpr->iDocid = pLeft->iDocid;
5313           pExpr->bEof = pLeft->bEof;
5314         }else{
5315           /* Neither the RHS or LHS are deferred. */
5316           fts3EvalNextRow(pCsr, pLeft, pRc);
5317           fts3EvalNextRow(pCsr, pRight, pRc);
5318           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
5319             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
5320             if( iDiff==0 ) break;
5321             if( iDiff<0 ){
5322               fts3EvalNextRow(pCsr, pLeft, pRc);
5323             }else{
5324               fts3EvalNextRow(pCsr, pRight, pRc);
5325             }
5326           }
5327           pExpr->iDocid = pLeft->iDocid;
5328           pExpr->bEof = (pLeft->bEof || pRight->bEof);
5329           if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
5330             assert( pRight->eType==FTSQUERY_PHRASE );
5331             if( pRight->pPhrase->doclist.aAll ){
5332               Fts3Doclist *pDl = &pRight->pPhrase->doclist;
5333               while( *pRc==SQLITE_OK && pRight->bEof==0 ){
5334                 memset(pDl->pList, 0, pDl->nList);
5335                 fts3EvalNextRow(pCsr, pRight, pRc);
5336               }
5337             }
5338             if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
5339               Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
5340               while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
5341                 memset(pDl->pList, 0, pDl->nList);
5342                 fts3EvalNextRow(pCsr, pLeft, pRc);
5343               }
5344             }
5345             pRight->bEof = pLeft->bEof = 1;
5346           }
5347         }
5348         break;
5349       }
5350 
5351       case FTSQUERY_OR: {
5352         Fts3Expr *pLeft = pExpr->pLeft;
5353         Fts3Expr *pRight = pExpr->pRight;
5354         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
5355 
5356         assert_fts3_nc( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
5357         assert_fts3_nc( pRight->bStart || pLeft->iDocid==pRight->iDocid );
5358 
5359         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
5360           fts3EvalNextRow(pCsr, pLeft, pRc);
5361         }else if( pLeft->bEof || iCmp>0 ){
5362           fts3EvalNextRow(pCsr, pRight, pRc);
5363         }else{
5364           fts3EvalNextRow(pCsr, pLeft, pRc);
5365           fts3EvalNextRow(pCsr, pRight, pRc);
5366         }
5367 
5368         pExpr->bEof = (pLeft->bEof && pRight->bEof);
5369         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
5370         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
5371           pExpr->iDocid = pLeft->iDocid;
5372         }else{
5373           pExpr->iDocid = pRight->iDocid;
5374         }
5375 
5376         break;
5377       }
5378 
5379       case FTSQUERY_NOT: {
5380         Fts3Expr *pLeft = pExpr->pLeft;
5381         Fts3Expr *pRight = pExpr->pRight;
5382 
5383         if( pRight->bStart==0 ){
5384           fts3EvalNextRow(pCsr, pRight, pRc);
5385           assert( *pRc!=SQLITE_OK || pRight->bStart );
5386         }
5387 
5388         fts3EvalNextRow(pCsr, pLeft, pRc);
5389         if( pLeft->bEof==0 ){
5390           while( !*pRc
5391               && !pRight->bEof
5392               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
5393           ){
5394             fts3EvalNextRow(pCsr, pRight, pRc);
5395           }
5396         }
5397         pExpr->iDocid = pLeft->iDocid;
5398         pExpr->bEof = pLeft->bEof;
5399         break;
5400       }
5401 
5402       default: {
5403         Fts3Phrase *pPhrase = pExpr->pPhrase;
5404         fts3EvalInvalidatePoslist(pPhrase);
5405         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
5406         pExpr->iDocid = pPhrase->doclist.iDocid;
5407         break;
5408       }
5409     }
5410   }
5411 }
5412 
5413 /*
5414 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
5415 ** cluster, then this function returns 1 immediately.
5416 **
5417 ** Otherwise, it checks if the current row really does match the NEAR
5418 ** expression, using the data currently stored in the position lists
5419 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
5420 **
5421 ** If the current row is a match, the position list associated with each
5422 ** phrase in the NEAR expression is edited in place to contain only those
5423 ** phrase instances sufficiently close to their peers to satisfy all NEAR
5424 ** constraints. In this case it returns 1. If the NEAR expression does not
5425 ** match the current row, 0 is returned. The position lists may or may not
5426 ** be edited if 0 is returned.
5427 */
fts3EvalNearTest(Fts3Expr * pExpr,int * pRc)5428 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
5429   int res = 1;
5430 
5431   /* The following block runs if pExpr is the root of a NEAR query.
5432   ** For example, the query:
5433   **
5434   **         "w" NEAR "x" NEAR "y" NEAR "z"
5435   **
5436   ** which is represented in tree form as:
5437   **
5438   **                               |
5439   **                          +--NEAR--+      <-- root of NEAR query
5440   **                          |        |
5441   **                     +--NEAR--+   "z"
5442   **                     |        |
5443   **                +--NEAR--+   "y"
5444   **                |        |
5445   **               "w"      "x"
5446   **
5447   ** The right-hand child of a NEAR node is always a phrase. The
5448   ** left-hand child may be either a phrase or a NEAR node. There are
5449   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
5450   */
5451   if( *pRc==SQLITE_OK
5452    && pExpr->eType==FTSQUERY_NEAR
5453    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
5454   ){
5455     Fts3Expr *p;
5456     sqlite3_int64 nTmp = 0;       /* Bytes of temp space */
5457     char *aTmp;                   /* Temp space for PoslistNearMerge() */
5458 
5459     /* Allocate temporary working space. */
5460     for(p=pExpr; p->pLeft; p=p->pLeft){
5461       assert( p->pRight->pPhrase->doclist.nList>0 );
5462       nTmp += p->pRight->pPhrase->doclist.nList;
5463     }
5464     nTmp += p->pPhrase->doclist.nList;
5465     aTmp = sqlite3_malloc64(nTmp*2);
5466     if( !aTmp ){
5467       *pRc = SQLITE_NOMEM;
5468       res = 0;
5469     }else{
5470       char *aPoslist = p->pPhrase->doclist.pList;
5471       int nToken = p->pPhrase->nToken;
5472 
5473       for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
5474         Fts3Phrase *pPhrase = p->pRight->pPhrase;
5475         int nNear = p->nNear;
5476         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
5477       }
5478 
5479       aPoslist = pExpr->pRight->pPhrase->doclist.pList;
5480       nToken = pExpr->pRight->pPhrase->nToken;
5481       for(p=pExpr->pLeft; p && res; p=p->pLeft){
5482         int nNear;
5483         Fts3Phrase *pPhrase;
5484         assert( p->pParent && p->pParent->pLeft==p );
5485         nNear = p->pParent->nNear;
5486         pPhrase = (
5487             p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
5488         );
5489         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
5490       }
5491     }
5492 
5493     sqlite3_free(aTmp);
5494   }
5495 
5496   return res;
5497 }
5498 
5499 /*
5500 ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
5501 ** Assuming no error occurs or has occurred, It returns non-zero if the
5502 ** expression passed as the second argument matches the row that pCsr
5503 ** currently points to, or zero if it does not.
5504 **
5505 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
5506 ** If an error occurs during execution of this function, *pRc is set to
5507 ** the appropriate SQLite error code. In this case the returned value is
5508 ** undefined.
5509 */
fts3EvalTestExpr(Fts3Cursor * pCsr,Fts3Expr * pExpr,int * pRc)5510 static int fts3EvalTestExpr(
5511   Fts3Cursor *pCsr,               /* FTS cursor handle */
5512   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
5513   int *pRc                        /* IN/OUT: Error code */
5514 ){
5515   int bHit = 1;                   /* Return value */
5516   if( *pRc==SQLITE_OK ){
5517     switch( pExpr->eType ){
5518       case FTSQUERY_NEAR:
5519       case FTSQUERY_AND:
5520         bHit = (
5521             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
5522          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
5523          && fts3EvalNearTest(pExpr, pRc)
5524         );
5525 
5526         /* If the NEAR expression does not match any rows, zero the doclist for
5527         ** all phrases involved in the NEAR. This is because the snippet(),
5528         ** offsets() and matchinfo() functions are not supposed to recognize
5529         ** any instances of phrases that are part of unmatched NEAR queries.
5530         ** For example if this expression:
5531         **
5532         **    ... MATCH 'a OR (b NEAR c)'
5533         **
5534         ** is matched against a row containing:
5535         **
5536         **        'a b d e'
5537         **
5538         ** then any snippet() should ony highlight the "a" term, not the "b"
5539         ** (as "b" is part of a non-matching NEAR clause).
5540         */
5541         if( bHit==0
5542          && pExpr->eType==FTSQUERY_NEAR
5543          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
5544         ){
5545           Fts3Expr *p;
5546           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
5547             if( p->pRight->iDocid==pCsr->iPrevId ){
5548               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
5549             }
5550           }
5551           if( p->iDocid==pCsr->iPrevId ){
5552             fts3EvalInvalidatePoslist(p->pPhrase);
5553           }
5554         }
5555 
5556         break;
5557 
5558       case FTSQUERY_OR: {
5559         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
5560         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
5561         bHit = bHit1 || bHit2;
5562         break;
5563       }
5564 
5565       case FTSQUERY_NOT:
5566         bHit = (
5567             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
5568          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
5569         );
5570         break;
5571 
5572       default: {
5573 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
5574         if( pCsr->pDeferred && (pExpr->bDeferred || (
5575             pExpr->iDocid==pCsr->iPrevId && pExpr->pPhrase->doclist.pList
5576         ))){
5577           Fts3Phrase *pPhrase = pExpr->pPhrase;
5578           if( pExpr->bDeferred ){
5579             fts3EvalInvalidatePoslist(pPhrase);
5580           }
5581           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
5582           bHit = (pPhrase->doclist.pList!=0);
5583           pExpr->iDocid = pCsr->iPrevId;
5584         }else
5585 #endif
5586         {
5587           bHit = (
5588               pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId
5589            && pExpr->pPhrase->doclist.nList>0
5590           );
5591         }
5592         break;
5593       }
5594     }
5595   }
5596   return bHit;
5597 }
5598 
5599 /*
5600 ** This function is called as the second part of each xNext operation when
5601 ** iterating through the results of a full-text query. At this point the
5602 ** cursor points to a row that matches the query expression, with the
5603 ** following caveats:
5604 **
5605 **   * Up until this point, "NEAR" operators in the expression have been
5606 **     treated as "AND".
5607 **
5608 **   * Deferred tokens have not yet been considered.
5609 **
5610 ** If *pRc is not SQLITE_OK when this function is called, it immediately
5611 ** returns 0. Otherwise, it tests whether or not after considering NEAR
5612 ** operators and deferred tokens the current row is still a match for the
5613 ** expression. It returns 1 if both of the following are true:
5614 **
5615 **   1. *pRc is SQLITE_OK when this function returns, and
5616 **
5617 **   2. After scanning the current FTS table row for the deferred tokens,
5618 **      it is determined that the row does *not* match the query.
5619 **
5620 ** Or, if no error occurs and it seems the current row does match the FTS
5621 ** query, return 0.
5622 */
sqlite3Fts3EvalTestDeferred(Fts3Cursor * pCsr,int * pRc)5623 int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
5624   int rc = *pRc;
5625   int bMiss = 0;
5626   if( rc==SQLITE_OK ){
5627 
5628     /* If there are one or more deferred tokens, load the current row into
5629     ** memory and scan it to determine the position list for each deferred
5630     ** token. Then, see if this row is really a match, considering deferred
5631     ** tokens and NEAR operators (neither of which were taken into account
5632     ** earlier, by fts3EvalNextRow()).
5633     */
5634     if( pCsr->pDeferred ){
5635       rc = fts3CursorSeek(0, pCsr);
5636       if( rc==SQLITE_OK ){
5637         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
5638       }
5639     }
5640     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
5641 
5642     /* Free the position-lists accumulated for each deferred token above. */
5643     sqlite3Fts3FreeDeferredDoclists(pCsr);
5644     *pRc = rc;
5645   }
5646   return (rc==SQLITE_OK && bMiss);
5647 }
5648 
5649 /*
5650 ** Advance to the next document that matches the FTS expression in
5651 ** Fts3Cursor.pExpr.
5652 */
fts3EvalNext(Fts3Cursor * pCsr)5653 static int fts3EvalNext(Fts3Cursor *pCsr){
5654   int rc = SQLITE_OK;             /* Return Code */
5655   Fts3Expr *pExpr = pCsr->pExpr;
5656   assert( pCsr->isEof==0 );
5657   if( pExpr==0 ){
5658     pCsr->isEof = 1;
5659   }else{
5660     do {
5661       if( pCsr->isRequireSeek==0 ){
5662         sqlite3_reset(pCsr->pStmt);
5663       }
5664       assert( sqlite3_data_count(pCsr->pStmt)==0 );
5665       fts3EvalNextRow(pCsr, pExpr, &rc);
5666       pCsr->isEof = pExpr->bEof;
5667       pCsr->isRequireSeek = 1;
5668       pCsr->isMatchinfoNeeded = 1;
5669       pCsr->iPrevId = pExpr->iDocid;
5670     }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
5671   }
5672 
5673   /* Check if the cursor is past the end of the docid range specified
5674   ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
5675   if( rc==SQLITE_OK && (
5676         (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
5677      || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
5678   )){
5679     pCsr->isEof = 1;
5680   }
5681 
5682   return rc;
5683 }
5684 
5685 /*
5686 ** Restart interation for expression pExpr so that the next call to
5687 ** fts3EvalNext() visits the first row. Do not allow incremental
5688 ** loading or merging of phrase doclists for this iteration.
5689 **
5690 ** If *pRc is other than SQLITE_OK when this function is called, it is
5691 ** a no-op. If an error occurs within this function, *pRc is set to an
5692 ** SQLite error code before returning.
5693 */
fts3EvalRestart(Fts3Cursor * pCsr,Fts3Expr * pExpr,int * pRc)5694 static void fts3EvalRestart(
5695   Fts3Cursor *pCsr,
5696   Fts3Expr *pExpr,
5697   int *pRc
5698 ){
5699   if( pExpr && *pRc==SQLITE_OK ){
5700     Fts3Phrase *pPhrase = pExpr->pPhrase;
5701 
5702     if( pPhrase ){
5703       fts3EvalInvalidatePoslist(pPhrase);
5704       if( pPhrase->bIncr ){
5705         int i;
5706         for(i=0; i<pPhrase->nToken; i++){
5707           Fts3PhraseToken *pToken = &pPhrase->aToken[i];
5708           assert( pToken->pDeferred==0 );
5709           if( pToken->pSegcsr ){
5710             sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
5711           }
5712         }
5713         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
5714       }
5715       pPhrase->doclist.pNextDocid = 0;
5716       pPhrase->doclist.iDocid = 0;
5717       pPhrase->pOrPoslist = 0;
5718     }
5719 
5720     pExpr->iDocid = 0;
5721     pExpr->bEof = 0;
5722     pExpr->bStart = 0;
5723 
5724     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
5725     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
5726   }
5727 }
5728 
5729 /*
5730 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
5731 ** expression rooted at pExpr, the cursor iterates through all rows matched
5732 ** by pExpr, calling this function for each row. This function increments
5733 ** the values in Fts3Expr.aMI[] according to the position-list currently
5734 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
5735 ** expression nodes.
5736 */
fts3EvalUpdateCounts(Fts3Expr * pExpr,int nCol)5737 static void fts3EvalUpdateCounts(Fts3Expr *pExpr, int nCol){
5738   if( pExpr ){
5739     Fts3Phrase *pPhrase = pExpr->pPhrase;
5740     if( pPhrase && pPhrase->doclist.pList ){
5741       int iCol = 0;
5742       char *p = pPhrase->doclist.pList;
5743 
5744       do{
5745         u8 c = 0;
5746         int iCnt = 0;
5747         while( 0xFE & (*p | c) ){
5748           if( (c&0x80)==0 ) iCnt++;
5749           c = *p++ & 0x80;
5750         }
5751 
5752         /* aMI[iCol*3 + 1] = Number of occurrences
5753         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
5754         */
5755         pExpr->aMI[iCol*3 + 1] += iCnt;
5756         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
5757         if( *p==0x00 ) break;
5758         p++;
5759         p += fts3GetVarint32(p, &iCol);
5760       }while( iCol<nCol );
5761     }
5762 
5763     fts3EvalUpdateCounts(pExpr->pLeft, nCol);
5764     fts3EvalUpdateCounts(pExpr->pRight, nCol);
5765   }
5766 }
5767 
5768 /*
5769 ** Expression pExpr must be of type FTSQUERY_PHRASE.
5770 **
5771 ** If it is not already allocated and populated, this function allocates and
5772 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
5773 ** of a NEAR expression, then it also allocates and populates the same array
5774 ** for all other phrases that are part of the NEAR expression.
5775 **
5776 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
5777 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
5778 */
fts3EvalGatherStats(Fts3Cursor * pCsr,Fts3Expr * pExpr)5779 static int fts3EvalGatherStats(
5780   Fts3Cursor *pCsr,               /* Cursor object */
5781   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
5782 ){
5783   int rc = SQLITE_OK;             /* Return code */
5784 
5785   assert( pExpr->eType==FTSQUERY_PHRASE );
5786   if( pExpr->aMI==0 ){
5787     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
5788     Fts3Expr *pRoot;                /* Root of NEAR expression */
5789     Fts3Expr *p;                    /* Iterator used for several purposes */
5790 
5791     sqlite3_int64 iPrevId = pCsr->iPrevId;
5792     sqlite3_int64 iDocid;
5793     u8 bEof;
5794 
5795     /* Find the root of the NEAR expression */
5796     pRoot = pExpr;
5797     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
5798       pRoot = pRoot->pParent;
5799     }
5800     iDocid = pRoot->iDocid;
5801     bEof = pRoot->bEof;
5802     assert( pRoot->bStart );
5803 
5804     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
5805     for(p=pRoot; p; p=p->pLeft){
5806       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
5807       assert( pE->aMI==0 );
5808       pE->aMI = (u32 *)sqlite3_malloc64(pTab->nColumn * 3 * sizeof(u32));
5809       if( !pE->aMI ) return SQLITE_NOMEM;
5810       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
5811     }
5812 
5813     fts3EvalRestart(pCsr, pRoot, &rc);
5814 
5815     while( pCsr->isEof==0 && rc==SQLITE_OK ){
5816 
5817       do {
5818         /* Ensure the %_content statement is reset. */
5819         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
5820         assert( sqlite3_data_count(pCsr->pStmt)==0 );
5821 
5822         /* Advance to the next document */
5823         fts3EvalNextRow(pCsr, pRoot, &rc);
5824         pCsr->isEof = pRoot->bEof;
5825         pCsr->isRequireSeek = 1;
5826         pCsr->isMatchinfoNeeded = 1;
5827         pCsr->iPrevId = pRoot->iDocid;
5828       }while( pCsr->isEof==0
5829            && pRoot->eType==FTSQUERY_NEAR
5830            && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
5831       );
5832 
5833       if( rc==SQLITE_OK && pCsr->isEof==0 ){
5834         fts3EvalUpdateCounts(pRoot, pTab->nColumn);
5835       }
5836     }
5837 
5838     pCsr->isEof = 0;
5839     pCsr->iPrevId = iPrevId;
5840 
5841     if( bEof ){
5842       pRoot->bEof = bEof;
5843     }else{
5844       /* Caution: pRoot may iterate through docids in ascending or descending
5845       ** order. For this reason, even though it seems more defensive, the
5846       ** do loop can not be written:
5847       **
5848       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
5849       */
5850       fts3EvalRestart(pCsr, pRoot, &rc);
5851       do {
5852         fts3EvalNextRow(pCsr, pRoot, &rc);
5853         assert_fts3_nc( pRoot->bEof==0 );
5854         if( pRoot->bEof ) rc = FTS_CORRUPT_VTAB;
5855       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
5856     }
5857   }
5858   return rc;
5859 }
5860 
5861 /*
5862 ** This function is used by the matchinfo() module to query a phrase
5863 ** expression node for the following information:
5864 **
5865 **   1. The total number of occurrences of the phrase in each column of
5866 **      the FTS table (considering all rows), and
5867 **
5868 **   2. For each column, the number of rows in the table for which the
5869 **      column contains at least one instance of the phrase.
5870 **
5871 ** If no error occurs, SQLITE_OK is returned and the values for each column
5872 ** written into the array aiOut as follows:
5873 **
5874 **   aiOut[iCol*3 + 1] = Number of occurrences
5875 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
5876 **
5877 ** Caveats:
5878 **
5879 **   * If a phrase consists entirely of deferred tokens, then all output
5880 **     values are set to the number of documents in the table. In other
5881 **     words we assume that very common tokens occur exactly once in each
5882 **     column of each row of the table.
5883 **
5884 **   * If a phrase contains some deferred tokens (and some non-deferred
5885 **     tokens), count the potential occurrence identified by considering
5886 **     the non-deferred tokens instead of actual phrase occurrences.
5887 **
5888 **   * If the phrase is part of a NEAR expression, then only phrase instances
5889 **     that meet the NEAR constraint are included in the counts.
5890 */
sqlite3Fts3EvalPhraseStats(Fts3Cursor * pCsr,Fts3Expr * pExpr,u32 * aiOut)5891 int sqlite3Fts3EvalPhraseStats(
5892   Fts3Cursor *pCsr,               /* FTS cursor handle */
5893   Fts3Expr *pExpr,                /* Phrase expression */
5894   u32 *aiOut                      /* Array to write results into (see above) */
5895 ){
5896   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
5897   int rc = SQLITE_OK;
5898   int iCol;
5899 
5900   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
5901     assert( pCsr->nDoc>0 );
5902     for(iCol=0; iCol<pTab->nColumn; iCol++){
5903       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
5904       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
5905     }
5906   }else{
5907     rc = fts3EvalGatherStats(pCsr, pExpr);
5908     if( rc==SQLITE_OK ){
5909       assert( pExpr->aMI );
5910       for(iCol=0; iCol<pTab->nColumn; iCol++){
5911         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
5912         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
5913       }
5914     }
5915   }
5916 
5917   return rc;
5918 }
5919 
5920 /*
5921 ** The expression pExpr passed as the second argument to this function
5922 ** must be of type FTSQUERY_PHRASE.
5923 **
5924 ** The returned value is either NULL or a pointer to a buffer containing
5925 ** a position-list indicating the occurrences of the phrase in column iCol
5926 ** of the current row.
5927 **
5928 ** More specifically, the returned buffer contains 1 varint for each
5929 ** occurrence of the phrase in the column, stored using the normal (delta+2)
5930 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
5931 ** if the requested column contains "a b X c d X X" and the position-list
5932 ** for 'X' is requested, the buffer returned may contain:
5933 **
5934 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
5935 **
5936 ** This function works regardless of whether or not the phrase is deferred,
5937 ** incremental, or neither.
5938 */
sqlite3Fts3EvalPhrasePoslist(Fts3Cursor * pCsr,Fts3Expr * pExpr,int iCol,char ** ppOut)5939 int sqlite3Fts3EvalPhrasePoslist(
5940   Fts3Cursor *pCsr,               /* FTS3 cursor object */
5941   Fts3Expr *pExpr,                /* Phrase to return doclist for */
5942   int iCol,                       /* Column to return position list for */
5943   char **ppOut                    /* OUT: Pointer to position list */
5944 ){
5945   Fts3Phrase *pPhrase = pExpr->pPhrase;
5946   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
5947   char *pIter;
5948   int iThis;
5949   sqlite3_int64 iDocid;
5950 
5951   /* If this phrase is applies specifically to some column other than
5952   ** column iCol, return a NULL pointer.  */
5953   *ppOut = 0;
5954   assert( iCol>=0 && iCol<pTab->nColumn );
5955   if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
5956     return SQLITE_OK;
5957   }
5958 
5959   iDocid = pExpr->iDocid;
5960   pIter = pPhrase->doclist.pList;
5961   if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
5962     int rc = SQLITE_OK;
5963     int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
5964     int bOr = 0;
5965     u8 bTreeEof = 0;
5966     Fts3Expr *p;                  /* Used to iterate from pExpr to root */
5967     Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
5968     int bMatch;
5969 
5970     /* Check if this phrase descends from an OR expression node. If not,
5971     ** return NULL. Otherwise, the entry that corresponds to docid
5972     ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
5973     ** tree that the node is part of has been marked as EOF, but the node
5974     ** itself is not EOF, then it may point to an earlier entry. */
5975     pNear = pExpr;
5976     for(p=pExpr->pParent; p; p=p->pParent){
5977       if( p->eType==FTSQUERY_OR ) bOr = 1;
5978       if( p->eType==FTSQUERY_NEAR ) pNear = p;
5979       if( p->bEof ) bTreeEof = 1;
5980     }
5981     if( bOr==0 ) return SQLITE_OK;
5982 
5983     /* This is the descendent of an OR node. In this case we cannot use
5984     ** an incremental phrase. Load the entire doclist for the phrase
5985     ** into memory in this case.  */
5986     if( pPhrase->bIncr ){
5987       int bEofSave = pNear->bEof;
5988       fts3EvalRestart(pCsr, pNear, &rc);
5989       while( rc==SQLITE_OK && !pNear->bEof ){
5990         fts3EvalNextRow(pCsr, pNear, &rc);
5991         if( bEofSave==0 && pNear->iDocid==iDocid ) break;
5992       }
5993       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
5994       if( rc==SQLITE_OK && pNear->bEof!=bEofSave ){
5995         rc = FTS_CORRUPT_VTAB;
5996       }
5997     }
5998     if( bTreeEof ){
5999       while( rc==SQLITE_OK && !pNear->bEof ){
6000         fts3EvalNextRow(pCsr, pNear, &rc);
6001       }
6002     }
6003     if( rc!=SQLITE_OK ) return rc;
6004 
6005     bMatch = 1;
6006     for(p=pNear; p; p=p->pLeft){
6007       u8 bEof = 0;
6008       Fts3Expr *pTest = p;
6009       Fts3Phrase *pPh;
6010       assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
6011       if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
6012       assert( pTest->eType==FTSQUERY_PHRASE );
6013       pPh = pTest->pPhrase;
6014 
6015       pIter = pPh->pOrPoslist;
6016       iDocid = pPh->iOrDocid;
6017       if( pCsr->bDesc==bDescDoclist ){
6018         bEof = !pPh->doclist.nAll ||
6019           (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
6020         while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
6021           sqlite3Fts3DoclistNext(
6022               bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
6023               &pIter, &iDocid, &bEof
6024           );
6025         }
6026       }else{
6027         bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
6028         while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
6029           int dummy;
6030           sqlite3Fts3DoclistPrev(
6031               bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
6032               &pIter, &iDocid, &dummy, &bEof
6033               );
6034         }
6035       }
6036       pPh->pOrPoslist = pIter;
6037       pPh->iOrDocid = iDocid;
6038       if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
6039     }
6040 
6041     if( bMatch ){
6042       pIter = pPhrase->pOrPoslist;
6043     }else{
6044       pIter = 0;
6045     }
6046   }
6047   if( pIter==0 ) return SQLITE_OK;
6048 
6049   if( *pIter==0x01 ){
6050     pIter++;
6051     pIter += fts3GetVarint32(pIter, &iThis);
6052   }else{
6053     iThis = 0;
6054   }
6055   while( iThis<iCol ){
6056     fts3ColumnlistCopy(0, &pIter);
6057     if( *pIter==0x00 ) return SQLITE_OK;
6058     pIter++;
6059     pIter += fts3GetVarint32(pIter, &iThis);
6060   }
6061   if( *pIter==0x00 ){
6062     pIter = 0;
6063   }
6064 
6065   *ppOut = ((iCol==iThis)?pIter:0);
6066   return SQLITE_OK;
6067 }
6068 
6069 /*
6070 ** Free all components of the Fts3Phrase structure that were allocated by
6071 ** the eval module. Specifically, this means to free:
6072 **
6073 **   * the contents of pPhrase->doclist, and
6074 **   * any Fts3MultiSegReader objects held by phrase tokens.
6075 */
sqlite3Fts3EvalPhraseCleanup(Fts3Phrase * pPhrase)6076 void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
6077   if( pPhrase ){
6078     int i;
6079     sqlite3_free(pPhrase->doclist.aAll);
6080     fts3EvalInvalidatePoslist(pPhrase);
6081     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
6082     for(i=0; i<pPhrase->nToken; i++){
6083       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
6084       pPhrase->aToken[i].pSegcsr = 0;
6085     }
6086   }
6087 }
6088 
6089 
6090 /*
6091 ** Return SQLITE_CORRUPT_VTAB.
6092 */
6093 #ifdef SQLITE_DEBUG
sqlite3Fts3Corrupt()6094 int sqlite3Fts3Corrupt(){
6095   return SQLITE_CORRUPT_VTAB;
6096 }
6097 #endif
6098 
6099 #if !SQLITE_CORE
6100 /*
6101 ** Initialize API pointer table, if required.
6102 */
6103 #ifdef _WIN32
6104 __declspec(dllexport)
6105 #endif
sqlite3_fts3_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)6106 int sqlite3_fts3_init(
6107   sqlite3 *db,
6108   char **pzErrMsg,
6109   const sqlite3_api_routines *pApi
6110 ){
6111   SQLITE_EXTENSION_INIT2(pApi)
6112   return sqlite3Fts3Init(db);
6113 }
6114 #endif
6115 
6116 #endif
6117