4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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
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:
40 ** A = 0xxxxxxx 7 bits of data and one flag bit
41 ** B = 1xxxxxxx 7 bits of data and one flag bit
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).
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:
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)
78 ** varint POS_COLUMN; (marks start of position list for new column)
79 ** varint column; (index of new column)
81 ** varint position; (2 more than the delta from previous position)
84 ** varint POS_END; (marks end of positions for this document.
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
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)
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)
137 ** Here, array { X } means zero or more occurrences of X, adjacent in
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
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
169 ** varint iHeight; (height from leaf level, always >0)
170 ** varint iBlockid; (block id of node's leftmost subtree)
172 ** varint nTerm; (length of first term)
173 ** char pTerm[nTerm]; (content of first term)
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)
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
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
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
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
261 ** MERGE_COUNT segments
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
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
292 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
294 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
295 # define SQLITE_CORE 1
307 # include "sqlite3ext.h"
308 SQLITE_EXTENSION_INIT1
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.
329 int sqlite3_fts3_may_be_corrupt
= 1;
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);
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) \
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
;
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){
371 b
+= (c
&0x7F) << shift
;
372 if( (c
& 0x80)==0 ) break;
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(
398 const unsigned char *p
= (const unsigned char*)pBuf
;
399 const unsigned char *pStart
= p
;
400 const unsigned char *pX
= (const unsigned char*)pEnd
;
403 for(shift
=0; shift
<=63; shift
+=7){
404 u64 c
= p
<pX
? *p
: 0;
406 b
+= (c
&0x7F) << shift
;
407 if( (c
& 0x80)==0 ) break;
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
;
421 #ifndef fts3GetVarint32
422 GETVARINT_INIT(a
, ptr
, 0, 0x00, 0x80, *pi
, 1);
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) );
439 ** Return the number of bytes required to encode v as a varint
441 int sqlite3Fts3VarintLen(sqlite3_uint64 v
){
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
464 void sqlite3Fts3Dequote(char *z
){
465 char quote
; /* Quote character (if any ) */
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
= ']';
477 if( z
[iIn
+1]!=quote
) break;
481 z
[iOut
++] = z
[iIn
++];
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
493 static void fts3GetDeltaVarint(char **pp
, sqlite3_int64
*pVal
){
495 *pp
+= sqlite3Fts3GetVarint(*pp
, &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(
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
--);
523 sqlite3Fts3GetVarint(p
, &iVal
);
528 ** The xDisconnect() virtual table method.
530 static int fts3DisconnectMethod(sqlite3_vtab
*pVtab
){
531 Fts3Table
*p
= (Fts3Table
*)pVtab
;
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
);
556 ** Write an error message into *pzErr
558 void sqlite3Fts3ErrMsg(char **pzErr
, const char *zFormat
, ...){
560 sqlite3_free(*pzErr
);
561 va_start(ap
, zFormat
);
562 *pzErr
= sqlite3_vmprintf(zFormat
, ap
);
567 ** Construct one or more SQL statements from the format string given
568 ** and then evaluate those statements. The success code is written
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 */
582 va_start(ap
, zFormat
);
583 zSql
= sqlite3_vmprintf(zFormat
, ap
);
588 *pRc
= sqlite3_exec(db
, zSql
, 0, 0, 0);
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 */
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';",
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
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);
644 /* Create a list of user columns for the virtual table */
645 zCols
= sqlite3_mprintf("%Q, ", p
->azColumn
[0]);
646 for(i
=1; zCols
&& i
<p
->nColumn
; i
++){
647 zCols
= sqlite3_mprintf("%z%Q, ", zCols
, p
->azColumn
[i
]);
650 /* Create the whole "CREATE TABLE" statement to pass to SQLite */
651 zSql
= sqlite3_mprintf(
652 "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
653 zCols
, p
->zName
, zLanguageid
655 if( !zCols
|| !zSql
){
658 rc
= sqlite3_declare_vtab(p
->db
, zSql
);
668 ** Create the %_stat table if it does not already exist.
670 void sqlite3Fts3CreateStatTable(int *pRc
, Fts3Table
*p
){
671 fts3DbExec(pRc
, p
->db
,
672 "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
673 "(id INTEGER PRIMARY KEY, value BLOB);",
676 if( (*pRc
)==SQLITE_OK
) p
->bHasStat
= 1;
680 ** Create the backing store tables (%_content, %_segments and %_segdir)
681 ** required by the FTS3 table passed as the only argument. This is done
682 ** as part of the vtab xCreate() method.
684 ** If the p->bHasDocsize boolean is true (indicating that this is an
685 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
686 ** %_stat tables required by FTS4.
688 static int fts3CreateTables(Fts3Table
*p
){
689 int rc
= SQLITE_OK
; /* Return code */
690 int i
; /* Iterator variable */
691 sqlite3
*db
= p
->db
; /* The database connection */
693 if( p
->zContentTbl
==0 ){
694 const char *zLanguageid
= p
->zLanguageid
;
695 char *zContentCols
; /* Columns of %_content table */
697 /* Create a list of user columns for the content table */
698 zContentCols
= sqlite3_mprintf("docid INTEGER PRIMARY KEY");
699 for(i
=0; zContentCols
&& i
<p
->nColumn
; i
++){
700 char *z
= p
->azColumn
[i
];
701 zContentCols
= sqlite3_mprintf("%z, 'c%d%q'", zContentCols
, i
, z
);
703 if( zLanguageid
&& zContentCols
){
704 zContentCols
= sqlite3_mprintf("%z, langid", zContentCols
, zLanguageid
);
706 if( zContentCols
==0 ) rc
= SQLITE_NOMEM
;
708 /* Create the content table */
710 "CREATE TABLE %Q.'%q_content'(%s)",
711 p
->zDb
, p
->zName
, zContentCols
713 sqlite3_free(zContentCols
);
716 /* Create other tables */
718 "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
722 "CREATE TABLE %Q.'%q_segdir'("
725 "start_block INTEGER,"
726 "leaves_end_block INTEGER,"
729 "PRIMARY KEY(level, idx)"
733 if( p
->bHasDocsize
){
735 "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
739 assert( p
->bHasStat
==p
->bFts4
);
741 sqlite3Fts3CreateStatTable(&rc
, p
);
747 ** Store the current database page-size in bytes in p->nPgsz.
749 ** If *pRc is non-zero when this function is called, it is a no-op.
750 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
753 static void fts3DatabasePageSize(int *pRc
, Fts3Table
*p
){
754 if( *pRc
==SQLITE_OK
){
755 int rc
; /* Return code */
756 char *zSql
; /* SQL text "PRAGMA %Q.page_size" */
757 sqlite3_stmt
*pStmt
; /* Compiled "PRAGMA %Q.page_size" statement */
759 zSql
= sqlite3_mprintf("PRAGMA %Q.page_size", p
->zDb
);
763 rc
= sqlite3_prepare(p
->db
, zSql
, -1, &pStmt
, 0);
766 p
->nPgsz
= sqlite3_column_int(pStmt
, 0);
767 rc
= sqlite3_finalize(pStmt
);
768 }else if( rc
==SQLITE_AUTH
){
773 assert( p
->nPgsz
>0 || rc
!=SQLITE_OK
);
780 ** "Special" FTS4 arguments are column specifications of the following form:
784 ** There may not be whitespace surrounding the "=" character. The <value>
785 ** term may be quoted, but the <key> may not.
787 static int fts3IsSpecialColumn(
793 const char *zCsr
= z
;
796 if( *zCsr
=='\0' ) return 0;
800 *pnKey
= (int)(zCsr
-z
);
801 zValue
= sqlite3_mprintf("%s", &zCsr
[1]);
803 sqlite3Fts3Dequote(zValue
);
810 ** Append the output of a printf() style formatting to an existing string.
812 static void fts3Appendf(
813 int *pRc
, /* IN/OUT: Error code */
814 char **pz
, /* IN/OUT: Pointer to string buffer */
815 const char *zFormat
, /* Printf format string to append */
816 ... /* Arguments for printf format string */
818 if( *pRc
==SQLITE_OK
){
821 va_start(ap
, zFormat
);
822 z
= sqlite3_vmprintf(zFormat
, ap
);
825 char *z2
= sqlite3_mprintf("%s%s", *pz
, z
);
829 if( z
==0 ) *pRc
= SQLITE_NOMEM
;
836 ** Return a copy of input string zInput enclosed in double-quotes (") and
837 ** with all double quote characters escaped. For example:
839 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
841 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
842 ** is the callers responsibility to call sqlite3_free() to release this
845 static char *fts3QuoteId(char const *zInput
){
848 nRet
= 2 + (int)strlen(zInput
)*2 + 1;
849 zRet
= sqlite3_malloc64(nRet
);
854 for(i
=0; zInput
[i
]; i
++){
855 if( zInput
[i
]=='"' ) *(z
++) = '"';
865 ** Return a list of comma separated SQL expressions and a FROM clause that
866 ** could be used in a SELECT statement such as the following:
868 ** SELECT <list of expressions> FROM %_content AS x ...
870 ** to return the docid, followed by each column of text data in order
871 ** from left to write. If parameter zFunc is not NULL, then instead of
872 ** being returned directly each column of text data is passed to an SQL
873 ** function named zFunc first. For example, if zFunc is "unzip" and the
874 ** table has the three user-defined columns "a", "b", and "c", the following
875 ** string is returned:
877 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
879 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
880 ** is the responsibility of the caller to eventually free it.
882 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
883 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
884 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
885 ** no error occurs, *pRc is left unmodified.
887 static char *fts3ReadExprList(Fts3Table
*p
, const char *zFunc
, int *pRc
){
893 if( p
->zContentTbl
==0 ){
897 zFree
= zFunction
= fts3QuoteId(zFunc
);
899 fts3Appendf(pRc
, &zRet
, "docid");
900 for(i
=0; i
<p
->nColumn
; i
++){
901 fts3Appendf(pRc
, &zRet
, ",%s(x.'c%d%q')", zFunction
, i
, p
->azColumn
[i
]);
903 if( p
->zLanguageid
){
904 fts3Appendf(pRc
, &zRet
, ", x.%Q", "langid");
908 fts3Appendf(pRc
, &zRet
, "rowid");
909 for(i
=0; i
<p
->nColumn
; i
++){
910 fts3Appendf(pRc
, &zRet
, ", x.'%q'", p
->azColumn
[i
]);
912 if( p
->zLanguageid
){
913 fts3Appendf(pRc
, &zRet
, ", x.%Q", p
->zLanguageid
);
916 fts3Appendf(pRc
, &zRet
, " FROM '%q'.'%q%s' AS x",
918 (p
->zContentTbl
? p
->zContentTbl
: p
->zName
),
919 (p
->zContentTbl
? "" : "_content")
925 ** Return a list of N comma separated question marks, where N is the number
926 ** of columns in the %_content table (one for the docid plus one for each
927 ** user-defined text column).
929 ** If argument zFunc is not NULL, then all but the first question mark
930 ** is preceded by zFunc and an open bracket, and followed by a closed
931 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
932 ** user-defined text columns, the following string is returned:
934 ** "?, zip(?), zip(?), zip(?)"
936 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
937 ** is the responsibility of the caller to eventually free it.
939 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
940 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
941 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
942 ** no error occurs, *pRc is left unmodified.
944 static char *fts3WriteExprList(Fts3Table
*p
, const char *zFunc
, int *pRc
){
953 zFree
= zFunction
= fts3QuoteId(zFunc
);
955 fts3Appendf(pRc
, &zRet
, "?");
956 for(i
=0; i
<p
->nColumn
; i
++){
957 fts3Appendf(pRc
, &zRet
, ",%s(?)", zFunction
);
959 if( p
->zLanguageid
){
960 fts3Appendf(pRc
, &zRet
, ", ?");
967 ** Buffer z contains a positive integer value encoded as utf-8 text.
968 ** Decode this value and store it in *pnOut, returning the number of bytes
969 ** consumed. If an overflow error occurs return a negative value.
971 int sqlite3Fts3ReadInt(const char *z
, int *pnOut
){
974 for(i
=0; z
[i
]>='0' && z
[i
]<='9'; i
++){
975 iVal
= iVal
*10 + (z
[i
] - '0');
976 if( iVal
>0x7FFFFFFF ) return -1;
983 ** This function interprets the string at (*pp) as a non-negative integer
984 ** value. It reads the integer and sets *pnOut to the value read, then
985 ** sets *pp to point to the byte immediately following the last byte of
986 ** the integer value.
988 ** Only decimal digits ('0'..'9') may be part of an integer value.
990 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
991 ** the output value undefined. Otherwise SQLITE_OK is returned.
993 ** This function is used when parsing the "prefix=" FTS4 parameter.
995 static int fts3GobbleInt(const char **pp
, int *pnOut
){
996 const int MAX_NPREFIX
= 10000000;
997 int nInt
= 0; /* Output value */
999 nByte
= sqlite3Fts3ReadInt(*pp
, &nInt
);
1000 if( nInt
>MAX_NPREFIX
){
1004 return SQLITE_ERROR
;
1012 ** This function is called to allocate an array of Fts3Index structures
1013 ** representing the indexes maintained by the current FTS table. FTS tables
1014 ** always maintain the main "terms" index, but may also maintain one or
1015 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
1016 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
1018 ** Argument zParam is passed the value of the "prefix=" option if one was
1019 ** specified, or NULL otherwise.
1021 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
1022 ** the allocated array. *pnIndex is set to the number of elements in the
1023 ** array. If an error does occur, an SQLite error code is returned.
1025 ** Regardless of whether or not an error is returned, it is the responsibility
1026 ** of the caller to call sqlite3_free() on the output array to free it.
1028 static int fts3PrefixParameter(
1029 const char *zParam
, /* ABC in prefix=ABC parameter to parse */
1030 int *pnIndex
, /* OUT: size of *apIndex[] array */
1031 struct Fts3Index
**apIndex
/* OUT: Array of indexes for this table */
1033 struct Fts3Index
*aIndex
; /* Allocated array */
1034 int nIndex
= 1; /* Number of entries in array */
1036 if( zParam
&& zParam
[0] ){
1039 for(p
=zParam
; *p
; p
++){
1040 if( *p
==',' ) nIndex
++;
1044 aIndex
= sqlite3_malloc64(sizeof(struct Fts3Index
) * nIndex
);
1047 return SQLITE_NOMEM
;
1050 memset(aIndex
, 0, sizeof(struct Fts3Index
) * nIndex
);
1052 const char *p
= zParam
;
1054 for(i
=1; i
<nIndex
; i
++){
1056 if( fts3GobbleInt(&p
, &nPrefix
) ) return SQLITE_ERROR
;
1057 assert( nPrefix
>=0 );
1062 aIndex
[i
].nPrefix
= nPrefix
;
1073 ** This function is called when initializing an FTS4 table that uses the
1074 ** content=xxx option. It determines the number of and names of the columns
1075 ** of the new FTS4 table.
1077 ** The third argument passed to this function is the value passed to the
1078 ** config=xxx option (i.e. "xxx"). This function queries the database for
1079 ** a table of that name. If found, the output variables are populated
1082 ** *pnCol: Set to the number of columns table xxx has,
1084 ** *pnStr: Set to the total amount of space required to store a copy
1085 ** of each columns name, including the nul-terminator.
1087 ** *pazCol: Set to point to an array of *pnCol strings. Each string is
1088 ** the name of the corresponding column in table xxx. The array
1089 ** and its contents are allocated using a single allocation. It
1090 ** is the responsibility of the caller to free this allocation
1091 ** by eventually passing the *pazCol value to sqlite3_free().
1093 ** If the table cannot be found, an error code is returned and the output
1094 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
1095 ** returned (and the output variables are undefined).
1097 static int fts3ContentColumns(
1098 sqlite3
*db
, /* Database handle */
1099 const char *zDb
, /* Name of db (i.e. "main", "temp" etc.) */
1100 const char *zTbl
, /* Name of content table */
1101 const char ***pazCol
, /* OUT: Malloc'd array of column names */
1102 int *pnCol
, /* OUT: Size of array *pazCol */
1103 int *pnStr
, /* OUT: Bytes of string content */
1104 char **pzErr
/* OUT: error message */
1106 int rc
= SQLITE_OK
; /* Return code */
1107 char *zSql
; /* "SELECT *" statement on zTbl */
1108 sqlite3_stmt
*pStmt
= 0; /* Compiled version of zSql */
1110 zSql
= sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb
, zTbl
);
1114 rc
= sqlite3_prepare(db
, zSql
, -1, &pStmt
, 0);
1115 if( rc
!=SQLITE_OK
){
1116 sqlite3Fts3ErrMsg(pzErr
, "%s", sqlite3_errmsg(db
));
1121 if( rc
==SQLITE_OK
){
1122 const char **azCol
; /* Output array */
1123 sqlite3_int64 nStr
= 0; /* Size of all column names (incl. 0x00) */
1124 int nCol
; /* Number of table columns */
1125 int i
; /* Used to iterate through columns */
1127 /* Loop through the returned columns. Set nStr to the number of bytes of
1128 ** space required to store a copy of each column name, including the
1129 ** nul-terminator byte. */
1130 nCol
= sqlite3_column_count(pStmt
);
1131 for(i
=0; i
<nCol
; i
++){
1132 const char *zCol
= sqlite3_column_name(pStmt
, i
);
1133 nStr
+= strlen(zCol
) + 1;
1136 /* Allocate and populate the array to return. */
1137 azCol
= (const char **)sqlite3_malloc64(sizeof(char *) * nCol
+ nStr
);
1141 char *p
= (char *)&azCol
[nCol
];
1142 for(i
=0; i
<nCol
; i
++){
1143 const char *zCol
= sqlite3_column_name(pStmt
, i
);
1144 int n
= (int)strlen(zCol
)+1;
1150 sqlite3_finalize(pStmt
);
1152 /* Set the output variables. */
1162 ** This function is the implementation of both the xConnect and xCreate
1163 ** methods of the FTS3 virtual table.
1165 ** The argv[] array contains the following:
1167 ** argv[0] -> module name ("fts3" or "fts4")
1168 ** argv[1] -> database name
1169 ** argv[2] -> table name
1170 ** argv[...] -> "column name" and other module argument fields.
1172 static int fts3InitVtab(
1173 int isCreate
, /* True for xCreate, false for xConnect */
1174 sqlite3
*db
, /* The SQLite database connection */
1175 void *pAux
, /* Hash table containing tokenizers */
1176 int argc
, /* Number of elements in argv array */
1177 const char * const *argv
, /* xCreate/xConnect argument array */
1178 sqlite3_vtab
**ppVTab
, /* Write the resulting vtab structure here */
1179 char **pzErr
/* Write any error message here */
1181 Fts3Hash
*pHash
= &((Fts3HashWrapper
*)pAux
)->hash
;
1182 Fts3Table
*p
= 0; /* Pointer to allocated vtab */
1183 int rc
= SQLITE_OK
; /* Return code */
1184 int i
; /* Iterator variable */
1185 sqlite3_int64 nByte
; /* Size of allocation used for *p */
1186 int iCol
; /* Column index */
1187 int nString
= 0; /* Bytes required to hold all column names */
1188 int nCol
= 0; /* Number of columns in the FTS table */
1189 char *zCsr
; /* Space for holding column names */
1190 int nDb
; /* Bytes required to hold database name */
1191 int nName
; /* Bytes required to hold table name */
1192 int isFts4
= (argv
[0][3]=='4'); /* True for FTS4, false for FTS3 */
1193 const char **aCol
; /* Array of column names */
1194 sqlite3_tokenizer
*pTokenizer
= 0; /* Tokenizer for this table */
1196 int nIndex
= 0; /* Size of aIndex[] array */
1197 struct Fts3Index
*aIndex
= 0; /* Array of indexes for this table */
1199 /* The results of parsing supported FTS4 key=value options: */
1200 int bNoDocsize
= 0; /* True to omit %_docsize table */
1201 int bDescIdx
= 0; /* True to store descending indexes */
1202 char *zPrefix
= 0; /* Prefix parameter value (or NULL) */
1203 char *zCompress
= 0; /* compress=? parameter (or NULL) */
1204 char *zUncompress
= 0; /* uncompress=? parameter (or NULL) */
1205 char *zContent
= 0; /* content=? parameter (or NULL) */
1206 char *zLanguageid
= 0; /* languageid=? parameter (or NULL) */
1207 char **azNotindexed
= 0; /* The set of notindexed= columns */
1208 int nNotindexed
= 0; /* Size of azNotindexed[] array */
1210 assert( strlen(argv
[0])==4 );
1211 assert( (sqlite3_strnicmp(argv
[0], "fts4", 4)==0 && isFts4
)
1212 || (sqlite3_strnicmp(argv
[0], "fts3", 4)==0 && !isFts4
)
1215 nDb
= (int)strlen(argv
[1]) + 1;
1216 nName
= (int)strlen(argv
[2]) + 1;
1218 nByte
= sizeof(const char *) * (argc
-2);
1219 aCol
= (const char **)sqlite3_malloc64(nByte
);
1221 memset((void*)aCol
, 0, nByte
);
1222 azNotindexed
= (char **)sqlite3_malloc64(nByte
);
1225 memset(azNotindexed
, 0, nByte
);
1227 if( !aCol
|| !azNotindexed
){
1232 /* Loop through all of the arguments passed by the user to the FTS3/4
1233 ** module (i.e. all the column names and special arguments). This loop
1234 ** does the following:
1236 ** + Figures out the number of columns the FTSX table will have, and
1237 ** the number of bytes of space that must be allocated to store copies
1238 ** of the column names.
1240 ** + If there is a tokenizer specification included in the arguments,
1241 ** initializes the tokenizer pTokenizer.
1243 for(i
=3; rc
==SQLITE_OK
&& i
<argc
; i
++){
1244 char const *z
= argv
[i
];
1248 /* Check if this is a tokenizer specification */
1251 && 0==sqlite3_strnicmp(z
, "tokenize", 8)
1252 && 0==sqlite3Fts3IsIdChar(z
[8])
1254 rc
= sqlite3Fts3InitTokenizer(pHash
, &z
[9], &pTokenizer
, pzErr
);
1257 /* Check if it is an FTS4 special argument. */
1258 else if( isFts4
&& fts3IsSpecialColumn(z
, &nKey
, &zVal
) ){
1263 { "matchinfo", 9 }, /* 0 -> MATCHINFO */
1264 { "prefix", 6 }, /* 1 -> PREFIX */
1265 { "compress", 8 }, /* 2 -> COMPRESS */
1266 { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
1267 { "order", 5 }, /* 4 -> ORDER */
1268 { "content", 7 }, /* 5 -> CONTENT */
1269 { "languageid", 10 }, /* 6 -> LANGUAGEID */
1270 { "notindexed", 10 } /* 7 -> NOTINDEXED */
1277 for(iOpt
=0; iOpt
<SizeofArray(aFts4Opt
); iOpt
++){
1278 struct Fts4Option
*pOp
= &aFts4Opt
[iOpt
];
1279 if( nKey
==pOp
->nOpt
&& !sqlite3_strnicmp(z
, pOp
->zOpt
, pOp
->nOpt
) ){
1284 case 0: /* MATCHINFO */
1285 if( strlen(zVal
)!=4 || sqlite3_strnicmp(zVal
, "fts3", 4) ){
1286 sqlite3Fts3ErrMsg(pzErr
, "unrecognized matchinfo: %s", zVal
);
1292 case 1: /* PREFIX */
1293 sqlite3_free(zPrefix
);
1298 case 2: /* COMPRESS */
1299 sqlite3_free(zCompress
);
1304 case 3: /* UNCOMPRESS */
1305 sqlite3_free(zUncompress
);
1311 if( (strlen(zVal
)!=3 || sqlite3_strnicmp(zVal
, "asc", 3))
1312 && (strlen(zVal
)!=4 || sqlite3_strnicmp(zVal
, "desc", 4))
1314 sqlite3Fts3ErrMsg(pzErr
, "unrecognized order: %s", zVal
);
1317 bDescIdx
= (zVal
[0]=='d' || zVal
[0]=='D');
1320 case 5: /* CONTENT */
1321 sqlite3_free(zContent
);
1326 case 6: /* LANGUAGEID */
1328 sqlite3_free(zLanguageid
);
1333 case 7: /* NOTINDEXED */
1334 azNotindexed
[nNotindexed
++] = zVal
;
1339 assert( iOpt
==SizeofArray(aFts4Opt
) );
1340 sqlite3Fts3ErrMsg(pzErr
, "unrecognized parameter: %s", z
);
1348 /* Otherwise, the argument is a column name. */
1350 nString
+= (int)(strlen(z
) + 1);
1355 /* If a content=xxx option was specified, the following:
1357 ** 1. Ignore any compress= and uncompress= options.
1359 ** 2. If no column names were specified as part of the CREATE VIRTUAL
1360 ** TABLE statement, use all columns from the content table.
1362 if( rc
==SQLITE_OK
&& zContent
){
1363 sqlite3_free(zCompress
);
1364 sqlite3_free(zUncompress
);
1368 sqlite3_free((void*)aCol
);
1370 rc
= fts3ContentColumns(db
, argv
[1], zContent
,&aCol
,&nCol
,&nString
,pzErr
);
1372 /* If a languageid= option was specified, remove the language id
1373 ** column from the aCol[] array. */
1374 if( rc
==SQLITE_OK
&& zLanguageid
){
1376 for(j
=0; j
<nCol
; j
++){
1377 if( sqlite3_stricmp(zLanguageid
, aCol
[j
])==0 ){
1379 for(k
=j
; k
<nCol
; k
++) aCol
[k
] = aCol
[k
+1];
1387 if( rc
!=SQLITE_OK
) goto fts3_init_out
;
1390 assert( nString
==0 );
1391 aCol
[0] = "content";
1396 if( pTokenizer
==0 ){
1397 rc
= sqlite3Fts3InitTokenizer(pHash
, "simple", &pTokenizer
, pzErr
);
1398 if( rc
!=SQLITE_OK
) goto fts3_init_out
;
1400 assert( pTokenizer
);
1402 rc
= fts3PrefixParameter(zPrefix
, &nIndex
, &aIndex
);
1403 if( rc
==SQLITE_ERROR
){
1405 sqlite3Fts3ErrMsg(pzErr
, "error parsing prefix parameter: %s", zPrefix
);
1407 if( rc
!=SQLITE_OK
) goto fts3_init_out
;
1409 /* Allocate and populate the Fts3Table structure. */
1410 nByte
= sizeof(Fts3Table
) + /* Fts3Table */
1411 nCol
* sizeof(char *) + /* azColumn */
1412 nIndex
* sizeof(struct Fts3Index
) + /* aIndex */
1413 nCol
* sizeof(u8
) + /* abNotindexed */
1416 nString
; /* Space for azColumn strings */
1417 p
= (Fts3Table
*)sqlite3_malloc64(nByte
);
1422 memset(p
, 0, nByte
);
1425 p
->nPendingData
= 0;
1426 p
->azColumn
= (char **)&p
[1];
1427 p
->pTokenizer
= pTokenizer
;
1428 p
->nMaxPendingData
= FTS3_MAX_PENDING_DATA
;
1429 p
->bHasDocsize
= (isFts4
&& bNoDocsize
==0);
1430 p
->bHasStat
= (u8
)isFts4
;
1431 p
->bFts4
= (u8
)isFts4
;
1432 p
->bDescIdx
= (u8
)bDescIdx
;
1433 p
->nAutoincrmerge
= 0xff; /* 0xff means setting unknown */
1434 p
->zContentTbl
= zContent
;
1435 p
->zLanguageid
= zLanguageid
;
1438 TESTONLY( p
->inTransaction
= -1 );
1439 TESTONLY( p
->mxSavepoint
= -1 );
1441 p
->aIndex
= (struct Fts3Index
*)&p
->azColumn
[nCol
];
1442 memcpy(p
->aIndex
, aIndex
, sizeof(struct Fts3Index
) * nIndex
);
1444 for(i
=0; i
<nIndex
; i
++){
1445 fts3HashInit(&p
->aIndex
[i
].hPending
, FTS3_HASH_STRING
, 1);
1447 p
->abNotindexed
= (u8
*)&p
->aIndex
[nIndex
];
1449 /* Fill in the zName and zDb fields of the vtab structure. */
1450 zCsr
= (char *)&p
->abNotindexed
[nCol
];
1452 memcpy(zCsr
, argv
[2], nName
);
1455 memcpy(zCsr
, argv
[1], nDb
);
1458 /* Fill in the azColumn array */
1459 for(iCol
=0; iCol
<nCol
; iCol
++){
1462 z
= (char *)sqlite3Fts3NextToken(aCol
[iCol
], &n
);
1467 sqlite3Fts3Dequote(zCsr
);
1468 p
->azColumn
[iCol
] = zCsr
;
1470 assert( zCsr
<= &((char *)p
)[nByte
] );
1473 /* Fill in the abNotindexed array */
1474 for(iCol
=0; iCol
<nCol
; iCol
++){
1475 int n
= (int)strlen(p
->azColumn
[iCol
]);
1476 for(i
=0; i
<nNotindexed
; i
++){
1477 char *zNot
= azNotindexed
[i
];
1478 if( zNot
&& n
==(int)strlen(zNot
)
1479 && 0==sqlite3_strnicmp(p
->azColumn
[iCol
], zNot
, n
)
1481 p
->abNotindexed
[iCol
] = 1;
1483 azNotindexed
[i
] = 0;
1487 for(i
=0; i
<nNotindexed
; i
++){
1488 if( azNotindexed
[i
] ){
1489 sqlite3Fts3ErrMsg(pzErr
, "no such column: %s", azNotindexed
[i
]);
1494 if( rc
==SQLITE_OK
&& (zCompress
==0)!=(zUncompress
==0) ){
1495 char const *zMiss
= (zCompress
==0 ? "compress" : "uncompress");
1497 sqlite3Fts3ErrMsg(pzErr
, "missing %s parameter in fts4 constructor", zMiss
);
1499 p
->zReadExprlist
= fts3ReadExprList(p
, zUncompress
, &rc
);
1500 p
->zWriteExprlist
= fts3WriteExprList(p
, zCompress
, &rc
);
1501 if( rc
!=SQLITE_OK
) goto fts3_init_out
;
1503 /* If this is an xCreate call, create the underlying tables in the
1504 ** database. TODO: For xConnect(), it could verify that said tables exist.
1507 rc
= fts3CreateTables(p
);
1510 /* Check to see if a legacy fts3 table has been "upgraded" by the
1511 ** addition of a %_stat table so that it can use incremental merge.
1513 if( !isFts4
&& !isCreate
){
1517 /* Figure out the page-size for the database. This is required in order to
1518 ** estimate the cost of loading large doclists from the database. */
1519 fts3DatabasePageSize(&rc
, p
);
1520 p
->nNodeSize
= p
->nPgsz
-35;
1522 #if defined(SQLITE_DEBUG)||defined(SQLITE_TEST)
1523 p
->nMergeCount
= FTS3_MERGE_COUNT
;
1526 /* Declare the table schema to SQLite. */
1527 fts3DeclareVtab(&rc
, p
);
1530 sqlite3_free(zPrefix
);
1531 sqlite3_free(aIndex
);
1532 sqlite3_free(zCompress
);
1533 sqlite3_free(zUncompress
);
1534 sqlite3_free(zContent
);
1535 sqlite3_free(zLanguageid
);
1536 for(i
=0; i
<nNotindexed
; i
++) sqlite3_free(azNotindexed
[i
]);
1537 sqlite3_free((void *)aCol
);
1538 sqlite3_free((void *)azNotindexed
);
1539 if( rc
!=SQLITE_OK
){
1541 fts3DisconnectMethod((sqlite3_vtab
*)p
);
1542 }else if( pTokenizer
){
1543 pTokenizer
->pModule
->xDestroy(pTokenizer
);
1546 assert( p
->pSegments
==0 );
1553 ** The xConnect() and xCreate() methods for the virtual table. All the
1554 ** work is done in function fts3InitVtab().
1556 static int fts3ConnectMethod(
1557 sqlite3
*db
, /* Database connection */
1558 void *pAux
, /* Pointer to tokenizer hash table */
1559 int argc
, /* Number of elements in argv array */
1560 const char * const *argv
, /* xCreate/xConnect argument array */
1561 sqlite3_vtab
**ppVtab
, /* OUT: New sqlite3_vtab object */
1562 char **pzErr
/* OUT: sqlite3_malloc'd error message */
1564 return fts3InitVtab(0, db
, pAux
, argc
, argv
, ppVtab
, pzErr
);
1566 static int fts3CreateMethod(
1567 sqlite3
*db
, /* Database connection */
1568 void *pAux
, /* Pointer to tokenizer hash table */
1569 int argc
, /* Number of elements in argv array */
1570 const char * const *argv
, /* xCreate/xConnect argument array */
1571 sqlite3_vtab
**ppVtab
, /* OUT: New sqlite3_vtab object */
1572 char **pzErr
/* OUT: sqlite3_malloc'd error message */
1574 return fts3InitVtab(1, db
, pAux
, argc
, argv
, ppVtab
, pzErr
);
1578 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
1579 ** extension is currently being used by a version of SQLite too old to
1580 ** support estimatedRows. In that case this function is a no-op.
1582 static void fts3SetEstimatedRows(sqlite3_index_info
*pIdxInfo
, i64 nRow
){
1583 #if SQLITE_VERSION_NUMBER>=3008002
1584 if( sqlite3_libversion_number()>=3008002 ){
1585 pIdxInfo
->estimatedRows
= nRow
;
1591 ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
1592 ** extension is currently being used by a version of SQLite too old to
1593 ** support index-info flags. In that case this function is a no-op.
1595 static void fts3SetUniqueFlag(sqlite3_index_info
*pIdxInfo
){
1596 #if SQLITE_VERSION_NUMBER>=3008012
1597 if( sqlite3_libversion_number()>=3008012 ){
1598 pIdxInfo
->idxFlags
|= SQLITE_INDEX_SCAN_UNIQUE
;
1604 ** Implementation of the xBestIndex method for FTS3 tables. There
1605 ** are three possible strategies, in order of preference:
1607 ** 1. Direct lookup by rowid or docid.
1608 ** 2. Full-text search using a MATCH operator on a non-docid column.
1609 ** 3. Linear scan of %_content table.
1611 static int fts3BestIndexMethod(sqlite3_vtab
*pVTab
, sqlite3_index_info
*pInfo
){
1612 Fts3Table
*p
= (Fts3Table
*)pVTab
;
1613 int i
; /* Iterator variable */
1614 int iCons
= -1; /* Index of constraint to use */
1616 int iLangidCons
= -1; /* Index of langid=x constraint, if present */
1617 int iDocidGe
= -1; /* Index of docid>=x constraint, if present */
1618 int iDocidLe
= -1; /* Index of docid<=x constraint, if present */
1622 return SQLITE_ERROR
;
1625 /* By default use a full table scan. This is an expensive option,
1626 ** so search through the constraints to see if a more efficient
1627 ** strategy is possible.
1629 pInfo
->idxNum
= FTS3_FULLSCAN_SEARCH
;
1630 pInfo
->estimatedCost
= 5000000;
1631 for(i
=0; i
<pInfo
->nConstraint
; i
++){
1632 int bDocid
; /* True if this constraint is on docid */
1633 struct sqlite3_index_constraint
*pCons
= &pInfo
->aConstraint
[i
];
1634 if( pCons
->usable
==0 ){
1635 if( pCons
->op
==SQLITE_INDEX_CONSTRAINT_MATCH
){
1636 /* There exists an unusable MATCH constraint. This means that if
1637 ** the planner does elect to use the results of this call as part
1638 ** of the overall query plan the user will see an "unable to use
1639 ** function MATCH in the requested context" error. To discourage
1640 ** this, return a very high cost here. */
1641 pInfo
->idxNum
= FTS3_FULLSCAN_SEARCH
;
1642 pInfo
->estimatedCost
= 1e50
;
1643 fts3SetEstimatedRows(pInfo
, ((sqlite3_int64
)1) << 50);
1649 bDocid
= (pCons
->iColumn
<0 || pCons
->iColumn
==p
->nColumn
+1);
1651 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
1652 if( iCons
<0 && pCons
->op
==SQLITE_INDEX_CONSTRAINT_EQ
&& bDocid
){
1653 pInfo
->idxNum
= FTS3_DOCID_SEARCH
;
1654 pInfo
->estimatedCost
= 1.0;
1658 /* A MATCH constraint. Use a full-text search.
1660 ** If there is more than one MATCH constraint available, use the first
1661 ** one encountered. If there is both a MATCH constraint and a direct
1662 ** rowid/docid lookup, prefer the MATCH strategy. This is done even
1663 ** though the rowid/docid lookup is faster than a MATCH query, selecting
1664 ** it would lead to an "unable to use function MATCH in the requested
1667 if( pCons
->op
==SQLITE_INDEX_CONSTRAINT_MATCH
1668 && pCons
->iColumn
>=0 && pCons
->iColumn
<=p
->nColumn
1670 pInfo
->idxNum
= FTS3_FULLTEXT_SEARCH
+ pCons
->iColumn
;
1671 pInfo
->estimatedCost
= 2.0;
1675 /* Equality constraint on the langid column */
1676 if( pCons
->op
==SQLITE_INDEX_CONSTRAINT_EQ
1677 && pCons
->iColumn
==p
->nColumn
+ 2
1683 switch( pCons
->op
){
1684 case SQLITE_INDEX_CONSTRAINT_GE
:
1685 case SQLITE_INDEX_CONSTRAINT_GT
:
1689 case SQLITE_INDEX_CONSTRAINT_LE
:
1690 case SQLITE_INDEX_CONSTRAINT_LT
:
1697 /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
1698 if( pInfo
->idxNum
==FTS3_DOCID_SEARCH
) fts3SetUniqueFlag(pInfo
);
1702 pInfo
->aConstraintUsage
[iCons
].argvIndex
= iIdx
++;
1703 pInfo
->aConstraintUsage
[iCons
].omit
= 1;
1705 if( iLangidCons
>=0 ){
1706 pInfo
->idxNum
|= FTS3_HAVE_LANGID
;
1707 pInfo
->aConstraintUsage
[iLangidCons
].argvIndex
= iIdx
++;
1710 pInfo
->idxNum
|= FTS3_HAVE_DOCID_GE
;
1711 pInfo
->aConstraintUsage
[iDocidGe
].argvIndex
= iIdx
++;
1714 pInfo
->idxNum
|= FTS3_HAVE_DOCID_LE
;
1715 pInfo
->aConstraintUsage
[iDocidLe
].argvIndex
= iIdx
++;
1718 /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
1719 ** docid) order. Both ascending and descending are possible.
1721 if( pInfo
->nOrderBy
==1 ){
1722 struct sqlite3_index_orderby
*pOrder
= &pInfo
->aOrderBy
[0];
1723 if( pOrder
->iColumn
<0 || pOrder
->iColumn
==p
->nColumn
+1 ){
1725 pInfo
->idxStr
= "DESC";
1727 pInfo
->idxStr
= "ASC";
1729 pInfo
->orderByConsumed
= 1;
1733 assert( p
->pSegments
==0 );
1738 ** Implementation of xOpen method.
1740 static int fts3OpenMethod(sqlite3_vtab
*pVTab
, sqlite3_vtab_cursor
**ppCsr
){
1741 sqlite3_vtab_cursor
*pCsr
; /* Allocated cursor */
1743 UNUSED_PARAMETER(pVTab
);
1745 /* Allocate a buffer large enough for an Fts3Cursor structure. If the
1746 ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
1747 ** if the allocation fails, return SQLITE_NOMEM.
1749 *ppCsr
= pCsr
= (sqlite3_vtab_cursor
*)sqlite3_malloc(sizeof(Fts3Cursor
));
1751 return SQLITE_NOMEM
;
1753 memset(pCsr
, 0, sizeof(Fts3Cursor
));
1758 ** Finalize the statement handle at pCsr->pStmt.
1760 ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
1761 ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
1762 ** pointer there instead of finalizing it.
1764 static void fts3CursorFinalizeStmt(Fts3Cursor
*pCsr
){
1765 if( pCsr
->bSeekStmt
){
1766 Fts3Table
*p
= (Fts3Table
*)pCsr
->base
.pVtab
;
1767 if( p
->pSeekStmt
==0 ){
1768 p
->pSeekStmt
= pCsr
->pStmt
;
1769 sqlite3_reset(pCsr
->pStmt
);
1772 pCsr
->bSeekStmt
= 0;
1774 sqlite3_finalize(pCsr
->pStmt
);
1778 ** Free all resources currently held by the cursor passed as the only
1781 static void fts3ClearCursor(Fts3Cursor
*pCsr
){
1782 fts3CursorFinalizeStmt(pCsr
);
1783 sqlite3Fts3FreeDeferredTokens(pCsr
);
1784 sqlite3_free(pCsr
->aDoclist
);
1785 sqlite3Fts3MIBufferFree(pCsr
->pMIBuffer
);
1786 sqlite3Fts3ExprFree(pCsr
->pExpr
);
1787 memset(&(&pCsr
->base
)[1], 0, sizeof(Fts3Cursor
)-sizeof(sqlite3_vtab_cursor
));
1791 ** Close the cursor. For additional information see the documentation
1792 ** on the xClose method of the virtual table interface.
1794 static int fts3CloseMethod(sqlite3_vtab_cursor
*pCursor
){
1795 Fts3Cursor
*pCsr
= (Fts3Cursor
*)pCursor
;
1796 assert( ((Fts3Table
*)pCsr
->base
.pVtab
)->pSegments
==0 );
1797 fts3ClearCursor(pCsr
);
1798 assert( ((Fts3Table
*)pCsr
->base
.pVtab
)->pSegments
==0 );
1804 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
1805 ** compose and prepare an SQL statement of the form:
1807 ** "SELECT <columns> FROM %_content WHERE rowid = ?"
1809 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
1810 ** it. If an error occurs, return an SQLite error code.
1812 static int fts3CursorSeekStmt(Fts3Cursor
*pCsr
){
1814 if( pCsr
->pStmt
==0 ){
1815 Fts3Table
*p
= (Fts3Table
*)pCsr
->base
.pVtab
;
1818 pCsr
->pStmt
= p
->pSeekStmt
;
1821 zSql
= sqlite3_mprintf("SELECT %s WHERE rowid = ?", p
->zReadExprlist
);
1822 if( !zSql
) return SQLITE_NOMEM
;
1824 rc
= sqlite3_prepare_v3(
1825 p
->db
, zSql
,-1,SQLITE_PREPARE_PERSISTENT
,&pCsr
->pStmt
,0
1830 if( rc
==SQLITE_OK
) pCsr
->bSeekStmt
= 1;
1836 ** Position the pCsr->pStmt statement so that it is on the row
1837 ** of the %_content table that contains the last match. Return
1838 ** SQLITE_OK on success.
1840 static int fts3CursorSeek(sqlite3_context
*pContext
, Fts3Cursor
*pCsr
){
1842 if( pCsr
->isRequireSeek
){
1843 rc
= fts3CursorSeekStmt(pCsr
);
1844 if( rc
==SQLITE_OK
){
1845 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
1847 sqlite3_bind_int64(pCsr
->pStmt
, 1, pCsr
->iPrevId
);
1848 pCsr
->isRequireSeek
= 0;
1849 if( SQLITE_ROW
==sqlite3_step(pCsr
->pStmt
) ){
1854 rc
= sqlite3_reset(pCsr
->pStmt
);
1855 if( rc
==SQLITE_OK
&& ((Fts3Table
*)pCsr
->base
.pVtab
)->zContentTbl
==0 ){
1856 /* If no row was found and no error has occurred, then the %_content
1857 ** table is missing a row that is present in the full-text index.
1858 ** The data structures are corrupt. */
1859 rc
= FTS_CORRUPT_VTAB
;
1866 if( rc
!=SQLITE_OK
&& pContext
){
1867 sqlite3_result_error_code(pContext
, rc
);
1873 ** This function is used to process a single interior node when searching
1874 ** a b-tree for a term or term prefix. The node data is passed to this
1875 ** function via the zNode/nNode parameters. The term to search for is
1876 ** passed in zTerm/nTerm.
1878 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
1879 ** of the child node that heads the sub-tree that may contain the term.
1881 ** If piLast is not NULL, then *piLast is set to the right-most child node
1882 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
1885 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
1887 static int fts3ScanInteriorNode(
1888 const char *zTerm
, /* Term to select leaves for */
1889 int nTerm
, /* Size of term zTerm in bytes */
1890 const char *zNode
, /* Buffer containing segment interior node */
1891 int nNode
, /* Size of buffer at zNode */
1892 sqlite3_int64
*piFirst
, /* OUT: Selected child node */
1893 sqlite3_int64
*piLast
/* OUT: Selected child node */
1895 int rc
= SQLITE_OK
; /* Return code */
1896 const char *zCsr
= zNode
; /* Cursor to iterate through node */
1897 const char *zEnd
= &zCsr
[nNode
];/* End of interior node buffer */
1898 char *zBuffer
= 0; /* Buffer to load terms into */
1899 i64 nAlloc
= 0; /* Size of allocated buffer */
1900 int isFirstTerm
= 1; /* True when processing first term on page */
1901 u64 iChild
; /* Block id of child node to descend to */
1902 int nBuffer
= 0; /* Total term size */
1904 /* Skip over the 'height' varint that occurs at the start of every
1905 ** interior node. Then load the blockid of the left-child of the b-tree
1906 ** node into variable iChild.
1908 ** Even if the data structure on disk is corrupted, this (reading two
1909 ** varints from the buffer) does not risk an overread. If zNode is a
1910 ** root node, then the buffer comes from a SELECT statement. SQLite does
1911 ** not make this guarantee explicitly, but in practice there are always
1912 ** either more than 20 bytes of allocated space following the nNode bytes of
1913 ** contents, or two zero bytes. Or, if the node is read from the %_segments
1914 ** table, then there are always 20 bytes of zeroed padding following the
1915 ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
1917 zCsr
+= sqlite3Fts3GetVarintU(zCsr
, &iChild
);
1918 zCsr
+= sqlite3Fts3GetVarintU(zCsr
, &iChild
);
1920 return FTS_CORRUPT_VTAB
;
1923 while( zCsr
<zEnd
&& (piFirst
|| piLast
) ){
1924 int cmp
; /* memcmp() result */
1925 int nSuffix
; /* Size of term suffix */
1926 int nPrefix
= 0; /* Size of term prefix */
1928 /* Load the next term on the node into zBuffer. Use realloc() to expand
1929 ** the size of zBuffer if required. */
1931 zCsr
+= fts3GetVarint32(zCsr
, &nPrefix
);
1932 if( nPrefix
>nBuffer
){
1933 rc
= FTS_CORRUPT_VTAB
;
1938 zCsr
+= fts3GetVarint32(zCsr
, &nSuffix
);
1940 assert( nPrefix
>=0 && nSuffix
>=0 );
1941 if( nPrefix
>zCsr
-zNode
|| nSuffix
>zEnd
-zCsr
|| nSuffix
==0 ){
1942 rc
= FTS_CORRUPT_VTAB
;
1945 if( (i64
)nPrefix
+nSuffix
>nAlloc
){
1947 nAlloc
= ((i64
)nPrefix
+nSuffix
) * 2;
1948 zNew
= (char *)sqlite3_realloc64(zBuffer
, nAlloc
);
1956 memcpy(&zBuffer
[nPrefix
], zCsr
, nSuffix
);
1957 nBuffer
= nPrefix
+ nSuffix
;
1960 /* Compare the term we are searching for with the term just loaded from
1961 ** the interior node. If the specified term is greater than or equal
1962 ** to the term from the interior node, then all terms on the sub-tree
1963 ** headed by node iChild are smaller than zTerm. No need to search
1966 ** If the interior node term is larger than the specified term, then
1967 ** the tree headed by iChild may contain the specified term.
1969 cmp
= memcmp(zTerm
, zBuffer
, (nBuffer
>nTerm
? nTerm
: nBuffer
));
1970 if( piFirst
&& (cmp
<0 || (cmp
==0 && nBuffer
>nTerm
)) ){
1971 *piFirst
= (i64
)iChild
;
1975 if( piLast
&& cmp
<0 ){
1976 *piLast
= (i64
)iChild
;
1983 if( piFirst
) *piFirst
= (i64
)iChild
;
1984 if( piLast
) *piLast
= (i64
)iChild
;
1987 sqlite3_free(zBuffer
);
1993 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
1994 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
1995 ** contains a term. This function searches the sub-tree headed by the zNode
1996 ** node for the range of leaf nodes that may contain the specified term
1997 ** or terms for which the specified term is a prefix.
1999 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
2000 ** left-most leaf node in the tree that may contain the specified term.
2001 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
2002 ** right-most leaf node that may contain a term for which the specified
2003 ** term is a prefix.
2005 ** It is possible that the range of returned leaf nodes does not contain
2006 ** the specified term or any terms for which it is a prefix. However, if the
2007 ** segment does contain any such terms, they are stored within the identified
2008 ** range. Because this function only inspects interior segment nodes (and
2009 ** never loads leaf nodes into memory), it is not possible to be sure.
2011 ** If an error occurs, an error code other than SQLITE_OK is returned.
2013 static int fts3SelectLeaf(
2014 Fts3Table
*p
, /* Virtual table handle */
2015 const char *zTerm
, /* Term to select leaves for */
2016 int nTerm
, /* Size of term zTerm in bytes */
2017 const char *zNode
, /* Buffer containing segment interior node */
2018 int nNode
, /* Size of buffer at zNode */
2019 sqlite3_int64
*piLeaf
, /* Selected leaf node */
2020 sqlite3_int64
*piLeaf2
/* Selected leaf node */
2022 int rc
= SQLITE_OK
; /* Return code */
2023 int iHeight
; /* Height of this node in tree */
2025 assert( piLeaf
|| piLeaf2
);
2027 fts3GetVarint32(zNode
, &iHeight
);
2028 rc
= fts3ScanInteriorNode(zTerm
, nTerm
, zNode
, nNode
, piLeaf
, piLeaf2
);
2029 assert_fts3_nc( !piLeaf2
|| !piLeaf
|| rc
!=SQLITE_OK
|| (*piLeaf
<=*piLeaf2
) );
2031 if( rc
==SQLITE_OK
&& iHeight
>1 ){
2032 char *zBlob
= 0; /* Blob read from %_segments table */
2033 int nBlob
= 0; /* Size of zBlob in bytes */
2035 if( piLeaf
&& piLeaf2
&& (*piLeaf
!=*piLeaf2
) ){
2036 rc
= sqlite3Fts3ReadBlock(p
, *piLeaf
, &zBlob
, &nBlob
, 0);
2037 if( rc
==SQLITE_OK
){
2038 rc
= fts3SelectLeaf(p
, zTerm
, nTerm
, zBlob
, nBlob
, piLeaf
, 0);
2040 sqlite3_free(zBlob
);
2045 if( rc
==SQLITE_OK
){
2046 rc
= sqlite3Fts3ReadBlock(p
, piLeaf
?*piLeaf
:*piLeaf2
, &zBlob
, &nBlob
, 0);
2048 if( rc
==SQLITE_OK
){
2050 fts3GetVarint32(zBlob
, &iNewHeight
);
2051 if( iNewHeight
>=iHeight
){
2052 rc
= FTS_CORRUPT_VTAB
;
2054 rc
= fts3SelectLeaf(p
, zTerm
, nTerm
, zBlob
, nBlob
, piLeaf
, piLeaf2
);
2057 sqlite3_free(zBlob
);
2064 ** This function is used to create delta-encoded serialized lists of FTS3
2065 ** varints. Each call to this function appends a single varint to a list.
2067 static void fts3PutDeltaVarint(
2068 char **pp
, /* IN/OUT: Output pointer */
2069 sqlite3_int64
*piPrev
, /* IN/OUT: Previous value written to list */
2070 sqlite3_int64 iVal
/* Write this value to the list */
2072 assert_fts3_nc( iVal
-*piPrev
> 0 || (*piPrev
==0 && iVal
==0) );
2073 *pp
+= sqlite3Fts3PutVarint(*pp
, iVal
-*piPrev
);
2078 ** When this function is called, *ppPoslist is assumed to point to the
2079 ** start of a position-list. After it returns, *ppPoslist points to the
2080 ** first byte after the position-list.
2082 ** A position list is list of positions (delta encoded) and columns for
2083 ** a single document record of a doclist. So, in other words, this
2084 ** routine advances *ppPoslist so that it points to the next docid in
2085 ** the doclist, or to the first byte past the end of the doclist.
2087 ** If pp is not NULL, then the contents of the position list are copied
2088 ** to *pp. *pp is set to point to the first byte past the last byte copied
2089 ** before this function returns.
2091 static void fts3PoslistCopy(char **pp
, char **ppPoslist
){
2092 char *pEnd
= *ppPoslist
;
2095 /* The end of a position list is marked by a zero encoded as an FTS3
2096 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
2097 ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
2098 ** of some other, multi-byte, value.
2100 ** The following while-loop moves pEnd to point to the first byte that is not
2101 ** immediately preceded by a byte with the 0x80 bit set. Then increments
2102 ** pEnd once more so that it points to the byte immediately following the
2103 ** last byte in the position-list.
2107 testcase( c
!=0 && (*pEnd
)==0 );
2109 pEnd
++; /* Advance past the POS_END terminator byte */
2112 int n
= (int)(pEnd
- *ppPoslist
);
2114 memcpy(p
, *ppPoslist
, n
);
2122 ** When this function is called, *ppPoslist is assumed to point to the
2123 ** start of a column-list. After it returns, *ppPoslist points to the
2124 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
2126 ** A column-list is list of delta-encoded positions for a single column
2127 ** within a single document within a doclist.
2129 ** The column-list is terminated either by a POS_COLUMN varint (1) or
2130 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
2131 ** the POS_COLUMN or POS_END that terminates the column-list.
2133 ** If pp is not NULL, then the contents of the column-list are copied
2134 ** to *pp. *pp is set to point to the first byte past the last byte copied
2135 ** before this function returns. The POS_COLUMN or POS_END terminator
2136 ** is not copied into *pp.
2138 static void fts3ColumnlistCopy(char **pp
, char **ppPoslist
){
2139 char *pEnd
= *ppPoslist
;
2142 /* A column-list is terminated by either a 0x01 or 0x00 byte that is
2143 ** not part of a multi-byte varint.
2145 while( 0xFE & (*pEnd
| c
) ){
2147 testcase( c
!=0 && ((*pEnd
)&0xfe)==0 );
2150 int n
= (int)(pEnd
- *ppPoslist
);
2152 memcpy(p
, *ppPoslist
, n
);
2160 ** Value used to signify the end of an position-list. This must be
2161 ** as large or larger than any value that might appear on the
2162 ** position-list, even a position list that has been corrupted.
2164 #define POSITION_LIST_END LARGEST_INT64
2167 ** This function is used to help parse position-lists. When this function is
2168 ** called, *pp may point to the start of the next varint in the position-list
2169 ** being parsed, or it may point to 1 byte past the end of the position-list
2170 ** (in which case **pp will be a terminator bytes POS_END (0) or
2173 ** If *pp points past the end of the current position-list, set *pi to
2174 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
2175 ** increment the current value of *pi by the value read, and set *pp to
2176 ** point to the next value before returning.
2178 ** Before calling this routine *pi must be initialized to the value of
2179 ** the previous position, or zero if we are reading the first position
2180 ** in the position-list. Because positions are delta-encoded, the value
2181 ** of the previous position is needed in order to compute the value of
2182 ** the next position.
2184 static void fts3ReadNextPos(
2185 char **pp
, /* IN/OUT: Pointer into position-list buffer */
2186 sqlite3_int64
*pi
/* IN/OUT: Value read from position-list */
2190 *pp
+= fts3GetVarint32((*pp
), &iVal
);
2194 *pi
= POSITION_LIST_END
;
2199 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
2200 ** the value of iCol encoded as a varint to *pp. This will start a new
2203 ** Set *pp to point to the byte just after the last byte written before
2204 ** returning (do not modify it if iCol==0). Return the total number of bytes
2205 ** written (0 if iCol==0).
2207 static int fts3PutColNumber(char **pp
, int iCol
){
2208 int n
= 0; /* Number of bytes written */
2210 char *p
= *pp
; /* Output pointer */
2211 n
= 1 + sqlite3Fts3PutVarint(&p
[1], iCol
);
2219 ** Compute the union of two position lists. The output written
2220 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
2221 ** order and with any duplicates removed. All pointers are
2222 ** updated appropriately. The caller is responsible for insuring
2223 ** that there is enough space in *pp to hold the complete output.
2225 static int fts3PoslistMerge(
2226 char **pp
, /* Output buffer */
2227 char **pp1
, /* Left input list */
2228 char **pp2
/* Right input list */
2234 while( *p1
|| *p2
){
2235 int iCol1
; /* The current column index in pp1 */
2236 int iCol2
; /* The current column index in pp2 */
2238 if( *p1
==POS_COLUMN
){
2239 fts3GetVarint32(&p1
[1], &iCol1
);
2240 if( iCol1
==0 ) return FTS_CORRUPT_VTAB
;
2242 else if( *p1
==POS_END
) iCol1
= 0x7fffffff;
2245 if( *p2
==POS_COLUMN
){
2246 fts3GetVarint32(&p2
[1], &iCol2
);
2247 if( iCol2
==0 ) return FTS_CORRUPT_VTAB
;
2249 else if( *p2
==POS_END
) iCol2
= 0x7fffffff;
2253 sqlite3_int64 i1
= 0; /* Last position from pp1 */
2254 sqlite3_int64 i2
= 0; /* Last position from pp2 */
2255 sqlite3_int64 iPrev
= 0;
2256 int n
= fts3PutColNumber(&p
, iCol1
);
2260 /* At this point, both p1 and p2 point to the start of column-lists
2261 ** for the same column (the column with index iCol1 and iCol2).
2262 ** A column-list is a list of non-negative delta-encoded varints, each
2263 ** incremented by 2 before being stored. Each list is terminated by a
2264 ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
2265 ** and writes the results to buffer p. p is left pointing to the byte
2266 ** after the list written. No terminator (POS_END or POS_COLUMN) is
2267 ** written to the output.
2269 fts3GetDeltaVarint(&p1
, &i1
);
2270 fts3GetDeltaVarint(&p2
, &i2
);
2275 fts3PutDeltaVarint(&p
, &iPrev
, (i1
<i2
) ? i1
: i2
);
2278 fts3ReadNextPos(&p1
, &i1
);
2279 fts3ReadNextPos(&p2
, &i2
);
2281 fts3ReadNextPos(&p1
, &i1
);
2283 fts3ReadNextPos(&p2
, &i2
);
2285 }while( i1
!=POSITION_LIST_END
|| i2
!=POSITION_LIST_END
);
2286 }else if( iCol1
<iCol2
){
2287 p1
+= fts3PutColNumber(&p
, iCol1
);
2288 fts3ColumnlistCopy(&p
, &p1
);
2290 p2
+= fts3PutColNumber(&p
, iCol2
);
2291 fts3ColumnlistCopy(&p
, &p2
);
2303 ** This function is used to merge two position lists into one. When it is
2304 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
2305 ** the part of a doclist that follows each document id. For example, if a row
2308 ** 'a b c'|'x y z'|'a b b a'
2310 ** Then the position list for this row for token 'b' would consist of:
2312 ** 0x02 0x01 0x02 0x03 0x03 0x00
2314 ** When this function returns, both *pp1 and *pp2 are left pointing to the
2315 ** byte following the 0x00 terminator of their respective position lists.
2317 ** If isSaveLeft is 0, an entry is added to the output position list for
2318 ** each position in *pp2 for which there exists one or more positions in
2319 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
2320 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
2323 ** e.g. nToken==1 searches for adjacent positions.
2325 static int fts3PoslistPhraseMerge(
2326 char **pp
, /* IN/OUT: Preallocated output buffer */
2327 int nToken
, /* Maximum difference in token positions */
2328 int isSaveLeft
, /* Save the left position */
2329 int isExact
, /* If *pp1 is exactly nTokens before *pp2 */
2330 char **pp1
, /* IN/OUT: Left input list */
2331 char **pp2
/* IN/OUT: Right input list */
2339 /* Never set both isSaveLeft and isExact for the same invocation. */
2340 assert( isSaveLeft
==0 || isExact
==0 );
2342 assert_fts3_nc( p
!=0 && *p1
!=0 && *p2
!=0 );
2343 if( *p1
==POS_COLUMN
){
2345 p1
+= fts3GetVarint32(p1
, &iCol1
);
2347 if( *p2
==POS_COLUMN
){
2349 p2
+= fts3GetVarint32(p2
, &iCol2
);
2355 sqlite3_int64 iPrev
= 0;
2356 sqlite3_int64 iPos1
= 0;
2357 sqlite3_int64 iPos2
= 0;
2361 p
+= sqlite3Fts3PutVarint(p
, iCol1
);
2364 fts3GetDeltaVarint(&p1
, &iPos1
); iPos1
-= 2;
2365 fts3GetDeltaVarint(&p2
, &iPos2
); iPos2
-= 2;
2366 if( iPos1
<0 || iPos2
<0 ) break;
2369 if( iPos2
==iPos1
+nToken
2370 || (isExact
==0 && iPos2
>iPos1
&& iPos2
<=iPos1
+nToken
)
2372 sqlite3_int64 iSave
;
2373 iSave
= isSaveLeft
? iPos1
: iPos2
;
2374 fts3PutDeltaVarint(&p
, &iPrev
, iSave
+2); iPrev
-= 2;
2378 if( (!isSaveLeft
&& iPos2
<=(iPos1
+nToken
)) || iPos2
<=iPos1
){
2379 if( (*p2
&0xFE)==0 ) break;
2380 fts3GetDeltaVarint(&p2
, &iPos2
); iPos2
-= 2;
2382 if( (*p1
&0xFE)==0 ) break;
2383 fts3GetDeltaVarint(&p1
, &iPos1
); iPos1
-= 2;
2392 fts3ColumnlistCopy(0, &p1
);
2393 fts3ColumnlistCopy(0, &p2
);
2394 assert( (*p1
&0xFE)==0 && (*p2
&0xFE)==0 );
2395 if( 0==*p1
|| 0==*p2
) break;
2398 p1
+= fts3GetVarint32(p1
, &iCol1
);
2400 p2
+= fts3GetVarint32(p2
, &iCol2
);
2403 /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
2404 ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
2405 ** end of the position list, or the 0x01 that precedes the next
2406 ** column-number in the position list.
2408 else if( iCol1
<iCol2
){
2409 fts3ColumnlistCopy(0, &p1
);
2412 p1
+= fts3GetVarint32(p1
, &iCol1
);
2414 fts3ColumnlistCopy(0, &p2
);
2417 p2
+= fts3GetVarint32(p2
, &iCol2
);
2421 fts3PoslistCopy(0, &p2
);
2422 fts3PoslistCopy(0, &p1
);
2434 ** Merge two position-lists as required by the NEAR operator. The argument
2435 ** position lists correspond to the left and right phrases of an expression
2438 ** "phrase 1" NEAR "phrase number 2"
2440 ** Position list *pp1 corresponds to the left-hand side of the NEAR
2441 ** expression and *pp2 to the right. As usual, the indexes in the position
2442 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
2443 ** in the example above).
2445 ** The output position list - written to *pp - is a copy of *pp2 with those
2446 ** entries that are not sufficiently NEAR entries in *pp1 removed.
2448 static int fts3PoslistNearMerge(
2449 char **pp
, /* Output buffer */
2450 char *aTmp
, /* Temporary buffer space */
2451 int nRight
, /* Maximum difference in token positions */
2452 int nLeft
, /* Maximum difference in token positions */
2453 char **pp1
, /* IN/OUT: Left input list */
2454 char **pp2
/* IN/OUT: Right input list */
2464 fts3PoslistPhraseMerge(&pTmp1
, nRight
, 0, 0, pp1
, pp2
);
2465 aTmp2
= pTmp2
= pTmp1
;
2468 fts3PoslistPhraseMerge(&pTmp2
, nLeft
, 1, 0, pp2
, pp1
);
2469 if( pTmp1
!=aTmp
&& pTmp2
!=aTmp2
){
2470 fts3PoslistMerge(pp
, &aTmp
, &aTmp2
);
2471 }else if( pTmp1
!=aTmp
){
2472 fts3PoslistCopy(pp
, &aTmp
);
2473 }else if( pTmp2
!=aTmp2
){
2474 fts3PoslistCopy(pp
, &aTmp2
);
2483 ** An instance of this function is used to merge together the (potentially
2484 ** large number of) doclists for each term that matches a prefix query.
2485 ** See function fts3TermSelectMerge() for details.
2487 typedef struct TermSelect TermSelect
;
2489 char *aaOutput
[16]; /* Malloc'd output buffers */
2490 int anOutput
[16]; /* Size each output buffer in bytes */
2494 ** This function is used to read a single varint from a buffer. Parameter
2495 ** pEnd points 1 byte past the end of the buffer. When this function is
2496 ** called, if *pp points to pEnd or greater, then the end of the buffer
2497 ** has been reached. In this case *pp is set to 0 and the function returns.
2499 ** If *pp does not point to or past pEnd, then a single varint is read
2500 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
2502 ** If bDescIdx is false, the value read is added to *pVal before returning.
2503 ** If it is true, the value read is subtracted from *pVal before this
2504 ** function returns.
2506 static void fts3GetDeltaVarint3(
2507 char **pp
, /* IN/OUT: Point to read varint from */
2508 char *pEnd
, /* End of buffer */
2509 int bDescIdx
, /* True if docids are descending */
2510 sqlite3_int64
*pVal
/* IN/OUT: Integer value */
2516 *pp
+= sqlite3Fts3GetVarintU(*pp
, &iVal
);
2518 *pVal
= (i64
)((u64
)*pVal
- iVal
);
2520 *pVal
= (i64
)((u64
)*pVal
+ iVal
);
2526 ** This function is used to write a single varint to a buffer. The varint
2527 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
2528 ** end of the value written.
2530 ** If *pbFirst is zero when this function is called, the value written to
2531 ** the buffer is that of parameter iVal.
2533 ** If *pbFirst is non-zero when this function is called, then the value
2534 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
2535 ** (if bDescIdx is non-zero).
2537 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
2538 ** to the value of parameter iVal.
2540 static void fts3PutDeltaVarint3(
2541 char **pp
, /* IN/OUT: Output pointer */
2542 int bDescIdx
, /* True for descending docids */
2543 sqlite3_int64
*piPrev
, /* IN/OUT: Previous value written to list */
2544 int *pbFirst
, /* IN/OUT: True after first int written */
2545 sqlite3_int64 iVal
/* Write this value to the list */
2547 sqlite3_uint64 iWrite
;
2548 if( bDescIdx
==0 || *pbFirst
==0 ){
2549 assert_fts3_nc( *pbFirst
==0 || iVal
>=*piPrev
);
2550 iWrite
= (u64
)iVal
- (u64
)*piPrev
;
2552 assert_fts3_nc( *piPrev
>=iVal
);
2553 iWrite
= (u64
)*piPrev
- (u64
)iVal
;
2555 assert( *pbFirst
|| *piPrev
==0 );
2556 assert_fts3_nc( *pbFirst
==0 || iWrite
>0 );
2557 *pp
+= sqlite3Fts3PutVarint(*pp
, iWrite
);
2564 ** This macro is used by various functions that merge doclists. The two
2565 ** arguments are 64-bit docid values. If the value of the stack variable
2566 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
2567 ** Otherwise, (i2-i1).
2569 ** Using this makes it easier to write code that can merge doclists that are
2570 ** sorted in either ascending or descending order.
2572 /* #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i64)((u64)i1-i2)) */
2573 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1>i2?1:((i1==i2)?0:-1)))
2576 ** This function does an "OR" merge of two doclists (output contains all
2577 ** positions contained in either argument doclist). If the docids in the
2578 ** input doclists are sorted in ascending order, parameter bDescDoclist
2579 ** should be false. If they are sorted in ascending order, it should be
2580 ** passed a non-zero value.
2582 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
2583 ** containing the output doclist and SQLITE_OK is returned. In this case
2584 ** *pnOut is set to the number of bytes in the output doclist.
2586 ** If an error occurs, an SQLite error code is returned. The output values
2587 ** are undefined in this case.
2589 static int fts3DoclistOrMerge(
2590 int bDescDoclist
, /* True if arguments are desc */
2591 char *a1
, int n1
, /* First doclist */
2592 char *a2
, int n2
, /* Second doclist */
2593 char **paOut
, int *pnOut
/* OUT: Malloc'd doclist */
2596 sqlite3_int64 i1
= 0;
2597 sqlite3_int64 i2
= 0;
2598 sqlite3_int64 iPrev
= 0;
2599 char *pEnd1
= &a1
[n1
];
2600 char *pEnd2
= &a2
[n2
];
2610 /* Allocate space for the output. Both the input and output doclists
2611 ** are delta encoded. If they are in ascending order (bDescDoclist==0),
2612 ** then the first docid in each list is simply encoded as a varint. For
2613 ** each subsequent docid, the varint stored is the difference between the
2614 ** current and previous docid (a positive number - since the list is in
2615 ** ascending order).
2617 ** The first docid written to the output is therefore encoded using the
2618 ** same number of bytes as it is in whichever of the input lists it is
2619 ** read from. And each subsequent docid read from the same input list
2620 ** consumes either the same or less bytes as it did in the input (since
2621 ** the difference between it and the previous value in the output must
2622 ** be a positive value less than or equal to the delta value read from
2623 ** the input list). The same argument applies to all but the first docid
2624 ** read from the 'other' list. And to the contents of all position lists
2625 ** that will be copied and merged from the input to the output.
2627 ** However, if the first docid copied to the output is a negative number,
2628 ** then the encoding of the first docid from the 'other' input list may
2629 ** be larger in the output than it was in the input (since the delta value
2630 ** may be a larger positive integer than the actual docid).
2632 ** The space required to store the output is therefore the sum of the
2633 ** sizes of the two inputs, plus enough space for exactly one of the input
2636 ** A symetric argument may be made if the doclists are in descending
2639 aOut
= sqlite3_malloc64((i64
)n1
+n2
+FTS3_VARINT_MAX
-1+FTS3_BUFFER_PADDING
);
2640 if( !aOut
) return SQLITE_NOMEM
;
2643 fts3GetDeltaVarint3(&p1
, pEnd1
, 0, &i1
);
2644 fts3GetDeltaVarint3(&p2
, pEnd2
, 0, &i2
);
2646 sqlite3_int64 iDiff
= DOCID_CMP(i1
, i2
);
2648 if( p2
&& p1
&& iDiff
==0 ){
2649 fts3PutDeltaVarint3(&p
, bDescDoclist
, &iPrev
, &bFirstOut
, i1
);
2650 rc
= fts3PoslistMerge(&p
, &p1
, &p2
);
2652 fts3GetDeltaVarint3(&p1
, pEnd1
, bDescDoclist
, &i1
);
2653 fts3GetDeltaVarint3(&p2
, pEnd2
, bDescDoclist
, &i2
);
2654 }else if( !p2
|| (p1
&& iDiff
<0) ){
2655 fts3PutDeltaVarint3(&p
, bDescDoclist
, &iPrev
, &bFirstOut
, i1
);
2656 fts3PoslistCopy(&p
, &p1
);
2657 fts3GetDeltaVarint3(&p1
, pEnd1
, bDescDoclist
, &i1
);
2659 fts3PutDeltaVarint3(&p
, bDescDoclist
, &iPrev
, &bFirstOut
, i2
);
2660 fts3PoslistCopy(&p
, &p2
);
2661 fts3GetDeltaVarint3(&p2
, pEnd2
, bDescDoclist
, &i2
);
2664 assert( (p
-aOut
)<=((p1
?(p1
-a1
):n1
)+(p2
?(p2
-a2
):n2
)+FTS3_VARINT_MAX
-1) );
2667 if( rc
!=SQLITE_OK
){
2671 assert( (p
-aOut
)<=n1
+n2
+FTS3_VARINT_MAX
-1 );
2672 memset(&aOut
[(p
-aOut
)], 0, FTS3_BUFFER_PADDING
);
2675 *pnOut
= (int)(p
-aOut
);
2680 ** This function does a "phrase" merge of two doclists. In a phrase merge,
2681 ** the output contains a copy of each position from the right-hand input
2682 ** doclist for which there is a position in the left-hand input doclist
2683 ** exactly nDist tokens before it.
2685 ** If the docids in the input doclists are sorted in ascending order,
2686 ** parameter bDescDoclist should be false. If they are sorted in ascending
2687 ** order, it should be passed a non-zero value.
2689 ** The right-hand input doclist is overwritten by this function.
2691 static int fts3DoclistPhraseMerge(
2692 int bDescDoclist
, /* True if arguments are desc */
2693 int nDist
, /* Distance from left to right (1=adjacent) */
2694 char *aLeft
, int nLeft
, /* Left doclist */
2695 char **paRight
, int *pnRight
/* IN/OUT: Right/output doclist */
2697 sqlite3_int64 i1
= 0;
2698 sqlite3_int64 i2
= 0;
2699 sqlite3_int64 iPrev
= 0;
2700 char *aRight
= *paRight
;
2701 char *pEnd1
= &aLeft
[nLeft
];
2702 char *pEnd2
= &aRight
[*pnRight
];
2711 aOut
= sqlite3_malloc64((sqlite3_int64
)*pnRight
+ FTS3_VARINT_MAX
);
2712 if( aOut
==0 ) return SQLITE_NOMEM
;
2718 fts3GetDeltaVarint3(&p1
, pEnd1
, 0, &i1
);
2719 fts3GetDeltaVarint3(&p2
, pEnd2
, 0, &i2
);
2722 sqlite3_int64 iDiff
= DOCID_CMP(i1
, i2
);
2725 sqlite3_int64 iPrevSave
= iPrev
;
2726 int bFirstOutSave
= bFirstOut
;
2728 fts3PutDeltaVarint3(&p
, bDescDoclist
, &iPrev
, &bFirstOut
, i1
);
2729 if( 0==fts3PoslistPhraseMerge(&p
, nDist
, 0, 1, &p1
, &p2
) ){
2732 bFirstOut
= bFirstOutSave
;
2734 fts3GetDeltaVarint3(&p1
, pEnd1
, bDescDoclist
, &i1
);
2735 fts3GetDeltaVarint3(&p2
, pEnd2
, bDescDoclist
, &i2
);
2736 }else if( iDiff
<0 ){
2737 fts3PoslistCopy(0, &p1
);
2738 fts3GetDeltaVarint3(&p1
, pEnd1
, bDescDoclist
, &i1
);
2740 fts3PoslistCopy(0, &p2
);
2741 fts3GetDeltaVarint3(&p2
, pEnd2
, bDescDoclist
, &i2
);
2745 *pnRight
= (int)(p
- aOut
);
2747 sqlite3_free(aRight
);
2755 ** Argument pList points to a position list nList bytes in size. This
2756 ** function checks to see if the position list contains any entries for
2757 ** a token in position 0 (of any column). If so, it writes argument iDelta
2758 ** to the output buffer pOut, followed by a position list consisting only
2759 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
2760 ** The value returned is the number of bytes written to pOut (if any).
2762 int sqlite3Fts3FirstFilter(
2763 sqlite3_int64 iDelta
, /* Varint that may be written to pOut */
2764 char *pList
, /* Position list (no 0x00 term) */
2765 int nList
, /* Size of pList in bytes */
2766 char *pOut
/* Write output here */
2769 int bWritten
= 0; /* True once iDelta has been written */
2771 char *pEnd
= &pList
[nList
];
2775 nOut
+= sqlite3Fts3PutVarint(&pOut
[nOut
], iDelta
);
2776 pOut
[nOut
++] = 0x02;
2779 fts3ColumnlistCopy(0, &p
);
2785 p
+= sqlite3Fts3GetVarint(p
, &iCol
);
2788 nOut
+= sqlite3Fts3PutVarint(&pOut
[nOut
], iDelta
);
2791 pOut
[nOut
++] = 0x01;
2792 nOut
+= sqlite3Fts3PutVarint(&pOut
[nOut
], iCol
);
2793 pOut
[nOut
++] = 0x02;
2795 fts3ColumnlistCopy(0, &p
);
2798 pOut
[nOut
++] = 0x00;
2806 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
2807 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
2808 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
2810 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
2811 ** the responsibility of the caller to free any doclists left in the
2812 ** TermSelect.aaOutput[] array.
2814 static int fts3TermSelectFinishMerge(Fts3Table
*p
, TermSelect
*pTS
){
2819 /* Loop through the doclists in the aaOutput[] array. Merge them all
2820 ** into a single doclist.
2822 for(i
=0; i
<SizeofArray(pTS
->aaOutput
); i
++){
2823 if( pTS
->aaOutput
[i
] ){
2825 aOut
= pTS
->aaOutput
[i
];
2826 nOut
= pTS
->anOutput
[i
];
2827 pTS
->aaOutput
[i
] = 0;
2832 int rc
= fts3DoclistOrMerge(p
->bDescIdx
,
2833 pTS
->aaOutput
[i
], pTS
->anOutput
[i
], aOut
, nOut
, &aNew
, &nNew
2835 if( rc
!=SQLITE_OK
){
2840 sqlite3_free(pTS
->aaOutput
[i
]);
2842 pTS
->aaOutput
[i
] = 0;
2849 pTS
->aaOutput
[0] = aOut
;
2850 pTS
->anOutput
[0] = nOut
;
2855 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
2856 ** as the first argument. The merge is an "OR" merge (see function
2857 ** fts3DoclistOrMerge() for details).
2859 ** This function is called with the doclist for each term that matches
2860 ** a queried prefix. It merges all these doclists into one, the doclist
2861 ** for the specified prefix. Since there can be a very large number of
2862 ** doclists to merge, the merging is done pair-wise using the TermSelect
2865 ** This function returns SQLITE_OK if the merge is successful, or an
2866 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
2868 static int fts3TermSelectMerge(
2869 Fts3Table
*p
, /* FTS table handle */
2870 TermSelect
*pTS
, /* TermSelect object to merge into */
2871 char *aDoclist
, /* Pointer to doclist */
2872 int nDoclist
/* Size of aDoclist in bytes */
2874 if( pTS
->aaOutput
[0]==0 ){
2875 /* If this is the first term selected, copy the doclist to the output
2876 ** buffer using memcpy().
2878 ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
2879 ** allocation. This is so as to ensure that the buffer is big enough
2880 ** to hold the current doclist AND'd with any other doclist. If the
2881 ** doclists are stored in order=ASC order, this padding would not be
2882 ** required (since the size of [doclistA AND doclistB] is always less
2883 ** than or equal to the size of [doclistA] in that case). But this is
2884 ** not true for order=DESC. For example, a doclist containing (1, -1)
2885 ** may be smaller than (-1), as in the first example the -1 may be stored
2886 ** as a single-byte delta, whereas in the second it must be stored as a
2887 ** FTS3_VARINT_MAX byte varint.
2889 ** Similar padding is added in the fts3DoclistOrMerge() function.
2891 pTS
->aaOutput
[0] = sqlite3_malloc64((i64
)nDoclist
+ FTS3_VARINT_MAX
+ 1);
2892 pTS
->anOutput
[0] = nDoclist
;
2893 if( pTS
->aaOutput
[0] ){
2894 memcpy(pTS
->aaOutput
[0], aDoclist
, nDoclist
);
2895 memset(&pTS
->aaOutput
[0][nDoclist
], 0, FTS3_VARINT_MAX
);
2897 return SQLITE_NOMEM
;
2900 char *aMerge
= aDoclist
;
2901 int nMerge
= nDoclist
;
2904 for(iOut
=0; iOut
<SizeofArray(pTS
->aaOutput
); iOut
++){
2905 if( pTS
->aaOutput
[iOut
]==0 ){
2907 pTS
->aaOutput
[iOut
] = aMerge
;
2908 pTS
->anOutput
[iOut
] = nMerge
;
2914 int rc
= fts3DoclistOrMerge(p
->bDescIdx
, aMerge
, nMerge
,
2915 pTS
->aaOutput
[iOut
], pTS
->anOutput
[iOut
], &aNew
, &nNew
2917 if( rc
!=SQLITE_OK
){
2918 if( aMerge
!=aDoclist
) sqlite3_free(aMerge
);
2922 if( aMerge
!=aDoclist
) sqlite3_free(aMerge
);
2923 sqlite3_free(pTS
->aaOutput
[iOut
]);
2924 pTS
->aaOutput
[iOut
] = 0;
2928 if( (iOut
+1)==SizeofArray(pTS
->aaOutput
) ){
2929 pTS
->aaOutput
[iOut
] = aMerge
;
2930 pTS
->anOutput
[iOut
] = nMerge
;
2939 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
2941 static int fts3SegReaderCursorAppend(
2942 Fts3MultiSegReader
*pCsr
,
2945 if( (pCsr
->nSegment
%16)==0 ){
2946 Fts3SegReader
**apNew
;
2947 sqlite3_int64 nByte
= (pCsr
->nSegment
+ 16)*sizeof(Fts3SegReader
*);
2948 apNew
= (Fts3SegReader
**)sqlite3_realloc64(pCsr
->apSegment
, nByte
);
2950 sqlite3Fts3SegReaderFree(pNew
);
2951 return SQLITE_NOMEM
;
2953 pCsr
->apSegment
= apNew
;
2955 pCsr
->apSegment
[pCsr
->nSegment
++] = pNew
;
2960 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
2963 ** This function returns SQLITE_OK if successful, or an SQLite error code
2966 static int fts3SegReaderCursor(
2967 Fts3Table
*p
, /* FTS3 table handle */
2968 int iLangid
, /* Language id */
2969 int iIndex
, /* Index to search (from 0 to p->nIndex-1) */
2970 int iLevel
, /* Level of segments to scan */
2971 const char *zTerm
, /* Term to query for */
2972 int nTerm
, /* Size of zTerm in bytes */
2973 int isPrefix
, /* True for a prefix search */
2974 int isScan
, /* True to scan from zTerm to EOF */
2975 Fts3MultiSegReader
*pCsr
/* Cursor object to populate */
2977 int rc
= SQLITE_OK
; /* Error code */
2978 sqlite3_stmt
*pStmt
= 0; /* Statement to iterate through segments */
2979 int rc2
; /* Result of sqlite3_reset() */
2981 /* If iLevel is less than 0 and this is not a scan, include a seg-reader
2982 ** for the pending-terms. If this is a scan, then this call must be being
2983 ** made by an fts4aux module, not an FTS table. In this case calling
2984 ** Fts3SegReaderPending might segfault, as the data structures used by
2985 ** fts4aux are not completely populated. So it's easiest to filter these
2986 ** calls out here. */
2987 if( iLevel
<0 && p
->aIndex
&& p
->iPrevLangid
==iLangid
){
2988 Fts3SegReader
*pSeg
= 0;
2989 rc
= sqlite3Fts3SegReaderPending(p
, iIndex
, zTerm
, nTerm
, isPrefix
||isScan
, &pSeg
);
2990 if( rc
==SQLITE_OK
&& pSeg
){
2991 rc
= fts3SegReaderCursorAppend(pCsr
, pSeg
);
2995 if( iLevel
!=FTS3_SEGCURSOR_PENDING
){
2996 if( rc
==SQLITE_OK
){
2997 rc
= sqlite3Fts3AllSegdirs(p
, iLangid
, iIndex
, iLevel
, &pStmt
);
3000 while( rc
==SQLITE_OK
&& SQLITE_ROW
==(rc
= sqlite3_step(pStmt
)) ){
3001 Fts3SegReader
*pSeg
= 0;
3003 /* Read the values returned by the SELECT into local variables. */
3004 sqlite3_int64 iStartBlock
= sqlite3_column_int64(pStmt
, 1);
3005 sqlite3_int64 iLeavesEndBlock
= sqlite3_column_int64(pStmt
, 2);
3006 sqlite3_int64 iEndBlock
= sqlite3_column_int64(pStmt
, 3);
3007 int nRoot
= sqlite3_column_bytes(pStmt
, 4);
3008 char const *zRoot
= sqlite3_column_blob(pStmt
, 4);
3010 /* If zTerm is not NULL, and this segment is not stored entirely on its
3011 ** root node, the range of leaves scanned can be reduced. Do this. */
3012 if( iStartBlock
&& zTerm
&& zRoot
){
3013 sqlite3_int64
*pi
= (isPrefix
? &iLeavesEndBlock
: 0);
3014 rc
= fts3SelectLeaf(p
, zTerm
, nTerm
, zRoot
, nRoot
, &iStartBlock
, pi
);
3015 if( rc
!=SQLITE_OK
) goto finished
;
3016 if( isPrefix
==0 && isScan
==0 ) iLeavesEndBlock
= iStartBlock
;
3019 rc
= sqlite3Fts3SegReaderNew(pCsr
->nSegment
+1,
3020 (isPrefix
==0 && isScan
==0),
3021 iStartBlock
, iLeavesEndBlock
,
3022 iEndBlock
, zRoot
, nRoot
, &pSeg
3024 if( rc
!=SQLITE_OK
) goto finished
;
3025 rc
= fts3SegReaderCursorAppend(pCsr
, pSeg
);
3030 rc2
= sqlite3_reset(pStmt
);
3031 if( rc
==SQLITE_DONE
) rc
= rc2
;
3037 ** Set up a cursor object for iterating through a full-text index or a
3038 ** single level therein.
3040 int sqlite3Fts3SegReaderCursor(
3041 Fts3Table
*p
, /* FTS3 table handle */
3042 int iLangid
, /* Language-id to search */
3043 int iIndex
, /* Index to search (from 0 to p->nIndex-1) */
3044 int iLevel
, /* Level of segments to scan */
3045 const char *zTerm
, /* Term to query for */
3046 int nTerm
, /* Size of zTerm in bytes */
3047 int isPrefix
, /* True for a prefix search */
3048 int isScan
, /* True to scan from zTerm to EOF */
3049 Fts3MultiSegReader
*pCsr
/* Cursor object to populate */
3051 assert( iIndex
>=0 && iIndex
<p
->nIndex
);
3052 assert( iLevel
==FTS3_SEGCURSOR_ALL
3053 || iLevel
==FTS3_SEGCURSOR_PENDING
3056 assert( iLevel
<FTS3_SEGDIR_MAXLEVEL
);
3057 assert( FTS3_SEGCURSOR_ALL
<0 && FTS3_SEGCURSOR_PENDING
<0 );
3058 assert( isPrefix
==0 || isScan
==0 );
3060 memset(pCsr
, 0, sizeof(Fts3MultiSegReader
));
3061 return fts3SegReaderCursor(
3062 p
, iLangid
, iIndex
, iLevel
, zTerm
, nTerm
, isPrefix
, isScan
, pCsr
3067 ** In addition to its current configuration, have the Fts3MultiSegReader
3068 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
3070 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
3072 static int fts3SegReaderCursorAddZero(
3073 Fts3Table
*p
, /* FTS virtual table handle */
3075 const char *zTerm
, /* Term to scan doclist of */
3076 int nTerm
, /* Number of bytes in zTerm */
3077 Fts3MultiSegReader
*pCsr
/* Fts3MultiSegReader to modify */
3079 return fts3SegReaderCursor(p
,
3080 iLangid
, 0, FTS3_SEGCURSOR_ALL
, zTerm
, nTerm
, 0, 0,pCsr
3085 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
3086 ** if isPrefix is true, to scan the doclist for all terms for which
3087 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
3088 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
3089 ** an SQLite error code.
3091 ** It is the responsibility of the caller to free this object by eventually
3092 ** passing it to fts3SegReaderCursorFree()
3094 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
3095 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
3097 static int fts3TermSegReaderCursor(
3098 Fts3Cursor
*pCsr
, /* Virtual table cursor handle */
3099 const char *zTerm
, /* Term to query for */
3100 int nTerm
, /* Size of zTerm in bytes */
3101 int isPrefix
, /* True for a prefix search */
3102 Fts3MultiSegReader
**ppSegcsr
/* OUT: Allocated seg-reader cursor */
3104 Fts3MultiSegReader
*pSegcsr
; /* Object to allocate and return */
3105 int rc
= SQLITE_NOMEM
; /* Return code */
3107 pSegcsr
= sqlite3_malloc(sizeof(Fts3MultiSegReader
));
3110 int bFound
= 0; /* True once an index has been found */
3111 Fts3Table
*p
= (Fts3Table
*)pCsr
->base
.pVtab
;
3114 for(i
=1; bFound
==0 && i
<p
->nIndex
; i
++){
3115 if( p
->aIndex
[i
].nPrefix
==nTerm
){
3117 rc
= sqlite3Fts3SegReaderCursor(p
, pCsr
->iLangid
,
3118 i
, FTS3_SEGCURSOR_ALL
, zTerm
, nTerm
, 0, 0, pSegcsr
3120 pSegcsr
->bLookup
= 1;
3124 for(i
=1; bFound
==0 && i
<p
->nIndex
; i
++){
3125 if( p
->aIndex
[i
].nPrefix
==nTerm
+1 ){
3127 rc
= sqlite3Fts3SegReaderCursor(p
, pCsr
->iLangid
,
3128 i
, FTS3_SEGCURSOR_ALL
, zTerm
, nTerm
, 1, 0, pSegcsr
3130 if( rc
==SQLITE_OK
){
3131 rc
= fts3SegReaderCursorAddZero(
3132 p
, pCsr
->iLangid
, zTerm
, nTerm
, pSegcsr
3140 rc
= sqlite3Fts3SegReaderCursor(p
, pCsr
->iLangid
,
3141 0, FTS3_SEGCURSOR_ALL
, zTerm
, nTerm
, isPrefix
, 0, pSegcsr
3143 pSegcsr
->bLookup
= !isPrefix
;
3147 *ppSegcsr
= pSegcsr
;
3152 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
3154 static void fts3SegReaderCursorFree(Fts3MultiSegReader
*pSegcsr
){
3155 sqlite3Fts3SegReaderFinish(pSegcsr
);
3156 sqlite3_free(pSegcsr
);
3160 ** This function retrieves the doclist for the specified term (or term
3161 ** prefix) from the database.
3163 static int fts3TermSelect(
3164 Fts3Table
*p
, /* Virtual table handle */
3165 Fts3PhraseToken
*pTok
, /* Token to query for */
3166 int iColumn
, /* Column to query (or -ve for all columns) */
3167 int *pnOut
, /* OUT: Size of buffer at *ppOut */
3168 char **ppOut
/* OUT: Malloced result buffer */
3170 int rc
; /* Return code */
3171 Fts3MultiSegReader
*pSegcsr
; /* Seg-reader cursor for this term */
3172 TermSelect tsc
; /* Object for pair-wise doclist merging */
3173 Fts3SegFilter filter
; /* Segment term filter configuration */
3175 pSegcsr
= pTok
->pSegcsr
;
3176 memset(&tsc
, 0, sizeof(TermSelect
));
3178 filter
.flags
= FTS3_SEGMENT_IGNORE_EMPTY
| FTS3_SEGMENT_REQUIRE_POS
3179 | (pTok
->isPrefix
? FTS3_SEGMENT_PREFIX
: 0)
3180 | (pTok
->bFirst
? FTS3_SEGMENT_FIRST
: 0)
3181 | (iColumn
<p
->nColumn
? FTS3_SEGMENT_COLUMN_FILTER
: 0);
3182 filter
.iCol
= iColumn
;
3183 filter
.zTerm
= pTok
->z
;
3184 filter
.nTerm
= pTok
->n
;
3186 rc
= sqlite3Fts3SegReaderStart(p
, pSegcsr
, &filter
);
3187 while( SQLITE_OK
==rc
3188 && SQLITE_ROW
==(rc
= sqlite3Fts3SegReaderStep(p
, pSegcsr
))
3190 rc
= fts3TermSelectMerge(p
, &tsc
, pSegcsr
->aDoclist
, pSegcsr
->nDoclist
);
3193 if( rc
==SQLITE_OK
){
3194 rc
= fts3TermSelectFinishMerge(p
, &tsc
);
3196 if( rc
==SQLITE_OK
){
3197 *ppOut
= tsc
.aaOutput
[0];
3198 *pnOut
= tsc
.anOutput
[0];
3201 for(i
=0; i
<SizeofArray(tsc
.aaOutput
); i
++){
3202 sqlite3_free(tsc
.aaOutput
[i
]);
3206 fts3SegReaderCursorFree(pSegcsr
);
3212 ** This function counts the total number of docids in the doclist stored
3213 ** in buffer aList[], size nList bytes.
3215 ** If the isPoslist argument is true, then it is assumed that the doclist
3216 ** contains a position-list following each docid. Otherwise, it is assumed
3217 ** that the doclist is simply a list of docids stored as delta encoded
3220 static int fts3DoclistCountDocids(char *aList
, int nList
){
3221 int nDoc
= 0; /* Return value */
3223 char *aEnd
= &aList
[nList
]; /* Pointer to one byte after EOF */
3224 char *p
= aList
; /* Cursor */
3227 while( (*p
++)&0x80 ); /* Skip docid varint */
3228 fts3PoslistCopy(0, &p
); /* Skip over position list */
3236 ** Advance the cursor to the next row in the %_content table that
3237 ** matches the search criteria. For a MATCH search, this will be
3238 ** the next row that matches. For a full-table scan, this will be
3239 ** simply the next row in the %_content table. For a docid lookup,
3240 ** this routine simply sets the EOF flag.
3242 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
3243 ** even if we reach end-of-file. The fts3EofMethod() will be called
3244 ** subsequently to determine whether or not an EOF was hit.
3246 static int fts3NextMethod(sqlite3_vtab_cursor
*pCursor
){
3248 Fts3Cursor
*pCsr
= (Fts3Cursor
*)pCursor
;
3249 if( pCsr
->eSearch
==FTS3_DOCID_SEARCH
|| pCsr
->eSearch
==FTS3_FULLSCAN_SEARCH
){
3250 Fts3Table
*pTab
= (Fts3Table
*)pCursor
->pVtab
;
3252 if( SQLITE_ROW
!=sqlite3_step(pCsr
->pStmt
) ){
3254 rc
= sqlite3_reset(pCsr
->pStmt
);
3256 pCsr
->iPrevId
= sqlite3_column_int64(pCsr
->pStmt
, 0);
3261 rc
= fts3EvalNext((Fts3Cursor
*)pCursor
);
3263 assert( ((Fts3Table
*)pCsr
->base
.pVtab
)->pSegments
==0 );
3268 ** If the numeric type of argument pVal is "integer", then return it
3269 ** converted to a 64-bit signed integer. Otherwise, return a copy of
3270 ** the second parameter, iDefault.
3272 static sqlite3_int64
fts3DocidRange(sqlite3_value
*pVal
, i64 iDefault
){
3274 int eType
= sqlite3_value_numeric_type(pVal
);
3275 if( eType
==SQLITE_INTEGER
){
3276 return sqlite3_value_int64(pVal
);
3283 ** This is the xFilter interface for the virtual table. See
3284 ** the virtual table xFilter method documentation for additional
3287 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
3288 ** the %_content table.
3290 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
3291 ** in the %_content table.
3293 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
3294 ** column on the left-hand side of the MATCH operator is column
3295 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
3296 ** side of the MATCH operator.
3298 static int fts3FilterMethod(
3299 sqlite3_vtab_cursor
*pCursor
, /* The cursor used for this query */
3300 int idxNum
, /* Strategy index */
3301 const char *idxStr
, /* Unused */
3302 int nVal
, /* Number of elements in apVal */
3303 sqlite3_value
**apVal
/* Arguments for the indexing scheme */
3306 char *zSql
; /* SQL statement used to access %_content */
3308 Fts3Table
*p
= (Fts3Table
*)pCursor
->pVtab
;
3309 Fts3Cursor
*pCsr
= (Fts3Cursor
*)pCursor
;
3311 sqlite3_value
*pCons
= 0; /* The MATCH or rowid constraint, if any */
3312 sqlite3_value
*pLangid
= 0; /* The "langid = ?" constraint, if any */
3313 sqlite3_value
*pDocidGe
= 0; /* The "docid >= ?" constraint, if any */
3314 sqlite3_value
*pDocidLe
= 0; /* The "docid <= ?" constraint, if any */
3317 UNUSED_PARAMETER(idxStr
);
3318 UNUSED_PARAMETER(nVal
);
3321 return SQLITE_ERROR
;
3324 eSearch
= (idxNum
& 0x0000FFFF);
3325 assert( eSearch
>=0 && eSearch
<=(FTS3_FULLTEXT_SEARCH
+p
->nColumn
) );
3326 assert( p
->pSegments
==0 );
3328 /* Collect arguments into local variables */
3330 if( eSearch
!=FTS3_FULLSCAN_SEARCH
) pCons
= apVal
[iIdx
++];
3331 if( idxNum
& FTS3_HAVE_LANGID
) pLangid
= apVal
[iIdx
++];
3332 if( idxNum
& FTS3_HAVE_DOCID_GE
) pDocidGe
= apVal
[iIdx
++];
3333 if( idxNum
& FTS3_HAVE_DOCID_LE
) pDocidLe
= apVal
[iIdx
++];
3334 assert( iIdx
==nVal
);
3336 /* In case the cursor has been used before, clear it now. */
3337 fts3ClearCursor(pCsr
);
3339 /* Set the lower and upper bounds on docids to return */
3340 pCsr
->iMinDocid
= fts3DocidRange(pDocidGe
, SMALLEST_INT64
);
3341 pCsr
->iMaxDocid
= fts3DocidRange(pDocidLe
, LARGEST_INT64
);
3344 pCsr
->bDesc
= (idxStr
[0]=='D');
3346 pCsr
->bDesc
= p
->bDescIdx
;
3348 pCsr
->eSearch
= (i16
)eSearch
;
3350 if( eSearch
!=FTS3_DOCID_SEARCH
&& eSearch
!=FTS3_FULLSCAN_SEARCH
){
3351 int iCol
= eSearch
-FTS3_FULLTEXT_SEARCH
;
3352 const char *zQuery
= (const char *)sqlite3_value_text(pCons
);
3354 if( zQuery
==0 && sqlite3_value_type(pCons
)!=SQLITE_NULL
){
3355 return SQLITE_NOMEM
;
3359 if( pLangid
) pCsr
->iLangid
= sqlite3_value_int(pLangid
);
3361 assert( p
->base
.zErrMsg
==0 );
3362 rc
= sqlite3Fts3ExprParse(p
->pTokenizer
, pCsr
->iLangid
,
3363 p
->azColumn
, p
->bFts4
, p
->nColumn
, iCol
, zQuery
, -1, &pCsr
->pExpr
,
3366 if( rc
!=SQLITE_OK
){
3370 rc
= fts3EvalStart(pCsr
);
3371 sqlite3Fts3SegmentsClose(p
);
3372 if( rc
!=SQLITE_OK
) return rc
;
3373 pCsr
->pNextId
= pCsr
->aDoclist
;
3377 /* Compile a SELECT statement for this cursor. For a full-table-scan, the
3378 ** statement loops through all rows of the %_content table. For a
3379 ** full-text query or docid lookup, the statement retrieves a single
3382 if( eSearch
==FTS3_FULLSCAN_SEARCH
){
3383 if( pDocidGe
|| pDocidLe
){
3384 zSql
= sqlite3_mprintf(
3385 "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
3386 p
->zReadExprlist
, pCsr
->iMinDocid
, pCsr
->iMaxDocid
,
3387 (pCsr
->bDesc
? "DESC" : "ASC")
3390 zSql
= sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
3391 p
->zReadExprlist
, (pCsr
->bDesc
? "DESC" : "ASC")
3396 rc
= sqlite3_prepare_v3(
3397 p
->db
,zSql
,-1,SQLITE_PREPARE_PERSISTENT
,&pCsr
->pStmt
,0
3404 }else if( eSearch
==FTS3_DOCID_SEARCH
){
3405 rc
= fts3CursorSeekStmt(pCsr
);
3406 if( rc
==SQLITE_OK
){
3407 rc
= sqlite3_bind_value(pCsr
->pStmt
, 1, pCons
);
3410 if( rc
!=SQLITE_OK
) return rc
;
3412 return fts3NextMethod(pCursor
);
3416 ** This is the xEof method of the virtual table. SQLite calls this
3417 ** routine to find out if it has reached the end of a result set.
3419 static int fts3EofMethod(sqlite3_vtab_cursor
*pCursor
){
3420 Fts3Cursor
*pCsr
= (Fts3Cursor
*)pCursor
;
3422 fts3ClearCursor(pCsr
);
3429 ** This is the xRowid method. The SQLite core calls this routine to
3430 ** retrieve the rowid for the current row of the result set. fts3
3431 ** exposes %_content.docid as the rowid for the virtual table. The
3432 ** rowid should be written to *pRowid.
3434 static int fts3RowidMethod(sqlite3_vtab_cursor
*pCursor
, sqlite_int64
*pRowid
){
3435 Fts3Cursor
*pCsr
= (Fts3Cursor
*) pCursor
;
3436 *pRowid
= pCsr
->iPrevId
;
3441 ** This is the xColumn method, called by SQLite to request a value from
3442 ** the row that the supplied cursor currently points to.
3446 ** (iCol < p->nColumn) -> The value of the iCol'th user column.
3447 ** (iCol == p->nColumn) -> Magic column with the same name as the table.
3448 ** (iCol == p->nColumn+1) -> Docid column
3449 ** (iCol == p->nColumn+2) -> Langid column
3451 static int fts3ColumnMethod(
3452 sqlite3_vtab_cursor
*pCursor
, /* Cursor to retrieve value from */
3453 sqlite3_context
*pCtx
, /* Context for sqlite3_result_xxx() calls */
3454 int iCol
/* Index of column to read value from */
3456 int rc
= SQLITE_OK
; /* Return Code */
3457 Fts3Cursor
*pCsr
= (Fts3Cursor
*) pCursor
;
3458 Fts3Table
*p
= (Fts3Table
*)pCursor
->pVtab
;
3460 /* The column value supplied by SQLite must be in range. */
3461 assert( iCol
>=0 && iCol
<=p
->nColumn
+2 );
3463 switch( iCol
-p
->nColumn
){
3465 /* The special 'table-name' column */
3466 sqlite3_result_pointer(pCtx
, pCsr
, "fts3cursor", 0);
3470 /* The docid column */
3471 sqlite3_result_int64(pCtx
, pCsr
->iPrevId
);
3476 sqlite3_result_int64(pCtx
, pCsr
->iLangid
);
3478 }else if( p
->zLanguageid
==0 ){
3479 sqlite3_result_int(pCtx
, 0);
3483 /* no break */ deliberate_fall_through
3487 /* A user column. Or, if this is a full-table scan, possibly the
3488 ** language-id column. Seek the cursor. */
3489 rc
= fts3CursorSeek(0, pCsr
);
3490 if( rc
==SQLITE_OK
&& sqlite3_data_count(pCsr
->pStmt
)-1>iCol
){
3491 sqlite3_result_value(pCtx
, sqlite3_column_value(pCsr
->pStmt
, iCol
+1));
3496 assert( ((Fts3Table
*)pCsr
->base
.pVtab
)->pSegments
==0 );
3501 ** This function is the implementation of the xUpdate callback used by
3502 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
3503 ** inserted, updated or deleted.
3505 static int fts3UpdateMethod(
3506 sqlite3_vtab
*pVtab
, /* Virtual table handle */
3507 int nArg
, /* Size of argument array */
3508 sqlite3_value
**apVal
, /* Array of arguments */
3509 sqlite_int64
*pRowid
/* OUT: The affected (or effected) rowid */
3511 return sqlite3Fts3UpdateMethod(pVtab
, nArg
, apVal
, pRowid
);
3515 ** Implementation of xSync() method. Flush the contents of the pending-terms
3516 ** hash-table to the database.
3518 static int fts3SyncMethod(sqlite3_vtab
*pVtab
){
3520 /* Following an incremental-merge operation, assuming that the input
3521 ** segments are not completely consumed (the usual case), they are updated
3522 ** in place to remove the entries that have already been merged. This
3523 ** involves updating the leaf block that contains the smallest unmerged
3524 ** entry and each block (if any) between the leaf and the root node. So
3525 ** if the height of the input segment b-trees is N, and input segments
3526 ** are merged eight at a time, updating the input segments at the end
3527 ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
3528 ** small - often between 0 and 2. So the overhead of the incremental
3529 ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
3530 ** dwarfing the actual productive work accomplished, the incremental merge
3531 ** is only attempted if it will write at least 64 leaf blocks. Hence
3534 ** Of course, updating the input segments also involves deleting a bunch
3535 ** of blocks from the segments table. But this is not considered overhead
3536 ** as it would also be required by a crisis-merge that used the same input
3539 const u32 nMinMerge
= 64; /* Minimum amount of incr-merge work to do */
3541 Fts3Table
*p
= (Fts3Table
*)pVtab
;
3543 i64 iLastRowid
= sqlite3_last_insert_rowid(p
->db
);
3545 rc
= sqlite3Fts3PendingTermsFlush(p
);
3547 && p
->nLeafAdd
>(nMinMerge
/16)
3548 && p
->nAutoincrmerge
&& p
->nAutoincrmerge
!=0xff
3550 int mxLevel
= 0; /* Maximum relative level value in db */
3551 int A
; /* Incr-merge parameter A */
3553 rc
= sqlite3Fts3MaxLevel(p
, &mxLevel
);
3554 assert( rc
==SQLITE_OK
|| mxLevel
==0 );
3555 A
= p
->nLeafAdd
* mxLevel
;
3557 if( A
>(int)nMinMerge
) rc
= sqlite3Fts3Incrmerge(p
, A
, p
->nAutoincrmerge
);
3559 sqlite3Fts3SegmentsClose(p
);
3560 sqlite3_set_last_insert_rowid(p
->db
, iLastRowid
);
3565 ** If it is currently unknown whether or not the FTS table has an %_stat
3566 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
3567 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
3568 ** if an error occurs.
3570 static int fts3SetHasStat(Fts3Table
*p
){
3572 if( p
->bHasStat
==2 ){
3573 char *zTbl
= sqlite3_mprintf("%s_stat", p
->zName
);
3575 int res
= sqlite3_table_column_metadata(p
->db
, p
->zDb
, zTbl
, 0,0,0,0,0,0);
3577 p
->bHasStat
= (res
==SQLITE_OK
);
3586 ** Implementation of xBegin() method.
3588 static int fts3BeginMethod(sqlite3_vtab
*pVtab
){
3589 Fts3Table
*p
= (Fts3Table
*)pVtab
;
3591 UNUSED_PARAMETER(pVtab
);
3592 assert( p
->pSegments
==0 );
3593 assert( p
->nPendingData
==0 );
3594 assert( p
->inTransaction
!=1 );
3596 rc
= fts3SetHasStat(p
);
3598 if( rc
==SQLITE_OK
){
3599 p
->inTransaction
= 1;
3600 p
->mxSavepoint
= -1;
3607 ** Implementation of xCommit() method. This is a no-op. The contents of
3608 ** the pending-terms hash-table have already been flushed into the database
3609 ** by fts3SyncMethod().
3611 static int fts3CommitMethod(sqlite3_vtab
*pVtab
){
3612 TESTONLY( Fts3Table
*p
= (Fts3Table
*)pVtab
);
3613 UNUSED_PARAMETER(pVtab
);
3614 assert( p
->nPendingData
==0 );
3615 assert( p
->inTransaction
!=0 );
3616 assert( p
->pSegments
==0 );
3617 TESTONLY( p
->inTransaction
= 0 );
3618 TESTONLY( p
->mxSavepoint
= -1; );
3623 ** Implementation of xRollback(). Discard the contents of the pending-terms
3624 ** hash-table. Any changes made to the database are reverted by SQLite.
3626 static int fts3RollbackMethod(sqlite3_vtab
*pVtab
){
3627 Fts3Table
*p
= (Fts3Table
*)pVtab
;
3628 sqlite3Fts3PendingTermsClear(p
);
3629 assert( p
->inTransaction
!=0 );
3630 TESTONLY( p
->inTransaction
= 0 );
3631 TESTONLY( p
->mxSavepoint
= -1; );
3636 ** When called, *ppPoslist must point to the byte immediately following the
3637 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
3638 ** moves *ppPoslist so that it instead points to the first byte of the
3639 ** same position list.
3641 static void fts3ReversePoslist(char *pStart
, char **ppPoslist
){
3642 char *p
= &(*ppPoslist
)[-2];
3645 /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
3646 while( p
>pStart
&& (c
=*p
--)==0 );
3648 /* Search backwards for a varint with value zero (the end of the previous
3649 ** poslist). This is an 0x00 byte preceded by some byte that does not
3650 ** have the 0x80 bit set. */
3651 while( p
>pStart
&& (*p
& 0x80) | c
){
3654 assert( p
==pStart
|| c
==0 );
3656 /* At this point p points to that preceding byte without the 0x80 bit
3657 ** set. So to find the start of the poslist, skip forward 2 bytes then
3660 ** Normally. The other case is that p==pStart and the poslist to return
3661 ** is the first in the doclist. In this case do not skip forward 2 bytes.
3662 ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
3663 ** is required for cases where the first byte of a doclist and the
3664 ** doclist is empty. For example, if the first docid is 10, a doclist
3665 ** that begins with:
3667 ** 0x0A 0x00 <next docid delta varint>
3669 if( p
>pStart
|| (c
==0 && *ppPoslist
>&p
[2]) ){ p
= &p
[2]; }
3675 ** Helper function used by the implementation of the overloaded snippet(),
3676 ** offsets() and optimize() SQL functions.
3678 ** If the value passed as the third argument is a blob of size
3679 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
3680 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
3681 ** message is written to context pContext and SQLITE_ERROR returned. The
3682 ** string passed via zFunc is used as part of the error message.
3684 static int fts3FunctionArg(
3685 sqlite3_context
*pContext
, /* SQL function call context */
3686 const char *zFunc
, /* Function name */
3687 sqlite3_value
*pVal
, /* argv[0] passed to function */
3688 Fts3Cursor
**ppCsr
/* OUT: Store cursor handle here */
3691 *ppCsr
= (Fts3Cursor
*)sqlite3_value_pointer(pVal
, "fts3cursor");
3695 char *zErr
= sqlite3_mprintf("illegal first argument to %s", zFunc
);
3696 sqlite3_result_error(pContext
, zErr
, -1);
3704 ** Implementation of the snippet() function for FTS3
3706 static void fts3SnippetFunc(
3707 sqlite3_context
*pContext
, /* SQLite function call context */
3708 int nVal
, /* Size of apVal[] array */
3709 sqlite3_value
**apVal
/* Array of arguments */
3711 Fts3Cursor
*pCsr
; /* Cursor handle passed through apVal[0] */
3712 const char *zStart
= "<b>";
3713 const char *zEnd
= "</b>";
3714 const char *zEllipsis
= "<b>...</b>";
3716 int nToken
= 15; /* Default number of tokens in snippet */
3718 /* There must be at least one argument passed to this function (otherwise
3719 ** the non-overloaded version would have been called instead of this one).
3724 sqlite3_result_error(pContext
,
3725 "wrong number of arguments to function snippet()", -1);
3728 if( fts3FunctionArg(pContext
, "snippet", apVal
[0], &pCsr
) ) return;
3731 case 6: nToken
= sqlite3_value_int(apVal
[5]);
3732 /* no break */ deliberate_fall_through
3733 case 5: iCol
= sqlite3_value_int(apVal
[4]);
3734 /* no break */ deliberate_fall_through
3735 case 4: zEllipsis
= (const char*)sqlite3_value_text(apVal
[3]);
3736 /* no break */ deliberate_fall_through
3737 case 3: zEnd
= (const char*)sqlite3_value_text(apVal
[2]);
3738 /* no break */ deliberate_fall_through
3739 case 2: zStart
= (const char*)sqlite3_value_text(apVal
[1]);
3741 if( !zEllipsis
|| !zEnd
|| !zStart
){
3742 sqlite3_result_error_nomem(pContext
);
3743 }else if( nToken
==0 ){
3744 sqlite3_result_text(pContext
, "", -1, SQLITE_STATIC
);
3745 }else if( SQLITE_OK
==fts3CursorSeek(pContext
, pCsr
) ){
3746 sqlite3Fts3Snippet(pContext
, pCsr
, zStart
, zEnd
, zEllipsis
, iCol
, nToken
);
3751 ** Implementation of the offsets() function for FTS3
3753 static void fts3OffsetsFunc(
3754 sqlite3_context
*pContext
, /* SQLite function call context */
3755 int nVal
, /* Size of argument array */
3756 sqlite3_value
**apVal
/* Array of arguments */
3758 Fts3Cursor
*pCsr
; /* Cursor handle passed through apVal[0] */
3760 UNUSED_PARAMETER(nVal
);
3763 if( fts3FunctionArg(pContext
, "offsets", apVal
[0], &pCsr
) ) return;
3765 if( SQLITE_OK
==fts3CursorSeek(pContext
, pCsr
) ){
3766 sqlite3Fts3Offsets(pContext
, pCsr
);
3771 ** Implementation of the special optimize() function for FTS3. This
3772 ** function merges all segments in the database to a single segment.
3773 ** Example usage is:
3775 ** SELECT optimize(t) FROM t LIMIT 1;
3777 ** where 't' is the name of an FTS3 table.
3779 static void fts3OptimizeFunc(
3780 sqlite3_context
*pContext
, /* SQLite function call context */
3781 int nVal
, /* Size of argument array */
3782 sqlite3_value
**apVal
/* Array of arguments */
3784 int rc
; /* Return code */
3785 Fts3Table
*p
; /* Virtual table handle */
3786 Fts3Cursor
*pCursor
; /* Cursor handle passed through apVal[0] */
3788 UNUSED_PARAMETER(nVal
);
3791 if( fts3FunctionArg(pContext
, "optimize", apVal
[0], &pCursor
) ) return;
3792 p
= (Fts3Table
*)pCursor
->base
.pVtab
;
3795 rc
= sqlite3Fts3Optimize(p
);
3799 sqlite3_result_text(pContext
, "Index optimized", -1, SQLITE_STATIC
);
3802 sqlite3_result_text(pContext
, "Index already optimal", -1, SQLITE_STATIC
);
3805 sqlite3_result_error_code(pContext
, rc
);
3811 ** Implementation of the matchinfo() function for FTS3
3813 static void fts3MatchinfoFunc(
3814 sqlite3_context
*pContext
, /* SQLite function call context */
3815 int nVal
, /* Size of argument array */
3816 sqlite3_value
**apVal
/* Array of arguments */
3818 Fts3Cursor
*pCsr
; /* Cursor handle passed through apVal[0] */
3819 assert( nVal
==1 || nVal
==2 );
3820 if( SQLITE_OK
==fts3FunctionArg(pContext
, "matchinfo", apVal
[0], &pCsr
) ){
3821 const char *zArg
= 0;
3823 zArg
= (const char *)sqlite3_value_text(apVal
[1]);
3825 sqlite3Fts3Matchinfo(pContext
, pCsr
, zArg
);
3830 ** This routine implements the xFindFunction method for the FTS3
3833 static int fts3FindFunctionMethod(
3834 sqlite3_vtab
*pVtab
, /* Virtual table handle */
3835 int nArg
, /* Number of SQL function arguments */
3836 const char *zName
, /* Name of SQL function */
3837 void (**pxFunc
)(sqlite3_context
*,int,sqlite3_value
**), /* OUT: Result */
3838 void **ppArg
/* Unused */
3842 void (*xFunc
)(sqlite3_context
*,int,sqlite3_value
**);
3844 { "snippet", fts3SnippetFunc
},
3845 { "offsets", fts3OffsetsFunc
},
3846 { "optimize", fts3OptimizeFunc
},
3847 { "matchinfo", fts3MatchinfoFunc
},
3849 int i
; /* Iterator variable */
3851 UNUSED_PARAMETER(pVtab
);
3852 UNUSED_PARAMETER(nArg
);
3853 UNUSED_PARAMETER(ppArg
);
3855 for(i
=0; i
<SizeofArray(aOverload
); i
++){
3856 if( strcmp(zName
, aOverload
[i
].zName
)==0 ){
3857 *pxFunc
= aOverload
[i
].xFunc
;
3862 /* No function of the specified name was found. Return 0. */
3867 ** Implementation of FTS3 xRename method. Rename an fts3 table.
3869 static int fts3RenameMethod(
3870 sqlite3_vtab
*pVtab
, /* Virtual table handle */
3871 const char *zName
/* New name of table */
3873 Fts3Table
*p
= (Fts3Table
*)pVtab
;
3874 sqlite3
*db
= p
->db
; /* Database connection */
3875 int rc
; /* Return Code */
3877 /* At this point it must be known if the %_stat table exists or not.
3878 ** So bHasStat may not be 2. */
3879 rc
= fts3SetHasStat(p
);
3881 /* As it happens, the pending terms table is always empty here. This is
3882 ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
3883 ** always opens a savepoint transaction. And the xSavepoint() method
3884 ** flushes the pending terms table. But leave the (no-op) call to
3885 ** PendingTermsFlush() in in case that changes.
3887 assert( p
->nPendingData
==0 );
3888 if( rc
==SQLITE_OK
){
3889 rc
= sqlite3Fts3PendingTermsFlush(p
);
3892 if( p
->zContentTbl
==0 ){
3894 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
3895 p
->zDb
, p
->zName
, zName
3899 if( p
->bHasDocsize
){
3901 "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
3902 p
->zDb
, p
->zName
, zName
3907 "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
3908 p
->zDb
, p
->zName
, zName
3912 "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
3913 p
->zDb
, p
->zName
, zName
3916 "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
3917 p
->zDb
, p
->zName
, zName
3923 ** The xSavepoint() method.
3925 ** Flush the contents of the pending-terms table to disk.
3927 static int fts3SavepointMethod(sqlite3_vtab
*pVtab
, int iSavepoint
){
3929 UNUSED_PARAMETER(iSavepoint
);
3930 assert( ((Fts3Table
*)pVtab
)->inTransaction
);
3931 assert( ((Fts3Table
*)pVtab
)->mxSavepoint
<= iSavepoint
);
3932 TESTONLY( ((Fts3Table
*)pVtab
)->mxSavepoint
= iSavepoint
);
3933 if( ((Fts3Table
*)pVtab
)->bIgnoreSavepoint
==0 ){
3934 rc
= fts3SyncMethod(pVtab
);
3940 ** The xRelease() method.
3944 static int fts3ReleaseMethod(sqlite3_vtab
*pVtab
, int iSavepoint
){
3945 TESTONLY( Fts3Table
*p
= (Fts3Table
*)pVtab
);
3946 UNUSED_PARAMETER(iSavepoint
);
3947 UNUSED_PARAMETER(pVtab
);
3948 assert( p
->inTransaction
);
3949 assert( p
->mxSavepoint
>= iSavepoint
);
3950 TESTONLY( p
->mxSavepoint
= iSavepoint
-1 );
3955 ** The xRollbackTo() method.
3957 ** Discard the contents of the pending terms table.
3959 static int fts3RollbackToMethod(sqlite3_vtab
*pVtab
, int iSavepoint
){
3960 Fts3Table
*p
= (Fts3Table
*)pVtab
;
3961 UNUSED_PARAMETER(iSavepoint
);
3962 assert( p
->inTransaction
);
3963 TESTONLY( p
->mxSavepoint
= iSavepoint
);
3964 sqlite3Fts3PendingTermsClear(p
);
3969 ** Return true if zName is the extension on one of the shadow tables used
3972 static int fts3ShadowName(const char *zName
){
3973 static const char *azName
[] = {
3974 "content", "docsize", "segdir", "segments", "stat",
3977 for(i
=0; i
<sizeof(azName
)/sizeof(azName
[0]); i
++){
3978 if( sqlite3_stricmp(zName
, azName
[i
])==0 ) return 1;
3983 static const sqlite3_module fts3Module
= {
3985 /* xCreate */ fts3CreateMethod
,
3986 /* xConnect */ fts3ConnectMethod
,
3987 /* xBestIndex */ fts3BestIndexMethod
,
3988 /* xDisconnect */ fts3DisconnectMethod
,
3989 /* xDestroy */ fts3DestroyMethod
,
3990 /* xOpen */ fts3OpenMethod
,
3991 /* xClose */ fts3CloseMethod
,
3992 /* xFilter */ fts3FilterMethod
,
3993 /* xNext */ fts3NextMethod
,
3994 /* xEof */ fts3EofMethod
,
3995 /* xColumn */ fts3ColumnMethod
,
3996 /* xRowid */ fts3RowidMethod
,
3997 /* xUpdate */ fts3UpdateMethod
,
3998 /* xBegin */ fts3BeginMethod
,
3999 /* xSync */ fts3SyncMethod
,
4000 /* xCommit */ fts3CommitMethod
,
4001 /* xRollback */ fts3RollbackMethod
,
4002 /* xFindFunction */ fts3FindFunctionMethod
,
4003 /* xRename */ fts3RenameMethod
,
4004 /* xSavepoint */ fts3SavepointMethod
,
4005 /* xRelease */ fts3ReleaseMethod
,
4006 /* xRollbackTo */ fts3RollbackToMethod
,
4007 /* xShadowName */ fts3ShadowName
,
4011 ** This function is registered as the module destructor (called when an
4012 ** FTS3 enabled database connection is closed). It frees the memory
4013 ** allocated for the tokenizer hash table.
4015 static void hashDestroy(void *p
){
4016 Fts3HashWrapper
*pHash
= (Fts3HashWrapper
*)p
;
4018 if( pHash
->nRef
<=0 ){
4019 sqlite3Fts3HashClear(&pHash
->hash
);
4020 sqlite3_free(pHash
);
4025 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
4026 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
4027 ** respectively. The following three forward declarations are for functions
4028 ** declared in these files used to retrieve the respective implementations.
4030 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
4031 ** to by the argument to point to the "simple" tokenizer implementation.
4034 void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module
const**ppModule
);
4035 void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module
const**ppModule
);
4036 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4037 void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module
const**ppModule
);
4039 #ifdef SQLITE_ENABLE_ICU
4040 void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module
const**ppModule
);
4044 ** Initialize the fts3 extension. If this extension is built as part
4045 ** of the sqlite library, then this function is called directly by
4046 ** SQLite. If fts3 is built as a dynamically loadable extension, this
4047 ** function is called by the sqlite3_extension_init() entry point.
4049 int sqlite3Fts3Init(sqlite3
*db
){
4051 Fts3HashWrapper
*pHash
= 0;
4052 const sqlite3_tokenizer_module
*pSimple
= 0;
4053 const sqlite3_tokenizer_module
*pPorter
= 0;
4054 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4055 const sqlite3_tokenizer_module
*pUnicode
= 0;
4058 #ifdef SQLITE_ENABLE_ICU
4059 const sqlite3_tokenizer_module
*pIcu
= 0;
4060 sqlite3Fts3IcuTokenizerModule(&pIcu
);
4063 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4064 sqlite3Fts3UnicodeTokenizer(&pUnicode
);
4068 rc
= sqlite3Fts3InitTerm(db
);
4069 if( rc
!=SQLITE_OK
) return rc
;
4072 rc
= sqlite3Fts3InitAux(db
);
4073 if( rc
!=SQLITE_OK
) return rc
;
4075 sqlite3Fts3SimpleTokenizerModule(&pSimple
);
4076 sqlite3Fts3PorterTokenizerModule(&pPorter
);
4078 /* Allocate and initialize the hash-table used to store tokenizers. */
4079 pHash
= sqlite3_malloc(sizeof(Fts3HashWrapper
));
4083 sqlite3Fts3HashInit(&pHash
->hash
, FTS3_HASH_STRING
, 1);
4087 /* Load the built-in tokenizers into the hash table */
4088 if( rc
==SQLITE_OK
){
4089 if( sqlite3Fts3HashInsert(&pHash
->hash
, "simple", 7, (void *)pSimple
)
4090 || sqlite3Fts3HashInsert(&pHash
->hash
, "porter", 7, (void *)pPorter
)
4092 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4093 || sqlite3Fts3HashInsert(&pHash
->hash
, "unicode61", 10, (void *)pUnicode
)
4095 #ifdef SQLITE_ENABLE_ICU
4096 || (pIcu
&& sqlite3Fts3HashInsert(&pHash
->hash
, "icu", 4, (void *)pIcu
))
4104 if( rc
==SQLITE_OK
){
4105 rc
= sqlite3Fts3ExprInitTestInterface(db
, &pHash
->hash
);
4109 /* Create the virtual table wrapper around the hash-table and overload
4110 ** the four scalar functions. If this is successful, register the
4111 ** module with sqlite.
4114 && SQLITE_OK
==(rc
=sqlite3Fts3InitHashTable(db
,&pHash
->hash
,"fts3_tokenizer"))
4115 && SQLITE_OK
==(rc
= sqlite3_overload_function(db
, "snippet", -1))
4116 && SQLITE_OK
==(rc
= sqlite3_overload_function(db
, "offsets", 1))
4117 && SQLITE_OK
==(rc
= sqlite3_overload_function(db
, "matchinfo", 1))
4118 && SQLITE_OK
==(rc
= sqlite3_overload_function(db
, "matchinfo", 2))
4119 && SQLITE_OK
==(rc
= sqlite3_overload_function(db
, "optimize", 1))
4122 rc
= sqlite3_create_module_v2(
4123 db
, "fts3", &fts3Module
, (void *)pHash
, hashDestroy
4125 if( rc
==SQLITE_OK
){
4127 rc
= sqlite3_create_module_v2(
4128 db
, "fts4", &fts3Module
, (void *)pHash
, hashDestroy
4131 if( rc
==SQLITE_OK
){
4133 rc
= sqlite3Fts3InitTok(db
, (void *)pHash
, hashDestroy
);
4139 /* An error has occurred. Delete the hash table and return the error code. */
4140 assert( rc
!=SQLITE_OK
);
4142 sqlite3Fts3HashClear(&pHash
->hash
);
4143 sqlite3_free(pHash
);
4149 ** Allocate an Fts3MultiSegReader for each token in the expression headed
4152 ** An Fts3SegReader object is a cursor that can seek or scan a range of
4153 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
4154 ** Fts3SegReader objects internally to provide an interface to seek or scan
4155 ** within the union of all segments of a b-tree. Hence the name.
4157 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
4158 ** segment b-tree (if the term is not a prefix or it is a prefix for which
4159 ** there exists prefix b-tree of the right length) then it may be traversed
4160 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
4161 ** doclist and then traversed.
4163 static void fts3EvalAllocateReaders(
4164 Fts3Cursor
*pCsr
, /* FTS cursor handle */
4165 Fts3Expr
*pExpr
, /* Allocate readers for this expression */
4166 int *pnToken
, /* OUT: Total number of tokens in phrase. */
4167 int *pnOr
, /* OUT: Total number of OR nodes in expr. */
4168 int *pRc
/* IN/OUT: Error code */
4170 if( pExpr
&& SQLITE_OK
==*pRc
){
4171 if( pExpr
->eType
==FTSQUERY_PHRASE
){
4173 int nToken
= pExpr
->pPhrase
->nToken
;
4175 for(i
=0; i
<nToken
; i
++){
4176 Fts3PhraseToken
*pToken
= &pExpr
->pPhrase
->aToken
[i
];
4177 int rc
= fts3TermSegReaderCursor(pCsr
,
4178 pToken
->z
, pToken
->n
, pToken
->isPrefix
, &pToken
->pSegcsr
4180 if( rc
!=SQLITE_OK
){
4185 assert( pExpr
->pPhrase
->iDoclistToken
==0 );
4186 pExpr
->pPhrase
->iDoclistToken
= -1;
4188 *pnOr
+= (pExpr
->eType
==FTSQUERY_OR
);
4189 fts3EvalAllocateReaders(pCsr
, pExpr
->pLeft
, pnToken
, pnOr
, pRc
);
4190 fts3EvalAllocateReaders(pCsr
, pExpr
->pRight
, pnToken
, pnOr
, pRc
);
4196 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
4197 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
4199 ** This function assumes that pList points to a buffer allocated using
4200 ** sqlite3_malloc(). This function takes responsibility for eventually
4201 ** freeing the buffer.
4203 ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
4205 static int fts3EvalPhraseMergeToken(
4206 Fts3Table
*pTab
, /* FTS Table pointer */
4207 Fts3Phrase
*p
, /* Phrase to merge pList/nList into */
4208 int iToken
, /* Token pList/nList corresponds to */
4209 char *pList
, /* Pointer to doclist */
4210 int nList
/* Number of bytes in pList */
4213 assert( iToken
!=p
->iDoclistToken
);
4216 sqlite3_free(p
->doclist
.aAll
);
4217 p
->doclist
.aAll
= 0;
4218 p
->doclist
.nAll
= 0;
4221 else if( p
->iDoclistToken
<0 ){
4222 p
->doclist
.aAll
= pList
;
4223 p
->doclist
.nAll
= nList
;
4226 else if( p
->doclist
.aAll
==0 ){
4227 sqlite3_free(pList
);
4237 if( p
->iDoclistToken
<iToken
){
4238 pLeft
= p
->doclist
.aAll
;
4239 nLeft
= p
->doclist
.nAll
;
4242 nDiff
= iToken
- p
->iDoclistToken
;
4244 pRight
= p
->doclist
.aAll
;
4245 nRight
= p
->doclist
.nAll
;
4248 nDiff
= p
->iDoclistToken
- iToken
;
4251 rc
= fts3DoclistPhraseMerge(
4252 pTab
->bDescIdx
, nDiff
, pLeft
, nLeft
, &pRight
, &nRight
4254 sqlite3_free(pLeft
);
4255 p
->doclist
.aAll
= pRight
;
4256 p
->doclist
.nAll
= nRight
;
4259 if( iToken
>p
->iDoclistToken
) p
->iDoclistToken
= iToken
;
4264 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
4265 ** does not take deferred tokens into account.
4267 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
4269 static int fts3EvalPhraseLoad(
4270 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4271 Fts3Phrase
*p
/* Phrase object */
4273 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
4277 for(iToken
=0; rc
==SQLITE_OK
&& iToken
<p
->nToken
; iToken
++){
4278 Fts3PhraseToken
*pToken
= &p
->aToken
[iToken
];
4279 assert( pToken
->pDeferred
==0 || pToken
->pSegcsr
==0 );
4281 if( pToken
->pSegcsr
){
4284 rc
= fts3TermSelect(pTab
, pToken
, p
->iColumn
, &nThis
, &pThis
);
4285 if( rc
==SQLITE_OK
){
4286 rc
= fts3EvalPhraseMergeToken(pTab
, p
, iToken
, pThis
, nThis
);
4289 assert( pToken
->pSegcsr
==0 );
4295 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
4297 ** This function is called on each phrase after the position lists for
4298 ** any deferred tokens have been loaded into memory. It updates the phrases
4299 ** current position list to include only those positions that are really
4300 ** instances of the phrase (after considering deferred tokens). If this
4301 ** means that the phrase does not appear in the current row, doclist.pList
4302 ** and doclist.nList are both zeroed.
4304 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
4306 static int fts3EvalDeferredPhrase(Fts3Cursor
*pCsr
, Fts3Phrase
*pPhrase
){
4307 int iToken
; /* Used to iterate through phrase tokens */
4308 char *aPoslist
= 0; /* Position list for deferred tokens */
4309 int nPoslist
= 0; /* Number of bytes in aPoslist */
4310 int iPrev
= -1; /* Token number of previous deferred token */
4311 char *aFree
= (pPhrase
->doclist
.bFreeList
? pPhrase
->doclist
.pList
: 0);
4313 for(iToken
=0; iToken
<pPhrase
->nToken
; iToken
++){
4314 Fts3PhraseToken
*pToken
= &pPhrase
->aToken
[iToken
];
4315 Fts3DeferredToken
*pDeferred
= pToken
->pDeferred
;
4320 int rc
= sqlite3Fts3DeferredTokenList(pDeferred
, &pList
, &nList
);
4321 if( rc
!=SQLITE_OK
) return rc
;
4324 sqlite3_free(aPoslist
);
4325 sqlite3_free(aFree
);
4326 pPhrase
->doclist
.pList
= 0;
4327 pPhrase
->doclist
.nList
= 0;
4330 }else if( aPoslist
==0 ){
4336 char *p1
= aPoslist
;
4340 fts3PoslistPhraseMerge(&aOut
, iToken
-iPrev
, 0, 1, &p1
, &p2
);
4341 sqlite3_free(aPoslist
);
4343 nPoslist
= (int)(aOut
- aPoslist
);
4345 sqlite3_free(aPoslist
);
4346 sqlite3_free(aFree
);
4347 pPhrase
->doclist
.pList
= 0;
4348 pPhrase
->doclist
.nList
= 0;
4357 int nMaxUndeferred
= pPhrase
->iDoclistToken
;
4358 if( nMaxUndeferred
<0 ){
4359 pPhrase
->doclist
.pList
= aPoslist
;
4360 pPhrase
->doclist
.nList
= nPoslist
;
4361 pPhrase
->doclist
.iDocid
= pCsr
->iPrevId
;
4362 pPhrase
->doclist
.bFreeList
= 1;
4369 if( nMaxUndeferred
>iPrev
){
4371 p2
= pPhrase
->doclist
.pList
;
4372 nDistance
= nMaxUndeferred
- iPrev
;
4374 p1
= pPhrase
->doclist
.pList
;
4376 nDistance
= iPrev
- nMaxUndeferred
;
4379 aOut
= (char *)sqlite3Fts3MallocZero(nPoslist
+FTS3_BUFFER_PADDING
);
4381 sqlite3_free(aPoslist
);
4382 return SQLITE_NOMEM
;
4385 pPhrase
->doclist
.pList
= aOut
;
4387 if( fts3PoslistPhraseMerge(&aOut
, nDistance
, 0, 1, &p1
, &p2
) ){
4388 pPhrase
->doclist
.bFreeList
= 1;
4389 pPhrase
->doclist
.nList
= (int)(aOut
- pPhrase
->doclist
.pList
);
4392 pPhrase
->doclist
.pList
= 0;
4393 pPhrase
->doclist
.nList
= 0;
4395 sqlite3_free(aPoslist
);
4399 if( pPhrase
->doclist
.pList
!=aFree
) sqlite3_free(aFree
);
4402 #endif /* SQLITE_DISABLE_FTS4_DEFERRED */
4405 ** Maximum number of tokens a phrase may have to be considered for the
4406 ** incremental doclists strategy.
4408 #define MAX_INCR_PHRASE_TOKENS 4
4411 ** This function is called for each Fts3Phrase in a full-text query
4412 ** expression to initialize the mechanism for returning rows. Once this
4413 ** function has been called successfully on an Fts3Phrase, it may be
4414 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
4416 ** If parameter bOptOk is true, then the phrase may (or may not) use the
4417 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
4418 ** memory within this call.
4420 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
4422 static int fts3EvalPhraseStart(Fts3Cursor
*pCsr
, int bOptOk
, Fts3Phrase
*p
){
4423 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
4424 int rc
= SQLITE_OK
; /* Error code */
4427 /* Determine if doclists may be loaded from disk incrementally. This is
4428 ** possible if the bOptOk argument is true, the FTS doclists will be
4429 ** scanned in forward order, and the phrase consists of
4430 ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
4431 ** tokens or prefix tokens that cannot use a prefix-index. */
4433 int bIncrOk
= (bOptOk
4434 && pCsr
->bDesc
==pTab
->bDescIdx
4435 && p
->nToken
<=MAX_INCR_PHRASE_TOKENS
&& p
->nToken
>0
4436 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
4437 && pTab
->bNoIncrDoclist
==0
4440 for(i
=0; bIncrOk
==1 && i
<p
->nToken
; i
++){
4441 Fts3PhraseToken
*pToken
= &p
->aToken
[i
];
4442 if( pToken
->bFirst
|| (pToken
->pSegcsr
!=0 && !pToken
->pSegcsr
->bLookup
) ){
4445 if( pToken
->pSegcsr
) bHaveIncr
= 1;
4448 if( bIncrOk
&& bHaveIncr
){
4449 /* Use the incremental approach. */
4450 int iCol
= (p
->iColumn
>= pTab
->nColumn
? -1 : p
->iColumn
);
4451 for(i
=0; rc
==SQLITE_OK
&& i
<p
->nToken
; i
++){
4452 Fts3PhraseToken
*pToken
= &p
->aToken
[i
];
4453 Fts3MultiSegReader
*pSegcsr
= pToken
->pSegcsr
;
4455 rc
= sqlite3Fts3MsrIncrStart(pTab
, pSegcsr
, iCol
, pToken
->z
, pToken
->n
);
4460 /* Load the full doclist for the phrase into memory. */
4461 rc
= fts3EvalPhraseLoad(pCsr
, p
);
4465 assert( rc
!=SQLITE_OK
|| p
->nToken
<1 || p
->aToken
[0].pSegcsr
==0 || p
->bIncr
);
4470 ** This function is used to iterate backwards (from the end to start)
4471 ** through doclists. It is used by this module to iterate through phrase
4472 ** doclists in reverse and by the fts3_write.c module to iterate through
4473 ** pending-terms lists when writing to databases with "order=desc".
4475 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
4476 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
4477 ** function iterates from the end of the doclist to the beginning.
4479 void sqlite3Fts3DoclistPrev(
4480 int bDescIdx
, /* True if the doclist is desc */
4481 char *aDoclist
, /* Pointer to entire doclist */
4482 int nDoclist
, /* Length of aDoclist in bytes */
4483 char **ppIter
, /* IN/OUT: Iterator pointer */
4484 sqlite3_int64
*piDocid
, /* IN/OUT: Docid pointer */
4485 int *pnList
, /* OUT: List length pointer */
4486 u8
*pbEof
/* OUT: End-of-file flag */
4490 assert( nDoclist
>0 );
4491 assert( *pbEof
==0 );
4492 assert_fts3_nc( p
|| *piDocid
==0 );
4493 assert( !p
|| (p
>aDoclist
&& p
<&aDoclist
[nDoclist
]) );
4496 sqlite3_int64 iDocid
= 0;
4498 char *pDocid
= aDoclist
;
4499 char *pEnd
= &aDoclist
[nDoclist
];
4502 while( pDocid
<pEnd
){
4503 sqlite3_int64 iDelta
;
4504 pDocid
+= sqlite3Fts3GetVarint(pDocid
, &iDelta
);
4505 iDocid
+= (iMul
* iDelta
);
4507 fts3PoslistCopy(0, &pDocid
);
4508 while( pDocid
<pEnd
&& *pDocid
==0 ) pDocid
++;
4509 iMul
= (bDescIdx
? -1 : 1);
4512 *pnList
= (int)(pEnd
- pNext
);
4516 int iMul
= (bDescIdx
? -1 : 1);
4517 sqlite3_int64 iDelta
;
4518 fts3GetReverseVarint(&p
, aDoclist
, &iDelta
);
4519 *piDocid
-= (iMul
* iDelta
);
4525 fts3ReversePoslist(aDoclist
, &p
);
4526 *pnList
= (int)(pSave
- p
);
4533 ** Iterate forwards through a doclist.
4535 void sqlite3Fts3DoclistNext(
4536 int bDescIdx
, /* True if the doclist is desc */
4537 char *aDoclist
, /* Pointer to entire doclist */
4538 int nDoclist
, /* Length of aDoclist in bytes */
4539 char **ppIter
, /* IN/OUT: Iterator pointer */
4540 sqlite3_int64
*piDocid
, /* IN/OUT: Docid pointer */
4541 u8
*pbEof
/* OUT: End-of-file flag */
4545 assert( nDoclist
>0 );
4546 assert( *pbEof
==0 );
4547 assert_fts3_nc( p
|| *piDocid
==0 );
4548 assert( !p
|| (p
>=aDoclist
&& p
<=&aDoclist
[nDoclist
]) );
4552 p
+= sqlite3Fts3GetVarint(p
, piDocid
);
4554 fts3PoslistCopy(0, &p
);
4555 while( p
<&aDoclist
[nDoclist
] && *p
==0 ) p
++;
4556 if( p
>=&aDoclist
[nDoclist
] ){
4560 p
+= sqlite3Fts3GetVarint(p
, &iVar
);
4561 *piDocid
+= ((bDescIdx
? -1 : 1) * iVar
);
4569 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
4570 ** to true if EOF is reached.
4572 static void fts3EvalDlPhraseNext(
4577 char *pIter
; /* Used to iterate through aAll */
4578 char *pEnd
; /* 1 byte past end of aAll */
4580 if( pDL
->pNextDocid
){
4581 pIter
= pDL
->pNextDocid
;
4582 assert( pDL
->aAll
!=0 || pIter
==0 );
4587 if( pIter
==0 || pIter
>=(pEnd
= pDL
->aAll
+ pDL
->nAll
) ){
4588 /* We have already reached the end of this doclist. EOF. */
4591 sqlite3_int64 iDelta
;
4592 pIter
+= sqlite3Fts3GetVarint(pIter
, &iDelta
);
4593 if( pTab
->bDescIdx
==0 || pDL
->pNextDocid
==0 ){
4594 pDL
->iDocid
+= iDelta
;
4596 pDL
->iDocid
-= iDelta
;
4599 fts3PoslistCopy(0, &pIter
);
4600 pDL
->nList
= (int)(pIter
- pDL
->pList
);
4602 /* pIter now points just past the 0x00 that terminates the position-
4603 ** list for document pDL->iDocid. However, if this position-list was
4604 ** edited in place by fts3EvalNearTrim(), then pIter may not actually
4605 ** point to the start of the next docid value. The following line deals
4606 ** with this case by advancing pIter past the zero-padding added by
4607 ** fts3EvalNearTrim(). */
4608 while( pIter
<pEnd
&& *pIter
==0 ) pIter
++;
4610 pDL
->pNextDocid
= pIter
;
4611 assert( pIter
>=&pDL
->aAll
[pDL
->nAll
] || *pIter
);
4617 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
4619 typedef struct TokenDoclist TokenDoclist
;
4620 struct TokenDoclist
{
4622 sqlite3_int64 iDocid
;
4628 ** Token pToken is an incrementally loaded token that is part of a
4629 ** multi-token phrase. Advance it to the next matching document in the
4630 ** database and populate output variable *p with the details of the new
4631 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
4633 ** If an error occurs, return an SQLite error code. Otherwise, return
4636 static int incrPhraseTokenNext(
4637 Fts3Table
*pTab
, /* Virtual table handle */
4638 Fts3Phrase
*pPhrase
, /* Phrase to advance token of */
4639 int iToken
, /* Specific token to advance */
4640 TokenDoclist
*p
, /* OUT: Docid and doclist for new entry */
4641 u8
*pbEof
/* OUT: True if iterator is at EOF */
4645 if( pPhrase
->iDoclistToken
==iToken
){
4646 assert( p
->bIgnore
==0 );
4647 assert( pPhrase
->aToken
[iToken
].pSegcsr
==0 );
4648 fts3EvalDlPhraseNext(pTab
, &pPhrase
->doclist
, pbEof
);
4649 p
->pList
= pPhrase
->doclist
.pList
;
4650 p
->nList
= pPhrase
->doclist
.nList
;
4651 p
->iDocid
= pPhrase
->doclist
.iDocid
;
4653 Fts3PhraseToken
*pToken
= &pPhrase
->aToken
[iToken
];
4654 assert( pToken
->pDeferred
==0 );
4655 assert( pToken
->pSegcsr
|| pPhrase
->iDoclistToken
>=0 );
4656 if( pToken
->pSegcsr
){
4657 assert( p
->bIgnore
==0 );
4658 rc
= sqlite3Fts3MsrIncrNext(
4659 pTab
, pToken
->pSegcsr
, &p
->iDocid
, &p
->pList
, &p
->nList
4661 if( p
->pList
==0 ) *pbEof
= 1;
4672 ** The phrase iterator passed as the second argument:
4674 ** * features at least one token that uses an incremental doclist, and
4676 ** * does not contain any deferred tokens.
4678 ** Advance it to the next matching documnent in the database and populate
4679 ** the Fts3Doclist.pList and nList fields.
4681 ** If there is no "next" entry and no error occurs, then *pbEof is set to
4682 ** 1 before returning. Otherwise, if no error occurs and the iterator is
4683 ** successfully advanced, *pbEof is set to 0.
4685 ** If an error occurs, return an SQLite error code. Otherwise, return
4688 static int fts3EvalIncrPhraseNext(
4689 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4690 Fts3Phrase
*p
, /* Phrase object to advance to next docid */
4691 u8
*pbEof
/* OUT: Set to 1 if EOF */
4694 Fts3Doclist
*pDL
= &p
->doclist
;
4695 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
4698 /* This is only called if it is guaranteed that the phrase has at least
4699 ** one incremental token. In which case the bIncr flag is set. */
4700 assert( p
->bIncr
==1 );
4703 rc
= sqlite3Fts3MsrIncrNext(pTab
, p
->aToken
[0].pSegcsr
,
4704 &pDL
->iDocid
, &pDL
->pList
, &pDL
->nList
4706 if( pDL
->pList
==0 ) bEof
= 1;
4708 int bDescDoclist
= pCsr
->bDesc
;
4709 struct TokenDoclist a
[MAX_INCR_PHRASE_TOKENS
];
4711 memset(a
, 0, sizeof(a
));
4712 assert( p
->nToken
<=MAX_INCR_PHRASE_TOKENS
);
4713 assert( p
->iDoclistToken
<MAX_INCR_PHRASE_TOKENS
);
4717 sqlite3_int64 iMax
= 0; /* Largest docid for all iterators */
4718 int i
; /* Used to iterate through tokens */
4720 /* Advance the iterator for each token in the phrase once. */
4721 for(i
=0; rc
==SQLITE_OK
&& i
<p
->nToken
&& bEof
==0; i
++){
4722 rc
= incrPhraseTokenNext(pTab
, p
, i
, &a
[i
], &bEof
);
4723 if( a
[i
].bIgnore
==0 && (bMaxSet
==0 || DOCID_CMP(iMax
, a
[i
].iDocid
)<0) ){
4728 assert( rc
!=SQLITE_OK
|| (p
->nToken
>=1 && a
[p
->nToken
-1].bIgnore
==0) );
4729 assert( rc
!=SQLITE_OK
|| bMaxSet
);
4731 /* Keep advancing iterators until they all point to the same document */
4732 for(i
=0; i
<p
->nToken
; i
++){
4733 while( rc
==SQLITE_OK
&& bEof
==0
4734 && a
[i
].bIgnore
==0 && DOCID_CMP(a
[i
].iDocid
, iMax
)<0
4736 rc
= incrPhraseTokenNext(pTab
, p
, i
, &a
[i
], &bEof
);
4737 if( DOCID_CMP(a
[i
].iDocid
, iMax
)>0 ){
4744 /* Check if the current entries really are a phrase match */
4747 int nByte
= a
[p
->nToken
-1].nList
;
4748 char *aDoclist
= sqlite3_malloc64((i64
)nByte
+FTS3_BUFFER_PADDING
);
4749 if( !aDoclist
) return SQLITE_NOMEM
;
4750 memcpy(aDoclist
, a
[p
->nToken
-1].pList
, nByte
+1);
4751 memset(&aDoclist
[nByte
], 0, FTS3_BUFFER_PADDING
);
4753 for(i
=0; i
<(p
->nToken
-1); i
++){
4754 if( a
[i
].bIgnore
==0 ){
4755 char *pL
= a
[i
].pList
;
4756 char *pR
= aDoclist
;
4757 char *pOut
= aDoclist
;
4758 int nDist
= p
->nToken
-1-i
;
4759 int res
= fts3PoslistPhraseMerge(&pOut
, nDist
, 0, 1, &pL
, &pR
);
4761 nList
= (int)(pOut
- aDoclist
);
4764 if( i
==(p
->nToken
-1) ){
4766 pDL
->pList
= aDoclist
;
4771 sqlite3_free(aDoclist
);
4781 ** Attempt to move the phrase iterator to point to the next matching docid.
4782 ** If an error occurs, return an SQLite error code. Otherwise, return
4785 ** If there is no "next" entry and no error occurs, then *pbEof is set to
4786 ** 1 before returning. Otherwise, if no error occurs and the iterator is
4787 ** successfully advanced, *pbEof is set to 0.
4789 static int fts3EvalPhraseNext(
4790 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4791 Fts3Phrase
*p
, /* Phrase object to advance to next docid */
4792 u8
*pbEof
/* OUT: Set to 1 if EOF */
4795 Fts3Doclist
*pDL
= &p
->doclist
;
4796 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
4799 rc
= fts3EvalIncrPhraseNext(pCsr
, p
, pbEof
);
4800 }else if( pCsr
->bDesc
!=pTab
->bDescIdx
&& pDL
->nAll
){
4801 sqlite3Fts3DoclistPrev(pTab
->bDescIdx
, pDL
->aAll
, pDL
->nAll
,
4802 &pDL
->pNextDocid
, &pDL
->iDocid
, &pDL
->nList
, pbEof
4804 pDL
->pList
= pDL
->pNextDocid
;
4806 fts3EvalDlPhraseNext(pTab
, pDL
, pbEof
);
4814 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
4815 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
4816 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
4817 ** expressions for which all descendent tokens are deferred.
4819 ** If parameter bOptOk is zero, then it is guaranteed that the
4820 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
4821 ** each phrase in the expression (subject to deferred token processing).
4822 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
4823 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
4825 ** If an error occurs within this function, *pRc is set to an SQLite error
4826 ** code before returning.
4828 static void fts3EvalStartReaders(
4829 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4830 Fts3Expr
*pExpr
, /* Expression to initialize phrases in */
4831 int *pRc
/* IN/OUT: Error code */
4833 if( pExpr
&& SQLITE_OK
==*pRc
){
4834 if( pExpr
->eType
==FTSQUERY_PHRASE
){
4835 int nToken
= pExpr
->pPhrase
->nToken
;
4838 for(i
=0; i
<nToken
; i
++){
4839 if( pExpr
->pPhrase
->aToken
[i
].pDeferred
==0 ) break;
4841 pExpr
->bDeferred
= (i
==nToken
);
4843 *pRc
= fts3EvalPhraseStart(pCsr
, 1, pExpr
->pPhrase
);
4845 fts3EvalStartReaders(pCsr
, pExpr
->pLeft
, pRc
);
4846 fts3EvalStartReaders(pCsr
, pExpr
->pRight
, pRc
);
4847 pExpr
->bDeferred
= (pExpr
->pLeft
->bDeferred
&& pExpr
->pRight
->bDeferred
);
4853 ** An array of the following structures is assembled as part of the process
4854 ** of selecting tokens to defer before the query starts executing (as part
4855 ** of the xFilter() method). There is one element in the array for each
4856 ** token in the FTS expression.
4858 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
4859 ** to phrases that are connected only by AND and NEAR operators (not OR or
4860 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
4861 ** separately. The root of a tokens AND/NEAR cluster is stored in
4862 ** Fts3TokenAndCost.pRoot.
4864 typedef struct Fts3TokenAndCost Fts3TokenAndCost
;
4865 struct Fts3TokenAndCost
{
4866 Fts3Phrase
*pPhrase
; /* The phrase the token belongs to */
4867 int iToken
; /* Position of token in phrase */
4868 Fts3PhraseToken
*pToken
; /* The token itself */
4869 Fts3Expr
*pRoot
; /* Root of NEAR/AND cluster */
4870 int nOvfl
; /* Number of overflow pages to load doclist */
4871 int iCol
; /* The column the token must match */
4875 ** This function is used to populate an allocated Fts3TokenAndCost array.
4877 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
4878 ** Otherwise, if an error occurs during execution, *pRc is set to an
4879 ** SQLite error code.
4881 static void fts3EvalTokenCosts(
4882 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4883 Fts3Expr
*pRoot
, /* Root of current AND/NEAR cluster */
4884 Fts3Expr
*pExpr
, /* Expression to consider */
4885 Fts3TokenAndCost
**ppTC
, /* Write new entries to *(*ppTC)++ */
4886 Fts3Expr
***ppOr
, /* Write new OR root to *(*ppOr)++ */
4887 int *pRc
/* IN/OUT: Error code */
4889 if( *pRc
==SQLITE_OK
){
4890 if( pExpr
->eType
==FTSQUERY_PHRASE
){
4891 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
4893 for(i
=0; *pRc
==SQLITE_OK
&& i
<pPhrase
->nToken
; i
++){
4894 Fts3TokenAndCost
*pTC
= (*ppTC
)++;
4895 pTC
->pPhrase
= pPhrase
;
4898 pTC
->pToken
= &pPhrase
->aToken
[i
];
4899 pTC
->iCol
= pPhrase
->iColumn
;
4900 *pRc
= sqlite3Fts3MsrOvfl(pCsr
, pTC
->pToken
->pSegcsr
, &pTC
->nOvfl
);
4902 }else if( pExpr
->eType
!=FTSQUERY_NOT
){
4903 assert( pExpr
->eType
==FTSQUERY_OR
4904 || pExpr
->eType
==FTSQUERY_AND
4905 || pExpr
->eType
==FTSQUERY_NEAR
4907 assert( pExpr
->pLeft
&& pExpr
->pRight
);
4908 if( pExpr
->eType
==FTSQUERY_OR
){
4909 pRoot
= pExpr
->pLeft
;
4913 fts3EvalTokenCosts(pCsr
, pRoot
, pExpr
->pLeft
, ppTC
, ppOr
, pRc
);
4914 if( pExpr
->eType
==FTSQUERY_OR
){
4915 pRoot
= pExpr
->pRight
;
4919 fts3EvalTokenCosts(pCsr
, pRoot
, pExpr
->pRight
, ppTC
, ppOr
, pRc
);
4925 ** Determine the average document (row) size in pages. If successful,
4926 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
4927 ** an SQLite error code.
4929 ** The average document size in pages is calculated by first calculating
4930 ** determining the average size in bytes, B. If B is less than the amount
4931 ** of data that will fit on a single leaf page of an intkey table in
4932 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
4933 ** the number of overflow pages consumed by a record B bytes in size.
4935 static int fts3EvalAverageDocsize(Fts3Cursor
*pCsr
, int *pnPage
){
4937 if( pCsr
->nRowAvg
==0 ){
4938 /* The average document size, which is required to calculate the cost
4939 ** of each doclist, has not yet been determined. Read the required
4940 ** data from the %_stat table to calculate it.
4942 ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
4943 ** varints, where nCol is the number of columns in the FTS3 table.
4944 ** The first varint is the number of documents currently stored in
4945 ** the table. The following nCol varints contain the total amount of
4946 ** data stored in all rows of each column of the table, from left
4949 Fts3Table
*p
= (Fts3Table
*)pCsr
->base
.pVtab
;
4950 sqlite3_stmt
*pStmt
;
4951 sqlite3_int64 nDoc
= 0;
4952 sqlite3_int64 nByte
= 0;
4956 rc
= sqlite3Fts3SelectDoctotal(p
, &pStmt
);
4957 if( rc
!=SQLITE_OK
) return rc
;
4958 a
= sqlite3_column_blob(pStmt
, 0);
4959 testcase( a
==0 ); /* If %_stat.value set to X'' */
4961 pEnd
= &a
[sqlite3_column_bytes(pStmt
, 0)];
4962 a
+= sqlite3Fts3GetVarintBounded(a
, pEnd
, &nDoc
);
4964 a
+= sqlite3Fts3GetVarintBounded(a
, pEnd
, &nByte
);
4967 if( nDoc
==0 || nByte
==0 ){
4968 sqlite3_reset(pStmt
);
4969 return FTS_CORRUPT_VTAB
;
4973 pCsr
->nRowAvg
= (int)(((nByte
/ nDoc
) + p
->nPgsz
) / p
->nPgsz
);
4974 assert( pCsr
->nRowAvg
>0 );
4975 rc
= sqlite3_reset(pStmt
);
4978 *pnPage
= pCsr
->nRowAvg
;
4983 ** This function is called to select the tokens (if any) that will be
4984 ** deferred. The array aTC[] has already been populated when this is
4987 ** This function is called once for each AND/NEAR cluster in the
4988 ** expression. Each invocation determines which tokens to defer within
4989 ** the cluster with root node pRoot. See comments above the definition
4990 ** of struct Fts3TokenAndCost for more details.
4992 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
4993 ** called on each token to defer. Otherwise, an SQLite error code is
4996 static int fts3EvalSelectDeferred(
4997 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4998 Fts3Expr
*pRoot
, /* Consider tokens with this root node */
4999 Fts3TokenAndCost
*aTC
, /* Array of expression tokens and costs */
5000 int nTC
/* Number of entries in aTC[] */
5002 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
5003 int nDocSize
= 0; /* Number of pages per doc loaded */
5004 int rc
= SQLITE_OK
; /* Return code */
5005 int ii
; /* Iterator variable for various purposes */
5006 int nOvfl
= 0; /* Total overflow pages used by doclists */
5007 int nToken
= 0; /* Total number of tokens in cluster */
5009 int nMinEst
= 0; /* The minimum count for any phrase so far. */
5010 int nLoad4
= 1; /* (Phrases that will be loaded)^4. */
5012 /* Tokens are never deferred for FTS tables created using the content=xxx
5013 ** option. The reason being that it is not guaranteed that the content
5014 ** table actually contains the same data as the index. To prevent this from
5015 ** causing any problems, the deferred token optimization is completely
5016 ** disabled for content=xxx tables. */
5017 if( pTab
->zContentTbl
){
5021 /* Count the tokens in this AND/NEAR cluster. If none of the doclists
5022 ** associated with the tokens spill onto overflow pages, or if there is
5023 ** only 1 token, exit early. No tokens to defer in this case. */
5024 for(ii
=0; ii
<nTC
; ii
++){
5025 if( aTC
[ii
].pRoot
==pRoot
){
5026 nOvfl
+= aTC
[ii
].nOvfl
;
5030 if( nOvfl
==0 || nToken
<2 ) return SQLITE_OK
;
5032 /* Obtain the average docsize (in pages). */
5033 rc
= fts3EvalAverageDocsize(pCsr
, &nDocSize
);
5034 assert( rc
!=SQLITE_OK
|| nDocSize
>0 );
5037 /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
5038 ** of the number of overflow pages that will be loaded by the pager layer
5039 ** to retrieve the entire doclist for the token from the full-text index.
5040 ** Load the doclists for tokens that are either:
5042 ** a. The cheapest token in the entire query (i.e. the one visited by the
5043 ** first iteration of this loop), or
5045 ** b. Part of a multi-token phrase.
5047 ** After each token doclist is loaded, merge it with the others from the
5048 ** same phrase and count the number of documents that the merged doclist
5049 ** contains. Set variable "nMinEst" to the smallest number of documents in
5050 ** any phrase doclist for which 1 or more token doclists have been loaded.
5051 ** Let nOther be the number of other phrases for which it is certain that
5052 ** one or more tokens will not be deferred.
5054 ** Then, for each token, defer it if loading the doclist would result in
5055 ** loading N or more overflow pages into memory, where N is computed as:
5057 ** (nMinEst + 4^nOther - 1) / (4^nOther)
5059 for(ii
=0; ii
<nToken
&& rc
==SQLITE_OK
; ii
++){
5060 int iTC
; /* Used to iterate through aTC[] array. */
5061 Fts3TokenAndCost
*pTC
= 0; /* Set to cheapest remaining token. */
5063 /* Set pTC to point to the cheapest remaining token. */
5064 for(iTC
=0; iTC
<nTC
; iTC
++){
5065 if( aTC
[iTC
].pToken
&& aTC
[iTC
].pRoot
==pRoot
5066 && (!pTC
|| aTC
[iTC
].nOvfl
<pTC
->nOvfl
)
5073 if( ii
&& pTC
->nOvfl
>=((nMinEst
+(nLoad4
/4)-1)/(nLoad4
/4))*nDocSize
){
5074 /* The number of overflow pages to load for this (and therefore all
5075 ** subsequent) tokens is greater than the estimated number of pages
5076 ** that will be loaded if all subsequent tokens are deferred.
5078 Fts3PhraseToken
*pToken
= pTC
->pToken
;
5079 rc
= sqlite3Fts3DeferToken(pCsr
, pToken
, pTC
->iCol
);
5080 fts3SegReaderCursorFree(pToken
->pSegcsr
);
5081 pToken
->pSegcsr
= 0;
5083 /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
5084 ** for-loop. Except, limit the value to 2^24 to prevent it from
5085 ** overflowing the 32-bit integer it is stored in. */
5086 if( ii
<12 ) nLoad4
= nLoad4
*4;
5088 if( ii
==0 || (pTC
->pPhrase
->nToken
>1 && ii
!=nToken
-1) ){
5089 /* Either this is the cheapest token in the entire query, or it is
5090 ** part of a multi-token phrase. Either way, the entire doclist will
5091 ** (eventually) be loaded into memory. It may as well be now. */
5092 Fts3PhraseToken
*pToken
= pTC
->pToken
;
5095 rc
= fts3TermSelect(pTab
, pToken
, pTC
->iCol
, &nList
, &pList
);
5096 assert( rc
==SQLITE_OK
|| pList
==0 );
5097 if( rc
==SQLITE_OK
){
5098 rc
= fts3EvalPhraseMergeToken(
5099 pTab
, pTC
->pPhrase
, pTC
->iToken
,pList
,nList
5102 if( rc
==SQLITE_OK
){
5104 nCount
= fts3DoclistCountDocids(
5105 pTC
->pPhrase
->doclist
.aAll
, pTC
->pPhrase
->doclist
.nAll
5107 if( ii
==0 || nCount
<nMinEst
) nMinEst
= nCount
;
5118 ** This function is called from within the xFilter method. It initializes
5119 ** the full-text query currently stored in pCsr->pExpr. To iterate through
5120 ** the results of a query, the caller does:
5122 ** fts3EvalStart(pCsr);
5124 ** fts3EvalNext(pCsr);
5125 ** if( pCsr->bEof ) break;
5126 ** ... return row pCsr->iPrevId to the caller ...
5129 static int fts3EvalStart(Fts3Cursor
*pCsr
){
5130 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
5135 /* Allocate a MultiSegReader for each token in the expression. */
5136 fts3EvalAllocateReaders(pCsr
, pCsr
->pExpr
, &nToken
, &nOr
, &rc
);
5138 /* Determine which, if any, tokens in the expression should be deferred. */
5139 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
5140 if( rc
==SQLITE_OK
&& nToken
>1 && pTab
->bFts4
){
5141 Fts3TokenAndCost
*aTC
;
5142 aTC
= (Fts3TokenAndCost
*)sqlite3_malloc64(
5143 sizeof(Fts3TokenAndCost
) * nToken
5144 + sizeof(Fts3Expr
*) * nOr
* 2
5150 Fts3Expr
**apOr
= (Fts3Expr
**)&aTC
[nToken
];
5152 Fts3TokenAndCost
*pTC
= aTC
;
5153 Fts3Expr
**ppOr
= apOr
;
5155 fts3EvalTokenCosts(pCsr
, 0, pCsr
->pExpr
, &pTC
, &ppOr
, &rc
);
5156 nToken
= (int)(pTC
-aTC
);
5157 nOr
= (int)(ppOr
-apOr
);
5159 if( rc
==SQLITE_OK
){
5160 rc
= fts3EvalSelectDeferred(pCsr
, 0, aTC
, nToken
);
5161 for(ii
=0; rc
==SQLITE_OK
&& ii
<nOr
; ii
++){
5162 rc
= fts3EvalSelectDeferred(pCsr
, apOr
[ii
], aTC
, nToken
);
5171 fts3EvalStartReaders(pCsr
, pCsr
->pExpr
, &rc
);
5176 ** Invalidate the current position list for phrase pPhrase.
5178 static void fts3EvalInvalidatePoslist(Fts3Phrase
*pPhrase
){
5179 if( pPhrase
->doclist
.bFreeList
){
5180 sqlite3_free(pPhrase
->doclist
.pList
);
5182 pPhrase
->doclist
.pList
= 0;
5183 pPhrase
->doclist
.nList
= 0;
5184 pPhrase
->doclist
.bFreeList
= 0;
5188 ** This function is called to edit the position list associated with
5189 ** the phrase object passed as the fifth argument according to a NEAR
5190 ** condition. For example:
5192 ** abc NEAR/5 "def ghi"
5194 ** Parameter nNear is passed the NEAR distance of the expression (5 in
5195 ** the example above). When this function is called, *paPoslist points to
5196 ** the position list, and *pnToken is the number of phrase tokens in the
5197 ** phrase on the other side of the NEAR operator to pPhrase. For example,
5198 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
5199 ** the position list associated with phrase "abc".
5201 ** All positions in the pPhrase position list that are not sufficiently
5202 ** close to a position in the *paPoslist position list are removed. If this
5203 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
5205 ** Before returning, *paPoslist is set to point to the position lsit
5206 ** associated with pPhrase. And *pnToken is set to the number of tokens in
5209 static int fts3EvalNearTrim(
5210 int nNear
, /* NEAR distance. As in "NEAR/nNear". */
5211 char *aTmp
, /* Temporary space to use */
5212 char **paPoslist
, /* IN/OUT: Position list */
5213 int *pnToken
, /* IN/OUT: Tokens in phrase of *paPoslist */
5214 Fts3Phrase
*pPhrase
/* The phrase object to trim the doclist of */
5216 int nParam1
= nNear
+ pPhrase
->nToken
;
5217 int nParam2
= nNear
+ *pnToken
;
5223 assert( pPhrase
->doclist
.pList
);
5225 p2
= pOut
= pPhrase
->doclist
.pList
;
5226 res
= fts3PoslistNearMerge(
5227 &pOut
, aTmp
, nParam1
, nParam2
, paPoslist
, &p2
5230 nNew
= (int)(pOut
- pPhrase
->doclist
.pList
) - 1;
5231 assert_fts3_nc( nNew
<=pPhrase
->doclist
.nList
&& nNew
>0 );
5232 if( nNew
>=0 && nNew
<=pPhrase
->doclist
.nList
){
5233 assert( pPhrase
->doclist
.pList
[nNew
]=='\0' );
5234 memset(&pPhrase
->doclist
.pList
[nNew
], 0, pPhrase
->doclist
.nList
- nNew
);
5235 pPhrase
->doclist
.nList
= nNew
;
5237 *paPoslist
= pPhrase
->doclist
.pList
;
5238 *pnToken
= pPhrase
->nToken
;
5245 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
5246 ** Otherwise, it advances the expression passed as the second argument to
5247 ** point to the next matching row in the database. Expressions iterate through
5248 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
5249 ** or descending if it is non-zero.
5251 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
5252 ** successful, the following variables in pExpr are set:
5254 ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
5255 ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
5257 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
5258 ** at EOF, then the following variables are populated with the position list
5259 ** for the phrase for the visited row:
5261 ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
5262 ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
5264 ** It says above that this function advances the expression to the next
5265 ** matching row. This is usually true, but there are the following exceptions:
5267 ** 1. Deferred tokens are not taken into account. If a phrase consists
5268 ** entirely of deferred tokens, it is assumed to match every row in
5269 ** the db. In this case the position-list is not populated at all.
5271 ** Or, if a phrase contains one or more deferred tokens and one or
5272 ** more non-deferred tokens, then the expression is advanced to the
5273 ** next possible match, considering only non-deferred tokens. In other
5274 ** words, if the phrase is "A B C", and "B" is deferred, the expression
5275 ** is advanced to the next row that contains an instance of "A * C",
5276 ** where "*" may match any single token. The position list in this case
5277 ** is populated as for "A * C" before returning.
5279 ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
5280 ** advanced to point to the next row that matches "x AND y".
5282 ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
5283 ** really a match, taking into account deferred tokens and NEAR operators.
5285 static void fts3EvalNextRow(
5286 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
5287 Fts3Expr
*pExpr
, /* Expr. to advance to next matching row */
5288 int *pRc
/* IN/OUT: Error code */
5290 if( *pRc
==SQLITE_OK
&& pExpr
->bEof
==0 ){
5291 int bDescDoclist
= pCsr
->bDesc
; /* Used by DOCID_CMP() macro */
5294 switch( pExpr
->eType
){
5296 case FTSQUERY_AND
: {
5297 Fts3Expr
*pLeft
= pExpr
->pLeft
;
5298 Fts3Expr
*pRight
= pExpr
->pRight
;
5299 assert( !pLeft
->bDeferred
|| !pRight
->bDeferred
);
5301 if( pLeft
->bDeferred
){
5302 /* LHS is entirely deferred. So we assume it matches every row.
5303 ** Advance the RHS iterator to find the next row visited. */
5304 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5305 pExpr
->iDocid
= pRight
->iDocid
;
5306 pExpr
->bEof
= pRight
->bEof
;
5307 }else if( pRight
->bDeferred
){
5308 /* RHS is entirely deferred. So we assume it matches every row.
5309 ** Advance the LHS iterator to find the next row visited. */
5310 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5311 pExpr
->iDocid
= pLeft
->iDocid
;
5312 pExpr
->bEof
= pLeft
->bEof
;
5314 /* Neither the RHS or LHS are deferred. */
5315 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5316 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5317 while( !pLeft
->bEof
&& !pRight
->bEof
&& *pRc
==SQLITE_OK
){
5318 sqlite3_int64 iDiff
= DOCID_CMP(pLeft
->iDocid
, pRight
->iDocid
);
5319 if( iDiff
==0 ) break;
5321 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5323 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5326 pExpr
->iDocid
= pLeft
->iDocid
;
5327 pExpr
->bEof
= (pLeft
->bEof
|| pRight
->bEof
);
5328 if( pExpr
->eType
==FTSQUERY_NEAR
&& pExpr
->bEof
){
5329 assert( pRight
->eType
==FTSQUERY_PHRASE
);
5330 if( pRight
->pPhrase
->doclist
.aAll
){
5331 Fts3Doclist
*pDl
= &pRight
->pPhrase
->doclist
;
5332 while( *pRc
==SQLITE_OK
&& pRight
->bEof
==0 ){
5333 memset(pDl
->pList
, 0, pDl
->nList
);
5334 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5337 if( pLeft
->pPhrase
&& pLeft
->pPhrase
->doclist
.aAll
){
5338 Fts3Doclist
*pDl
= &pLeft
->pPhrase
->doclist
;
5339 while( *pRc
==SQLITE_OK
&& pLeft
->bEof
==0 ){
5340 memset(pDl
->pList
, 0, pDl
->nList
);
5341 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5344 pRight
->bEof
= pLeft
->bEof
= 1;
5351 Fts3Expr
*pLeft
= pExpr
->pLeft
;
5352 Fts3Expr
*pRight
= pExpr
->pRight
;
5353 sqlite3_int64 iCmp
= DOCID_CMP(pLeft
->iDocid
, pRight
->iDocid
);
5355 assert_fts3_nc( pLeft
->bStart
|| pLeft
->iDocid
==pRight
->iDocid
);
5356 assert_fts3_nc( pRight
->bStart
|| pLeft
->iDocid
==pRight
->iDocid
);
5358 if( pRight
->bEof
|| (pLeft
->bEof
==0 && iCmp
<0) ){
5359 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5360 }else if( pLeft
->bEof
|| iCmp
>0 ){
5361 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5363 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5364 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5367 pExpr
->bEof
= (pLeft
->bEof
&& pRight
->bEof
);
5368 iCmp
= DOCID_CMP(pLeft
->iDocid
, pRight
->iDocid
);
5369 if( pRight
->bEof
|| (pLeft
->bEof
==0 && iCmp
<0) ){
5370 pExpr
->iDocid
= pLeft
->iDocid
;
5372 pExpr
->iDocid
= pRight
->iDocid
;
5378 case FTSQUERY_NOT
: {
5379 Fts3Expr
*pLeft
= pExpr
->pLeft
;
5380 Fts3Expr
*pRight
= pExpr
->pRight
;
5382 if( pRight
->bStart
==0 ){
5383 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5384 assert( *pRc
!=SQLITE_OK
|| pRight
->bStart
);
5387 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5388 if( pLeft
->bEof
==0 ){
5391 && DOCID_CMP(pLeft
->iDocid
, pRight
->iDocid
)>0
5393 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5396 pExpr
->iDocid
= pLeft
->iDocid
;
5397 pExpr
->bEof
= pLeft
->bEof
;
5402 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
5403 fts3EvalInvalidatePoslist(pPhrase
);
5404 *pRc
= fts3EvalPhraseNext(pCsr
, pPhrase
, &pExpr
->bEof
);
5405 pExpr
->iDocid
= pPhrase
->doclist
.iDocid
;
5413 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
5414 ** cluster, then this function returns 1 immediately.
5416 ** Otherwise, it checks if the current row really does match the NEAR
5417 ** expression, using the data currently stored in the position lists
5418 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
5420 ** If the current row is a match, the position list associated with each
5421 ** phrase in the NEAR expression is edited in place to contain only those
5422 ** phrase instances sufficiently close to their peers to satisfy all NEAR
5423 ** constraints. In this case it returns 1. If the NEAR expression does not
5424 ** match the current row, 0 is returned. The position lists may or may not
5425 ** be edited if 0 is returned.
5427 static int fts3EvalNearTest(Fts3Expr
*pExpr
, int *pRc
){
5430 /* The following block runs if pExpr is the root of a NEAR query.
5431 ** For example, the query:
5433 ** "w" NEAR "x" NEAR "y" NEAR "z"
5435 ** which is represented in tree form as:
5438 ** +--NEAR--+ <-- root of NEAR query
5446 ** The right-hand child of a NEAR node is always a phrase. The
5447 ** left-hand child may be either a phrase or a NEAR node. There are
5448 ** no exceptions to this - it's the way the parser in fts3_expr.c works.
5451 && pExpr
->eType
==FTSQUERY_NEAR
5452 && (pExpr
->pParent
==0 || pExpr
->pParent
->eType
!=FTSQUERY_NEAR
)
5455 sqlite3_int64 nTmp
= 0; /* Bytes of temp space */
5456 char *aTmp
; /* Temp space for PoslistNearMerge() */
5458 /* Allocate temporary working space. */
5459 for(p
=pExpr
; p
->pLeft
; p
=p
->pLeft
){
5460 assert( p
->pRight
->pPhrase
->doclist
.nList
>0 );
5461 nTmp
+= p
->pRight
->pPhrase
->doclist
.nList
;
5463 nTmp
+= p
->pPhrase
->doclist
.nList
;
5464 aTmp
= sqlite3_malloc64(nTmp
*2);
5466 *pRc
= SQLITE_NOMEM
;
5469 char *aPoslist
= p
->pPhrase
->doclist
.pList
;
5470 int nToken
= p
->pPhrase
->nToken
;
5472 for(p
=p
->pParent
;res
&& p
&& p
->eType
==FTSQUERY_NEAR
; p
=p
->pParent
){
5473 Fts3Phrase
*pPhrase
= p
->pRight
->pPhrase
;
5474 int nNear
= p
->nNear
;
5475 res
= fts3EvalNearTrim(nNear
, aTmp
, &aPoslist
, &nToken
, pPhrase
);
5478 aPoslist
= pExpr
->pRight
->pPhrase
->doclist
.pList
;
5479 nToken
= pExpr
->pRight
->pPhrase
->nToken
;
5480 for(p
=pExpr
->pLeft
; p
&& res
; p
=p
->pLeft
){
5482 Fts3Phrase
*pPhrase
;
5483 assert( p
->pParent
&& p
->pParent
->pLeft
==p
);
5484 nNear
= p
->pParent
->nNear
;
5486 p
->eType
==FTSQUERY_NEAR
? p
->pRight
->pPhrase
: p
->pPhrase
5488 res
= fts3EvalNearTrim(nNear
, aTmp
, &aPoslist
, &nToken
, pPhrase
);
5499 ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
5500 ** Assuming no error occurs or has occurred, It returns non-zero if the
5501 ** expression passed as the second argument matches the row that pCsr
5502 ** currently points to, or zero if it does not.
5504 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
5505 ** If an error occurs during execution of this function, *pRc is set to
5506 ** the appropriate SQLite error code. In this case the returned value is
5509 static int fts3EvalTestExpr(
5510 Fts3Cursor
*pCsr
, /* FTS cursor handle */
5511 Fts3Expr
*pExpr
, /* Expr to test. May or may not be root. */
5512 int *pRc
/* IN/OUT: Error code */
5514 int bHit
= 1; /* Return value */
5515 if( *pRc
==SQLITE_OK
){
5516 switch( pExpr
->eType
){
5520 fts3EvalTestExpr(pCsr
, pExpr
->pLeft
, pRc
)
5521 && fts3EvalTestExpr(pCsr
, pExpr
->pRight
, pRc
)
5522 && fts3EvalNearTest(pExpr
, pRc
)
5525 /* If the NEAR expression does not match any rows, zero the doclist for
5526 ** all phrases involved in the NEAR. This is because the snippet(),
5527 ** offsets() and matchinfo() functions are not supposed to recognize
5528 ** any instances of phrases that are part of unmatched NEAR queries.
5529 ** For example if this expression:
5531 ** ... MATCH 'a OR (b NEAR c)'
5533 ** is matched against a row containing:
5537 ** then any snippet() should ony highlight the "a" term, not the "b"
5538 ** (as "b" is part of a non-matching NEAR clause).
5541 && pExpr
->eType
==FTSQUERY_NEAR
5542 && (pExpr
->pParent
==0 || pExpr
->pParent
->eType
!=FTSQUERY_NEAR
)
5545 for(p
=pExpr
; p
->pPhrase
==0; p
=p
->pLeft
){
5546 if( p
->pRight
->iDocid
==pCsr
->iPrevId
){
5547 fts3EvalInvalidatePoslist(p
->pRight
->pPhrase
);
5550 if( p
->iDocid
==pCsr
->iPrevId
){
5551 fts3EvalInvalidatePoslist(p
->pPhrase
);
5558 int bHit1
= fts3EvalTestExpr(pCsr
, pExpr
->pLeft
, pRc
);
5559 int bHit2
= fts3EvalTestExpr(pCsr
, pExpr
->pRight
, pRc
);
5560 bHit
= bHit1
|| bHit2
;
5566 fts3EvalTestExpr(pCsr
, pExpr
->pLeft
, pRc
)
5567 && !fts3EvalTestExpr(pCsr
, pExpr
->pRight
, pRc
)
5572 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
5573 if( pCsr
->pDeferred
&& (pExpr
->bDeferred
|| (
5574 pExpr
->iDocid
==pCsr
->iPrevId
&& pExpr
->pPhrase
->doclist
.pList
5576 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
5577 if( pExpr
->bDeferred
){
5578 fts3EvalInvalidatePoslist(pPhrase
);
5580 *pRc
= fts3EvalDeferredPhrase(pCsr
, pPhrase
);
5581 bHit
= (pPhrase
->doclist
.pList
!=0);
5582 pExpr
->iDocid
= pCsr
->iPrevId
;
5587 pExpr
->bEof
==0 && pExpr
->iDocid
==pCsr
->iPrevId
5588 && pExpr
->pPhrase
->doclist
.nList
>0
5599 ** This function is called as the second part of each xNext operation when
5600 ** iterating through the results of a full-text query. At this point the
5601 ** cursor points to a row that matches the query expression, with the
5602 ** following caveats:
5604 ** * Up until this point, "NEAR" operators in the expression have been
5605 ** treated as "AND".
5607 ** * Deferred tokens have not yet been considered.
5609 ** If *pRc is not SQLITE_OK when this function is called, it immediately
5610 ** returns 0. Otherwise, it tests whether or not after considering NEAR
5611 ** operators and deferred tokens the current row is still a match for the
5612 ** expression. It returns 1 if both of the following are true:
5614 ** 1. *pRc is SQLITE_OK when this function returns, and
5616 ** 2. After scanning the current FTS table row for the deferred tokens,
5617 ** it is determined that the row does *not* match the query.
5619 ** Or, if no error occurs and it seems the current row does match the FTS
5622 int sqlite3Fts3EvalTestDeferred(Fts3Cursor
*pCsr
, int *pRc
){
5625 if( rc
==SQLITE_OK
){
5627 /* If there are one or more deferred tokens, load the current row into
5628 ** memory and scan it to determine the position list for each deferred
5629 ** token. Then, see if this row is really a match, considering deferred
5630 ** tokens and NEAR operators (neither of which were taken into account
5631 ** earlier, by fts3EvalNextRow()).
5633 if( pCsr
->pDeferred
){
5634 rc
= fts3CursorSeek(0, pCsr
);
5635 if( rc
==SQLITE_OK
){
5636 rc
= sqlite3Fts3CacheDeferredDoclists(pCsr
);
5639 bMiss
= (0==fts3EvalTestExpr(pCsr
, pCsr
->pExpr
, &rc
));
5641 /* Free the position-lists accumulated for each deferred token above. */
5642 sqlite3Fts3FreeDeferredDoclists(pCsr
);
5645 return (rc
==SQLITE_OK
&& bMiss
);
5649 ** Advance to the next document that matches the FTS expression in
5650 ** Fts3Cursor.pExpr.
5652 static int fts3EvalNext(Fts3Cursor
*pCsr
){
5653 int rc
= SQLITE_OK
; /* Return Code */
5654 Fts3Expr
*pExpr
= pCsr
->pExpr
;
5655 assert( pCsr
->isEof
==0 );
5660 if( pCsr
->isRequireSeek
==0 ){
5661 sqlite3_reset(pCsr
->pStmt
);
5663 assert( sqlite3_data_count(pCsr
->pStmt
)==0 );
5664 fts3EvalNextRow(pCsr
, pExpr
, &rc
);
5665 pCsr
->isEof
= pExpr
->bEof
;
5666 pCsr
->isRequireSeek
= 1;
5667 pCsr
->isMatchinfoNeeded
= 1;
5668 pCsr
->iPrevId
= pExpr
->iDocid
;
5669 }while( pCsr
->isEof
==0 && sqlite3Fts3EvalTestDeferred(pCsr
, &rc
) );
5672 /* Check if the cursor is past the end of the docid range specified
5673 ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
5674 if( rc
==SQLITE_OK
&& (
5675 (pCsr
->bDesc
==0 && pCsr
->iPrevId
>pCsr
->iMaxDocid
)
5676 || (pCsr
->bDesc
!=0 && pCsr
->iPrevId
<pCsr
->iMinDocid
)
5685 ** Restart interation for expression pExpr so that the next call to
5686 ** fts3EvalNext() visits the first row. Do not allow incremental
5687 ** loading or merging of phrase doclists for this iteration.
5689 ** If *pRc is other than SQLITE_OK when this function is called, it is
5690 ** a no-op. If an error occurs within this function, *pRc is set to an
5691 ** SQLite error code before returning.
5693 static void fts3EvalRestart(
5698 if( pExpr
&& *pRc
==SQLITE_OK
){
5699 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
5702 fts3EvalInvalidatePoslist(pPhrase
);
5703 if( pPhrase
->bIncr
){
5705 for(i
=0; i
<pPhrase
->nToken
; i
++){
5706 Fts3PhraseToken
*pToken
= &pPhrase
->aToken
[i
];
5707 assert( pToken
->pDeferred
==0 );
5708 if( pToken
->pSegcsr
){
5709 sqlite3Fts3MsrIncrRestart(pToken
->pSegcsr
);
5712 *pRc
= fts3EvalPhraseStart(pCsr
, 0, pPhrase
);
5714 pPhrase
->doclist
.pNextDocid
= 0;
5715 pPhrase
->doclist
.iDocid
= 0;
5716 pPhrase
->pOrPoslist
= 0;
5723 fts3EvalRestart(pCsr
, pExpr
->pLeft
, pRc
);
5724 fts3EvalRestart(pCsr
, pExpr
->pRight
, pRc
);
5729 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
5730 ** expression rooted at pExpr, the cursor iterates through all rows matched
5731 ** by pExpr, calling this function for each row. This function increments
5732 ** the values in Fts3Expr.aMI[] according to the position-list currently
5733 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
5734 ** expression nodes.
5736 static void fts3EvalUpdateCounts(Fts3Expr
*pExpr
, int nCol
){
5738 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
5739 if( pPhrase
&& pPhrase
->doclist
.pList
){
5741 char *p
= pPhrase
->doclist
.pList
;
5746 while( 0xFE & (*p
| c
) ){
5747 if( (c
&0x80)==0 ) iCnt
++;
5751 /* aMI[iCol*3 + 1] = Number of occurrences
5752 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
5754 pExpr
->aMI
[iCol
*3 + 1] += iCnt
;
5755 pExpr
->aMI
[iCol
*3 + 2] += (iCnt
>0);
5756 if( *p
==0x00 ) break;
5758 p
+= fts3GetVarint32(p
, &iCol
);
5759 }while( iCol
<nCol
);
5762 fts3EvalUpdateCounts(pExpr
->pLeft
, nCol
);
5763 fts3EvalUpdateCounts(pExpr
->pRight
, nCol
);
5768 ** This is an sqlite3Fts3ExprIterate() callback. If the Fts3Expr.aMI[] array
5769 ** has not yet been allocated, allocate and zero it. Otherwise, just zero
5772 static int fts3AllocateMSI(Fts3Expr
*pExpr
, int iPhrase
, void *pCtx
){
5773 Fts3Table
*pTab
= (Fts3Table
*)pCtx
;
5774 UNUSED_PARAMETER(iPhrase
);
5775 if( pExpr
->aMI
==0 ){
5776 pExpr
->aMI
= (u32
*)sqlite3_malloc64(pTab
->nColumn
* 3 * sizeof(u32
));
5777 if( pExpr
->aMI
==0 ) return SQLITE_NOMEM
;
5779 memset(pExpr
->aMI
, 0, pTab
->nColumn
* 3 * sizeof(u32
));
5784 ** Expression pExpr must be of type FTSQUERY_PHRASE.
5786 ** If it is not already allocated and populated, this function allocates and
5787 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
5788 ** of a NEAR expression, then it also allocates and populates the same array
5789 ** for all other phrases that are part of the NEAR expression.
5791 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
5792 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
5794 static int fts3EvalGatherStats(
5795 Fts3Cursor
*pCsr
, /* Cursor object */
5796 Fts3Expr
*pExpr
/* FTSQUERY_PHRASE expression */
5798 int rc
= SQLITE_OK
; /* Return code */
5800 assert( pExpr
->eType
==FTSQUERY_PHRASE
);
5801 if( pExpr
->aMI
==0 ){
5802 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
5803 Fts3Expr
*pRoot
; /* Root of NEAR expression */
5805 sqlite3_int64 iPrevId
= pCsr
->iPrevId
;
5806 sqlite3_int64 iDocid
;
5809 /* Find the root of the NEAR expression */
5811 while( pRoot
->pParent
5812 && (pRoot
->pParent
->eType
==FTSQUERY_NEAR
|| pRoot
->bDeferred
)
5814 pRoot
= pRoot
->pParent
;
5816 iDocid
= pRoot
->iDocid
;
5818 assert( pRoot
->bStart
);
5820 /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
5821 rc
= sqlite3Fts3ExprIterate(pRoot
, fts3AllocateMSI
, (void*)pTab
);
5822 if( rc
!=SQLITE_OK
) return rc
;
5823 fts3EvalRestart(pCsr
, pRoot
, &rc
);
5825 while( pCsr
->isEof
==0 && rc
==SQLITE_OK
){
5828 /* Ensure the %_content statement is reset. */
5829 if( pCsr
->isRequireSeek
==0 ) sqlite3_reset(pCsr
->pStmt
);
5830 assert( sqlite3_data_count(pCsr
->pStmt
)==0 );
5832 /* Advance to the next document */
5833 fts3EvalNextRow(pCsr
, pRoot
, &rc
);
5834 pCsr
->isEof
= pRoot
->bEof
;
5835 pCsr
->isRequireSeek
= 1;
5836 pCsr
->isMatchinfoNeeded
= 1;
5837 pCsr
->iPrevId
= pRoot
->iDocid
;
5838 }while( pCsr
->isEof
==0
5839 && pRoot
->eType
==FTSQUERY_NEAR
5840 && sqlite3Fts3EvalTestDeferred(pCsr
, &rc
)
5843 if( rc
==SQLITE_OK
&& pCsr
->isEof
==0 ){
5844 fts3EvalUpdateCounts(pRoot
, pTab
->nColumn
);
5849 pCsr
->iPrevId
= iPrevId
;
5854 /* Caution: pRoot may iterate through docids in ascending or descending
5855 ** order. For this reason, even though it seems more defensive, the
5856 ** do loop can not be written:
5858 ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
5860 fts3EvalRestart(pCsr
, pRoot
, &rc
);
5862 fts3EvalNextRow(pCsr
, pRoot
, &rc
);
5863 assert_fts3_nc( pRoot
->bEof
==0 );
5864 if( pRoot
->bEof
) rc
= FTS_CORRUPT_VTAB
;
5865 }while( pRoot
->iDocid
!=iDocid
&& rc
==SQLITE_OK
);
5872 ** This function is used by the matchinfo() module to query a phrase
5873 ** expression node for the following information:
5875 ** 1. The total number of occurrences of the phrase in each column of
5876 ** the FTS table (considering all rows), and
5878 ** 2. For each column, the number of rows in the table for which the
5879 ** column contains at least one instance of the phrase.
5881 ** If no error occurs, SQLITE_OK is returned and the values for each column
5882 ** written into the array aiOut as follows:
5884 ** aiOut[iCol*3 + 1] = Number of occurrences
5885 ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
5889 ** * If a phrase consists entirely of deferred tokens, then all output
5890 ** values are set to the number of documents in the table. In other
5891 ** words we assume that very common tokens occur exactly once in each
5892 ** column of each row of the table.
5894 ** * If a phrase contains some deferred tokens (and some non-deferred
5895 ** tokens), count the potential occurrence identified by considering
5896 ** the non-deferred tokens instead of actual phrase occurrences.
5898 ** * If the phrase is part of a NEAR expression, then only phrase instances
5899 ** that meet the NEAR constraint are included in the counts.
5901 int sqlite3Fts3EvalPhraseStats(
5902 Fts3Cursor
*pCsr
, /* FTS cursor handle */
5903 Fts3Expr
*pExpr
, /* Phrase expression */
5904 u32
*aiOut
/* Array to write results into (see above) */
5906 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
5910 if( pExpr
->bDeferred
&& pExpr
->pParent
->eType
!=FTSQUERY_NEAR
){
5911 assert( pCsr
->nDoc
>0 );
5912 for(iCol
=0; iCol
<pTab
->nColumn
; iCol
++){
5913 aiOut
[iCol
*3 + 1] = (u32
)pCsr
->nDoc
;
5914 aiOut
[iCol
*3 + 2] = (u32
)pCsr
->nDoc
;
5917 rc
= fts3EvalGatherStats(pCsr
, pExpr
);
5918 if( rc
==SQLITE_OK
){
5919 assert( pExpr
->aMI
);
5920 for(iCol
=0; iCol
<pTab
->nColumn
; iCol
++){
5921 aiOut
[iCol
*3 + 1] = pExpr
->aMI
[iCol
*3 + 1];
5922 aiOut
[iCol
*3 + 2] = pExpr
->aMI
[iCol
*3 + 2];
5931 ** The expression pExpr passed as the second argument to this function
5932 ** must be of type FTSQUERY_PHRASE.
5934 ** The returned value is either NULL or a pointer to a buffer containing
5935 ** a position-list indicating the occurrences of the phrase in column iCol
5936 ** of the current row.
5938 ** More specifically, the returned buffer contains 1 varint for each
5939 ** occurrence of the phrase in the column, stored using the normal (delta+2)
5940 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
5941 ** if the requested column contains "a b X c d X X" and the position-list
5942 ** for 'X' is requested, the buffer returned may contain:
5944 ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
5946 ** This function works regardless of whether or not the phrase is deferred,
5947 ** incremental, or neither.
5949 int sqlite3Fts3EvalPhrasePoslist(
5950 Fts3Cursor
*pCsr
, /* FTS3 cursor object */
5951 Fts3Expr
*pExpr
, /* Phrase to return doclist for */
5952 int iCol
, /* Column to return position list for */
5953 char **ppOut
/* OUT: Pointer to position list */
5955 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
5956 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
5959 sqlite3_int64 iDocid
;
5961 /* If this phrase is applies specifically to some column other than
5962 ** column iCol, return a NULL pointer. */
5964 assert( iCol
>=0 && iCol
<pTab
->nColumn
);
5965 if( (pPhrase
->iColumn
<pTab
->nColumn
&& pPhrase
->iColumn
!=iCol
) ){
5969 iDocid
= pExpr
->iDocid
;
5970 pIter
= pPhrase
->doclist
.pList
;
5971 if( iDocid
!=pCsr
->iPrevId
|| pExpr
->bEof
){
5973 int bDescDoclist
= pTab
->bDescIdx
; /* For DOCID_CMP macro */
5976 Fts3Expr
*p
; /* Used to iterate from pExpr to root */
5977 Fts3Expr
*pNear
; /* Most senior NEAR ancestor (or pExpr) */
5978 Fts3Expr
*pRun
; /* Closest non-deferred ancestor of pNear */
5981 /* Check if this phrase descends from an OR expression node. If not,
5982 ** return NULL. Otherwise, the entry that corresponds to docid
5983 ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
5984 ** tree that the node is part of has been marked as EOF, but the node
5985 ** itself is not EOF, then it may point to an earlier entry. */
5987 for(p
=pExpr
->pParent
; p
; p
=p
->pParent
){
5988 if( p
->eType
==FTSQUERY_OR
) bOr
= 1;
5989 if( p
->eType
==FTSQUERY_NEAR
) pNear
= p
;
5990 if( p
->bEof
) bTreeEof
= 1;
5992 if( bOr
==0 ) return SQLITE_OK
;
5994 while( pRun
->bDeferred
){
5995 assert( pRun
->pParent
);
5996 pRun
= pRun
->pParent
;
5999 /* This is the descendent of an OR node. In this case we cannot use
6000 ** an incremental phrase. Load the entire doclist for the phrase
6001 ** into memory in this case. */
6002 if( pPhrase
->bIncr
){
6003 int bEofSave
= pRun
->bEof
;
6004 fts3EvalRestart(pCsr
, pRun
, &rc
);
6005 while( rc
==SQLITE_OK
&& !pRun
->bEof
){
6006 fts3EvalNextRow(pCsr
, pRun
, &rc
);
6007 if( bEofSave
==0 && pRun
->iDocid
==iDocid
) break;
6009 assert( rc
!=SQLITE_OK
|| pPhrase
->bIncr
==0 );
6010 if( rc
==SQLITE_OK
&& pRun
->bEof
!=bEofSave
){
6011 rc
= FTS_CORRUPT_VTAB
;
6015 while( rc
==SQLITE_OK
&& !pRun
->bEof
){
6016 fts3EvalNextRow(pCsr
, pRun
, &rc
);
6019 if( rc
!=SQLITE_OK
) return rc
;
6022 for(p
=pNear
; p
; p
=p
->pLeft
){
6024 Fts3Expr
*pTest
= p
;
6026 assert( pTest
->eType
==FTSQUERY_NEAR
|| pTest
->eType
==FTSQUERY_PHRASE
);
6027 if( pTest
->eType
==FTSQUERY_NEAR
) pTest
= pTest
->pRight
;
6028 assert( pTest
->eType
==FTSQUERY_PHRASE
);
6029 pPh
= pTest
->pPhrase
;
6031 pIter
= pPh
->pOrPoslist
;
6032 iDocid
= pPh
->iOrDocid
;
6033 if( pCsr
->bDesc
==bDescDoclist
){
6034 bEof
= !pPh
->doclist
.nAll
||
6035 (pIter
>= (pPh
->doclist
.aAll
+ pPh
->doclist
.nAll
));
6036 while( (pIter
==0 || DOCID_CMP(iDocid
, pCsr
->iPrevId
)<0 ) && bEof
==0 ){
6037 sqlite3Fts3DoclistNext(
6038 bDescDoclist
, pPh
->doclist
.aAll
, pPh
->doclist
.nAll
,
6039 &pIter
, &iDocid
, &bEof
6043 bEof
= !pPh
->doclist
.nAll
|| (pIter
&& pIter
<=pPh
->doclist
.aAll
);
6044 while( (pIter
==0 || DOCID_CMP(iDocid
, pCsr
->iPrevId
)>0 ) && bEof
==0 ){
6046 sqlite3Fts3DoclistPrev(
6047 bDescDoclist
, pPh
->doclist
.aAll
, pPh
->doclist
.nAll
,
6048 &pIter
, &iDocid
, &dummy
, &bEof
6052 pPh
->pOrPoslist
= pIter
;
6053 pPh
->iOrDocid
= iDocid
;
6054 if( bEof
|| iDocid
!=pCsr
->iPrevId
) bMatch
= 0;
6058 pIter
= pPhrase
->pOrPoslist
;
6063 if( pIter
==0 ) return SQLITE_OK
;
6067 pIter
+= fts3GetVarint32(pIter
, &iThis
);
6071 while( iThis
<iCol
){
6072 fts3ColumnlistCopy(0, &pIter
);
6073 if( *pIter
==0x00 ) return SQLITE_OK
;
6075 pIter
+= fts3GetVarint32(pIter
, &iThis
);
6081 *ppOut
= ((iCol
==iThis
)?pIter
:0);
6086 ** Free all components of the Fts3Phrase structure that were allocated by
6087 ** the eval module. Specifically, this means to free:
6089 ** * the contents of pPhrase->doclist, and
6090 ** * any Fts3MultiSegReader objects held by phrase tokens.
6092 void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase
*pPhrase
){
6095 sqlite3_free(pPhrase
->doclist
.aAll
);
6096 fts3EvalInvalidatePoslist(pPhrase
);
6097 memset(&pPhrase
->doclist
, 0, sizeof(Fts3Doclist
));
6098 for(i
=0; i
<pPhrase
->nToken
; i
++){
6099 fts3SegReaderCursorFree(pPhrase
->aToken
[i
].pSegcsr
);
6100 pPhrase
->aToken
[i
].pSegcsr
= 0;
6107 ** Return SQLITE_CORRUPT_VTAB.
6110 int sqlite3Fts3Corrupt(){
6111 return SQLITE_CORRUPT_VTAB
;
6117 ** Initialize API pointer table, if required.
6120 __declspec(dllexport
)
6122 int sqlite3_fts3_init(
6125 const sqlite3_api_routines
*pApi
6127 SQLITE_EXTENSION_INIT2(pApi
)
6128 return sqlite3Fts3Init(db
);