Add tests for the new code on this branch.
[sqlite.git] / ext / fts3 / fts3.c
blobf977aabfbcd39ef18d51c10169d38821996c9218
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.
11 ******************************************************************************
13 ** This is an SQLite module implementing full-text search.
17 ** The code in this file is only compiled if:
19 ** * The FTS3 module is being built as an extension
20 ** (in which case SQLITE_CORE is not defined), or
22 ** * The FTS3 module is being built into the core of
23 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
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.
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:
39 ** KEY:
40 ** A = 0xxxxxxx 7 bits of data and one flag bit
41 ** B = 1xxxxxxx 7 bits of data and one flag bit
43 ** 7 bits - A
44 ** 14 bits - BA
45 ** 21 bits - BBA
46 ** and so on.
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).
53 ** Example encodings:
55 ** 1: 0x01
56 ** 127: 0x7f
57 ** 128: 0x81 0x00
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.
67 ** FTS3 used to optionally store character offsets using a compile-time
68 ** option. But that functionality is no longer supported.
70 ** A doclist is stored like this:
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 ** }
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:
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
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.
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.
113 ** A bare doclist omits the position information, becoming an
114 ** array of varint-encoded docids.
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:
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 ** }
137 ** Here, array { X } means zero or more occurrences of X, adjacent in
138 ** memory.
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.
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.
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.
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:
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 ** }
182 ** Here, optional { X } means an optional element, while array { X }
183 ** means zero or more occurrences of X, adjacent in memory.
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).
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.
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.
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).
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
226 ** If the root node is a leaf node, then start_block,
227 ** leaves_end_block, and end_block are all 0.
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.
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.
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.
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.
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:
261 ** MERGE_COUNT segments
262 ** 16 25
263 ** 8 12
264 ** 4 10
265 ** 2 6
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.
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.
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.
291 #include "fts3Int.h"
292 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
294 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
295 # define SQLITE_CORE 1
296 #endif
298 #include <assert.h>
299 #include <stdlib.h>
300 #include <stddef.h>
301 #include <stdio.h>
302 #include <string.h>
303 #include <stdarg.h>
305 #include "fts3.h"
306 #ifndef SQLITE_CORE
307 # include "sqlite3ext.h"
308 SQLITE_EXTENSION_INIT1
309 #endif
311 typedef struct Fts3HashWrapper Fts3HashWrapper;
312 struct Fts3HashWrapper {
313 Fts3Hash hash; /* Hash table */
314 int nRef; /* Number of pointers to this object */
317 static int fts3EvalNext(Fts3Cursor *pCsr);
318 static int fts3EvalStart(Fts3Cursor *pCsr);
319 static int fts3TermSegReaderCursor(
320 Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
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.
328 #ifdef SQLITE_DEBUG
329 int sqlite3_fts3_may_be_corrupt = 1;
330 #endif
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.
337 int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
338 unsigned char *q = (unsigned char *) p;
339 sqlite_uint64 vu = v;
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);
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; }
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;
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 );
369 for(shift=28; shift<=63; shift+=7){
370 u64 c = *p++;
371 b += (c&0x7F) << shift;
372 if( (c & 0x80)==0 ) break;
374 *v = b;
375 return (int)(p - pStart);
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.
383 int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
384 return sqlite3Fts3GetVarintU(pBuf, (sqlite3_uint64*)v);
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.
393 int sqlite3Fts3GetVarintBounded(
394 const char *pBuf,
395 const char *pEnd,
396 sqlite_int64 *v
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;
409 *v = b;
410 return (int)(p - pStart);
414 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
415 ** a non-negative 32-bit integer before it is returned.
417 int sqlite3Fts3GetVarint32(const char *p, int *pi){
418 const unsigned char *ptr = (const unsigned char*)p;
419 u32 a;
421 #ifndef fts3GetVarint32
422 GETVARINT_INIT(a, ptr, 0, 0x00, 0x80, *pi, 1);
423 #else
424 a = (*ptr++);
425 assert( a & 0x80 );
426 #endif
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;
439 ** Return the number of bytes required to encode v as a varint
441 int sqlite3Fts3VarintLen(sqlite3_uint64 v){
442 int i = 0;
444 i++;
445 v >>= 7;
446 }while( v!=0 );
447 return i;
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.
456 ** Examples:
458 ** "abc" becomes abc
459 ** 'xyz' becomes xyz
460 ** [pqr] becomes pqr
461 ** `mno` becomes mno
464 void sqlite3Fts3Dequote(char *z){
465 char quote; /* Quote character (if any ) */
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 */
472 /* If the first byte was a '[', then the close-quote character is a ']' */
473 if( quote=='[' ) quote = ']';
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++];
484 z[iOut] = '\0';
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.
493 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
494 sqlite3_int64 iVal;
495 *pp += sqlite3Fts3GetVarint(*pp, &iVal);
496 *pVal += iVal;
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.
505 ** Argument pStart points to the first byte of the doclist that the
506 ** varint is part of.
508 static void fts3GetReverseVarint(
509 char **pp,
510 char *pStart,
511 sqlite3_int64 *pVal
513 sqlite3_int64 iVal;
514 char *p;
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;
523 sqlite3Fts3GetVarint(p, &iVal);
524 *pVal = iVal;
528 ** The xDisconnect() virtual table method.
530 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
531 Fts3Table *p = (Fts3Table *)pVtab;
532 int i;
534 assert( p->nPendingData==0 );
535 assert( p->pSegments==0 );
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]);
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);
548 /* Invoke the tokenizer destructor to free the tokenizer. */
549 p->pTokenizer->pModule->xDestroy(p->pTokenizer);
551 sqlite3_free(p);
552 return SQLITE_OK;
556 ** Write an error message into *pzErr
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);
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.
571 ** If *pRc is initially non-zero then this routine is a no-op.
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 */
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);
594 ** The xDestroy() virtual table method.
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 */
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
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.
620 return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
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.
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.
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;
641 zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
642 sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
643 sqlite3_vtab_config(p->db, SQLITE_VTAB_INNOCUOUS);
645 /* Create a list of user columns for the virtual table */
646 zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
647 for(i=1; zCols && i<p->nColumn; i++){
648 zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
651 /* Create the whole "CREATE TABLE" statement to pass to SQLite */
652 zSql = sqlite3_mprintf(
653 "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
654 zCols, p->zName, zLanguageid
656 if( !zCols || !zSql ){
657 rc = SQLITE_NOMEM;
658 }else{
659 rc = sqlite3_declare_vtab(p->db, zSql);
662 sqlite3_free(zSql);
663 sqlite3_free(zCols);
664 *pRc = rc;
669 ** Create the %_stat table if it does not already exist.
671 void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
672 fts3DbExec(pRc, p->db,
673 "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
674 "(id INTEGER PRIMARY KEY, value BLOB);",
675 p->zDb, p->zName
677 if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
681 ** Create the backing store tables (%_content, %_segments and %_segdir)
682 ** required by the FTS3 table passed as the only argument. This is done
683 ** as part of the vtab xCreate() method.
685 ** If the p->bHasDocsize boolean is true (indicating that this is an
686 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
687 ** %_stat tables required by FTS4.
689 static int fts3CreateTables(Fts3Table *p){
690 int rc = SQLITE_OK; /* Return code */
691 int i; /* Iterator variable */
692 sqlite3 *db = p->db; /* The database connection */
694 if( p->zContentTbl==0 ){
695 const char *zLanguageid = p->zLanguageid;
696 char *zContentCols; /* Columns of %_content table */
698 /* Create a list of user columns for the content table */
699 zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
700 for(i=0; zContentCols && i<p->nColumn; i++){
701 char *z = p->azColumn[i];
702 zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
704 if( zLanguageid && zContentCols ){
705 zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
707 if( zContentCols==0 ) rc = SQLITE_NOMEM;
709 /* Create the content table */
710 fts3DbExec(&rc, db,
711 "CREATE TABLE %Q.'%q_content'(%s)",
712 p->zDb, p->zName, zContentCols
714 sqlite3_free(zContentCols);
717 /* Create other tables */
718 fts3DbExec(&rc, db,
719 "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
720 p->zDb, p->zName
722 fts3DbExec(&rc, db,
723 "CREATE TABLE %Q.'%q_segdir'("
724 "level INTEGER,"
725 "idx INTEGER,"
726 "start_block INTEGER,"
727 "leaves_end_block INTEGER,"
728 "end_block INTEGER,"
729 "root BLOB,"
730 "PRIMARY KEY(level, idx)"
731 ");",
732 p->zDb, p->zName
734 if( p->bHasDocsize ){
735 fts3DbExec(&rc, db,
736 "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
737 p->zDb, p->zName
740 assert( p->bHasStat==p->bFts4 );
741 if( p->bHasStat ){
742 sqlite3Fts3CreateStatTable(&rc, p);
744 return rc;
748 ** Store the current database page-size in bytes in p->nPgsz.
750 ** If *pRc is non-zero when this function is called, it is a no-op.
751 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
752 ** before returning.
754 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
755 if( *pRc==SQLITE_OK ){
756 int rc; /* Return code */
757 char *zSql; /* SQL text "PRAGMA %Q.page_size" */
758 sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
760 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
761 if( !zSql ){
762 rc = SQLITE_NOMEM;
763 }else{
764 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
765 if( rc==SQLITE_OK ){
766 sqlite3_step(pStmt);
767 p->nPgsz = sqlite3_column_int(pStmt, 0);
768 rc = sqlite3_finalize(pStmt);
769 }else if( rc==SQLITE_AUTH ){
770 p->nPgsz = 1024;
771 rc = SQLITE_OK;
774 assert( p->nPgsz>0 || rc!=SQLITE_OK );
775 sqlite3_free(zSql);
776 *pRc = rc;
781 ** "Special" FTS4 arguments are column specifications of the following form:
783 ** <key> = <value>
785 ** There may not be whitespace surrounding the "=" character. The <value>
786 ** term may be quoted, but the <key> may not.
788 static int fts3IsSpecialColumn(
789 const char *z,
790 int *pnKey,
791 char **pzValue
793 char *zValue;
794 const char *zCsr = z;
796 while( *zCsr!='=' ){
797 if( *zCsr=='\0' ) return 0;
798 zCsr++;
801 *pnKey = (int)(zCsr-z);
802 zValue = sqlite3_mprintf("%s", &zCsr[1]);
803 if( zValue ){
804 sqlite3Fts3Dequote(zValue);
806 *pzValue = zValue;
807 return 1;
811 ** Append the output of a printf() style formatting to an existing string.
813 static void fts3Appendf(
814 int *pRc, /* IN/OUT: Error code */
815 char **pz, /* IN/OUT: Pointer to string buffer */
816 const char *zFormat, /* Printf format string to append */
817 ... /* Arguments for printf format string */
819 if( *pRc==SQLITE_OK ){
820 va_list ap;
821 char *z;
822 va_start(ap, zFormat);
823 z = sqlite3_vmprintf(zFormat, ap);
824 va_end(ap);
825 if( z && *pz ){
826 char *z2 = sqlite3_mprintf("%s%s", *pz, z);
827 sqlite3_free(z);
828 z = z2;
830 if( z==0 ) *pRc = SQLITE_NOMEM;
831 sqlite3_free(*pz);
832 *pz = z;
837 ** Return a copy of input string zInput enclosed in double-quotes (") and
838 ** with all double quote characters escaped. For example:
840 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
842 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
843 ** is the callers responsibility to call sqlite3_free() to release this
844 ** memory.
846 static char *fts3QuoteId(char const *zInput){
847 sqlite3_int64 nRet;
848 char *zRet;
849 nRet = 2 + (int)strlen(zInput)*2 + 1;
850 zRet = sqlite3_malloc64(nRet);
851 if( zRet ){
852 int i;
853 char *z = zRet;
854 *(z++) = '"';
855 for(i=0; zInput[i]; i++){
856 if( zInput[i]=='"' ) *(z++) = '"';
857 *(z++) = zInput[i];
859 *(z++) = '"';
860 *(z++) = '\0';
862 return zRet;
866 ** Return a list of comma separated SQL expressions and a FROM clause that
867 ** could be used in a SELECT statement such as the following:
869 ** SELECT <list of expressions> FROM %_content AS x ...
871 ** to return the docid, followed by each column of text data in order
872 ** from left to write. If parameter zFunc is not NULL, then instead of
873 ** being returned directly each column of text data is passed to an SQL
874 ** function named zFunc first. For example, if zFunc is "unzip" and the
875 ** table has the three user-defined columns "a", "b", and "c", the following
876 ** string is returned:
878 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
880 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
881 ** is the responsibility of the caller to eventually free it.
883 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
884 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
885 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
886 ** no error occurs, *pRc is left unmodified.
888 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
889 char *zRet = 0;
890 char *zFree = 0;
891 char *zFunction;
892 int i;
894 if( p->zContentTbl==0 ){
895 if( !zFunc ){
896 zFunction = "";
897 }else{
898 zFree = zFunction = fts3QuoteId(zFunc);
900 fts3Appendf(pRc, &zRet, "docid");
901 for(i=0; i<p->nColumn; i++){
902 fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
904 if( p->zLanguageid ){
905 fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
907 sqlite3_free(zFree);
908 }else{
909 fts3Appendf(pRc, &zRet, "rowid");
910 for(i=0; i<p->nColumn; i++){
911 fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
913 if( p->zLanguageid ){
914 fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
917 fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
918 p->zDb,
919 (p->zContentTbl ? p->zContentTbl : p->zName),
920 (p->zContentTbl ? "" : "_content")
922 return zRet;
926 ** Return a list of N comma separated question marks, where N is the number
927 ** of columns in the %_content table (one for the docid plus one for each
928 ** user-defined text column).
930 ** If argument zFunc is not NULL, then all but the first question mark
931 ** is preceded by zFunc and an open bracket, and followed by a closed
932 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
933 ** user-defined text columns, the following string is returned:
935 ** "?, zip(?), zip(?), zip(?)"
937 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
938 ** is the responsibility of the caller to eventually free it.
940 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
941 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
942 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
943 ** no error occurs, *pRc is left unmodified.
945 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
946 char *zRet = 0;
947 char *zFree = 0;
948 char *zFunction;
949 int i;
951 if( !zFunc ){
952 zFunction = "";
953 }else{
954 zFree = zFunction = fts3QuoteId(zFunc);
956 fts3Appendf(pRc, &zRet, "?");
957 for(i=0; i<p->nColumn; i++){
958 fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
960 if( p->zLanguageid ){
961 fts3Appendf(pRc, &zRet, ", ?");
963 sqlite3_free(zFree);
964 return zRet;
968 ** Buffer z contains a positive integer value encoded as utf-8 text.
969 ** Decode this value and store it in *pnOut, returning the number of bytes
970 ** consumed. If an overflow error occurs return a negative value.
972 int sqlite3Fts3ReadInt(const char *z, int *pnOut){
973 u64 iVal = 0;
974 int i;
975 for(i=0; z[i]>='0' && z[i]<='9'; i++){
976 iVal = iVal*10 + (z[i] - '0');
977 if( iVal>0x7FFFFFFF ) return -1;
979 *pnOut = (int)iVal;
980 return i;
984 ** This function interprets the string at (*pp) as a non-negative integer
985 ** value. It reads the integer and sets *pnOut to the value read, then
986 ** sets *pp to point to the byte immediately following the last byte of
987 ** the integer value.
989 ** Only decimal digits ('0'..'9') may be part of an integer value.
991 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
992 ** the output value undefined. Otherwise SQLITE_OK is returned.
994 ** This function is used when parsing the "prefix=" FTS4 parameter.
996 static int fts3GobbleInt(const char **pp, int *pnOut){
997 const int MAX_NPREFIX = 10000000;
998 int nInt = 0; /* Output value */
999 int nByte;
1000 nByte = sqlite3Fts3ReadInt(*pp, &nInt);
1001 if( nInt>MAX_NPREFIX ){
1002 nInt = 0;
1004 if( nByte==0 ){
1005 return SQLITE_ERROR;
1007 *pnOut = nInt;
1008 *pp += nByte;
1009 return SQLITE_OK;
1013 ** This function is called to allocate an array of Fts3Index structures
1014 ** representing the indexes maintained by the current FTS table. FTS tables
1015 ** always maintain the main "terms" index, but may also maintain one or
1016 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
1017 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
1019 ** Argument zParam is passed the value of the "prefix=" option if one was
1020 ** specified, or NULL otherwise.
1022 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
1023 ** the allocated array. *pnIndex is set to the number of elements in the
1024 ** array. If an error does occur, an SQLite error code is returned.
1026 ** Regardless of whether or not an error is returned, it is the responsibility
1027 ** of the caller to call sqlite3_free() on the output array to free it.
1029 static int fts3PrefixParameter(
1030 const char *zParam, /* ABC in prefix=ABC parameter to parse */
1031 int *pnIndex, /* OUT: size of *apIndex[] array */
1032 struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
1034 struct Fts3Index *aIndex; /* Allocated array */
1035 int nIndex = 1; /* Number of entries in array */
1037 if( zParam && zParam[0] ){
1038 const char *p;
1039 nIndex++;
1040 for(p=zParam; *p; p++){
1041 if( *p==',' ) nIndex++;
1045 aIndex = sqlite3_malloc64(sizeof(struct Fts3Index) * nIndex);
1046 *apIndex = aIndex;
1047 if( !aIndex ){
1048 return SQLITE_NOMEM;
1051 memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
1052 if( zParam ){
1053 const char *p = zParam;
1054 int i;
1055 for(i=1; i<nIndex; i++){
1056 int nPrefix = 0;
1057 if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
1058 assert( nPrefix>=0 );
1059 if( nPrefix==0 ){
1060 nIndex--;
1061 i--;
1062 }else{
1063 aIndex[i].nPrefix = nPrefix;
1065 p++;
1069 *pnIndex = nIndex;
1070 return SQLITE_OK;
1074 ** This function is called when initializing an FTS4 table that uses the
1075 ** content=xxx option. It determines the number of and names of the columns
1076 ** of the new FTS4 table.
1078 ** The third argument passed to this function is the value passed to the
1079 ** config=xxx option (i.e. "xxx"). This function queries the database for
1080 ** a table of that name. If found, the output variables are populated
1081 ** as follows:
1083 ** *pnCol: Set to the number of columns table xxx has,
1085 ** *pnStr: Set to the total amount of space required to store a copy
1086 ** of each columns name, including the nul-terminator.
1088 ** *pazCol: Set to point to an array of *pnCol strings. Each string is
1089 ** the name of the corresponding column in table xxx. The array
1090 ** and its contents are allocated using a single allocation. It
1091 ** is the responsibility of the caller to free this allocation
1092 ** by eventually passing the *pazCol value to sqlite3_free().
1094 ** If the table cannot be found, an error code is returned and the output
1095 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
1096 ** returned (and the output variables are undefined).
1098 static int fts3ContentColumns(
1099 sqlite3 *db, /* Database handle */
1100 const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
1101 const char *zTbl, /* Name of content table */
1102 const char ***pazCol, /* OUT: Malloc'd array of column names */
1103 int *pnCol, /* OUT: Size of array *pazCol */
1104 int *pnStr, /* OUT: Bytes of string content */
1105 char **pzErr /* OUT: error message */
1107 int rc = SQLITE_OK; /* Return code */
1108 char *zSql; /* "SELECT *" statement on zTbl */
1109 sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
1111 zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
1112 if( !zSql ){
1113 rc = SQLITE_NOMEM;
1114 }else{
1115 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1116 if( rc!=SQLITE_OK ){
1117 sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
1120 sqlite3_free(zSql);
1122 if( rc==SQLITE_OK ){
1123 const char **azCol; /* Output array */
1124 sqlite3_int64 nStr = 0; /* Size of all column names (incl. 0x00) */
1125 int nCol; /* Number of table columns */
1126 int i; /* Used to iterate through columns */
1128 /* Loop through the returned columns. Set nStr to the number of bytes of
1129 ** space required to store a copy of each column name, including the
1130 ** nul-terminator byte. */
1131 nCol = sqlite3_column_count(pStmt);
1132 for(i=0; i<nCol; i++){
1133 const char *zCol = sqlite3_column_name(pStmt, i);
1134 nStr += strlen(zCol) + 1;
1137 /* Allocate and populate the array to return. */
1138 azCol = (const char **)sqlite3_malloc64(sizeof(char *) * nCol + nStr);
1139 if( azCol==0 ){
1140 rc = SQLITE_NOMEM;
1141 }else{
1142 char *p = (char *)&azCol[nCol];
1143 for(i=0; i<nCol; i++){
1144 const char *zCol = sqlite3_column_name(pStmt, i);
1145 int n = (int)strlen(zCol)+1;
1146 memcpy(p, zCol, n);
1147 azCol[i] = p;
1148 p += n;
1151 sqlite3_finalize(pStmt);
1153 /* Set the output variables. */
1154 *pnCol = nCol;
1155 *pnStr = nStr;
1156 *pazCol = azCol;
1159 return rc;
1163 ** This function is the implementation of both the xConnect and xCreate
1164 ** methods of the FTS3 virtual table.
1166 ** The argv[] array contains the following:
1168 ** argv[0] -> module name ("fts3" or "fts4")
1169 ** argv[1] -> database name
1170 ** argv[2] -> table name
1171 ** argv[...] -> "column name" and other module argument fields.
1173 static int fts3InitVtab(
1174 int isCreate, /* True for xCreate, false for xConnect */
1175 sqlite3 *db, /* The SQLite database connection */
1176 void *pAux, /* Hash table containing tokenizers */
1177 int argc, /* Number of elements in argv array */
1178 const char * const *argv, /* xCreate/xConnect argument array */
1179 sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
1180 char **pzErr /* Write any error message here */
1182 Fts3Hash *pHash = &((Fts3HashWrapper*)pAux)->hash;
1183 Fts3Table *p = 0; /* Pointer to allocated vtab */
1184 int rc = SQLITE_OK; /* Return code */
1185 int i; /* Iterator variable */
1186 sqlite3_int64 nByte; /* Size of allocation used for *p */
1187 int iCol; /* Column index */
1188 int nString = 0; /* Bytes required to hold all column names */
1189 int nCol = 0; /* Number of columns in the FTS table */
1190 char *zCsr; /* Space for holding column names */
1191 int nDb; /* Bytes required to hold database name */
1192 int nName; /* Bytes required to hold table name */
1193 int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
1194 const char **aCol; /* Array of column names */
1195 sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
1197 int nIndex = 0; /* Size of aIndex[] array */
1198 struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
1200 /* The results of parsing supported FTS4 key=value options: */
1201 int bNoDocsize = 0; /* True to omit %_docsize table */
1202 int bDescIdx = 0; /* True to store descending indexes */
1203 char *zPrefix = 0; /* Prefix parameter value (or NULL) */
1204 char *zCompress = 0; /* compress=? parameter (or NULL) */
1205 char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
1206 char *zContent = 0; /* content=? parameter (or NULL) */
1207 char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
1208 char **azNotindexed = 0; /* The set of notindexed= columns */
1209 int nNotindexed = 0; /* Size of azNotindexed[] array */
1211 assert( strlen(argv[0])==4 );
1212 assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
1213 || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
1216 nDb = (int)strlen(argv[1]) + 1;
1217 nName = (int)strlen(argv[2]) + 1;
1219 nByte = sizeof(const char *) * (argc-2);
1220 aCol = (const char **)sqlite3_malloc64(nByte);
1221 if( aCol ){
1222 memset((void*)aCol, 0, nByte);
1223 azNotindexed = (char **)sqlite3_malloc64(nByte);
1225 if( azNotindexed ){
1226 memset(azNotindexed, 0, nByte);
1228 if( !aCol || !azNotindexed ){
1229 rc = SQLITE_NOMEM;
1230 goto fts3_init_out;
1233 /* Loop through all of the arguments passed by the user to the FTS3/4
1234 ** module (i.e. all the column names and special arguments). This loop
1235 ** does the following:
1237 ** + Figures out the number of columns the FTSX table will have, and
1238 ** the number of bytes of space that must be allocated to store copies
1239 ** of the column names.
1241 ** + If there is a tokenizer specification included in the arguments,
1242 ** initializes the tokenizer pTokenizer.
1244 for(i=3; rc==SQLITE_OK && i<argc; i++){
1245 char const *z = argv[i];
1246 int nKey;
1247 char *zVal;
1249 /* Check if this is a tokenizer specification */
1250 if( !pTokenizer
1251 && strlen(z)>8
1252 && 0==sqlite3_strnicmp(z, "tokenize", 8)
1253 && 0==sqlite3Fts3IsIdChar(z[8])
1255 rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
1258 /* Check if it is an FTS4 special argument. */
1259 else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
1260 struct Fts4Option {
1261 const char *zOpt;
1262 int nOpt;
1263 } aFts4Opt[] = {
1264 { "matchinfo", 9 }, /* 0 -> MATCHINFO */
1265 { "prefix", 6 }, /* 1 -> PREFIX */
1266 { "compress", 8 }, /* 2 -> COMPRESS */
1267 { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
1268 { "order", 5 }, /* 4 -> ORDER */
1269 { "content", 7 }, /* 5 -> CONTENT */
1270 { "languageid", 10 }, /* 6 -> LANGUAGEID */
1271 { "notindexed", 10 } /* 7 -> NOTINDEXED */
1274 int iOpt;
1275 if( !zVal ){
1276 rc = SQLITE_NOMEM;
1277 }else{
1278 for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
1279 struct Fts4Option *pOp = &aFts4Opt[iOpt];
1280 if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
1281 break;
1284 switch( iOpt ){
1285 case 0: /* MATCHINFO */
1286 if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
1287 sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
1288 rc = SQLITE_ERROR;
1290 bNoDocsize = 1;
1291 break;
1293 case 1: /* PREFIX */
1294 sqlite3_free(zPrefix);
1295 zPrefix = zVal;
1296 zVal = 0;
1297 break;
1299 case 2: /* COMPRESS */
1300 sqlite3_free(zCompress);
1301 zCompress = zVal;
1302 zVal = 0;
1303 break;
1305 case 3: /* UNCOMPRESS */
1306 sqlite3_free(zUncompress);
1307 zUncompress = zVal;
1308 zVal = 0;
1309 break;
1311 case 4: /* ORDER */
1312 if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
1313 && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
1315 sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
1316 rc = SQLITE_ERROR;
1318 bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
1319 break;
1321 case 5: /* CONTENT */
1322 sqlite3_free(zContent);
1323 zContent = zVal;
1324 zVal = 0;
1325 break;
1327 case 6: /* LANGUAGEID */
1328 assert( iOpt==6 );
1329 sqlite3_free(zLanguageid);
1330 zLanguageid = zVal;
1331 zVal = 0;
1332 break;
1334 case 7: /* NOTINDEXED */
1335 azNotindexed[nNotindexed++] = zVal;
1336 zVal = 0;
1337 break;
1339 default:
1340 assert( iOpt==SizeofArray(aFts4Opt) );
1341 sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
1342 rc = SQLITE_ERROR;
1343 break;
1345 sqlite3_free(zVal);
1349 /* Otherwise, the argument is a column name. */
1350 else {
1351 nString += (int)(strlen(z) + 1);
1352 aCol[nCol++] = z;
1356 /* If a content=xxx option was specified, the following:
1358 ** 1. Ignore any compress= and uncompress= options.
1360 ** 2. If no column names were specified as part of the CREATE VIRTUAL
1361 ** TABLE statement, use all columns from the content table.
1363 if( rc==SQLITE_OK && zContent ){
1364 sqlite3_free(zCompress);
1365 sqlite3_free(zUncompress);
1366 zCompress = 0;
1367 zUncompress = 0;
1368 if( nCol==0 ){
1369 sqlite3_free((void*)aCol);
1370 aCol = 0;
1371 rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
1373 /* If a languageid= option was specified, remove the language id
1374 ** column from the aCol[] array. */
1375 if( rc==SQLITE_OK && zLanguageid ){
1376 int j;
1377 for(j=0; j<nCol; j++){
1378 if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
1379 int k;
1380 for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
1381 nCol--;
1382 break;
1388 if( rc!=SQLITE_OK ) goto fts3_init_out;
1390 if( nCol==0 ){
1391 assert( nString==0 );
1392 aCol[0] = "content";
1393 nString = 8;
1394 nCol = 1;
1397 if( pTokenizer==0 ){
1398 rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
1399 if( rc!=SQLITE_OK ) goto fts3_init_out;
1401 assert( pTokenizer );
1403 rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
1404 if( rc==SQLITE_ERROR ){
1405 assert( zPrefix );
1406 sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
1408 if( rc!=SQLITE_OK ) goto fts3_init_out;
1410 /* Allocate and populate the Fts3Table structure. */
1411 nByte = sizeof(Fts3Table) + /* Fts3Table */
1412 nCol * sizeof(char *) + /* azColumn */
1413 nIndex * sizeof(struct Fts3Index) + /* aIndex */
1414 nCol * sizeof(u8) + /* abNotindexed */
1415 nName + /* zName */
1416 nDb + /* zDb */
1417 nString; /* Space for azColumn strings */
1418 p = (Fts3Table*)sqlite3_malloc64(nByte);
1419 if( p==0 ){
1420 rc = SQLITE_NOMEM;
1421 goto fts3_init_out;
1423 memset(p, 0, nByte);
1424 p->db = db;
1425 p->nColumn = nCol;
1426 p->nPendingData = 0;
1427 p->azColumn = (char **)&p[1];
1428 p->pTokenizer = pTokenizer;
1429 p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
1430 p->bHasDocsize = (isFts4 && bNoDocsize==0);
1431 p->bHasStat = (u8)isFts4;
1432 p->bFts4 = (u8)isFts4;
1433 p->bDescIdx = (u8)bDescIdx;
1434 p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
1435 p->zContentTbl = zContent;
1436 p->zLanguageid = zLanguageid;
1437 zContent = 0;
1438 zLanguageid = 0;
1439 TESTONLY( p->inTransaction = -1 );
1440 TESTONLY( p->mxSavepoint = -1 );
1442 p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
1443 memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
1444 p->nIndex = nIndex;
1445 for(i=0; i<nIndex; i++){
1446 fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
1448 p->abNotindexed = (u8 *)&p->aIndex[nIndex];
1450 /* Fill in the zName and zDb fields of the vtab structure. */
1451 zCsr = (char *)&p->abNotindexed[nCol];
1452 p->zName = zCsr;
1453 memcpy(zCsr, argv[2], nName);
1454 zCsr += nName;
1455 p->zDb = zCsr;
1456 memcpy(zCsr, argv[1], nDb);
1457 zCsr += nDb;
1459 /* Fill in the azColumn array */
1460 for(iCol=0; iCol<nCol; iCol++){
1461 char *z;
1462 int n = 0;
1463 z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
1464 if( n>0 ){
1465 memcpy(zCsr, z, n);
1467 zCsr[n] = '\0';
1468 sqlite3Fts3Dequote(zCsr);
1469 p->azColumn[iCol] = zCsr;
1470 zCsr += n+1;
1471 assert( zCsr <= &((char *)p)[nByte] );
1474 /* Fill in the abNotindexed array */
1475 for(iCol=0; iCol<nCol; iCol++){
1476 int n = (int)strlen(p->azColumn[iCol]);
1477 for(i=0; i<nNotindexed; i++){
1478 char *zNot = azNotindexed[i];
1479 if( zNot && n==(int)strlen(zNot)
1480 && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
1482 p->abNotindexed[iCol] = 1;
1483 sqlite3_free(zNot);
1484 azNotindexed[i] = 0;
1488 for(i=0; i<nNotindexed; i++){
1489 if( azNotindexed[i] ){
1490 sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
1491 rc = SQLITE_ERROR;
1495 if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
1496 char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
1497 rc = SQLITE_ERROR;
1498 sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
1500 p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
1501 p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
1502 if( rc!=SQLITE_OK ) goto fts3_init_out;
1504 /* If this is an xCreate call, create the underlying tables in the
1505 ** database. TODO: For xConnect(), it could verify that said tables exist.
1507 if( isCreate ){
1508 rc = fts3CreateTables(p);
1511 /* Check to see if a legacy fts3 table has been "upgraded" by the
1512 ** addition of a %_stat table so that it can use incremental merge.
1514 if( !isFts4 && !isCreate ){
1515 p->bHasStat = 2;
1518 /* Figure out the page-size for the database. This is required in order to
1519 ** estimate the cost of loading large doclists from the database. */
1520 fts3DatabasePageSize(&rc, p);
1521 p->nNodeSize = p->nPgsz-35;
1523 #if defined(SQLITE_DEBUG)||defined(SQLITE_TEST)
1524 p->nMergeCount = FTS3_MERGE_COUNT;
1525 #endif
1527 /* Declare the table schema to SQLite. */
1528 fts3DeclareVtab(&rc, p);
1530 fts3_init_out:
1531 sqlite3_free(zPrefix);
1532 sqlite3_free(aIndex);
1533 sqlite3_free(zCompress);
1534 sqlite3_free(zUncompress);
1535 sqlite3_free(zContent);
1536 sqlite3_free(zLanguageid);
1537 for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
1538 sqlite3_free((void *)aCol);
1539 sqlite3_free((void *)azNotindexed);
1540 if( rc!=SQLITE_OK ){
1541 if( p ){
1542 fts3DisconnectMethod((sqlite3_vtab *)p);
1543 }else if( pTokenizer ){
1544 pTokenizer->pModule->xDestroy(pTokenizer);
1546 }else{
1547 assert( p->pSegments==0 );
1548 *ppVTab = &p->base;
1550 return rc;
1554 ** The xConnect() and xCreate() methods for the virtual table. All the
1555 ** work is done in function fts3InitVtab().
1557 static int fts3ConnectMethod(
1558 sqlite3 *db, /* Database connection */
1559 void *pAux, /* Pointer to tokenizer hash table */
1560 int argc, /* Number of elements in argv array */
1561 const char * const *argv, /* xCreate/xConnect argument array */
1562 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
1563 char **pzErr /* OUT: sqlite3_malloc'd error message */
1565 return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
1567 static int fts3CreateMethod(
1568 sqlite3 *db, /* Database connection */
1569 void *pAux, /* Pointer to tokenizer hash table */
1570 int argc, /* Number of elements in argv array */
1571 const char * const *argv, /* xCreate/xConnect argument array */
1572 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
1573 char **pzErr /* OUT: sqlite3_malloc'd error message */
1575 return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
1579 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
1580 ** extension is currently being used by a version of SQLite too old to
1581 ** support estimatedRows. In that case this function is a no-op.
1583 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
1584 #if SQLITE_VERSION_NUMBER>=3008002
1585 if( sqlite3_libversion_number()>=3008002 ){
1586 pIdxInfo->estimatedRows = nRow;
1588 #endif
1592 ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
1593 ** extension is currently being used by a version of SQLite too old to
1594 ** support index-info flags. In that case this function is a no-op.
1596 static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
1597 #if SQLITE_VERSION_NUMBER>=3008012
1598 if( sqlite3_libversion_number()>=3008012 ){
1599 pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
1601 #endif
1605 ** Implementation of the xBestIndex method for FTS3 tables. There
1606 ** are three possible strategies, in order of preference:
1608 ** 1. Direct lookup by rowid or docid.
1609 ** 2. Full-text search using a MATCH operator on a non-docid column.
1610 ** 3. Linear scan of %_content table.
1612 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
1613 Fts3Table *p = (Fts3Table *)pVTab;
1614 int i; /* Iterator variable */
1615 int iCons = -1; /* Index of constraint to use */
1617 int iLangidCons = -1; /* Index of langid=x constraint, if present */
1618 int iDocidGe = -1; /* Index of docid>=x constraint, if present */
1619 int iDocidLe = -1; /* Index of docid<=x constraint, if present */
1620 int iIdx;
1622 if( p->bLock ){
1623 return SQLITE_ERROR;
1626 /* By default use a full table scan. This is an expensive option,
1627 ** so search through the constraints to see if a more efficient
1628 ** strategy is possible.
1630 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
1631 pInfo->estimatedCost = 5000000;
1632 for(i=0; i<pInfo->nConstraint; i++){
1633 int bDocid; /* True if this constraint is on docid */
1634 struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
1635 if( pCons->usable==0 ){
1636 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
1637 /* There exists an unusable MATCH constraint. This means that if
1638 ** the planner does elect to use the results of this call as part
1639 ** of the overall query plan the user will see an "unable to use
1640 ** function MATCH in the requested context" error. To discourage
1641 ** this, return a very high cost here. */
1642 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
1643 pInfo->estimatedCost = 1e50;
1644 fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
1645 return SQLITE_OK;
1647 continue;
1650 bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
1652 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
1653 if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
1654 pInfo->idxNum = FTS3_DOCID_SEARCH;
1655 pInfo->estimatedCost = 1.0;
1656 iCons = i;
1659 /* A MATCH constraint. Use a full-text search.
1661 ** If there is more than one MATCH constraint available, use the first
1662 ** one encountered. If there is both a MATCH constraint and a direct
1663 ** rowid/docid lookup, prefer the MATCH strategy. This is done even
1664 ** though the rowid/docid lookup is faster than a MATCH query, selecting
1665 ** it would lead to an "unable to use function MATCH in the requested
1666 ** context" error.
1668 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
1669 && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
1671 pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
1672 pInfo->estimatedCost = 2.0;
1673 iCons = i;
1676 /* Equality constraint on the langid column */
1677 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
1678 && pCons->iColumn==p->nColumn + 2
1680 iLangidCons = i;
1683 if( bDocid ){
1684 switch( pCons->op ){
1685 case SQLITE_INDEX_CONSTRAINT_GE:
1686 case SQLITE_INDEX_CONSTRAINT_GT:
1687 iDocidGe = i;
1688 break;
1690 case SQLITE_INDEX_CONSTRAINT_LE:
1691 case SQLITE_INDEX_CONSTRAINT_LT:
1692 iDocidLe = i;
1693 break;
1698 /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
1699 if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
1701 iIdx = 1;
1702 if( iCons>=0 ){
1703 pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
1704 pInfo->aConstraintUsage[iCons].omit = 1;
1706 if( iLangidCons>=0 ){
1707 pInfo->idxNum |= FTS3_HAVE_LANGID;
1708 pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
1710 if( iDocidGe>=0 ){
1711 pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
1712 pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
1714 if( iDocidLe>=0 ){
1715 pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
1716 pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
1719 /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
1720 ** docid) order. Both ascending and descending are possible.
1722 if( pInfo->nOrderBy==1 ){
1723 struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
1724 if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
1725 if( pOrder->desc ){
1726 pInfo->idxStr = "DESC";
1727 }else{
1728 pInfo->idxStr = "ASC";
1730 pInfo->orderByConsumed = 1;
1734 assert( p->pSegments==0 );
1735 return SQLITE_OK;
1739 ** Implementation of xOpen method.
1741 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
1742 sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
1744 UNUSED_PARAMETER(pVTab);
1746 /* Allocate a buffer large enough for an Fts3Cursor structure. If the
1747 ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
1748 ** if the allocation fails, return SQLITE_NOMEM.
1750 *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
1751 if( !pCsr ){
1752 return SQLITE_NOMEM;
1754 memset(pCsr, 0, sizeof(Fts3Cursor));
1755 return SQLITE_OK;
1759 ** Finalize the statement handle at pCsr->pStmt.
1761 ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
1762 ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
1763 ** pointer there instead of finalizing it.
1765 static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
1766 if( pCsr->bSeekStmt ){
1767 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
1768 if( p->pSeekStmt==0 ){
1769 p->pSeekStmt = pCsr->pStmt;
1770 sqlite3_reset(pCsr->pStmt);
1771 pCsr->pStmt = 0;
1773 pCsr->bSeekStmt = 0;
1775 sqlite3_finalize(pCsr->pStmt);
1779 ** Free all resources currently held by the cursor passed as the only
1780 ** argument.
1782 static void fts3ClearCursor(Fts3Cursor *pCsr){
1783 fts3CursorFinalizeStmt(pCsr);
1784 sqlite3Fts3FreeDeferredTokens(pCsr);
1785 sqlite3_free(pCsr->aDoclist);
1786 sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
1787 sqlite3Fts3ExprFree(pCsr->pExpr);
1788 memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
1792 ** Close the cursor. For additional information see the documentation
1793 ** on the xClose method of the virtual table interface.
1795 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
1796 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
1797 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
1798 fts3ClearCursor(pCsr);
1799 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
1800 sqlite3_free(pCsr);
1801 return SQLITE_OK;
1805 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
1806 ** compose and prepare an SQL statement of the form:
1808 ** "SELECT <columns> FROM %_content WHERE rowid = ?"
1810 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
1811 ** it. If an error occurs, return an SQLite error code.
1813 static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
1814 int rc = SQLITE_OK;
1815 if( pCsr->pStmt==0 ){
1816 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
1817 char *zSql;
1818 if( p->pSeekStmt ){
1819 pCsr->pStmt = p->pSeekStmt;
1820 p->pSeekStmt = 0;
1821 }else{
1822 zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
1823 if( !zSql ) return SQLITE_NOMEM;
1824 p->bLock++;
1825 rc = sqlite3_prepare_v3(
1826 p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0
1828 p->bLock--;
1829 sqlite3_free(zSql);
1831 if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
1833 return rc;
1837 ** Position the pCsr->pStmt statement so that it is on the row
1838 ** of the %_content table that contains the last match. Return
1839 ** SQLITE_OK on success.
1841 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
1842 int rc = SQLITE_OK;
1843 if( pCsr->isRequireSeek ){
1844 rc = fts3CursorSeekStmt(pCsr);
1845 if( rc==SQLITE_OK ){
1846 Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab;
1847 pTab->bLock++;
1848 sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
1849 pCsr->isRequireSeek = 0;
1850 if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
1851 pTab->bLock--;
1852 return SQLITE_OK;
1853 }else{
1854 pTab->bLock--;
1855 rc = sqlite3_reset(pCsr->pStmt);
1856 if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
1857 /* If no row was found and no error has occurred, then the %_content
1858 ** table is missing a row that is present in the full-text index.
1859 ** The data structures are corrupt. */
1860 rc = FTS_CORRUPT_VTAB;
1861 pCsr->isEof = 1;
1867 if( rc!=SQLITE_OK && pContext ){
1868 sqlite3_result_error_code(pContext, rc);
1870 return rc;
1874 ** This function is used to process a single interior node when searching
1875 ** a b-tree for a term or term prefix. The node data is passed to this
1876 ** function via the zNode/nNode parameters. The term to search for is
1877 ** passed in zTerm/nTerm.
1879 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
1880 ** of the child node that heads the sub-tree that may contain the term.
1882 ** If piLast is not NULL, then *piLast is set to the right-most child node
1883 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
1884 ** a prefix.
1886 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
1888 static int fts3ScanInteriorNode(
1889 const char *zTerm, /* Term to select leaves for */
1890 int nTerm, /* Size of term zTerm in bytes */
1891 const char *zNode, /* Buffer containing segment interior node */
1892 int nNode, /* Size of buffer at zNode */
1893 sqlite3_int64 *piFirst, /* OUT: Selected child node */
1894 sqlite3_int64 *piLast /* OUT: Selected child node */
1896 int rc = SQLITE_OK; /* Return code */
1897 const char *zCsr = zNode; /* Cursor to iterate through node */
1898 const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
1899 char *zBuffer = 0; /* Buffer to load terms into */
1900 i64 nAlloc = 0; /* Size of allocated buffer */
1901 int isFirstTerm = 1; /* True when processing first term on page */
1902 u64 iChild; /* Block id of child node to descend to */
1903 int nBuffer = 0; /* Total term size */
1905 /* Skip over the 'height' varint that occurs at the start of every
1906 ** interior node. Then load the blockid of the left-child of the b-tree
1907 ** node into variable iChild.
1909 ** Even if the data structure on disk is corrupted, this (reading two
1910 ** varints from the buffer) does not risk an overread. If zNode is a
1911 ** root node, then the buffer comes from a SELECT statement. SQLite does
1912 ** not make this guarantee explicitly, but in practice there are always
1913 ** either more than 20 bytes of allocated space following the nNode bytes of
1914 ** contents, or two zero bytes. Or, if the node is read from the %_segments
1915 ** table, then there are always 20 bytes of zeroed padding following the
1916 ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
1918 zCsr += sqlite3Fts3GetVarintU(zCsr, &iChild);
1919 zCsr += sqlite3Fts3GetVarintU(zCsr, &iChild);
1920 if( zCsr>zEnd ){
1921 return FTS_CORRUPT_VTAB;
1924 while( zCsr<zEnd && (piFirst || piLast) ){
1925 int cmp; /* memcmp() result */
1926 int nSuffix; /* Size of term suffix */
1927 int nPrefix = 0; /* Size of term prefix */
1929 /* Load the next term on the node into zBuffer. Use realloc() to expand
1930 ** the size of zBuffer if required. */
1931 if( !isFirstTerm ){
1932 zCsr += fts3GetVarint32(zCsr, &nPrefix);
1933 if( nPrefix>nBuffer ){
1934 rc = FTS_CORRUPT_VTAB;
1935 goto finish_scan;
1938 isFirstTerm = 0;
1939 zCsr += fts3GetVarint32(zCsr, &nSuffix);
1941 assert( nPrefix>=0 && nSuffix>=0 );
1942 if( nPrefix>zCsr-zNode || nSuffix>zEnd-zCsr || nSuffix==0 ){
1943 rc = FTS_CORRUPT_VTAB;
1944 goto finish_scan;
1946 if( (i64)nPrefix+nSuffix>nAlloc ){
1947 char *zNew;
1948 nAlloc = ((i64)nPrefix+nSuffix) * 2;
1949 zNew = (char *)sqlite3_realloc64(zBuffer, nAlloc);
1950 if( !zNew ){
1951 rc = SQLITE_NOMEM;
1952 goto finish_scan;
1954 zBuffer = zNew;
1956 assert( zBuffer );
1957 memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
1958 nBuffer = nPrefix + nSuffix;
1959 zCsr += nSuffix;
1961 /* Compare the term we are searching for with the term just loaded from
1962 ** the interior node. If the specified term is greater than or equal
1963 ** to the term from the interior node, then all terms on the sub-tree
1964 ** headed by node iChild are smaller than zTerm. No need to search
1965 ** iChild.
1967 ** If the interior node term is larger than the specified term, then
1968 ** the tree headed by iChild may contain the specified term.
1970 cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
1971 if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
1972 *piFirst = (i64)iChild;
1973 piFirst = 0;
1976 if( piLast && cmp<0 ){
1977 *piLast = (i64)iChild;
1978 piLast = 0;
1981 iChild++;
1984 if( piFirst ) *piFirst = (i64)iChild;
1985 if( piLast ) *piLast = (i64)iChild;
1987 finish_scan:
1988 sqlite3_free(zBuffer);
1989 return rc;
1994 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
1995 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
1996 ** contains a term. This function searches the sub-tree headed by the zNode
1997 ** node for the range of leaf nodes that may contain the specified term
1998 ** or terms for which the specified term is a prefix.
2000 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
2001 ** left-most leaf node in the tree that may contain the specified term.
2002 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
2003 ** right-most leaf node that may contain a term for which the specified
2004 ** term is a prefix.
2006 ** It is possible that the range of returned leaf nodes does not contain
2007 ** the specified term or any terms for which it is a prefix. However, if the
2008 ** segment does contain any such terms, they are stored within the identified
2009 ** range. Because this function only inspects interior segment nodes (and
2010 ** never loads leaf nodes into memory), it is not possible to be sure.
2012 ** If an error occurs, an error code other than SQLITE_OK is returned.
2014 static int fts3SelectLeaf(
2015 Fts3Table *p, /* Virtual table handle */
2016 const char *zTerm, /* Term to select leaves for */
2017 int nTerm, /* Size of term zTerm in bytes */
2018 const char *zNode, /* Buffer containing segment interior node */
2019 int nNode, /* Size of buffer at zNode */
2020 sqlite3_int64 *piLeaf, /* Selected leaf node */
2021 sqlite3_int64 *piLeaf2 /* Selected leaf node */
2023 int rc = SQLITE_OK; /* Return code */
2024 int iHeight; /* Height of this node in tree */
2026 assert( piLeaf || piLeaf2 );
2028 fts3GetVarint32(zNode, &iHeight);
2029 rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
2030 assert_fts3_nc( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
2032 if( rc==SQLITE_OK && iHeight>1 ){
2033 char *zBlob = 0; /* Blob read from %_segments table */
2034 int nBlob = 0; /* Size of zBlob in bytes */
2036 if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
2037 rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
2038 if( rc==SQLITE_OK ){
2039 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
2041 sqlite3_free(zBlob);
2042 piLeaf = 0;
2043 zBlob = 0;
2046 if( rc==SQLITE_OK ){
2047 rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
2049 if( rc==SQLITE_OK ){
2050 int iNewHeight = 0;
2051 fts3GetVarint32(zBlob, &iNewHeight);
2052 if( iNewHeight>=iHeight ){
2053 rc = FTS_CORRUPT_VTAB;
2054 }else{
2055 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
2058 sqlite3_free(zBlob);
2061 return rc;
2065 ** This function is used to create delta-encoded serialized lists of FTS3
2066 ** varints. Each call to this function appends a single varint to a list.
2068 static void fts3PutDeltaVarint(
2069 char **pp, /* IN/OUT: Output pointer */
2070 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
2071 sqlite3_int64 iVal /* Write this value to the list */
2073 assert_fts3_nc( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
2074 *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
2075 *piPrev = iVal;
2079 ** When this function is called, *ppPoslist is assumed to point to the
2080 ** start of a position-list. After it returns, *ppPoslist points to the
2081 ** first byte after the position-list.
2083 ** A position list is list of positions (delta encoded) and columns for
2084 ** a single document record of a doclist. So, in other words, this
2085 ** routine advances *ppPoslist so that it points to the next docid in
2086 ** the doclist, or to the first byte past the end of the doclist.
2088 ** If pp is not NULL, then the contents of the position list are copied
2089 ** to *pp. *pp is set to point to the first byte past the last byte copied
2090 ** before this function returns.
2092 static void fts3PoslistCopy(char **pp, char **ppPoslist){
2093 char *pEnd = *ppPoslist;
2094 char c = 0;
2096 /* The end of a position list is marked by a zero encoded as an FTS3
2097 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
2098 ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
2099 ** of some other, multi-byte, value.
2101 ** The following while-loop moves pEnd to point to the first byte that is not
2102 ** immediately preceded by a byte with the 0x80 bit set. Then increments
2103 ** pEnd once more so that it points to the byte immediately following the
2104 ** last byte in the position-list.
2106 while( *pEnd | c ){
2107 c = *pEnd++ & 0x80;
2108 testcase( c!=0 && (*pEnd)==0 );
2110 pEnd++; /* Advance past the POS_END terminator byte */
2112 if( pp ){
2113 int n = (int)(pEnd - *ppPoslist);
2114 char *p = *pp;
2115 memcpy(p, *ppPoslist, n);
2116 p += n;
2117 *pp = p;
2119 *ppPoslist = pEnd;
2123 ** When this function is called, *ppPoslist is assumed to point to the
2124 ** start of a column-list. After it returns, *ppPoslist points to the
2125 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
2127 ** A column-list is list of delta-encoded positions for a single column
2128 ** within a single document within a doclist.
2130 ** The column-list is terminated either by a POS_COLUMN varint (1) or
2131 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
2132 ** the POS_COLUMN or POS_END that terminates the column-list.
2134 ** If pp is not NULL, then the contents of the column-list are copied
2135 ** to *pp. *pp is set to point to the first byte past the last byte copied
2136 ** before this function returns. The POS_COLUMN or POS_END terminator
2137 ** is not copied into *pp.
2139 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
2140 char *pEnd = *ppPoslist;
2141 char c = 0;
2143 /* A column-list is terminated by either a 0x01 or 0x00 byte that is
2144 ** not part of a multi-byte varint.
2146 while( 0xFE & (*pEnd | c) ){
2147 c = *pEnd++ & 0x80;
2148 testcase( c!=0 && ((*pEnd)&0xfe)==0 );
2150 if( pp ){
2151 int n = (int)(pEnd - *ppPoslist);
2152 char *p = *pp;
2153 memcpy(p, *ppPoslist, n);
2154 p += n;
2155 *pp = p;
2157 *ppPoslist = pEnd;
2161 ** Value used to signify the end of an position-list. This must be
2162 ** as large or larger than any value that might appear on the
2163 ** position-list, even a position list that has been corrupted.
2165 #define POSITION_LIST_END LARGEST_INT64
2168 ** This function is used to help parse position-lists. When this function is
2169 ** called, *pp may point to the start of the next varint in the position-list
2170 ** being parsed, or it may point to 1 byte past the end of the position-list
2171 ** (in which case **pp will be a terminator bytes POS_END (0) or
2172 ** (1)).
2174 ** If *pp points past the end of the current position-list, set *pi to
2175 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
2176 ** increment the current value of *pi by the value read, and set *pp to
2177 ** point to the next value before returning.
2179 ** Before calling this routine *pi must be initialized to the value of
2180 ** the previous position, or zero if we are reading the first position
2181 ** in the position-list. Because positions are delta-encoded, the value
2182 ** of the previous position is needed in order to compute the value of
2183 ** the next position.
2185 static void fts3ReadNextPos(
2186 char **pp, /* IN/OUT: Pointer into position-list buffer */
2187 sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
2189 if( (**pp)&0xFE ){
2190 int iVal;
2191 *pp += fts3GetVarint32((*pp), &iVal);
2192 *pi += iVal;
2193 *pi -= 2;
2194 }else{
2195 *pi = POSITION_LIST_END;
2200 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
2201 ** the value of iCol encoded as a varint to *pp. This will start a new
2202 ** column list.
2204 ** Set *pp to point to the byte just after the last byte written before
2205 ** returning (do not modify it if iCol==0). Return the total number of bytes
2206 ** written (0 if iCol==0).
2208 static int fts3PutColNumber(char **pp, int iCol){
2209 int n = 0; /* Number of bytes written */
2210 if( iCol ){
2211 char *p = *pp; /* Output pointer */
2212 n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
2213 *p = 0x01;
2214 *pp = &p[n];
2216 return n;
2220 ** Compute the union of two position lists. The output written
2221 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
2222 ** order and with any duplicates removed. All pointers are
2223 ** updated appropriately. The caller is responsible for insuring
2224 ** that there is enough space in *pp to hold the complete output.
2226 static int fts3PoslistMerge(
2227 char **pp, /* Output buffer */
2228 char **pp1, /* Left input list */
2229 char **pp2 /* Right input list */
2231 char *p = *pp;
2232 char *p1 = *pp1;
2233 char *p2 = *pp2;
2235 while( *p1 || *p2 ){
2236 int iCol1; /* The current column index in pp1 */
2237 int iCol2; /* The current column index in pp2 */
2239 if( *p1==POS_COLUMN ){
2240 fts3GetVarint32(&p1[1], &iCol1);
2241 if( iCol1==0 ) return FTS_CORRUPT_VTAB;
2243 else if( *p1==POS_END ) iCol1 = 0x7fffffff;
2244 else iCol1 = 0;
2246 if( *p2==POS_COLUMN ){
2247 fts3GetVarint32(&p2[1], &iCol2);
2248 if( iCol2==0 ) return FTS_CORRUPT_VTAB;
2250 else if( *p2==POS_END ) iCol2 = 0x7fffffff;
2251 else iCol2 = 0;
2253 if( iCol1==iCol2 ){
2254 sqlite3_int64 i1 = 0; /* Last position from pp1 */
2255 sqlite3_int64 i2 = 0; /* Last position from pp2 */
2256 sqlite3_int64 iPrev = 0;
2257 int n = fts3PutColNumber(&p, iCol1);
2258 p1 += n;
2259 p2 += n;
2261 /* At this point, both p1 and p2 point to the start of column-lists
2262 ** for the same column (the column with index iCol1 and iCol2).
2263 ** A column-list is a list of non-negative delta-encoded varints, each
2264 ** incremented by 2 before being stored. Each list is terminated by a
2265 ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
2266 ** and writes the results to buffer p. p is left pointing to the byte
2267 ** after the list written. No terminator (POS_END or POS_COLUMN) is
2268 ** written to the output.
2270 fts3GetDeltaVarint(&p1, &i1);
2271 fts3GetDeltaVarint(&p2, &i2);
2272 if( i1<2 || i2<2 ){
2273 break;
2275 do {
2276 fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
2277 iPrev -= 2;
2278 if( i1==i2 ){
2279 fts3ReadNextPos(&p1, &i1);
2280 fts3ReadNextPos(&p2, &i2);
2281 }else if( i1<i2 ){
2282 fts3ReadNextPos(&p1, &i1);
2283 }else{
2284 fts3ReadNextPos(&p2, &i2);
2286 }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
2287 }else if( iCol1<iCol2 ){
2288 p1 += fts3PutColNumber(&p, iCol1);
2289 fts3ColumnlistCopy(&p, &p1);
2290 }else{
2291 p2 += fts3PutColNumber(&p, iCol2);
2292 fts3ColumnlistCopy(&p, &p2);
2296 *p++ = POS_END;
2297 *pp = p;
2298 *pp1 = p1 + 1;
2299 *pp2 = p2 + 1;
2300 return SQLITE_OK;
2304 ** This function is used to merge two position lists into one. When it is
2305 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
2306 ** the part of a doclist that follows each document id. For example, if a row
2307 ** contains:
2309 ** 'a b c'|'x y z'|'a b b a'
2311 ** Then the position list for this row for token 'b' would consist of:
2313 ** 0x02 0x01 0x02 0x03 0x03 0x00
2315 ** When this function returns, both *pp1 and *pp2 are left pointing to the
2316 ** byte following the 0x00 terminator of their respective position lists.
2318 ** If isSaveLeft is 0, an entry is added to the output position list for
2319 ** each position in *pp2 for which there exists one or more positions in
2320 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
2321 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
2322 ** slots before it.
2324 ** e.g. nToken==1 searches for adjacent positions.
2326 static int fts3PoslistPhraseMerge(
2327 char **pp, /* IN/OUT: Preallocated output buffer */
2328 int nToken, /* Maximum difference in token positions */
2329 int isSaveLeft, /* Save the left position */
2330 int isExact, /* If *pp1 is exactly nTokens before *pp2 */
2331 char **pp1, /* IN/OUT: Left input list */
2332 char **pp2 /* IN/OUT: Right input list */
2334 char *p = *pp;
2335 char *p1 = *pp1;
2336 char *p2 = *pp2;
2337 int iCol1 = 0;
2338 int iCol2 = 0;
2340 /* Never set both isSaveLeft and isExact for the same invocation. */
2341 assert( isSaveLeft==0 || isExact==0 );
2343 assert_fts3_nc( p!=0 && *p1!=0 && *p2!=0 );
2344 if( *p1==POS_COLUMN ){
2345 p1++;
2346 p1 += fts3GetVarint32(p1, &iCol1);
2348 if( *p2==POS_COLUMN ){
2349 p2++;
2350 p2 += fts3GetVarint32(p2, &iCol2);
2353 while( 1 ){
2354 if( iCol1==iCol2 ){
2355 char *pSave = p;
2356 sqlite3_int64 iPrev = 0;
2357 sqlite3_int64 iPos1 = 0;
2358 sqlite3_int64 iPos2 = 0;
2360 if( iCol1 ){
2361 *p++ = POS_COLUMN;
2362 p += sqlite3Fts3PutVarint(p, iCol1);
2365 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
2366 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
2367 if( iPos1<0 || iPos2<0 ) break;
2369 while( 1 ){
2370 if( iPos2==iPos1+nToken
2371 || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
2373 sqlite3_int64 iSave;
2374 iSave = isSaveLeft ? iPos1 : iPos2;
2375 fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
2376 pSave = 0;
2377 assert( p );
2379 if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
2380 if( (*p2&0xFE)==0 ) break;
2381 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
2382 }else{
2383 if( (*p1&0xFE)==0 ) break;
2384 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
2388 if( pSave ){
2389 assert( pp && p );
2390 p = pSave;
2393 fts3ColumnlistCopy(0, &p1);
2394 fts3ColumnlistCopy(0, &p2);
2395 assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
2396 if( 0==*p1 || 0==*p2 ) break;
2398 p1++;
2399 p1 += fts3GetVarint32(p1, &iCol1);
2400 p2++;
2401 p2 += fts3GetVarint32(p2, &iCol2);
2404 /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
2405 ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
2406 ** end of the position list, or the 0x01 that precedes the next
2407 ** column-number in the position list.
2409 else if( iCol1<iCol2 ){
2410 fts3ColumnlistCopy(0, &p1);
2411 if( 0==*p1 ) break;
2412 p1++;
2413 p1 += fts3GetVarint32(p1, &iCol1);
2414 }else{
2415 fts3ColumnlistCopy(0, &p2);
2416 if( 0==*p2 ) break;
2417 p2++;
2418 p2 += fts3GetVarint32(p2, &iCol2);
2422 fts3PoslistCopy(0, &p2);
2423 fts3PoslistCopy(0, &p1);
2424 *pp1 = p1;
2425 *pp2 = p2;
2426 if( *pp==p ){
2427 return 0;
2429 *p++ = 0x00;
2430 *pp = p;
2431 return 1;
2435 ** Merge two position-lists as required by the NEAR operator. The argument
2436 ** position lists correspond to the left and right phrases of an expression
2437 ** like:
2439 ** "phrase 1" NEAR "phrase number 2"
2441 ** Position list *pp1 corresponds to the left-hand side of the NEAR
2442 ** expression and *pp2 to the right. As usual, the indexes in the position
2443 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
2444 ** in the example above).
2446 ** The output position list - written to *pp - is a copy of *pp2 with those
2447 ** entries that are not sufficiently NEAR entries in *pp1 removed.
2449 static int fts3PoslistNearMerge(
2450 char **pp, /* Output buffer */
2451 char *aTmp, /* Temporary buffer space */
2452 int nRight, /* Maximum difference in token positions */
2453 int nLeft, /* Maximum difference in token positions */
2454 char **pp1, /* IN/OUT: Left input list */
2455 char **pp2 /* IN/OUT: Right input list */
2457 char *p1 = *pp1;
2458 char *p2 = *pp2;
2460 char *pTmp1 = aTmp;
2461 char *pTmp2;
2462 char *aTmp2;
2463 int res = 1;
2465 fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
2466 aTmp2 = pTmp2 = pTmp1;
2467 *pp1 = p1;
2468 *pp2 = p2;
2469 fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
2470 if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
2471 fts3PoslistMerge(pp, &aTmp, &aTmp2);
2472 }else if( pTmp1!=aTmp ){
2473 fts3PoslistCopy(pp, &aTmp);
2474 }else if( pTmp2!=aTmp2 ){
2475 fts3PoslistCopy(pp, &aTmp2);
2476 }else{
2477 res = 0;
2480 return res;
2484 ** An instance of this function is used to merge together the (potentially
2485 ** large number of) doclists for each term that matches a prefix query.
2486 ** See function fts3TermSelectMerge() for details.
2488 typedef struct TermSelect TermSelect;
2489 struct TermSelect {
2490 char *aaOutput[16]; /* Malloc'd output buffers */
2491 int anOutput[16]; /* Size each output buffer in bytes */
2495 ** This function is used to read a single varint from a buffer. Parameter
2496 ** pEnd points 1 byte past the end of the buffer. When this function is
2497 ** called, if *pp points to pEnd or greater, then the end of the buffer
2498 ** has been reached. In this case *pp is set to 0 and the function returns.
2500 ** If *pp does not point to or past pEnd, then a single varint is read
2501 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
2503 ** If bDescIdx is false, the value read is added to *pVal before returning.
2504 ** If it is true, the value read is subtracted from *pVal before this
2505 ** function returns.
2507 static void fts3GetDeltaVarint3(
2508 char **pp, /* IN/OUT: Point to read varint from */
2509 char *pEnd, /* End of buffer */
2510 int bDescIdx, /* True if docids are descending */
2511 sqlite3_int64 *pVal /* IN/OUT: Integer value */
2513 if( *pp>=pEnd ){
2514 *pp = 0;
2515 }else{
2516 u64 iVal;
2517 *pp += sqlite3Fts3GetVarintU(*pp, &iVal);
2518 if( bDescIdx ){
2519 *pVal = (i64)((u64)*pVal - iVal);
2520 }else{
2521 *pVal = (i64)((u64)*pVal + iVal);
2527 ** This function is used to write a single varint to a buffer. The varint
2528 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
2529 ** end of the value written.
2531 ** If *pbFirst is zero when this function is called, the value written to
2532 ** the buffer is that of parameter iVal.
2534 ** If *pbFirst is non-zero when this function is called, then the value
2535 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
2536 ** (if bDescIdx is non-zero).
2538 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
2539 ** to the value of parameter iVal.
2541 static void fts3PutDeltaVarint3(
2542 char **pp, /* IN/OUT: Output pointer */
2543 int bDescIdx, /* True for descending docids */
2544 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
2545 int *pbFirst, /* IN/OUT: True after first int written */
2546 sqlite3_int64 iVal /* Write this value to the list */
2548 sqlite3_uint64 iWrite;
2549 if( bDescIdx==0 || *pbFirst==0 ){
2550 assert_fts3_nc( *pbFirst==0 || iVal>=*piPrev );
2551 iWrite = (u64)iVal - (u64)*piPrev;
2552 }else{
2553 assert_fts3_nc( *piPrev>=iVal );
2554 iWrite = (u64)*piPrev - (u64)iVal;
2556 assert( *pbFirst || *piPrev==0 );
2557 assert_fts3_nc( *pbFirst==0 || iWrite>0 );
2558 *pp += sqlite3Fts3PutVarint(*pp, iWrite);
2559 *piPrev = iVal;
2560 *pbFirst = 1;
2565 ** This macro is used by various functions that merge doclists. The two
2566 ** arguments are 64-bit docid values. If the value of the stack variable
2567 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
2568 ** Otherwise, (i2-i1).
2570 ** Using this makes it easier to write code that can merge doclists that are
2571 ** sorted in either ascending or descending order.
2573 /* #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i64)((u64)i1-i2)) */
2574 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1>i2?1:((i1==i2)?0:-1)))
2577 ** This function does an "OR" merge of two doclists (output contains all
2578 ** positions contained in either argument doclist). If the docids in the
2579 ** input doclists are sorted in ascending order, parameter bDescDoclist
2580 ** should be false. If they are sorted in ascending order, it should be
2581 ** passed a non-zero value.
2583 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
2584 ** containing the output doclist and SQLITE_OK is returned. In this case
2585 ** *pnOut is set to the number of bytes in the output doclist.
2587 ** If an error occurs, an SQLite error code is returned. The output values
2588 ** are undefined in this case.
2590 static int fts3DoclistOrMerge(
2591 int bDescDoclist, /* True if arguments are desc */
2592 char *a1, int n1, /* First doclist */
2593 char *a2, int n2, /* Second doclist */
2594 char **paOut, int *pnOut /* OUT: Malloc'd doclist */
2596 int rc = SQLITE_OK;
2597 sqlite3_int64 i1 = 0;
2598 sqlite3_int64 i2 = 0;
2599 sqlite3_int64 iPrev = 0;
2600 char *pEnd1 = &a1[n1];
2601 char *pEnd2 = &a2[n2];
2602 char *p1 = a1;
2603 char *p2 = a2;
2604 char *p;
2605 char *aOut;
2606 int bFirstOut = 0;
2608 *paOut = 0;
2609 *pnOut = 0;
2611 /* Allocate space for the output. Both the input and output doclists
2612 ** are delta encoded. If they are in ascending order (bDescDoclist==0),
2613 ** then the first docid in each list is simply encoded as a varint. For
2614 ** each subsequent docid, the varint stored is the difference between the
2615 ** current and previous docid (a positive number - since the list is in
2616 ** ascending order).
2618 ** The first docid written to the output is therefore encoded using the
2619 ** same number of bytes as it is in whichever of the input lists it is
2620 ** read from. And each subsequent docid read from the same input list
2621 ** consumes either the same or less bytes as it did in the input (since
2622 ** the difference between it and the previous value in the output must
2623 ** be a positive value less than or equal to the delta value read from
2624 ** the input list). The same argument applies to all but the first docid
2625 ** read from the 'other' list. And to the contents of all position lists
2626 ** that will be copied and merged from the input to the output.
2628 ** However, if the first docid copied to the output is a negative number,
2629 ** then the encoding of the first docid from the 'other' input list may
2630 ** be larger in the output than it was in the input (since the delta value
2631 ** may be a larger positive integer than the actual docid).
2633 ** The space required to store the output is therefore the sum of the
2634 ** sizes of the two inputs, plus enough space for exactly one of the input
2635 ** docids to grow.
2637 ** A symetric argument may be made if the doclists are in descending
2638 ** order.
2640 aOut = sqlite3_malloc64((i64)n1+n2+FTS3_VARINT_MAX-1+FTS3_BUFFER_PADDING);
2641 if( !aOut ) return SQLITE_NOMEM;
2643 p = aOut;
2644 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
2645 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
2646 while( p1 || p2 ){
2647 sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
2649 if( p2 && p1 && iDiff==0 ){
2650 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
2651 rc = fts3PoslistMerge(&p, &p1, &p2);
2652 if( rc ) break;
2653 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
2654 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
2655 }else if( !p2 || (p1 && iDiff<0) ){
2656 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
2657 fts3PoslistCopy(&p, &p1);
2658 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
2659 }else{
2660 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
2661 fts3PoslistCopy(&p, &p2);
2662 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
2665 assert( (p-aOut)<=((p1?(p1-a1):n1)+(p2?(p2-a2):n2)+FTS3_VARINT_MAX-1) );
2668 if( rc!=SQLITE_OK ){
2669 sqlite3_free(aOut);
2670 p = aOut = 0;
2671 }else{
2672 assert( (p-aOut)<=n1+n2+FTS3_VARINT_MAX-1 );
2673 memset(&aOut[(p-aOut)], 0, FTS3_BUFFER_PADDING);
2675 *paOut = aOut;
2676 *pnOut = (int)(p-aOut);
2677 return rc;
2681 ** This function does a "phrase" merge of two doclists. In a phrase merge,
2682 ** the output contains a copy of each position from the right-hand input
2683 ** doclist for which there is a position in the left-hand input doclist
2684 ** exactly nDist tokens before it.
2686 ** If the docids in the input doclists are sorted in ascending order,
2687 ** parameter bDescDoclist should be false. If they are sorted in ascending
2688 ** order, it should be passed a non-zero value.
2690 ** The right-hand input doclist is overwritten by this function.
2692 static int fts3DoclistPhraseMerge(
2693 int bDescDoclist, /* True if arguments are desc */
2694 int nDist, /* Distance from left to right (1=adjacent) */
2695 char *aLeft, int nLeft, /* Left doclist */
2696 char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
2698 sqlite3_int64 i1 = 0;
2699 sqlite3_int64 i2 = 0;
2700 sqlite3_int64 iPrev = 0;
2701 char *aRight = *paRight;
2702 char *pEnd1 = &aLeft[nLeft];
2703 char *pEnd2 = &aRight[*pnRight];
2704 char *p1 = aLeft;
2705 char *p2 = aRight;
2706 char *p;
2707 int bFirstOut = 0;
2708 char *aOut;
2710 assert( nDist>0 );
2711 if( bDescDoclist ){
2712 aOut = sqlite3_malloc64((sqlite3_int64)*pnRight + FTS3_VARINT_MAX);
2713 if( aOut==0 ) return SQLITE_NOMEM;
2714 }else{
2715 aOut = aRight;
2717 p = aOut;
2719 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
2720 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
2722 while( p1 && p2 ){
2723 sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
2724 if( iDiff==0 ){
2725 char *pSave = p;
2726 sqlite3_int64 iPrevSave = iPrev;
2727 int bFirstOutSave = bFirstOut;
2729 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
2730 if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
2731 p = pSave;
2732 iPrev = iPrevSave;
2733 bFirstOut = bFirstOutSave;
2735 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
2736 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
2737 }else if( iDiff<0 ){
2738 fts3PoslistCopy(0, &p1);
2739 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
2740 }else{
2741 fts3PoslistCopy(0, &p2);
2742 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
2746 *pnRight = (int)(p - aOut);
2747 if( bDescDoclist ){
2748 sqlite3_free(aRight);
2749 *paRight = aOut;
2752 return SQLITE_OK;
2756 ** Argument pList points to a position list nList bytes in size. This
2757 ** function checks to see if the position list contains any entries for
2758 ** a token in position 0 (of any column). If so, it writes argument iDelta
2759 ** to the output buffer pOut, followed by a position list consisting only
2760 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
2761 ** The value returned is the number of bytes written to pOut (if any).
2763 int sqlite3Fts3FirstFilter(
2764 sqlite3_int64 iDelta, /* Varint that may be written to pOut */
2765 char *pList, /* Position list (no 0x00 term) */
2766 int nList, /* Size of pList in bytes */
2767 char *pOut /* Write output here */
2769 int nOut = 0;
2770 int bWritten = 0; /* True once iDelta has been written */
2771 char *p = pList;
2772 char *pEnd = &pList[nList];
2774 if( *p!=0x01 ){
2775 if( *p==0x02 ){
2776 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
2777 pOut[nOut++] = 0x02;
2778 bWritten = 1;
2780 fts3ColumnlistCopy(0, &p);
2783 while( p<pEnd ){
2784 sqlite3_int64 iCol;
2785 p++;
2786 p += sqlite3Fts3GetVarint(p, &iCol);
2787 if( *p==0x02 ){
2788 if( bWritten==0 ){
2789 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
2790 bWritten = 1;
2792 pOut[nOut++] = 0x01;
2793 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
2794 pOut[nOut++] = 0x02;
2796 fts3ColumnlistCopy(0, &p);
2798 if( bWritten ){
2799 pOut[nOut++] = 0x00;
2802 return nOut;
2807 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
2808 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
2809 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
2811 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
2812 ** the responsibility of the caller to free any doclists left in the
2813 ** TermSelect.aaOutput[] array.
2815 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
2816 char *aOut = 0;
2817 int nOut = 0;
2818 int i;
2820 /* Loop through the doclists in the aaOutput[] array. Merge them all
2821 ** into a single doclist.
2823 for(i=0; i<SizeofArray(pTS->aaOutput); i++){
2824 if( pTS->aaOutput[i] ){
2825 if( !aOut ){
2826 aOut = pTS->aaOutput[i];
2827 nOut = pTS->anOutput[i];
2828 pTS->aaOutput[i] = 0;
2829 }else{
2830 int nNew;
2831 char *aNew;
2833 int rc = fts3DoclistOrMerge(p->bDescIdx,
2834 pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
2836 if( rc!=SQLITE_OK ){
2837 sqlite3_free(aOut);
2838 return rc;
2841 sqlite3_free(pTS->aaOutput[i]);
2842 sqlite3_free(aOut);
2843 pTS->aaOutput[i] = 0;
2844 aOut = aNew;
2845 nOut = nNew;
2850 pTS->aaOutput[0] = aOut;
2851 pTS->anOutput[0] = nOut;
2852 return SQLITE_OK;
2856 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
2857 ** as the first argument. The merge is an "OR" merge (see function
2858 ** fts3DoclistOrMerge() for details).
2860 ** This function is called with the doclist for each term that matches
2861 ** a queried prefix. It merges all these doclists into one, the doclist
2862 ** for the specified prefix. Since there can be a very large number of
2863 ** doclists to merge, the merging is done pair-wise using the TermSelect
2864 ** object.
2866 ** This function returns SQLITE_OK if the merge is successful, or an
2867 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
2869 static int fts3TermSelectMerge(
2870 Fts3Table *p, /* FTS table handle */
2871 TermSelect *pTS, /* TermSelect object to merge into */
2872 char *aDoclist, /* Pointer to doclist */
2873 int nDoclist /* Size of aDoclist in bytes */
2875 if( pTS->aaOutput[0]==0 ){
2876 /* If this is the first term selected, copy the doclist to the output
2877 ** buffer using memcpy().
2879 ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
2880 ** allocation. This is so as to ensure that the buffer is big enough
2881 ** to hold the current doclist AND'd with any other doclist. If the
2882 ** doclists are stored in order=ASC order, this padding would not be
2883 ** required (since the size of [doclistA AND doclistB] is always less
2884 ** than or equal to the size of [doclistA] in that case). But this is
2885 ** not true for order=DESC. For example, a doclist containing (1, -1)
2886 ** may be smaller than (-1), as in the first example the -1 may be stored
2887 ** as a single-byte delta, whereas in the second it must be stored as a
2888 ** FTS3_VARINT_MAX byte varint.
2890 ** Similar padding is added in the fts3DoclistOrMerge() function.
2892 pTS->aaOutput[0] = sqlite3_malloc64((i64)nDoclist + FTS3_VARINT_MAX + 1);
2893 pTS->anOutput[0] = nDoclist;
2894 if( pTS->aaOutput[0] ){
2895 memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
2896 memset(&pTS->aaOutput[0][nDoclist], 0, FTS3_VARINT_MAX);
2897 }else{
2898 return SQLITE_NOMEM;
2900 }else{
2901 char *aMerge = aDoclist;
2902 int nMerge = nDoclist;
2903 int iOut;
2905 for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
2906 if( pTS->aaOutput[iOut]==0 ){
2907 assert( iOut>0 );
2908 pTS->aaOutput[iOut] = aMerge;
2909 pTS->anOutput[iOut] = nMerge;
2910 break;
2911 }else{
2912 char *aNew;
2913 int nNew;
2915 int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
2916 pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
2918 if( rc!=SQLITE_OK ){
2919 if( aMerge!=aDoclist ) sqlite3_free(aMerge);
2920 return rc;
2923 if( aMerge!=aDoclist ) sqlite3_free(aMerge);
2924 sqlite3_free(pTS->aaOutput[iOut]);
2925 pTS->aaOutput[iOut] = 0;
2927 aMerge = aNew;
2928 nMerge = nNew;
2929 if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
2930 pTS->aaOutput[iOut] = aMerge;
2931 pTS->anOutput[iOut] = nMerge;
2936 return SQLITE_OK;
2940 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
2942 static int fts3SegReaderCursorAppend(
2943 Fts3MultiSegReader *pCsr,
2944 Fts3SegReader *pNew
2946 if( (pCsr->nSegment%16)==0 ){
2947 Fts3SegReader **apNew;
2948 sqlite3_int64 nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
2949 apNew = (Fts3SegReader **)sqlite3_realloc64(pCsr->apSegment, nByte);
2950 if( !apNew ){
2951 sqlite3Fts3SegReaderFree(pNew);
2952 return SQLITE_NOMEM;
2954 pCsr->apSegment = apNew;
2956 pCsr->apSegment[pCsr->nSegment++] = pNew;
2957 return SQLITE_OK;
2961 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
2962 ** 8th argument.
2964 ** This function returns SQLITE_OK if successful, or an SQLite error code
2965 ** otherwise.
2967 static int fts3SegReaderCursor(
2968 Fts3Table *p, /* FTS3 table handle */
2969 int iLangid, /* Language id */
2970 int iIndex, /* Index to search (from 0 to p->nIndex-1) */
2971 int iLevel, /* Level of segments to scan */
2972 const char *zTerm, /* Term to query for */
2973 int nTerm, /* Size of zTerm in bytes */
2974 int isPrefix, /* True for a prefix search */
2975 int isScan, /* True to scan from zTerm to EOF */
2976 Fts3MultiSegReader *pCsr /* Cursor object to populate */
2978 int rc = SQLITE_OK; /* Error code */
2979 sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
2980 int rc2; /* Result of sqlite3_reset() */
2982 /* If iLevel is less than 0 and this is not a scan, include a seg-reader
2983 ** for the pending-terms. If this is a scan, then this call must be being
2984 ** made by an fts4aux module, not an FTS table. In this case calling
2985 ** Fts3SegReaderPending might segfault, as the data structures used by
2986 ** fts4aux are not completely populated. So it's easiest to filter these
2987 ** calls out here. */
2988 if( iLevel<0 && p->aIndex && p->iPrevLangid==iLangid ){
2989 Fts3SegReader *pSeg = 0;
2990 rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
2991 if( rc==SQLITE_OK && pSeg ){
2992 rc = fts3SegReaderCursorAppend(pCsr, pSeg);
2996 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
2997 if( rc==SQLITE_OK ){
2998 rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
3001 while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
3002 Fts3SegReader *pSeg = 0;
3004 /* Read the values returned by the SELECT into local variables. */
3005 sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
3006 sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
3007 sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
3008 int nRoot = sqlite3_column_bytes(pStmt, 4);
3009 char const *zRoot = sqlite3_column_blob(pStmt, 4);
3011 /* If zTerm is not NULL, and this segment is not stored entirely on its
3012 ** root node, the range of leaves scanned can be reduced. Do this. */
3013 if( iStartBlock && zTerm && zRoot ){
3014 sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
3015 rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
3016 if( rc!=SQLITE_OK ) goto finished;
3017 if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
3020 rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
3021 (isPrefix==0 && isScan==0),
3022 iStartBlock, iLeavesEndBlock,
3023 iEndBlock, zRoot, nRoot, &pSeg
3025 if( rc!=SQLITE_OK ) goto finished;
3026 rc = fts3SegReaderCursorAppend(pCsr, pSeg);
3030 finished:
3031 rc2 = sqlite3_reset(pStmt);
3032 if( rc==SQLITE_DONE ) rc = rc2;
3034 return rc;
3038 ** Set up a cursor object for iterating through a full-text index or a
3039 ** single level therein.
3041 int sqlite3Fts3SegReaderCursor(
3042 Fts3Table *p, /* FTS3 table handle */
3043 int iLangid, /* Language-id to search */
3044 int iIndex, /* Index to search (from 0 to p->nIndex-1) */
3045 int iLevel, /* Level of segments to scan */
3046 const char *zTerm, /* Term to query for */
3047 int nTerm, /* Size of zTerm in bytes */
3048 int isPrefix, /* True for a prefix search */
3049 int isScan, /* True to scan from zTerm to EOF */
3050 Fts3MultiSegReader *pCsr /* Cursor object to populate */
3052 assert( iIndex>=0 && iIndex<p->nIndex );
3053 assert( iLevel==FTS3_SEGCURSOR_ALL
3054 || iLevel==FTS3_SEGCURSOR_PENDING
3055 || iLevel>=0
3057 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
3058 assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
3059 assert( isPrefix==0 || isScan==0 );
3061 memset(pCsr, 0, sizeof(Fts3MultiSegReader));
3062 return fts3SegReaderCursor(
3063 p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
3068 ** In addition to its current configuration, have the Fts3MultiSegReader
3069 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
3071 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
3073 static int fts3SegReaderCursorAddZero(
3074 Fts3Table *p, /* FTS virtual table handle */
3075 int iLangid,
3076 const char *zTerm, /* Term to scan doclist of */
3077 int nTerm, /* Number of bytes in zTerm */
3078 Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
3080 return fts3SegReaderCursor(p,
3081 iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
3086 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
3087 ** if isPrefix is true, to scan the doclist for all terms for which
3088 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
3089 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
3090 ** an SQLite error code.
3092 ** It is the responsibility of the caller to free this object by eventually
3093 ** passing it to fts3SegReaderCursorFree()
3095 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
3096 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
3098 static int fts3TermSegReaderCursor(
3099 Fts3Cursor *pCsr, /* Virtual table cursor handle */
3100 const char *zTerm, /* Term to query for */
3101 int nTerm, /* Size of zTerm in bytes */
3102 int isPrefix, /* True for a prefix search */
3103 Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
3105 Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
3106 int rc = SQLITE_NOMEM; /* Return code */
3108 pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
3109 if( pSegcsr ){
3110 int i;
3111 int bFound = 0; /* True once an index has been found */
3112 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
3114 if( isPrefix ){
3115 for(i=1; bFound==0 && i<p->nIndex; i++){
3116 if( p->aIndex[i].nPrefix==nTerm ){
3117 bFound = 1;
3118 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
3119 i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
3121 pSegcsr->bLookup = 1;
3125 for(i=1; bFound==0 && i<p->nIndex; i++){
3126 if( p->aIndex[i].nPrefix==nTerm+1 ){
3127 bFound = 1;
3128 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
3129 i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
3131 if( rc==SQLITE_OK ){
3132 rc = fts3SegReaderCursorAddZero(
3133 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
3140 if( bFound==0 ){
3141 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
3142 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
3144 pSegcsr->bLookup = !isPrefix;
3148 *ppSegcsr = pSegcsr;
3149 return rc;
3153 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
3155 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
3156 sqlite3Fts3SegReaderFinish(pSegcsr);
3157 sqlite3_free(pSegcsr);
3161 ** This function retrieves the doclist for the specified term (or term
3162 ** prefix) from the database.
3164 static int fts3TermSelect(
3165 Fts3Table *p, /* Virtual table handle */
3166 Fts3PhraseToken *pTok, /* Token to query for */
3167 int iColumn, /* Column to query (or -ve for all columns) */
3168 int *pnOut, /* OUT: Size of buffer at *ppOut */
3169 char **ppOut /* OUT: Malloced result buffer */
3171 int rc; /* Return code */
3172 Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
3173 TermSelect tsc; /* Object for pair-wise doclist merging */
3174 Fts3SegFilter filter; /* Segment term filter configuration */
3176 pSegcsr = pTok->pSegcsr;
3177 memset(&tsc, 0, sizeof(TermSelect));
3179 filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
3180 | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
3181 | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
3182 | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
3183 filter.iCol = iColumn;
3184 filter.zTerm = pTok->z;
3185 filter.nTerm = pTok->n;
3187 rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
3188 while( SQLITE_OK==rc
3189 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
3191 rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
3194 if( rc==SQLITE_OK ){
3195 rc = fts3TermSelectFinishMerge(p, &tsc);
3197 if( rc==SQLITE_OK ){
3198 *ppOut = tsc.aaOutput[0];
3199 *pnOut = tsc.anOutput[0];
3200 }else{
3201 int i;
3202 for(i=0; i<SizeofArray(tsc.aaOutput); i++){
3203 sqlite3_free(tsc.aaOutput[i]);
3207 fts3SegReaderCursorFree(pSegcsr);
3208 pTok->pSegcsr = 0;
3209 return rc;
3213 ** This function counts the total number of docids in the doclist stored
3214 ** in buffer aList[], size nList bytes.
3216 ** If the isPoslist argument is true, then it is assumed that the doclist
3217 ** contains a position-list following each docid. Otherwise, it is assumed
3218 ** that the doclist is simply a list of docids stored as delta encoded
3219 ** varints.
3221 static int fts3DoclistCountDocids(char *aList, int nList){
3222 int nDoc = 0; /* Return value */
3223 if( aList ){
3224 char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
3225 char *p = aList; /* Cursor */
3226 while( p<aEnd ){
3227 nDoc++;
3228 while( (*p++)&0x80 ); /* Skip docid varint */
3229 fts3PoslistCopy(0, &p); /* Skip over position list */
3233 return nDoc;
3237 ** Advance the cursor to the next row in the %_content table that
3238 ** matches the search criteria. For a MATCH search, this will be
3239 ** the next row that matches. For a full-table scan, this will be
3240 ** simply the next row in the %_content table. For a docid lookup,
3241 ** this routine simply sets the EOF flag.
3243 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
3244 ** even if we reach end-of-file. The fts3EofMethod() will be called
3245 ** subsequently to determine whether or not an EOF was hit.
3247 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
3248 int rc;
3249 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
3250 if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
3251 Fts3Table *pTab = (Fts3Table*)pCursor->pVtab;
3252 pTab->bLock++;
3253 if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
3254 pCsr->isEof = 1;
3255 rc = sqlite3_reset(pCsr->pStmt);
3256 }else{
3257 pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
3258 rc = SQLITE_OK;
3260 pTab->bLock--;
3261 }else{
3262 rc = fts3EvalNext((Fts3Cursor *)pCursor);
3264 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
3265 return rc;
3269 ** If the numeric type of argument pVal is "integer", then return it
3270 ** converted to a 64-bit signed integer. Otherwise, return a copy of
3271 ** the second parameter, iDefault.
3273 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
3274 if( pVal ){
3275 int eType = sqlite3_value_numeric_type(pVal);
3276 if( eType==SQLITE_INTEGER ){
3277 return sqlite3_value_int64(pVal);
3280 return iDefault;
3284 ** This is the xFilter interface for the virtual table. See
3285 ** the virtual table xFilter method documentation for additional
3286 ** information.
3288 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
3289 ** the %_content table.
3291 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
3292 ** in the %_content table.
3294 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
3295 ** column on the left-hand side of the MATCH operator is column
3296 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
3297 ** side of the MATCH operator.
3299 static int fts3FilterMethod(
3300 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
3301 int idxNum, /* Strategy index */
3302 const char *idxStr, /* Unused */
3303 int nVal, /* Number of elements in apVal */
3304 sqlite3_value **apVal /* Arguments for the indexing scheme */
3306 int rc = SQLITE_OK;
3307 char *zSql; /* SQL statement used to access %_content */
3308 int eSearch;
3309 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
3310 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
3312 sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
3313 sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
3314 sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
3315 sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
3316 int iIdx;
3318 UNUSED_PARAMETER(idxStr);
3319 UNUSED_PARAMETER(nVal);
3321 if( p->bLock ){
3322 return SQLITE_ERROR;
3325 eSearch = (idxNum & 0x0000FFFF);
3326 assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
3327 assert( p->pSegments==0 );
3329 /* Collect arguments into local variables */
3330 iIdx = 0;
3331 if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
3332 if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
3333 if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
3334 if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
3335 assert( iIdx==nVal );
3337 /* In case the cursor has been used before, clear it now. */
3338 fts3ClearCursor(pCsr);
3340 /* Set the lower and upper bounds on docids to return */
3341 pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
3342 pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
3344 if( idxStr ){
3345 pCsr->bDesc = (idxStr[0]=='D');
3346 }else{
3347 pCsr->bDesc = p->bDescIdx;
3349 pCsr->eSearch = (i16)eSearch;
3351 if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
3352 int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
3353 const char *zQuery = (const char *)sqlite3_value_text(pCons);
3355 if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
3356 return SQLITE_NOMEM;
3359 pCsr->iLangid = 0;
3360 if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
3362 assert( p->base.zErrMsg==0 );
3363 rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
3364 p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
3365 &p->base.zErrMsg
3367 if( rc!=SQLITE_OK ){
3368 return rc;
3371 rc = fts3EvalStart(pCsr);
3372 sqlite3Fts3SegmentsClose(p);
3373 if( rc!=SQLITE_OK ) return rc;
3374 pCsr->pNextId = pCsr->aDoclist;
3375 pCsr->iPrevId = 0;
3378 /* Compile a SELECT statement for this cursor. For a full-table-scan, the
3379 ** statement loops through all rows of the %_content table. For a
3380 ** full-text query or docid lookup, the statement retrieves a single
3381 ** row by docid.
3383 if( eSearch==FTS3_FULLSCAN_SEARCH ){
3384 if( pDocidGe || pDocidLe ){
3385 zSql = sqlite3_mprintf(
3386 "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
3387 p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
3388 (pCsr->bDesc ? "DESC" : "ASC")
3390 }else{
3391 zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
3392 p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
3395 if( zSql ){
3396 p->bLock++;
3397 rc = sqlite3_prepare_v3(
3398 p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0
3400 p->bLock--;
3401 sqlite3_free(zSql);
3402 }else{
3403 rc = SQLITE_NOMEM;
3405 }else if( eSearch==FTS3_DOCID_SEARCH ){
3406 rc = fts3CursorSeekStmt(pCsr);
3407 if( rc==SQLITE_OK ){
3408 rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
3411 if( rc!=SQLITE_OK ) return rc;
3413 return fts3NextMethod(pCursor);
3417 ** This is the xEof method of the virtual table. SQLite calls this
3418 ** routine to find out if it has reached the end of a result set.
3420 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
3421 Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
3422 if( pCsr->isEof ){
3423 fts3ClearCursor(pCsr);
3424 pCsr->isEof = 1;
3426 return pCsr->isEof;
3430 ** This is the xRowid method. The SQLite core calls this routine to
3431 ** retrieve the rowid for the current row of the result set. fts3
3432 ** exposes %_content.docid as the rowid for the virtual table. The
3433 ** rowid should be written to *pRowid.
3435 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
3436 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
3437 *pRowid = pCsr->iPrevId;
3438 return SQLITE_OK;
3442 ** This is the xColumn method, called by SQLite to request a value from
3443 ** the row that the supplied cursor currently points to.
3445 ** If:
3447 ** (iCol < p->nColumn) -> The value of the iCol'th user column.
3448 ** (iCol == p->nColumn) -> Magic column with the same name as the table.
3449 ** (iCol == p->nColumn+1) -> Docid column
3450 ** (iCol == p->nColumn+2) -> Langid column
3452 static int fts3ColumnMethod(
3453 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
3454 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
3455 int iCol /* Index of column to read value from */
3457 int rc = SQLITE_OK; /* Return Code */
3458 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
3459 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
3461 /* The column value supplied by SQLite must be in range. */
3462 assert( iCol>=0 && iCol<=p->nColumn+2 );
3464 switch( iCol-p->nColumn ){
3465 case 0:
3466 /* The special 'table-name' column */
3467 sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
3468 break;
3470 case 1:
3471 /* The docid column */
3472 sqlite3_result_int64(pCtx, pCsr->iPrevId);
3473 break;
3475 case 2:
3476 if( pCsr->pExpr ){
3477 sqlite3_result_int64(pCtx, pCsr->iLangid);
3478 break;
3479 }else if( p->zLanguageid==0 ){
3480 sqlite3_result_int(pCtx, 0);
3481 break;
3482 }else{
3483 iCol = p->nColumn;
3484 /* no break */ deliberate_fall_through
3487 default:
3488 /* A user column. Or, if this is a full-table scan, possibly the
3489 ** language-id column. Seek the cursor. */
3490 rc = fts3CursorSeek(0, pCsr);
3491 if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
3492 sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
3494 break;
3497 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
3498 return rc;
3502 ** This function is the implementation of the xUpdate callback used by
3503 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
3504 ** inserted, updated or deleted.
3506 static int fts3UpdateMethod(
3507 sqlite3_vtab *pVtab, /* Virtual table handle */
3508 int nArg, /* Size of argument array */
3509 sqlite3_value **apVal, /* Array of arguments */
3510 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
3512 return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
3516 ** Implementation of xSync() method. Flush the contents of the pending-terms
3517 ** hash-table to the database.
3519 static int fts3SyncMethod(sqlite3_vtab *pVtab){
3521 /* Following an incremental-merge operation, assuming that the input
3522 ** segments are not completely consumed (the usual case), they are updated
3523 ** in place to remove the entries that have already been merged. This
3524 ** involves updating the leaf block that contains the smallest unmerged
3525 ** entry and each block (if any) between the leaf and the root node. So
3526 ** if the height of the input segment b-trees is N, and input segments
3527 ** are merged eight at a time, updating the input segments at the end
3528 ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
3529 ** small - often between 0 and 2. So the overhead of the incremental
3530 ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
3531 ** dwarfing the actual productive work accomplished, the incremental merge
3532 ** is only attempted if it will write at least 64 leaf blocks. Hence
3533 ** nMinMerge.
3535 ** Of course, updating the input segments also involves deleting a bunch
3536 ** of blocks from the segments table. But this is not considered overhead
3537 ** as it would also be required by a crisis-merge that used the same input
3538 ** segments.
3540 const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
3542 Fts3Table *p = (Fts3Table*)pVtab;
3543 int rc;
3544 i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
3546 rc = sqlite3Fts3PendingTermsFlush(p);
3547 if( rc==SQLITE_OK
3548 && p->nLeafAdd>(nMinMerge/16)
3549 && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
3551 int mxLevel = 0; /* Maximum relative level value in db */
3552 int A; /* Incr-merge parameter A */
3554 rc = sqlite3Fts3MaxLevel(p, &mxLevel);
3555 assert( rc==SQLITE_OK || mxLevel==0 );
3556 A = p->nLeafAdd * mxLevel;
3557 A += (A/2);
3558 if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
3560 sqlite3Fts3SegmentsClose(p);
3561 sqlite3_set_last_insert_rowid(p->db, iLastRowid);
3562 return rc;
3566 ** If it is currently unknown whether or not the FTS table has an %_stat
3567 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
3568 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
3569 ** if an error occurs.
3571 static int fts3SetHasStat(Fts3Table *p){
3572 int rc = SQLITE_OK;
3573 if( p->bHasStat==2 ){
3574 char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
3575 if( zTbl ){
3576 int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
3577 sqlite3_free(zTbl);
3578 p->bHasStat = (res==SQLITE_OK);
3579 }else{
3580 rc = SQLITE_NOMEM;
3583 return rc;
3587 ** Implementation of xBegin() method.
3589 static int fts3BeginMethod(sqlite3_vtab *pVtab){
3590 Fts3Table *p = (Fts3Table*)pVtab;
3591 int rc;
3592 UNUSED_PARAMETER(pVtab);
3593 assert( p->pSegments==0 );
3594 assert( p->nPendingData==0 );
3595 assert( p->inTransaction!=1 );
3596 p->nLeafAdd = 0;
3597 rc = fts3SetHasStat(p);
3598 #ifdef SQLITE_DEBUG
3599 if( rc==SQLITE_OK ){
3600 p->inTransaction = 1;
3601 p->mxSavepoint = -1;
3603 #endif
3604 return rc;
3608 ** Implementation of xCommit() method. This is a no-op. The contents of
3609 ** the pending-terms hash-table have already been flushed into the database
3610 ** by fts3SyncMethod().
3612 static int fts3CommitMethod(sqlite3_vtab *pVtab){
3613 TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
3614 UNUSED_PARAMETER(pVtab);
3615 assert( p->nPendingData==0 );
3616 assert( p->inTransaction!=0 );
3617 assert( p->pSegments==0 );
3618 TESTONLY( p->inTransaction = 0 );
3619 TESTONLY( p->mxSavepoint = -1; );
3620 return SQLITE_OK;
3624 ** Implementation of xRollback(). Discard the contents of the pending-terms
3625 ** hash-table. Any changes made to the database are reverted by SQLite.
3627 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
3628 Fts3Table *p = (Fts3Table*)pVtab;
3629 sqlite3Fts3PendingTermsClear(p);
3630 assert( p->inTransaction!=0 );
3631 TESTONLY( p->inTransaction = 0 );
3632 TESTONLY( p->mxSavepoint = -1; );
3633 return SQLITE_OK;
3637 ** When called, *ppPoslist must point to the byte immediately following the
3638 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
3639 ** moves *ppPoslist so that it instead points to the first byte of the
3640 ** same position list.
3642 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
3643 char *p = &(*ppPoslist)[-2];
3644 char c = 0;
3646 /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
3647 while( p>pStart && (c=*p--)==0 );
3649 /* Search backwards for a varint with value zero (the end of the previous
3650 ** poslist). This is an 0x00 byte preceded by some byte that does not
3651 ** have the 0x80 bit set. */
3652 while( p>pStart && (*p & 0x80) | c ){
3653 c = *p--;
3655 assert( p==pStart || c==0 );
3657 /* At this point p points to that preceding byte without the 0x80 bit
3658 ** set. So to find the start of the poslist, skip forward 2 bytes then
3659 ** over a varint.
3661 ** Normally. The other case is that p==pStart and the poslist to return
3662 ** is the first in the doclist. In this case do not skip forward 2 bytes.
3663 ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
3664 ** is required for cases where the first byte of a doclist and the
3665 ** doclist is empty. For example, if the first docid is 10, a doclist
3666 ** that begins with:
3668 ** 0x0A 0x00 <next docid delta varint>
3670 if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
3671 while( *p++&0x80 );
3672 *ppPoslist = p;
3676 ** Helper function used by the implementation of the overloaded snippet(),
3677 ** offsets() and optimize() SQL functions.
3679 ** If the value passed as the third argument is a blob of size
3680 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
3681 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
3682 ** message is written to context pContext and SQLITE_ERROR returned. The
3683 ** string passed via zFunc is used as part of the error message.
3685 static int fts3FunctionArg(
3686 sqlite3_context *pContext, /* SQL function call context */
3687 const char *zFunc, /* Function name */
3688 sqlite3_value *pVal, /* argv[0] passed to function */
3689 Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
3691 int rc;
3692 *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
3693 if( (*ppCsr)!=0 ){
3694 rc = SQLITE_OK;
3695 }else{
3696 char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
3697 sqlite3_result_error(pContext, zErr, -1);
3698 sqlite3_free(zErr);
3699 rc = SQLITE_ERROR;
3701 return rc;
3705 ** Implementation of the snippet() function for FTS3
3707 static void fts3SnippetFunc(
3708 sqlite3_context *pContext, /* SQLite function call context */
3709 int nVal, /* Size of apVal[] array */
3710 sqlite3_value **apVal /* Array of arguments */
3712 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
3713 const char *zStart = "<b>";
3714 const char *zEnd = "</b>";
3715 const char *zEllipsis = "<b>...</b>";
3716 int iCol = -1;
3717 int nToken = 15; /* Default number of tokens in snippet */
3719 /* There must be at least one argument passed to this function (otherwise
3720 ** the non-overloaded version would have been called instead of this one).
3722 assert( nVal>=1 );
3724 if( nVal>6 ){
3725 sqlite3_result_error(pContext,
3726 "wrong number of arguments to function snippet()", -1);
3727 return;
3729 if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
3731 switch( nVal ){
3732 case 6: nToken = sqlite3_value_int(apVal[5]);
3733 /* no break */ deliberate_fall_through
3734 case 5: iCol = sqlite3_value_int(apVal[4]);
3735 /* no break */ deliberate_fall_through
3736 case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
3737 /* no break */ deliberate_fall_through
3738 case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
3739 /* no break */ deliberate_fall_through
3740 case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
3742 if( !zEllipsis || !zEnd || !zStart ){
3743 sqlite3_result_error_nomem(pContext);
3744 }else if( nToken==0 ){
3745 sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
3746 }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
3747 sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
3752 ** Implementation of the offsets() function for FTS3
3754 static void fts3OffsetsFunc(
3755 sqlite3_context *pContext, /* SQLite function call context */
3756 int nVal, /* Size of argument array */
3757 sqlite3_value **apVal /* Array of arguments */
3759 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
3761 UNUSED_PARAMETER(nVal);
3763 assert( nVal==1 );
3764 if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
3765 assert( pCsr );
3766 if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
3767 sqlite3Fts3Offsets(pContext, pCsr);
3772 ** Implementation of the special optimize() function for FTS3. This
3773 ** function merges all segments in the database to a single segment.
3774 ** Example usage is:
3776 ** SELECT optimize(t) FROM t LIMIT 1;
3778 ** where 't' is the name of an FTS3 table.
3780 static void fts3OptimizeFunc(
3781 sqlite3_context *pContext, /* SQLite function call context */
3782 int nVal, /* Size of argument array */
3783 sqlite3_value **apVal /* Array of arguments */
3785 int rc; /* Return code */
3786 Fts3Table *p; /* Virtual table handle */
3787 Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
3789 UNUSED_PARAMETER(nVal);
3791 assert( nVal==1 );
3792 if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
3793 p = (Fts3Table *)pCursor->base.pVtab;
3794 assert( p );
3796 rc = sqlite3Fts3Optimize(p);
3798 switch( rc ){
3799 case SQLITE_OK:
3800 sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
3801 break;
3802 case SQLITE_DONE:
3803 sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
3804 break;
3805 default:
3806 sqlite3_result_error_code(pContext, rc);
3807 break;
3812 ** Implementation of the matchinfo() function for FTS3
3814 static void fts3MatchinfoFunc(
3815 sqlite3_context *pContext, /* SQLite function call context */
3816 int nVal, /* Size of argument array */
3817 sqlite3_value **apVal /* Array of arguments */
3819 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
3820 assert( nVal==1 || nVal==2 );
3821 if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
3822 const char *zArg = 0;
3823 if( nVal>1 ){
3824 zArg = (const char *)sqlite3_value_text(apVal[1]);
3826 sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
3831 ** This routine implements the xFindFunction method for the FTS3
3832 ** virtual table.
3834 static int fts3FindFunctionMethod(
3835 sqlite3_vtab *pVtab, /* Virtual table handle */
3836 int nArg, /* Number of SQL function arguments */
3837 const char *zName, /* Name of SQL function */
3838 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
3839 void **ppArg /* Unused */
3841 struct Overloaded {
3842 const char *zName;
3843 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
3844 } aOverload[] = {
3845 { "snippet", fts3SnippetFunc },
3846 { "offsets", fts3OffsetsFunc },
3847 { "optimize", fts3OptimizeFunc },
3848 { "matchinfo", fts3MatchinfoFunc },
3850 int i; /* Iterator variable */
3852 UNUSED_PARAMETER(pVtab);
3853 UNUSED_PARAMETER(nArg);
3854 UNUSED_PARAMETER(ppArg);
3856 for(i=0; i<SizeofArray(aOverload); i++){
3857 if( strcmp(zName, aOverload[i].zName)==0 ){
3858 *pxFunc = aOverload[i].xFunc;
3859 return 1;
3863 /* No function of the specified name was found. Return 0. */
3864 return 0;
3868 ** Implementation of FTS3 xRename method. Rename an fts3 table.
3870 static int fts3RenameMethod(
3871 sqlite3_vtab *pVtab, /* Virtual table handle */
3872 const char *zName /* New name of table */
3874 Fts3Table *p = (Fts3Table *)pVtab;
3875 sqlite3 *db = p->db; /* Database connection */
3876 int rc; /* Return Code */
3878 /* At this point it must be known if the %_stat table exists or not.
3879 ** So bHasStat may not be 2. */
3880 rc = fts3SetHasStat(p);
3882 /* As it happens, the pending terms table is always empty here. This is
3883 ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
3884 ** always opens a savepoint transaction. And the xSavepoint() method
3885 ** flushes the pending terms table. But leave the (no-op) call to
3886 ** PendingTermsFlush() in in case that changes.
3888 assert( p->nPendingData==0 );
3889 if( rc==SQLITE_OK ){
3890 rc = sqlite3Fts3PendingTermsFlush(p);
3893 p->bIgnoreSavepoint = 1;
3895 if( p->zContentTbl==0 ){
3896 fts3DbExec(&rc, db,
3897 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
3898 p->zDb, p->zName, zName
3902 if( p->bHasDocsize ){
3903 fts3DbExec(&rc, db,
3904 "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
3905 p->zDb, p->zName, zName
3908 if( p->bHasStat ){
3909 fts3DbExec(&rc, db,
3910 "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
3911 p->zDb, p->zName, zName
3914 fts3DbExec(&rc, db,
3915 "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
3916 p->zDb, p->zName, zName
3918 fts3DbExec(&rc, db,
3919 "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
3920 p->zDb, p->zName, zName
3923 p->bIgnoreSavepoint = 0;
3924 return rc;
3928 ** The xSavepoint() method.
3930 ** Flush the contents of the pending-terms table to disk.
3932 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
3933 int rc = SQLITE_OK;
3934 Fts3Table *pTab = (Fts3Table*)pVtab;
3935 assert( pTab->inTransaction );
3936 assert( pTab->mxSavepoint<=iSavepoint );
3937 TESTONLY( pTab->mxSavepoint = iSavepoint );
3939 if( pTab->bIgnoreSavepoint==0 ){
3940 if( fts3HashCount(&pTab->aIndex[0].hPending)>0 ){
3941 char *zSql = sqlite3_mprintf("INSERT INTO %Q.%Q(%Q) VALUES('flush')",
3942 pTab->zDb, pTab->zName, pTab->zName
3944 if( zSql ){
3945 pTab->bIgnoreSavepoint = 1;
3946 rc = sqlite3_exec(pTab->db, zSql, 0, 0, 0);
3947 pTab->bIgnoreSavepoint = 0;
3948 sqlite3_free(zSql);
3949 }else{
3950 rc = SQLITE_NOMEM;
3953 if( rc==SQLITE_OK ){
3954 pTab->iSavepoint = iSavepoint+1;
3957 return rc;
3961 ** The xRelease() method.
3963 ** This is a no-op.
3965 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
3966 Fts3Table *pTab = (Fts3Table*)pVtab;
3967 assert( pTab->inTransaction );
3968 assert( pTab->mxSavepoint >= iSavepoint );
3969 TESTONLY( pTab->mxSavepoint = iSavepoint-1 );
3970 pTab->iSavepoint = iSavepoint;
3971 return SQLITE_OK;
3975 ** The xRollbackTo() method.
3977 ** Discard the contents of the pending terms table.
3979 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
3980 Fts3Table *pTab = (Fts3Table*)pVtab;
3981 UNUSED_PARAMETER(iSavepoint);
3982 assert( pTab->inTransaction );
3983 TESTONLY( pTab->mxSavepoint = iSavepoint );
3984 if( (iSavepoint+1)<=pTab->iSavepoint ){
3985 sqlite3Fts3PendingTermsClear(pTab);
3987 return SQLITE_OK;
3991 ** Return true if zName is the extension on one of the shadow tables used
3992 ** by this module.
3994 static int fts3ShadowName(const char *zName){
3995 static const char *azName[] = {
3996 "content", "docsize", "segdir", "segments", "stat",
3998 unsigned int i;
3999 for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
4000 if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
4002 return 0;
4006 ** Implementation of the xIntegrity() method on the FTS3/FTS4 virtual
4007 ** table.
4009 static int fts3IntegrityMethod(
4010 sqlite3_vtab *pVtab, /* The virtual table to be checked */
4011 const char *zSchema, /* Name of schema in which pVtab lives */
4012 const char *zTabname, /* Name of the pVTab table */
4013 int isQuick, /* True if this is a quick_check */
4014 char **pzErr /* Write error message here */
4016 Fts3Table *p = (Fts3Table*)pVtab;
4017 int rc = SQLITE_OK;
4018 int bOk = 0;
4020 UNUSED_PARAMETER(isQuick);
4021 rc = sqlite3Fts3IntegrityCheck(p, &bOk);
4022 assert( rc!=SQLITE_CORRUPT_VTAB );
4023 if( rc==SQLITE_ERROR || (rc&0xFF)==SQLITE_CORRUPT ){
4024 *pzErr = sqlite3_mprintf("unable to validate the inverted index for"
4025 " FTS%d table %s.%s: %s",
4026 p->bFts4 ? 4 : 3, zSchema, zTabname, sqlite3_errstr(rc));
4027 if( *pzErr ) rc = SQLITE_OK;
4028 }else if( rc==SQLITE_OK && bOk==0 ){
4029 *pzErr = sqlite3_mprintf("malformed inverted index for FTS%d table %s.%s",
4030 p->bFts4 ? 4 : 3, zSchema, zTabname);
4031 if( *pzErr==0 ) rc = SQLITE_NOMEM;
4033 sqlite3Fts3SegmentsClose(p);
4034 return rc;
4039 static const sqlite3_module fts3Module = {
4040 /* iVersion */ 4,
4041 /* xCreate */ fts3CreateMethod,
4042 /* xConnect */ fts3ConnectMethod,
4043 /* xBestIndex */ fts3BestIndexMethod,
4044 /* xDisconnect */ fts3DisconnectMethod,
4045 /* xDestroy */ fts3DestroyMethod,
4046 /* xOpen */ fts3OpenMethod,
4047 /* xClose */ fts3CloseMethod,
4048 /* xFilter */ fts3FilterMethod,
4049 /* xNext */ fts3NextMethod,
4050 /* xEof */ fts3EofMethod,
4051 /* xColumn */ fts3ColumnMethod,
4052 /* xRowid */ fts3RowidMethod,
4053 /* xUpdate */ fts3UpdateMethod,
4054 /* xBegin */ fts3BeginMethod,
4055 /* xSync */ fts3SyncMethod,
4056 /* xCommit */ fts3CommitMethod,
4057 /* xRollback */ fts3RollbackMethod,
4058 /* xFindFunction */ fts3FindFunctionMethod,
4059 /* xRename */ fts3RenameMethod,
4060 /* xSavepoint */ fts3SavepointMethod,
4061 /* xRelease */ fts3ReleaseMethod,
4062 /* xRollbackTo */ fts3RollbackToMethod,
4063 /* xShadowName */ fts3ShadowName,
4064 /* xIntegrity */ fts3IntegrityMethod,
4068 ** This function is registered as the module destructor (called when an
4069 ** FTS3 enabled database connection is closed). It frees the memory
4070 ** allocated for the tokenizer hash table.
4072 static void hashDestroy(void *p){
4073 Fts3HashWrapper *pHash = (Fts3HashWrapper *)p;
4074 pHash->nRef--;
4075 if( pHash->nRef<=0 ){
4076 sqlite3Fts3HashClear(&pHash->hash);
4077 sqlite3_free(pHash);
4082 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
4083 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
4084 ** respectively. The following three forward declarations are for functions
4085 ** declared in these files used to retrieve the respective implementations.
4087 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
4088 ** to by the argument to point to the "simple" tokenizer implementation.
4089 ** And so on.
4091 void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
4092 void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
4093 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4094 void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
4095 #endif
4096 #ifdef SQLITE_ENABLE_ICU
4097 void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
4098 #endif
4101 ** Initialize the fts3 extension. If this extension is built as part
4102 ** of the sqlite library, then this function is called directly by
4103 ** SQLite. If fts3 is built as a dynamically loadable extension, this
4104 ** function is called by the sqlite3_extension_init() entry point.
4106 int sqlite3Fts3Init(sqlite3 *db){
4107 int rc = SQLITE_OK;
4108 Fts3HashWrapper *pHash = 0;
4109 const sqlite3_tokenizer_module *pSimple = 0;
4110 const sqlite3_tokenizer_module *pPorter = 0;
4111 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4112 const sqlite3_tokenizer_module *pUnicode = 0;
4113 #endif
4115 #ifdef SQLITE_ENABLE_ICU
4116 const sqlite3_tokenizer_module *pIcu = 0;
4117 sqlite3Fts3IcuTokenizerModule(&pIcu);
4118 #endif
4120 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4121 sqlite3Fts3UnicodeTokenizer(&pUnicode);
4122 #endif
4124 #ifdef SQLITE_TEST
4125 rc = sqlite3Fts3InitTerm(db);
4126 if( rc!=SQLITE_OK ) return rc;
4127 #endif
4129 rc = sqlite3Fts3InitAux(db);
4130 if( rc!=SQLITE_OK ) return rc;
4132 sqlite3Fts3SimpleTokenizerModule(&pSimple);
4133 sqlite3Fts3PorterTokenizerModule(&pPorter);
4135 /* Allocate and initialize the hash-table used to store tokenizers. */
4136 pHash = sqlite3_malloc(sizeof(Fts3HashWrapper));
4137 if( !pHash ){
4138 rc = SQLITE_NOMEM;
4139 }else{
4140 sqlite3Fts3HashInit(&pHash->hash, FTS3_HASH_STRING, 1);
4141 pHash->nRef = 0;
4144 /* Load the built-in tokenizers into the hash table */
4145 if( rc==SQLITE_OK ){
4146 if( sqlite3Fts3HashInsert(&pHash->hash, "simple", 7, (void *)pSimple)
4147 || sqlite3Fts3HashInsert(&pHash->hash, "porter", 7, (void *)pPorter)
4149 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4150 || sqlite3Fts3HashInsert(&pHash->hash, "unicode61", 10, (void *)pUnicode)
4151 #endif
4152 #ifdef SQLITE_ENABLE_ICU
4153 || (pIcu && sqlite3Fts3HashInsert(&pHash->hash, "icu", 4, (void *)pIcu))
4154 #endif
4156 rc = SQLITE_NOMEM;
4160 #ifdef SQLITE_TEST
4161 if( rc==SQLITE_OK ){
4162 rc = sqlite3Fts3ExprInitTestInterface(db, &pHash->hash);
4164 #endif
4166 /* Create the virtual table wrapper around the hash-table and overload
4167 ** the four scalar functions. If this is successful, register the
4168 ** module with sqlite.
4170 if( SQLITE_OK==rc
4171 && SQLITE_OK==(rc=sqlite3Fts3InitHashTable(db,&pHash->hash,"fts3_tokenizer"))
4172 && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
4173 && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
4174 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
4175 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
4176 && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
4178 pHash->nRef++;
4179 rc = sqlite3_create_module_v2(
4180 db, "fts3", &fts3Module, (void *)pHash, hashDestroy
4182 if( rc==SQLITE_OK ){
4183 pHash->nRef++;
4184 rc = sqlite3_create_module_v2(
4185 db, "fts4", &fts3Module, (void *)pHash, hashDestroy
4188 if( rc==SQLITE_OK ){
4189 pHash->nRef++;
4190 rc = sqlite3Fts3InitTok(db, (void *)pHash, hashDestroy);
4192 return rc;
4196 /* An error has occurred. Delete the hash table and return the error code. */
4197 assert( rc!=SQLITE_OK );
4198 if( pHash ){
4199 sqlite3Fts3HashClear(&pHash->hash);
4200 sqlite3_free(pHash);
4202 return rc;
4206 ** Allocate an Fts3MultiSegReader for each token in the expression headed
4207 ** by pExpr.
4209 ** An Fts3SegReader object is a cursor that can seek or scan a range of
4210 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
4211 ** Fts3SegReader objects internally to provide an interface to seek or scan
4212 ** within the union of all segments of a b-tree. Hence the name.
4214 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
4215 ** segment b-tree (if the term is not a prefix or it is a prefix for which
4216 ** there exists prefix b-tree of the right length) then it may be traversed
4217 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
4218 ** doclist and then traversed.
4220 static void fts3EvalAllocateReaders(
4221 Fts3Cursor *pCsr, /* FTS cursor handle */
4222 Fts3Expr *pExpr, /* Allocate readers for this expression */
4223 int *pnToken, /* OUT: Total number of tokens in phrase. */
4224 int *pnOr, /* OUT: Total number of OR nodes in expr. */
4225 int *pRc /* IN/OUT: Error code */
4227 if( pExpr && SQLITE_OK==*pRc ){
4228 if( pExpr->eType==FTSQUERY_PHRASE ){
4229 int i;
4230 int nToken = pExpr->pPhrase->nToken;
4231 *pnToken += nToken;
4232 for(i=0; i<nToken; i++){
4233 Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
4234 int rc = fts3TermSegReaderCursor(pCsr,
4235 pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
4237 if( rc!=SQLITE_OK ){
4238 *pRc = rc;
4239 return;
4242 assert( pExpr->pPhrase->iDoclistToken==0 );
4243 pExpr->pPhrase->iDoclistToken = -1;
4244 }else{
4245 *pnOr += (pExpr->eType==FTSQUERY_OR);
4246 fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
4247 fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
4253 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
4254 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
4256 ** This function assumes that pList points to a buffer allocated using
4257 ** sqlite3_malloc(). This function takes responsibility for eventually
4258 ** freeing the buffer.
4260 ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
4262 static int fts3EvalPhraseMergeToken(
4263 Fts3Table *pTab, /* FTS Table pointer */
4264 Fts3Phrase *p, /* Phrase to merge pList/nList into */
4265 int iToken, /* Token pList/nList corresponds to */
4266 char *pList, /* Pointer to doclist */
4267 int nList /* Number of bytes in pList */
4269 int rc = SQLITE_OK;
4270 assert( iToken!=p->iDoclistToken );
4272 if( pList==0 ){
4273 sqlite3_free(p->doclist.aAll);
4274 p->doclist.aAll = 0;
4275 p->doclist.nAll = 0;
4278 else if( p->iDoclistToken<0 ){
4279 p->doclist.aAll = pList;
4280 p->doclist.nAll = nList;
4283 else if( p->doclist.aAll==0 ){
4284 sqlite3_free(pList);
4287 else {
4288 char *pLeft;
4289 char *pRight;
4290 int nLeft;
4291 int nRight;
4292 int nDiff;
4294 if( p->iDoclistToken<iToken ){
4295 pLeft = p->doclist.aAll;
4296 nLeft = p->doclist.nAll;
4297 pRight = pList;
4298 nRight = nList;
4299 nDiff = iToken - p->iDoclistToken;
4300 }else{
4301 pRight = p->doclist.aAll;
4302 nRight = p->doclist.nAll;
4303 pLeft = pList;
4304 nLeft = nList;
4305 nDiff = p->iDoclistToken - iToken;
4308 rc = fts3DoclistPhraseMerge(
4309 pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
4311 sqlite3_free(pLeft);
4312 p->doclist.aAll = pRight;
4313 p->doclist.nAll = nRight;
4316 if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
4317 return rc;
4321 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
4322 ** does not take deferred tokens into account.
4324 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
4326 static int fts3EvalPhraseLoad(
4327 Fts3Cursor *pCsr, /* FTS Cursor handle */
4328 Fts3Phrase *p /* Phrase object */
4330 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
4331 int iToken;
4332 int rc = SQLITE_OK;
4334 for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
4335 Fts3PhraseToken *pToken = &p->aToken[iToken];
4336 assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
4338 if( pToken->pSegcsr ){
4339 int nThis = 0;
4340 char *pThis = 0;
4341 rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
4342 if( rc==SQLITE_OK ){
4343 rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
4346 assert( pToken->pSegcsr==0 );
4349 return rc;
4352 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
4354 ** This function is called on each phrase after the position lists for
4355 ** any deferred tokens have been loaded into memory. It updates the phrases
4356 ** current position list to include only those positions that are really
4357 ** instances of the phrase (after considering deferred tokens). If this
4358 ** means that the phrase does not appear in the current row, doclist.pList
4359 ** and doclist.nList are both zeroed.
4361 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
4363 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
4364 int iToken; /* Used to iterate through phrase tokens */
4365 char *aPoslist = 0; /* Position list for deferred tokens */
4366 int nPoslist = 0; /* Number of bytes in aPoslist */
4367 int iPrev = -1; /* Token number of previous deferred token */
4368 char *aFree = (pPhrase->doclist.bFreeList ? pPhrase->doclist.pList : 0);
4370 for(iToken=0; iToken<pPhrase->nToken; iToken++){
4371 Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
4372 Fts3DeferredToken *pDeferred = pToken->pDeferred;
4374 if( pDeferred ){
4375 char *pList;
4376 int nList;
4377 int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
4378 if( rc!=SQLITE_OK ) return rc;
4380 if( pList==0 ){
4381 sqlite3_free(aPoslist);
4382 sqlite3_free(aFree);
4383 pPhrase->doclist.pList = 0;
4384 pPhrase->doclist.nList = 0;
4385 return SQLITE_OK;
4387 }else if( aPoslist==0 ){
4388 aPoslist = pList;
4389 nPoslist = nList;
4391 }else{
4392 char *aOut = pList;
4393 char *p1 = aPoslist;
4394 char *p2 = aOut;
4396 assert( iPrev>=0 );
4397 fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
4398 sqlite3_free(aPoslist);
4399 aPoslist = pList;
4400 nPoslist = (int)(aOut - aPoslist);
4401 if( nPoslist==0 ){
4402 sqlite3_free(aPoslist);
4403 sqlite3_free(aFree);
4404 pPhrase->doclist.pList = 0;
4405 pPhrase->doclist.nList = 0;
4406 return SQLITE_OK;
4409 iPrev = iToken;
4413 if( iPrev>=0 ){
4414 int nMaxUndeferred = pPhrase->iDoclistToken;
4415 if( nMaxUndeferred<0 ){
4416 pPhrase->doclist.pList = aPoslist;
4417 pPhrase->doclist.nList = nPoslist;
4418 pPhrase->doclist.iDocid = pCsr->iPrevId;
4419 pPhrase->doclist.bFreeList = 1;
4420 }else{
4421 int nDistance;
4422 char *p1;
4423 char *p2;
4424 char *aOut;
4426 if( nMaxUndeferred>iPrev ){
4427 p1 = aPoslist;
4428 p2 = pPhrase->doclist.pList;
4429 nDistance = nMaxUndeferred - iPrev;
4430 }else{
4431 p1 = pPhrase->doclist.pList;
4432 p2 = aPoslist;
4433 nDistance = iPrev - nMaxUndeferred;
4436 aOut = (char *)sqlite3Fts3MallocZero(nPoslist+FTS3_BUFFER_PADDING);
4437 if( !aOut ){
4438 sqlite3_free(aPoslist);
4439 return SQLITE_NOMEM;
4442 pPhrase->doclist.pList = aOut;
4443 assert( p1 && p2 );
4444 if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
4445 pPhrase->doclist.bFreeList = 1;
4446 pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
4447 }else{
4448 sqlite3_free(aOut);
4449 pPhrase->doclist.pList = 0;
4450 pPhrase->doclist.nList = 0;
4452 sqlite3_free(aPoslist);
4456 if( pPhrase->doclist.pList!=aFree ) sqlite3_free(aFree);
4457 return SQLITE_OK;
4459 #endif /* SQLITE_DISABLE_FTS4_DEFERRED */
4462 ** Maximum number of tokens a phrase may have to be considered for the
4463 ** incremental doclists strategy.
4465 #define MAX_INCR_PHRASE_TOKENS 4
4468 ** This function is called for each Fts3Phrase in a full-text query
4469 ** expression to initialize the mechanism for returning rows. Once this
4470 ** function has been called successfully on an Fts3Phrase, it may be
4471 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
4473 ** If parameter bOptOk is true, then the phrase may (or may not) use the
4474 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
4475 ** memory within this call.
4477 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
4479 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
4480 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
4481 int rc = SQLITE_OK; /* Error code */
4482 int i;
4484 /* Determine if doclists may be loaded from disk incrementally. This is
4485 ** possible if the bOptOk argument is true, the FTS doclists will be
4486 ** scanned in forward order, and the phrase consists of
4487 ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
4488 ** tokens or prefix tokens that cannot use a prefix-index. */
4489 int bHaveIncr = 0;
4490 int bIncrOk = (bOptOk
4491 && pCsr->bDesc==pTab->bDescIdx
4492 && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
4493 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
4494 && pTab->bNoIncrDoclist==0
4495 #endif
4497 for(i=0; bIncrOk==1 && i<p->nToken; i++){
4498 Fts3PhraseToken *pToken = &p->aToken[i];
4499 if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
4500 bIncrOk = 0;
4502 if( pToken->pSegcsr ) bHaveIncr = 1;
4505 if( bIncrOk && bHaveIncr ){
4506 /* Use the incremental approach. */
4507 int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
4508 for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
4509 Fts3PhraseToken *pToken = &p->aToken[i];
4510 Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
4511 if( pSegcsr ){
4512 rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
4515 p->bIncr = 1;
4516 }else{
4517 /* Load the full doclist for the phrase into memory. */
4518 rc = fts3EvalPhraseLoad(pCsr, p);
4519 p->bIncr = 0;
4522 assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
4523 return rc;
4527 ** This function is used to iterate backwards (from the end to start)
4528 ** through doclists. It is used by this module to iterate through phrase
4529 ** doclists in reverse and by the fts3_write.c module to iterate through
4530 ** pending-terms lists when writing to databases with "order=desc".
4532 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
4533 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
4534 ** function iterates from the end of the doclist to the beginning.
4536 void sqlite3Fts3DoclistPrev(
4537 int bDescIdx, /* True if the doclist is desc */
4538 char *aDoclist, /* Pointer to entire doclist */
4539 int nDoclist, /* Length of aDoclist in bytes */
4540 char **ppIter, /* IN/OUT: Iterator pointer */
4541 sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
4542 int *pnList, /* OUT: List length pointer */
4543 u8 *pbEof /* OUT: End-of-file flag */
4545 char *p = *ppIter;
4547 assert( nDoclist>0 );
4548 assert( *pbEof==0 );
4549 assert_fts3_nc( p || *piDocid==0 );
4550 assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
4552 if( p==0 ){
4553 sqlite3_int64 iDocid = 0;
4554 char *pNext = 0;
4555 char *pDocid = aDoclist;
4556 char *pEnd = &aDoclist[nDoclist];
4557 int iMul = 1;
4559 while( pDocid<pEnd ){
4560 sqlite3_int64 iDelta;
4561 pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
4562 iDocid += (iMul * iDelta);
4563 pNext = pDocid;
4564 fts3PoslistCopy(0, &pDocid);
4565 while( pDocid<pEnd && *pDocid==0 ) pDocid++;
4566 iMul = (bDescIdx ? -1 : 1);
4569 *pnList = (int)(pEnd - pNext);
4570 *ppIter = pNext;
4571 *piDocid = iDocid;
4572 }else{
4573 int iMul = (bDescIdx ? -1 : 1);
4574 sqlite3_int64 iDelta;
4575 fts3GetReverseVarint(&p, aDoclist, &iDelta);
4576 *piDocid -= (iMul * iDelta);
4578 if( p==aDoclist ){
4579 *pbEof = 1;
4580 }else{
4581 char *pSave = p;
4582 fts3ReversePoslist(aDoclist, &p);
4583 *pnList = (int)(pSave - p);
4585 *ppIter = p;
4590 ** Iterate forwards through a doclist.
4592 void sqlite3Fts3DoclistNext(
4593 int bDescIdx, /* True if the doclist is desc */
4594 char *aDoclist, /* Pointer to entire doclist */
4595 int nDoclist, /* Length of aDoclist in bytes */
4596 char **ppIter, /* IN/OUT: Iterator pointer */
4597 sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
4598 u8 *pbEof /* OUT: End-of-file flag */
4600 char *p = *ppIter;
4602 assert( nDoclist>0 );
4603 assert( *pbEof==0 );
4604 assert_fts3_nc( p || *piDocid==0 );
4605 assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
4607 if( p==0 ){
4608 p = aDoclist;
4609 p += sqlite3Fts3GetVarint(p, piDocid);
4610 }else{
4611 fts3PoslistCopy(0, &p);
4612 while( p<&aDoclist[nDoclist] && *p==0 ) p++;
4613 if( p>=&aDoclist[nDoclist] ){
4614 *pbEof = 1;
4615 }else{
4616 sqlite3_int64 iVar;
4617 p += sqlite3Fts3GetVarint(p, &iVar);
4618 *piDocid += ((bDescIdx ? -1 : 1) * iVar);
4622 *ppIter = p;
4626 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
4627 ** to true if EOF is reached.
4629 static void fts3EvalDlPhraseNext(
4630 Fts3Table *pTab,
4631 Fts3Doclist *pDL,
4632 u8 *pbEof
4634 char *pIter; /* Used to iterate through aAll */
4635 char *pEnd; /* 1 byte past end of aAll */
4637 if( pDL->pNextDocid ){
4638 pIter = pDL->pNextDocid;
4639 assert( pDL->aAll!=0 || pIter==0 );
4640 }else{
4641 pIter = pDL->aAll;
4644 if( pIter==0 || pIter>=(pEnd = pDL->aAll + pDL->nAll) ){
4645 /* We have already reached the end of this doclist. EOF. */
4646 *pbEof = 1;
4647 }else{
4648 sqlite3_int64 iDelta;
4649 pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
4650 if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
4651 pDL->iDocid += iDelta;
4652 }else{
4653 pDL->iDocid -= iDelta;
4655 pDL->pList = pIter;
4656 fts3PoslistCopy(0, &pIter);
4657 pDL->nList = (int)(pIter - pDL->pList);
4659 /* pIter now points just past the 0x00 that terminates the position-
4660 ** list for document pDL->iDocid. However, if this position-list was
4661 ** edited in place by fts3EvalNearTrim(), then pIter may not actually
4662 ** point to the start of the next docid value. The following line deals
4663 ** with this case by advancing pIter past the zero-padding added by
4664 ** fts3EvalNearTrim(). */
4665 while( pIter<pEnd && *pIter==0 ) pIter++;
4667 pDL->pNextDocid = pIter;
4668 assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
4669 *pbEof = 0;
4674 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
4676 typedef struct TokenDoclist TokenDoclist;
4677 struct TokenDoclist {
4678 int bIgnore;
4679 sqlite3_int64 iDocid;
4680 char *pList;
4681 int nList;
4685 ** Token pToken is an incrementally loaded token that is part of a
4686 ** multi-token phrase. Advance it to the next matching document in the
4687 ** database and populate output variable *p with the details of the new
4688 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
4690 ** If an error occurs, return an SQLite error code. Otherwise, return
4691 ** SQLITE_OK.
4693 static int incrPhraseTokenNext(
4694 Fts3Table *pTab, /* Virtual table handle */
4695 Fts3Phrase *pPhrase, /* Phrase to advance token of */
4696 int iToken, /* Specific token to advance */
4697 TokenDoclist *p, /* OUT: Docid and doclist for new entry */
4698 u8 *pbEof /* OUT: True if iterator is at EOF */
4700 int rc = SQLITE_OK;
4702 if( pPhrase->iDoclistToken==iToken ){
4703 assert( p->bIgnore==0 );
4704 assert( pPhrase->aToken[iToken].pSegcsr==0 );
4705 fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
4706 p->pList = pPhrase->doclist.pList;
4707 p->nList = pPhrase->doclist.nList;
4708 p->iDocid = pPhrase->doclist.iDocid;
4709 }else{
4710 Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
4711 assert( pToken->pDeferred==0 );
4712 assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
4713 if( pToken->pSegcsr ){
4714 assert( p->bIgnore==0 );
4715 rc = sqlite3Fts3MsrIncrNext(
4716 pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
4718 if( p->pList==0 ) *pbEof = 1;
4719 }else{
4720 p->bIgnore = 1;
4724 return rc;
4729 ** The phrase iterator passed as the second argument:
4731 ** * features at least one token that uses an incremental doclist, and
4733 ** * does not contain any deferred tokens.
4735 ** Advance it to the next matching documnent in the database and populate
4736 ** the Fts3Doclist.pList and nList fields.
4738 ** If there is no "next" entry and no error occurs, then *pbEof is set to
4739 ** 1 before returning. Otherwise, if no error occurs and the iterator is
4740 ** successfully advanced, *pbEof is set to 0.
4742 ** If an error occurs, return an SQLite error code. Otherwise, return
4743 ** SQLITE_OK.
4745 static int fts3EvalIncrPhraseNext(
4746 Fts3Cursor *pCsr, /* FTS Cursor handle */
4747 Fts3Phrase *p, /* Phrase object to advance to next docid */
4748 u8 *pbEof /* OUT: Set to 1 if EOF */
4750 int rc = SQLITE_OK;
4751 Fts3Doclist *pDL = &p->doclist;
4752 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
4753 u8 bEof = 0;
4755 /* This is only called if it is guaranteed that the phrase has at least
4756 ** one incremental token. In which case the bIncr flag is set. */
4757 assert( p->bIncr==1 );
4759 if( p->nToken==1 ){
4760 rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
4761 &pDL->iDocid, &pDL->pList, &pDL->nList
4763 if( pDL->pList==0 ) bEof = 1;
4764 }else{
4765 int bDescDoclist = pCsr->bDesc;
4766 struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
4768 memset(a, 0, sizeof(a));
4769 assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
4770 assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
4772 while( bEof==0 ){
4773 int bMaxSet = 0;
4774 sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
4775 int i; /* Used to iterate through tokens */
4777 /* Advance the iterator for each token in the phrase once. */
4778 for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
4779 rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
4780 if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
4781 iMax = a[i].iDocid;
4782 bMaxSet = 1;
4785 assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
4786 assert( rc!=SQLITE_OK || bMaxSet );
4788 /* Keep advancing iterators until they all point to the same document */
4789 for(i=0; i<p->nToken; i++){
4790 while( rc==SQLITE_OK && bEof==0
4791 && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
4793 rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
4794 if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
4795 iMax = a[i].iDocid;
4796 i = 0;
4801 /* Check if the current entries really are a phrase match */
4802 if( bEof==0 ){
4803 int nList = 0;
4804 int nByte = a[p->nToken-1].nList;
4805 char *aDoclist = sqlite3_malloc64((i64)nByte+FTS3_BUFFER_PADDING);
4806 if( !aDoclist ) return SQLITE_NOMEM;
4807 memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
4808 memset(&aDoclist[nByte], 0, FTS3_BUFFER_PADDING);
4810 for(i=0; i<(p->nToken-1); i++){
4811 if( a[i].bIgnore==0 ){
4812 char *pL = a[i].pList;
4813 char *pR = aDoclist;
4814 char *pOut = aDoclist;
4815 int nDist = p->nToken-1-i;
4816 int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
4817 if( res==0 ) break;
4818 nList = (int)(pOut - aDoclist);
4821 if( i==(p->nToken-1) ){
4822 pDL->iDocid = iMax;
4823 pDL->pList = aDoclist;
4824 pDL->nList = nList;
4825 pDL->bFreeList = 1;
4826 break;
4828 sqlite3_free(aDoclist);
4833 *pbEof = bEof;
4834 return rc;
4838 ** Attempt to move the phrase iterator to point to the next matching docid.
4839 ** If an error occurs, return an SQLite error code. Otherwise, return
4840 ** SQLITE_OK.
4842 ** If there is no "next" entry and no error occurs, then *pbEof is set to
4843 ** 1 before returning. Otherwise, if no error occurs and the iterator is
4844 ** successfully advanced, *pbEof is set to 0.
4846 static int fts3EvalPhraseNext(
4847 Fts3Cursor *pCsr, /* FTS Cursor handle */
4848 Fts3Phrase *p, /* Phrase object to advance to next docid */
4849 u8 *pbEof /* OUT: Set to 1 if EOF */
4851 int rc = SQLITE_OK;
4852 Fts3Doclist *pDL = &p->doclist;
4853 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
4855 if( p->bIncr ){
4856 rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
4857 }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
4858 sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
4859 &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
4861 pDL->pList = pDL->pNextDocid;
4862 }else{
4863 fts3EvalDlPhraseNext(pTab, pDL, pbEof);
4866 return rc;
4871 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
4872 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
4873 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
4874 ** expressions for which all descendent tokens are deferred.
4876 ** If parameter bOptOk is zero, then it is guaranteed that the
4877 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
4878 ** each phrase in the expression (subject to deferred token processing).
4879 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
4880 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
4882 ** If an error occurs within this function, *pRc is set to an SQLite error
4883 ** code before returning.
4885 static void fts3EvalStartReaders(
4886 Fts3Cursor *pCsr, /* FTS Cursor handle */
4887 Fts3Expr *pExpr, /* Expression to initialize phrases in */
4888 int *pRc /* IN/OUT: Error code */
4890 if( pExpr && SQLITE_OK==*pRc ){
4891 if( pExpr->eType==FTSQUERY_PHRASE ){
4892 int nToken = pExpr->pPhrase->nToken;
4893 if( nToken ){
4894 int i;
4895 for(i=0; i<nToken; i++){
4896 if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
4898 pExpr->bDeferred = (i==nToken);
4900 *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
4901 }else{
4902 fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
4903 fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
4904 pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
4910 ** An array of the following structures is assembled as part of the process
4911 ** of selecting tokens to defer before the query starts executing (as part
4912 ** of the xFilter() method). There is one element in the array for each
4913 ** token in the FTS expression.
4915 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
4916 ** to phrases that are connected only by AND and NEAR operators (not OR or
4917 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
4918 ** separately. The root of a tokens AND/NEAR cluster is stored in
4919 ** Fts3TokenAndCost.pRoot.
4921 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
4922 struct Fts3TokenAndCost {
4923 Fts3Phrase *pPhrase; /* The phrase the token belongs to */
4924 int iToken; /* Position of token in phrase */
4925 Fts3PhraseToken *pToken; /* The token itself */
4926 Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
4927 int nOvfl; /* Number of overflow pages to load doclist */
4928 int iCol; /* The column the token must match */
4932 ** This function is used to populate an allocated Fts3TokenAndCost array.
4934 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
4935 ** Otherwise, if an error occurs during execution, *pRc is set to an
4936 ** SQLite error code.
4938 static void fts3EvalTokenCosts(
4939 Fts3Cursor *pCsr, /* FTS Cursor handle */
4940 Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
4941 Fts3Expr *pExpr, /* Expression to consider */
4942 Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
4943 Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
4944 int *pRc /* IN/OUT: Error code */
4946 if( *pRc==SQLITE_OK ){
4947 if( pExpr->eType==FTSQUERY_PHRASE ){
4948 Fts3Phrase *pPhrase = pExpr->pPhrase;
4949 int i;
4950 for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
4951 Fts3TokenAndCost *pTC = (*ppTC)++;
4952 pTC->pPhrase = pPhrase;
4953 pTC->iToken = i;
4954 pTC->pRoot = pRoot;
4955 pTC->pToken = &pPhrase->aToken[i];
4956 pTC->iCol = pPhrase->iColumn;
4957 *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
4959 }else if( pExpr->eType!=FTSQUERY_NOT ){
4960 assert( pExpr->eType==FTSQUERY_OR
4961 || pExpr->eType==FTSQUERY_AND
4962 || pExpr->eType==FTSQUERY_NEAR
4964 assert( pExpr->pLeft && pExpr->pRight );
4965 if( pExpr->eType==FTSQUERY_OR ){
4966 pRoot = pExpr->pLeft;
4967 **ppOr = pRoot;
4968 (*ppOr)++;
4970 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
4971 if( pExpr->eType==FTSQUERY_OR ){
4972 pRoot = pExpr->pRight;
4973 **ppOr = pRoot;
4974 (*ppOr)++;
4976 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
4982 ** Determine the average document (row) size in pages. If successful,
4983 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
4984 ** an SQLite error code.
4986 ** The average document size in pages is calculated by first calculating
4987 ** determining the average size in bytes, B. If B is less than the amount
4988 ** of data that will fit on a single leaf page of an intkey table in
4989 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
4990 ** the number of overflow pages consumed by a record B bytes in size.
4992 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
4993 int rc = SQLITE_OK;
4994 if( pCsr->nRowAvg==0 ){
4995 /* The average document size, which is required to calculate the cost
4996 ** of each doclist, has not yet been determined. Read the required
4997 ** data from the %_stat table to calculate it.
4999 ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
5000 ** varints, where nCol is the number of columns in the FTS3 table.
5001 ** The first varint is the number of documents currently stored in
5002 ** the table. The following nCol varints contain the total amount of
5003 ** data stored in all rows of each column of the table, from left
5004 ** to right.
5006 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
5007 sqlite3_stmt *pStmt;
5008 sqlite3_int64 nDoc = 0;
5009 sqlite3_int64 nByte = 0;
5010 const char *pEnd;
5011 const char *a;
5013 rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
5014 if( rc!=SQLITE_OK ) return rc;
5015 a = sqlite3_column_blob(pStmt, 0);
5016 testcase( a==0 ); /* If %_stat.value set to X'' */
5017 if( a ){
5018 pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
5019 a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc);
5020 while( a<pEnd ){
5021 a += sqlite3Fts3GetVarintBounded(a, pEnd, &nByte);
5024 if( nDoc==0 || nByte==0 ){
5025 sqlite3_reset(pStmt);
5026 return FTS_CORRUPT_VTAB;
5029 pCsr->nDoc = nDoc;
5030 pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
5031 assert( pCsr->nRowAvg>0 );
5032 rc = sqlite3_reset(pStmt);
5035 *pnPage = pCsr->nRowAvg;
5036 return rc;
5040 ** This function is called to select the tokens (if any) that will be
5041 ** deferred. The array aTC[] has already been populated when this is
5042 ** called.
5044 ** This function is called once for each AND/NEAR cluster in the
5045 ** expression. Each invocation determines which tokens to defer within
5046 ** the cluster with root node pRoot. See comments above the definition
5047 ** of struct Fts3TokenAndCost for more details.
5049 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
5050 ** called on each token to defer. Otherwise, an SQLite error code is
5051 ** returned.
5053 static int fts3EvalSelectDeferred(
5054 Fts3Cursor *pCsr, /* FTS Cursor handle */
5055 Fts3Expr *pRoot, /* Consider tokens with this root node */
5056 Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
5057 int nTC /* Number of entries in aTC[] */
5059 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
5060 int nDocSize = 0; /* Number of pages per doc loaded */
5061 int rc = SQLITE_OK; /* Return code */
5062 int ii; /* Iterator variable for various purposes */
5063 int nOvfl = 0; /* Total overflow pages used by doclists */
5064 int nToken = 0; /* Total number of tokens in cluster */
5066 int nMinEst = 0; /* The minimum count for any phrase so far. */
5067 int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
5069 /* Tokens are never deferred for FTS tables created using the content=xxx
5070 ** option. The reason being that it is not guaranteed that the content
5071 ** table actually contains the same data as the index. To prevent this from
5072 ** causing any problems, the deferred token optimization is completely
5073 ** disabled for content=xxx tables. */
5074 if( pTab->zContentTbl ){
5075 return SQLITE_OK;
5078 /* Count the tokens in this AND/NEAR cluster. If none of the doclists
5079 ** associated with the tokens spill onto overflow pages, or if there is
5080 ** only 1 token, exit early. No tokens to defer in this case. */
5081 for(ii=0; ii<nTC; ii++){
5082 if( aTC[ii].pRoot==pRoot ){
5083 nOvfl += aTC[ii].nOvfl;
5084 nToken++;
5087 if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
5089 /* Obtain the average docsize (in pages). */
5090 rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
5091 assert( rc!=SQLITE_OK || nDocSize>0 );
5094 /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
5095 ** of the number of overflow pages that will be loaded by the pager layer
5096 ** to retrieve the entire doclist for the token from the full-text index.
5097 ** Load the doclists for tokens that are either:
5099 ** a. The cheapest token in the entire query (i.e. the one visited by the
5100 ** first iteration of this loop), or
5102 ** b. Part of a multi-token phrase.
5104 ** After each token doclist is loaded, merge it with the others from the
5105 ** same phrase and count the number of documents that the merged doclist
5106 ** contains. Set variable "nMinEst" to the smallest number of documents in
5107 ** any phrase doclist for which 1 or more token doclists have been loaded.
5108 ** Let nOther be the number of other phrases for which it is certain that
5109 ** one or more tokens will not be deferred.
5111 ** Then, for each token, defer it if loading the doclist would result in
5112 ** loading N or more overflow pages into memory, where N is computed as:
5114 ** (nMinEst + 4^nOther - 1) / (4^nOther)
5116 for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
5117 int iTC; /* Used to iterate through aTC[] array. */
5118 Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
5120 /* Set pTC to point to the cheapest remaining token. */
5121 for(iTC=0; iTC<nTC; iTC++){
5122 if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
5123 && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
5125 pTC = &aTC[iTC];
5128 assert( pTC );
5130 if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
5131 /* The number of overflow pages to load for this (and therefore all
5132 ** subsequent) tokens is greater than the estimated number of pages
5133 ** that will be loaded if all subsequent tokens are deferred.
5135 Fts3PhraseToken *pToken = pTC->pToken;
5136 rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
5137 fts3SegReaderCursorFree(pToken->pSegcsr);
5138 pToken->pSegcsr = 0;
5139 }else{
5140 /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
5141 ** for-loop. Except, limit the value to 2^24 to prevent it from
5142 ** overflowing the 32-bit integer it is stored in. */
5143 if( ii<12 ) nLoad4 = nLoad4*4;
5145 if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
5146 /* Either this is the cheapest token in the entire query, or it is
5147 ** part of a multi-token phrase. Either way, the entire doclist will
5148 ** (eventually) be loaded into memory. It may as well be now. */
5149 Fts3PhraseToken *pToken = pTC->pToken;
5150 int nList = 0;
5151 char *pList = 0;
5152 rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
5153 assert( rc==SQLITE_OK || pList==0 );
5154 if( rc==SQLITE_OK ){
5155 rc = fts3EvalPhraseMergeToken(
5156 pTab, pTC->pPhrase, pTC->iToken,pList,nList
5159 if( rc==SQLITE_OK ){
5160 int nCount;
5161 nCount = fts3DoclistCountDocids(
5162 pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
5164 if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
5168 pTC->pToken = 0;
5171 return rc;
5175 ** This function is called from within the xFilter method. It initializes
5176 ** the full-text query currently stored in pCsr->pExpr. To iterate through
5177 ** the results of a query, the caller does:
5179 ** fts3EvalStart(pCsr);
5180 ** while( 1 ){
5181 ** fts3EvalNext(pCsr);
5182 ** if( pCsr->bEof ) break;
5183 ** ... return row pCsr->iPrevId to the caller ...
5184 ** }
5186 static int fts3EvalStart(Fts3Cursor *pCsr){
5187 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
5188 int rc = SQLITE_OK;
5189 int nToken = 0;
5190 int nOr = 0;
5192 /* Allocate a MultiSegReader for each token in the expression. */
5193 fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
5195 /* Determine which, if any, tokens in the expression should be deferred. */
5196 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
5197 if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
5198 Fts3TokenAndCost *aTC;
5199 aTC = (Fts3TokenAndCost *)sqlite3_malloc64(
5200 sizeof(Fts3TokenAndCost) * nToken
5201 + sizeof(Fts3Expr *) * nOr * 2
5204 if( !aTC ){
5205 rc = SQLITE_NOMEM;
5206 }else{
5207 Fts3Expr **apOr = (Fts3Expr **)&aTC[nToken];
5208 int ii;
5209 Fts3TokenAndCost *pTC = aTC;
5210 Fts3Expr **ppOr = apOr;
5212 fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
5213 nToken = (int)(pTC-aTC);
5214 nOr = (int)(ppOr-apOr);
5216 if( rc==SQLITE_OK ){
5217 rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
5218 for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
5219 rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
5223 sqlite3_free(aTC);
5226 #endif
5228 fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
5229 return rc;
5233 ** Invalidate the current position list for phrase pPhrase.
5235 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
5236 if( pPhrase->doclist.bFreeList ){
5237 sqlite3_free(pPhrase->doclist.pList);
5239 pPhrase->doclist.pList = 0;
5240 pPhrase->doclist.nList = 0;
5241 pPhrase->doclist.bFreeList = 0;
5245 ** This function is called to edit the position list associated with
5246 ** the phrase object passed as the fifth argument according to a NEAR
5247 ** condition. For example:
5249 ** abc NEAR/5 "def ghi"
5251 ** Parameter nNear is passed the NEAR distance of the expression (5 in
5252 ** the example above). When this function is called, *paPoslist points to
5253 ** the position list, and *pnToken is the number of phrase tokens in the
5254 ** phrase on the other side of the NEAR operator to pPhrase. For example,
5255 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
5256 ** the position list associated with phrase "abc".
5258 ** All positions in the pPhrase position list that are not sufficiently
5259 ** close to a position in the *paPoslist position list are removed. If this
5260 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
5262 ** Before returning, *paPoslist is set to point to the position lsit
5263 ** associated with pPhrase. And *pnToken is set to the number of tokens in
5264 ** pPhrase.
5266 static int fts3EvalNearTrim(
5267 int nNear, /* NEAR distance. As in "NEAR/nNear". */
5268 char *aTmp, /* Temporary space to use */
5269 char **paPoslist, /* IN/OUT: Position list */
5270 int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
5271 Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
5273 int nParam1 = nNear + pPhrase->nToken;
5274 int nParam2 = nNear + *pnToken;
5275 int nNew;
5276 char *p2;
5277 char *pOut;
5278 int res;
5280 assert( pPhrase->doclist.pList );
5282 p2 = pOut = pPhrase->doclist.pList;
5283 res = fts3PoslistNearMerge(
5284 &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
5286 if( res ){
5287 nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
5288 assert_fts3_nc( nNew<=pPhrase->doclist.nList && nNew>0 );
5289 if( nNew>=0 && nNew<=pPhrase->doclist.nList ){
5290 assert( pPhrase->doclist.pList[nNew]=='\0' );
5291 memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
5292 pPhrase->doclist.nList = nNew;
5294 *paPoslist = pPhrase->doclist.pList;
5295 *pnToken = pPhrase->nToken;
5298 return res;
5302 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
5303 ** Otherwise, it advances the expression passed as the second argument to
5304 ** point to the next matching row in the database. Expressions iterate through
5305 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
5306 ** or descending if it is non-zero.
5308 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
5309 ** successful, the following variables in pExpr are set:
5311 ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
5312 ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
5314 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
5315 ** at EOF, then the following variables are populated with the position list
5316 ** for the phrase for the visited row:
5318 ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
5319 ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
5321 ** It says above that this function advances the expression to the next
5322 ** matching row. This is usually true, but there are the following exceptions:
5324 ** 1. Deferred tokens are not taken into account. If a phrase consists
5325 ** entirely of deferred tokens, it is assumed to match every row in
5326 ** the db. In this case the position-list is not populated at all.
5328 ** Or, if a phrase contains one or more deferred tokens and one or
5329 ** more non-deferred tokens, then the expression is advanced to the
5330 ** next possible match, considering only non-deferred tokens. In other
5331 ** words, if the phrase is "A B C", and "B" is deferred, the expression
5332 ** is advanced to the next row that contains an instance of "A * C",
5333 ** where "*" may match any single token. The position list in this case
5334 ** is populated as for "A * C" before returning.
5336 ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
5337 ** advanced to point to the next row that matches "x AND y".
5339 ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
5340 ** really a match, taking into account deferred tokens and NEAR operators.
5342 static void fts3EvalNextRow(
5343 Fts3Cursor *pCsr, /* FTS Cursor handle */
5344 Fts3Expr *pExpr, /* Expr. to advance to next matching row */
5345 int *pRc /* IN/OUT: Error code */
5347 if( *pRc==SQLITE_OK && pExpr->bEof==0 ){
5348 int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
5349 pExpr->bStart = 1;
5351 switch( pExpr->eType ){
5352 case FTSQUERY_NEAR:
5353 case FTSQUERY_AND: {
5354 Fts3Expr *pLeft = pExpr->pLeft;
5355 Fts3Expr *pRight = pExpr->pRight;
5356 assert( !pLeft->bDeferred || !pRight->bDeferred );
5358 if( pLeft->bDeferred ){
5359 /* LHS is entirely deferred. So we assume it matches every row.
5360 ** Advance the RHS iterator to find the next row visited. */
5361 fts3EvalNextRow(pCsr, pRight, pRc);
5362 pExpr->iDocid = pRight->iDocid;
5363 pExpr->bEof = pRight->bEof;
5364 }else if( pRight->bDeferred ){
5365 /* RHS is entirely deferred. So we assume it matches every row.
5366 ** Advance the LHS iterator to find the next row visited. */
5367 fts3EvalNextRow(pCsr, pLeft, pRc);
5368 pExpr->iDocid = pLeft->iDocid;
5369 pExpr->bEof = pLeft->bEof;
5370 }else{
5371 /* Neither the RHS or LHS are deferred. */
5372 fts3EvalNextRow(pCsr, pLeft, pRc);
5373 fts3EvalNextRow(pCsr, pRight, pRc);
5374 while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
5375 sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
5376 if( iDiff==0 ) break;
5377 if( iDiff<0 ){
5378 fts3EvalNextRow(pCsr, pLeft, pRc);
5379 }else{
5380 fts3EvalNextRow(pCsr, pRight, pRc);
5383 pExpr->iDocid = pLeft->iDocid;
5384 pExpr->bEof = (pLeft->bEof || pRight->bEof);
5385 if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
5386 assert( pRight->eType==FTSQUERY_PHRASE );
5387 if( pRight->pPhrase->doclist.aAll ){
5388 Fts3Doclist *pDl = &pRight->pPhrase->doclist;
5389 while( *pRc==SQLITE_OK && pRight->bEof==0 ){
5390 memset(pDl->pList, 0, pDl->nList);
5391 fts3EvalNextRow(pCsr, pRight, pRc);
5394 if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
5395 Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
5396 while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
5397 memset(pDl->pList, 0, pDl->nList);
5398 fts3EvalNextRow(pCsr, pLeft, pRc);
5401 pRight->bEof = pLeft->bEof = 1;
5404 break;
5407 case FTSQUERY_OR: {
5408 Fts3Expr *pLeft = pExpr->pLeft;
5409 Fts3Expr *pRight = pExpr->pRight;
5410 sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
5412 assert_fts3_nc( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
5413 assert_fts3_nc( pRight->bStart || pLeft->iDocid==pRight->iDocid );
5415 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
5416 fts3EvalNextRow(pCsr, pLeft, pRc);
5417 }else if( pLeft->bEof || iCmp>0 ){
5418 fts3EvalNextRow(pCsr, pRight, pRc);
5419 }else{
5420 fts3EvalNextRow(pCsr, pLeft, pRc);
5421 fts3EvalNextRow(pCsr, pRight, pRc);
5424 pExpr->bEof = (pLeft->bEof && pRight->bEof);
5425 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
5426 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
5427 pExpr->iDocid = pLeft->iDocid;
5428 }else{
5429 pExpr->iDocid = pRight->iDocid;
5432 break;
5435 case FTSQUERY_NOT: {
5436 Fts3Expr *pLeft = pExpr->pLeft;
5437 Fts3Expr *pRight = pExpr->pRight;
5439 if( pRight->bStart==0 ){
5440 fts3EvalNextRow(pCsr, pRight, pRc);
5441 assert( *pRc!=SQLITE_OK || pRight->bStart );
5444 fts3EvalNextRow(pCsr, pLeft, pRc);
5445 if( pLeft->bEof==0 ){
5446 while( !*pRc
5447 && !pRight->bEof
5448 && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
5450 fts3EvalNextRow(pCsr, pRight, pRc);
5453 pExpr->iDocid = pLeft->iDocid;
5454 pExpr->bEof = pLeft->bEof;
5455 break;
5458 default: {
5459 Fts3Phrase *pPhrase = pExpr->pPhrase;
5460 fts3EvalInvalidatePoslist(pPhrase);
5461 *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
5462 pExpr->iDocid = pPhrase->doclist.iDocid;
5463 break;
5470 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
5471 ** cluster, then this function returns 1 immediately.
5473 ** Otherwise, it checks if the current row really does match the NEAR
5474 ** expression, using the data currently stored in the position lists
5475 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
5477 ** If the current row is a match, the position list associated with each
5478 ** phrase in the NEAR expression is edited in place to contain only those
5479 ** phrase instances sufficiently close to their peers to satisfy all NEAR
5480 ** constraints. In this case it returns 1. If the NEAR expression does not
5481 ** match the current row, 0 is returned. The position lists may or may not
5482 ** be edited if 0 is returned.
5484 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
5485 int res = 1;
5487 /* The following block runs if pExpr is the root of a NEAR query.
5488 ** For example, the query:
5490 ** "w" NEAR "x" NEAR "y" NEAR "z"
5492 ** which is represented in tree form as:
5494 ** |
5495 ** +--NEAR--+ <-- root of NEAR query
5496 ** | |
5497 ** +--NEAR--+ "z"
5498 ** | |
5499 ** +--NEAR--+ "y"
5500 ** | |
5501 ** "w" "x"
5503 ** The right-hand child of a NEAR node is always a phrase. The
5504 ** left-hand child may be either a phrase or a NEAR node. There are
5505 ** no exceptions to this - it's the way the parser in fts3_expr.c works.
5507 if( *pRc==SQLITE_OK
5508 && pExpr->eType==FTSQUERY_NEAR
5509 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
5511 Fts3Expr *p;
5512 sqlite3_int64 nTmp = 0; /* Bytes of temp space */
5513 char *aTmp; /* Temp space for PoslistNearMerge() */
5515 /* Allocate temporary working space. */
5516 for(p=pExpr; p->pLeft; p=p->pLeft){
5517 assert( p->pRight->pPhrase->doclist.nList>0 );
5518 nTmp += p->pRight->pPhrase->doclist.nList;
5520 nTmp += p->pPhrase->doclist.nList;
5521 aTmp = sqlite3_malloc64(nTmp*2);
5522 if( !aTmp ){
5523 *pRc = SQLITE_NOMEM;
5524 res = 0;
5525 }else{
5526 char *aPoslist = p->pPhrase->doclist.pList;
5527 int nToken = p->pPhrase->nToken;
5529 for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
5530 Fts3Phrase *pPhrase = p->pRight->pPhrase;
5531 int nNear = p->nNear;
5532 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
5535 aPoslist = pExpr->pRight->pPhrase->doclist.pList;
5536 nToken = pExpr->pRight->pPhrase->nToken;
5537 for(p=pExpr->pLeft; p && res; p=p->pLeft){
5538 int nNear;
5539 Fts3Phrase *pPhrase;
5540 assert( p->pParent && p->pParent->pLeft==p );
5541 nNear = p->pParent->nNear;
5542 pPhrase = (
5543 p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
5545 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
5549 sqlite3_free(aTmp);
5552 return res;
5556 ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
5557 ** Assuming no error occurs or has occurred, It returns non-zero if the
5558 ** expression passed as the second argument matches the row that pCsr
5559 ** currently points to, or zero if it does not.
5561 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
5562 ** If an error occurs during execution of this function, *pRc is set to
5563 ** the appropriate SQLite error code. In this case the returned value is
5564 ** undefined.
5566 static int fts3EvalTestExpr(
5567 Fts3Cursor *pCsr, /* FTS cursor handle */
5568 Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
5569 int *pRc /* IN/OUT: Error code */
5571 int bHit = 1; /* Return value */
5572 if( *pRc==SQLITE_OK ){
5573 switch( pExpr->eType ){
5574 case FTSQUERY_NEAR:
5575 case FTSQUERY_AND:
5576 bHit = (
5577 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
5578 && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
5579 && fts3EvalNearTest(pExpr, pRc)
5582 /* If the NEAR expression does not match any rows, zero the doclist for
5583 ** all phrases involved in the NEAR. This is because the snippet(),
5584 ** offsets() and matchinfo() functions are not supposed to recognize
5585 ** any instances of phrases that are part of unmatched NEAR queries.
5586 ** For example if this expression:
5588 ** ... MATCH 'a OR (b NEAR c)'
5590 ** is matched against a row containing:
5592 ** 'a b d e'
5594 ** then any snippet() should ony highlight the "a" term, not the "b"
5595 ** (as "b" is part of a non-matching NEAR clause).
5597 if( bHit==0
5598 && pExpr->eType==FTSQUERY_NEAR
5599 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
5601 Fts3Expr *p;
5602 for(p=pExpr; p->pPhrase==0; p=p->pLeft){
5603 if( p->pRight->iDocid==pCsr->iPrevId ){
5604 fts3EvalInvalidatePoslist(p->pRight->pPhrase);
5607 if( p->iDocid==pCsr->iPrevId ){
5608 fts3EvalInvalidatePoslist(p->pPhrase);
5612 break;
5614 case FTSQUERY_OR: {
5615 int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
5616 int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
5617 bHit = bHit1 || bHit2;
5618 break;
5621 case FTSQUERY_NOT:
5622 bHit = (
5623 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
5624 && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
5626 break;
5628 default: {
5629 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
5630 if( pCsr->pDeferred && (pExpr->bDeferred || (
5631 pExpr->iDocid==pCsr->iPrevId && pExpr->pPhrase->doclist.pList
5632 ))){
5633 Fts3Phrase *pPhrase = pExpr->pPhrase;
5634 if( pExpr->bDeferred ){
5635 fts3EvalInvalidatePoslist(pPhrase);
5637 *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
5638 bHit = (pPhrase->doclist.pList!=0);
5639 pExpr->iDocid = pCsr->iPrevId;
5640 }else
5641 #endif
5643 bHit = (
5644 pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId
5645 && pExpr->pPhrase->doclist.nList>0
5648 break;
5652 return bHit;
5656 ** This function is called as the second part of each xNext operation when
5657 ** iterating through the results of a full-text query. At this point the
5658 ** cursor points to a row that matches the query expression, with the
5659 ** following caveats:
5661 ** * Up until this point, "NEAR" operators in the expression have been
5662 ** treated as "AND".
5664 ** * Deferred tokens have not yet been considered.
5666 ** If *pRc is not SQLITE_OK when this function is called, it immediately
5667 ** returns 0. Otherwise, it tests whether or not after considering NEAR
5668 ** operators and deferred tokens the current row is still a match for the
5669 ** expression. It returns 1 if both of the following are true:
5671 ** 1. *pRc is SQLITE_OK when this function returns, and
5673 ** 2. After scanning the current FTS table row for the deferred tokens,
5674 ** it is determined that the row does *not* match the query.
5676 ** Or, if no error occurs and it seems the current row does match the FTS
5677 ** query, return 0.
5679 int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
5680 int rc = *pRc;
5681 int bMiss = 0;
5682 if( rc==SQLITE_OK ){
5684 /* If there are one or more deferred tokens, load the current row into
5685 ** memory and scan it to determine the position list for each deferred
5686 ** token. Then, see if this row is really a match, considering deferred
5687 ** tokens and NEAR operators (neither of which were taken into account
5688 ** earlier, by fts3EvalNextRow()).
5690 if( pCsr->pDeferred ){
5691 rc = fts3CursorSeek(0, pCsr);
5692 if( rc==SQLITE_OK ){
5693 rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
5696 bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
5698 /* Free the position-lists accumulated for each deferred token above. */
5699 sqlite3Fts3FreeDeferredDoclists(pCsr);
5700 *pRc = rc;
5702 return (rc==SQLITE_OK && bMiss);
5706 ** Advance to the next document that matches the FTS expression in
5707 ** Fts3Cursor.pExpr.
5709 static int fts3EvalNext(Fts3Cursor *pCsr){
5710 int rc = SQLITE_OK; /* Return Code */
5711 Fts3Expr *pExpr = pCsr->pExpr;
5712 assert( pCsr->isEof==0 );
5713 if( pExpr==0 ){
5714 pCsr->isEof = 1;
5715 }else{
5716 do {
5717 if( pCsr->isRequireSeek==0 ){
5718 sqlite3_reset(pCsr->pStmt);
5720 assert( sqlite3_data_count(pCsr->pStmt)==0 );
5721 fts3EvalNextRow(pCsr, pExpr, &rc);
5722 pCsr->isEof = pExpr->bEof;
5723 pCsr->isRequireSeek = 1;
5724 pCsr->isMatchinfoNeeded = 1;
5725 pCsr->iPrevId = pExpr->iDocid;
5726 }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
5729 /* Check if the cursor is past the end of the docid range specified
5730 ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
5731 if( rc==SQLITE_OK && (
5732 (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
5733 || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
5735 pCsr->isEof = 1;
5738 return rc;
5742 ** Restart interation for expression pExpr so that the next call to
5743 ** fts3EvalNext() visits the first row. Do not allow incremental
5744 ** loading or merging of phrase doclists for this iteration.
5746 ** If *pRc is other than SQLITE_OK when this function is called, it is
5747 ** a no-op. If an error occurs within this function, *pRc is set to an
5748 ** SQLite error code before returning.
5750 static void fts3EvalRestart(
5751 Fts3Cursor *pCsr,
5752 Fts3Expr *pExpr,
5753 int *pRc
5755 if( pExpr && *pRc==SQLITE_OK ){
5756 Fts3Phrase *pPhrase = pExpr->pPhrase;
5758 if( pPhrase ){
5759 fts3EvalInvalidatePoslist(pPhrase);
5760 if( pPhrase->bIncr ){
5761 int i;
5762 for(i=0; i<pPhrase->nToken; i++){
5763 Fts3PhraseToken *pToken = &pPhrase->aToken[i];
5764 assert( pToken->pDeferred==0 );
5765 if( pToken->pSegcsr ){
5766 sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
5769 *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
5771 pPhrase->doclist.pNextDocid = 0;
5772 pPhrase->doclist.iDocid = 0;
5773 pPhrase->pOrPoslist = 0;
5776 pExpr->iDocid = 0;
5777 pExpr->bEof = 0;
5778 pExpr->bStart = 0;
5780 fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
5781 fts3EvalRestart(pCsr, pExpr->pRight, pRc);
5786 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
5787 ** expression rooted at pExpr, the cursor iterates through all rows matched
5788 ** by pExpr, calling this function for each row. This function increments
5789 ** the values in Fts3Expr.aMI[] according to the position-list currently
5790 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
5791 ** expression nodes.
5793 static void fts3EvalUpdateCounts(Fts3Expr *pExpr, int nCol){
5794 if( pExpr ){
5795 Fts3Phrase *pPhrase = pExpr->pPhrase;
5796 if( pPhrase && pPhrase->doclist.pList ){
5797 int iCol = 0;
5798 char *p = pPhrase->doclist.pList;
5801 u8 c = 0;
5802 int iCnt = 0;
5803 while( 0xFE & (*p | c) ){
5804 if( (c&0x80)==0 ) iCnt++;
5805 c = *p++ & 0x80;
5808 /* aMI[iCol*3 + 1] = Number of occurrences
5809 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
5811 pExpr->aMI[iCol*3 + 1] += iCnt;
5812 pExpr->aMI[iCol*3 + 2] += (iCnt>0);
5813 if( *p==0x00 ) break;
5814 p++;
5815 p += fts3GetVarint32(p, &iCol);
5816 }while( iCol<nCol );
5819 fts3EvalUpdateCounts(pExpr->pLeft, nCol);
5820 fts3EvalUpdateCounts(pExpr->pRight, nCol);
5825 ** This is an sqlite3Fts3ExprIterate() callback. If the Fts3Expr.aMI[] array
5826 ** has not yet been allocated, allocate and zero it. Otherwise, just zero
5827 ** it.
5829 static int fts3AllocateMSI(Fts3Expr *pExpr, int iPhrase, void *pCtx){
5830 Fts3Table *pTab = (Fts3Table*)pCtx;
5831 UNUSED_PARAMETER(iPhrase);
5832 if( pExpr->aMI==0 ){
5833 pExpr->aMI = (u32 *)sqlite3_malloc64(pTab->nColumn * 3 * sizeof(u32));
5834 if( pExpr->aMI==0 ) return SQLITE_NOMEM;
5836 memset(pExpr->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
5837 return SQLITE_OK;
5841 ** Expression pExpr must be of type FTSQUERY_PHRASE.
5843 ** If it is not already allocated and populated, this function allocates and
5844 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
5845 ** of a NEAR expression, then it also allocates and populates the same array
5846 ** for all other phrases that are part of the NEAR expression.
5848 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
5849 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
5851 static int fts3EvalGatherStats(
5852 Fts3Cursor *pCsr, /* Cursor object */
5853 Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
5855 int rc = SQLITE_OK; /* Return code */
5857 assert( pExpr->eType==FTSQUERY_PHRASE );
5858 if( pExpr->aMI==0 ){
5859 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
5860 Fts3Expr *pRoot; /* Root of NEAR expression */
5862 sqlite3_int64 iPrevId = pCsr->iPrevId;
5863 sqlite3_int64 iDocid;
5864 u8 bEof;
5866 /* Find the root of the NEAR expression */
5867 pRoot = pExpr;
5868 while( pRoot->pParent
5869 && (pRoot->pParent->eType==FTSQUERY_NEAR || pRoot->bDeferred)
5871 pRoot = pRoot->pParent;
5873 iDocid = pRoot->iDocid;
5874 bEof = pRoot->bEof;
5875 assert( pRoot->bStart );
5877 /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
5878 rc = sqlite3Fts3ExprIterate(pRoot, fts3AllocateMSI, (void*)pTab);
5879 if( rc!=SQLITE_OK ) return rc;
5880 fts3EvalRestart(pCsr, pRoot, &rc);
5882 while( pCsr->isEof==0 && rc==SQLITE_OK ){
5884 do {
5885 /* Ensure the %_content statement is reset. */
5886 if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
5887 assert( sqlite3_data_count(pCsr->pStmt)==0 );
5889 /* Advance to the next document */
5890 fts3EvalNextRow(pCsr, pRoot, &rc);
5891 pCsr->isEof = pRoot->bEof;
5892 pCsr->isRequireSeek = 1;
5893 pCsr->isMatchinfoNeeded = 1;
5894 pCsr->iPrevId = pRoot->iDocid;
5895 }while( pCsr->isEof==0
5896 && pRoot->eType==FTSQUERY_NEAR
5897 && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
5900 if( rc==SQLITE_OK && pCsr->isEof==0 ){
5901 fts3EvalUpdateCounts(pRoot, pTab->nColumn);
5905 pCsr->isEof = 0;
5906 pCsr->iPrevId = iPrevId;
5908 if( bEof ){
5909 pRoot->bEof = bEof;
5910 }else{
5911 /* Caution: pRoot may iterate through docids in ascending or descending
5912 ** order. For this reason, even though it seems more defensive, the
5913 ** do loop can not be written:
5915 ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
5917 fts3EvalRestart(pCsr, pRoot, &rc);
5918 do {
5919 fts3EvalNextRow(pCsr, pRoot, &rc);
5920 assert_fts3_nc( pRoot->bEof==0 );
5921 if( pRoot->bEof ) rc = FTS_CORRUPT_VTAB;
5922 }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
5925 return rc;
5929 ** This function is used by the matchinfo() module to query a phrase
5930 ** expression node for the following information:
5932 ** 1. The total number of occurrences of the phrase in each column of
5933 ** the FTS table (considering all rows), and
5935 ** 2. For each column, the number of rows in the table for which the
5936 ** column contains at least one instance of the phrase.
5938 ** If no error occurs, SQLITE_OK is returned and the values for each column
5939 ** written into the array aiOut as follows:
5941 ** aiOut[iCol*3 + 1] = Number of occurrences
5942 ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
5944 ** Caveats:
5946 ** * If a phrase consists entirely of deferred tokens, then all output
5947 ** values are set to the number of documents in the table. In other
5948 ** words we assume that very common tokens occur exactly once in each
5949 ** column of each row of the table.
5951 ** * If a phrase contains some deferred tokens (and some non-deferred
5952 ** tokens), count the potential occurrence identified by considering
5953 ** the non-deferred tokens instead of actual phrase occurrences.
5955 ** * If the phrase is part of a NEAR expression, then only phrase instances
5956 ** that meet the NEAR constraint are included in the counts.
5958 int sqlite3Fts3EvalPhraseStats(
5959 Fts3Cursor *pCsr, /* FTS cursor handle */
5960 Fts3Expr *pExpr, /* Phrase expression */
5961 u32 *aiOut /* Array to write results into (see above) */
5963 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
5964 int rc = SQLITE_OK;
5965 int iCol;
5967 if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
5968 assert( pCsr->nDoc>0 );
5969 for(iCol=0; iCol<pTab->nColumn; iCol++){
5970 aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
5971 aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
5973 }else{
5974 rc = fts3EvalGatherStats(pCsr, pExpr);
5975 if( rc==SQLITE_OK ){
5976 assert( pExpr->aMI );
5977 for(iCol=0; iCol<pTab->nColumn; iCol++){
5978 aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
5979 aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
5984 return rc;
5988 ** The expression pExpr passed as the second argument to this function
5989 ** must be of type FTSQUERY_PHRASE.
5991 ** The returned value is either NULL or a pointer to a buffer containing
5992 ** a position-list indicating the occurrences of the phrase in column iCol
5993 ** of the current row.
5995 ** More specifically, the returned buffer contains 1 varint for each
5996 ** occurrence of the phrase in the column, stored using the normal (delta+2)
5997 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
5998 ** if the requested column contains "a b X c d X X" and the position-list
5999 ** for 'X' is requested, the buffer returned may contain:
6001 ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
6003 ** This function works regardless of whether or not the phrase is deferred,
6004 ** incremental, or neither.
6006 int sqlite3Fts3EvalPhrasePoslist(
6007 Fts3Cursor *pCsr, /* FTS3 cursor object */
6008 Fts3Expr *pExpr, /* Phrase to return doclist for */
6009 int iCol, /* Column to return position list for */
6010 char **ppOut /* OUT: Pointer to position list */
6012 Fts3Phrase *pPhrase = pExpr->pPhrase;
6013 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
6014 char *pIter;
6015 int iThis;
6016 sqlite3_int64 iDocid;
6018 /* If this phrase is applies specifically to some column other than
6019 ** column iCol, return a NULL pointer. */
6020 *ppOut = 0;
6021 assert( iCol>=0 && iCol<pTab->nColumn );
6022 if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
6023 return SQLITE_OK;
6026 iDocid = pExpr->iDocid;
6027 pIter = pPhrase->doclist.pList;
6028 if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
6029 int rc = SQLITE_OK;
6030 int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
6031 int bOr = 0;
6032 u8 bTreeEof = 0;
6033 Fts3Expr *p; /* Used to iterate from pExpr to root */
6034 Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
6035 Fts3Expr *pRun; /* Closest non-deferred ancestor of pNear */
6036 int bMatch;
6038 /* Check if this phrase descends from an OR expression node. If not,
6039 ** return NULL. Otherwise, the entry that corresponds to docid
6040 ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
6041 ** tree that the node is part of has been marked as EOF, but the node
6042 ** itself is not EOF, then it may point to an earlier entry. */
6043 pNear = pExpr;
6044 for(p=pExpr->pParent; p; p=p->pParent){
6045 if( p->eType==FTSQUERY_OR ) bOr = 1;
6046 if( p->eType==FTSQUERY_NEAR ) pNear = p;
6047 if( p->bEof ) bTreeEof = 1;
6049 if( bOr==0 ) return SQLITE_OK;
6050 pRun = pNear;
6051 while( pRun->bDeferred ){
6052 assert( pRun->pParent );
6053 pRun = pRun->pParent;
6056 /* This is the descendent of an OR node. In this case we cannot use
6057 ** an incremental phrase. Load the entire doclist for the phrase
6058 ** into memory in this case. */
6059 if( pPhrase->bIncr ){
6060 int bEofSave = pRun->bEof;
6061 fts3EvalRestart(pCsr, pRun, &rc);
6062 while( rc==SQLITE_OK && !pRun->bEof ){
6063 fts3EvalNextRow(pCsr, pRun, &rc);
6064 if( bEofSave==0 && pRun->iDocid==iDocid ) break;
6066 assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
6067 if( rc==SQLITE_OK && pRun->bEof!=bEofSave ){
6068 rc = FTS_CORRUPT_VTAB;
6071 if( bTreeEof ){
6072 while( rc==SQLITE_OK && !pRun->bEof ){
6073 fts3EvalNextRow(pCsr, pRun, &rc);
6076 if( rc!=SQLITE_OK ) return rc;
6078 bMatch = 1;
6079 for(p=pNear; p; p=p->pLeft){
6080 u8 bEof = 0;
6081 Fts3Expr *pTest = p;
6082 Fts3Phrase *pPh;
6083 assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
6084 if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
6085 assert( pTest->eType==FTSQUERY_PHRASE );
6086 pPh = pTest->pPhrase;
6088 pIter = pPh->pOrPoslist;
6089 iDocid = pPh->iOrDocid;
6090 if( pCsr->bDesc==bDescDoclist ){
6091 bEof = !pPh->doclist.nAll ||
6092 (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
6093 while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
6094 sqlite3Fts3DoclistNext(
6095 bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
6096 &pIter, &iDocid, &bEof
6099 }else{
6100 bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
6101 while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
6102 int dummy;
6103 sqlite3Fts3DoclistPrev(
6104 bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
6105 &pIter, &iDocid, &dummy, &bEof
6109 pPh->pOrPoslist = pIter;
6110 pPh->iOrDocid = iDocid;
6111 if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
6114 if( bMatch ){
6115 pIter = pPhrase->pOrPoslist;
6116 }else{
6117 pIter = 0;
6120 if( pIter==0 ) return SQLITE_OK;
6122 if( *pIter==0x01 ){
6123 pIter++;
6124 pIter += fts3GetVarint32(pIter, &iThis);
6125 }else{
6126 iThis = 0;
6128 while( iThis<iCol ){
6129 fts3ColumnlistCopy(0, &pIter);
6130 if( *pIter==0x00 ) return SQLITE_OK;
6131 pIter++;
6132 pIter += fts3GetVarint32(pIter, &iThis);
6134 if( *pIter==0x00 ){
6135 pIter = 0;
6138 *ppOut = ((iCol==iThis)?pIter:0);
6139 return SQLITE_OK;
6143 ** Free all components of the Fts3Phrase structure that were allocated by
6144 ** the eval module. Specifically, this means to free:
6146 ** * the contents of pPhrase->doclist, and
6147 ** * any Fts3MultiSegReader objects held by phrase tokens.
6149 void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
6150 if( pPhrase ){
6151 int i;
6152 sqlite3_free(pPhrase->doclist.aAll);
6153 fts3EvalInvalidatePoslist(pPhrase);
6154 memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
6155 for(i=0; i<pPhrase->nToken; i++){
6156 fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
6157 pPhrase->aToken[i].pSegcsr = 0;
6164 ** Return SQLITE_CORRUPT_VTAB.
6166 #ifdef SQLITE_DEBUG
6167 int sqlite3Fts3Corrupt(){
6168 return SQLITE_CORRUPT_VTAB;
6170 #endif
6172 #if !SQLITE_CORE
6174 ** Initialize API pointer table, if required.
6176 #ifdef _WIN32
6177 __declspec(dllexport)
6178 #endif
6179 int sqlite3_fts3_init(
6180 sqlite3 *db,
6181 char **pzErrMsg,
6182 const sqlite3_api_routines *pApi
6184 SQLITE_EXTENSION_INIT2(pApi)
6185 return sqlite3Fts3Init(db);
6187 #endif
6189 #endif