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 static int fts3EvalNext(Fts3Cursor
*pCsr
);
312 static int fts3EvalStart(Fts3Cursor
*pCsr
);
313 static int fts3TermSegReaderCursor(
314 Fts3Cursor
*, const char *, int, int, Fts3MultiSegReader
**);
317 ** This variable is set to false when running tests for which the on disk
318 ** structures should not be corrupt. Otherwise, true. If it is false, extra
319 ** assert() conditions in the fts3 code are activated - conditions that are
320 ** only true if it is guaranteed that the fts3 database is not corrupt.
323 int sqlite3_fts3_may_be_corrupt
= 1;
327 ** Write a 64-bit variable-length integer to memory starting at p[0].
328 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
329 ** The number of bytes written is returned.
331 int sqlite3Fts3PutVarint(char *p
, sqlite_int64 v
){
332 unsigned char *q
= (unsigned char *) p
;
333 sqlite_uint64 vu
= v
;
335 *q
++ = (unsigned char) ((vu
& 0x7f) | 0x80);
338 q
[-1] &= 0x7f; /* turn off high bit in final byte */
339 assert( q
- (unsigned char *)p
<= FTS3_VARINT_MAX
);
340 return (int) (q
- (unsigned char *)p
);
343 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
344 v = (v & mask1) | ( (*(const unsigned char*)(ptr++)) << shift ); \
345 if( (v & mask2)==0 ){ var = v; return ret; }
346 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
348 if( (v & mask2)==0 ){ var = v; return ret; }
350 int sqlite3Fts3GetVarintU(const char *pBuf
, sqlite_uint64
*v
){
351 const unsigned char *p
= (const unsigned char*)pBuf
;
352 const unsigned char *pStart
= p
;
357 GETVARINT_INIT(a
, p
, 0, 0x00, 0x80, *v
, 1);
358 GETVARINT_STEP(a
, p
, 7, 0x7F, 0x4000, *v
, 2);
359 GETVARINT_STEP(a
, p
, 14, 0x3FFF, 0x200000, *v
, 3);
360 GETVARINT_STEP(a
, p
, 21, 0x1FFFFF, 0x10000000, *v
, 4);
361 b
= (a
& 0x0FFFFFFF );
363 for(shift
=28; shift
<=63; shift
+=7){
365 b
+= (c
&0x7F) << shift
;
366 if( (c
& 0x80)==0 ) break;
369 return (int)(p
- pStart
);
373 ** Read a 64-bit variable-length integer from memory starting at p[0].
374 ** Return the number of bytes read, or 0 on error.
375 ** The value is stored in *v.
377 int sqlite3Fts3GetVarint(const char *pBuf
, sqlite_int64
*v
){
378 return sqlite3Fts3GetVarintU(pBuf
, (sqlite3_uint64
*)v
);
382 ** Read a 64-bit variable-length integer from memory starting at p[0] and
383 ** not extending past pEnd[-1].
384 ** Return the number of bytes read, or 0 on error.
385 ** The value is stored in *v.
387 int sqlite3Fts3GetVarintBounded(
392 const unsigned char *p
= (const unsigned char*)pBuf
;
393 const unsigned char *pStart
= p
;
394 const unsigned char *pX
= (const unsigned char*)pEnd
;
397 for(shift
=0; shift
<=63; shift
+=7){
398 u64 c
= p
<pX
? *p
: 0;
400 b
+= (c
&0x7F) << shift
;
401 if( (c
& 0x80)==0 ) break;
404 return (int)(p
- pStart
);
408 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
409 ** a non-negative 32-bit integer before it is returned.
411 int sqlite3Fts3GetVarint32(const char *p
, int *pi
){
412 const unsigned char *ptr
= (const unsigned char*)p
;
415 #ifndef fts3GetVarint32
416 GETVARINT_INIT(a
, ptr
, 0, 0x00, 0x80, *pi
, 1);
422 GETVARINT_STEP(a
, ptr
, 7, 0x7F, 0x4000, *pi
, 2);
423 GETVARINT_STEP(a
, ptr
, 14, 0x3FFF, 0x200000, *pi
, 3);
424 GETVARINT_STEP(a
, ptr
, 21, 0x1FFFFF, 0x10000000, *pi
, 4);
425 a
= (a
& 0x0FFFFFFF );
426 *pi
= (int)(a
| ((u32
)(*ptr
& 0x07) << 28));
427 assert( 0==(a
& 0x80000000) );
433 ** Return the number of bytes required to encode v as a varint
435 int sqlite3Fts3VarintLen(sqlite3_uint64 v
){
445 ** Convert an SQL-style quoted string into a normal string by removing
446 ** the quote characters. The conversion is done in-place. If the
447 ** input does not begin with a quote character, then this routine
458 void sqlite3Fts3Dequote(char *z
){
459 char quote
; /* Quote character (if any ) */
462 if( quote
=='[' || quote
=='\'' || quote
=='"' || quote
=='`' ){
463 int iIn
= 1; /* Index of next byte to read from input */
464 int iOut
= 0; /* Index of next byte to write to output */
466 /* If the first byte was a '[', then the close-quote character is a ']' */
467 if( quote
=='[' ) quote
= ']';
471 if( z
[iIn
+1]!=quote
) break;
475 z
[iOut
++] = z
[iIn
++];
483 ** Read a single varint from the doclist at *pp and advance *pp to point
484 ** to the first byte past the end of the varint. Add the value of the varint
487 static void fts3GetDeltaVarint(char **pp
, sqlite3_int64
*pVal
){
489 *pp
+= sqlite3Fts3GetVarint(*pp
, &iVal
);
494 ** When this function is called, *pp points to the first byte following a
495 ** varint that is part of a doclist (or position-list, or any other list
496 ** of varints). This function moves *pp to point to the start of that varint,
497 ** and sets *pVal by the varint value.
499 ** Argument pStart points to the first byte of the doclist that the
500 ** varint is part of.
502 static void fts3GetReverseVarint(
510 /* Pointer p now points at the first byte past the varint we are
511 ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
512 ** clear on character p[-1]. */
513 for(p
= (*pp
)-2; p
>=pStart
&& *p
&0x80; p
--);
517 sqlite3Fts3GetVarint(p
, &iVal
);
522 ** The xDisconnect() virtual table method.
524 static int fts3DisconnectMethod(sqlite3_vtab
*pVtab
){
525 Fts3Table
*p
= (Fts3Table
*)pVtab
;
528 assert( p
->nPendingData
==0 );
529 assert( p
->pSegments
==0 );
531 /* Free any prepared statements held */
532 sqlite3_finalize(p
->pSeekStmt
);
533 for(i
=0; i
<SizeofArray(p
->aStmt
); i
++){
534 sqlite3_finalize(p
->aStmt
[i
]);
536 sqlite3_free(p
->zSegmentsTbl
);
537 sqlite3_free(p
->zReadExprlist
);
538 sqlite3_free(p
->zWriteExprlist
);
539 sqlite3_free(p
->zContentTbl
);
540 sqlite3_free(p
->zLanguageid
);
542 /* Invoke the tokenizer destructor to free the tokenizer. */
543 p
->pTokenizer
->pModule
->xDestroy(p
->pTokenizer
);
550 ** Write an error message into *pzErr
552 void sqlite3Fts3ErrMsg(char **pzErr
, const char *zFormat
, ...){
554 sqlite3_free(*pzErr
);
555 va_start(ap
, zFormat
);
556 *pzErr
= sqlite3_vmprintf(zFormat
, ap
);
561 ** Construct one or more SQL statements from the format string given
562 ** and then evaluate those statements. The success code is written
565 ** If *pRc is initially non-zero then this routine is a no-op.
567 static void fts3DbExec(
568 int *pRc
, /* Success code */
569 sqlite3
*db
, /* Database in which to run SQL */
570 const char *zFormat
, /* Format string for SQL */
571 ... /* Arguments to the format string */
576 va_start(ap
, zFormat
);
577 zSql
= sqlite3_vmprintf(zFormat
, ap
);
582 *pRc
= sqlite3_exec(db
, zSql
, 0, 0, 0);
588 ** The xDestroy() virtual table method.
590 static int fts3DestroyMethod(sqlite3_vtab
*pVtab
){
591 Fts3Table
*p
= (Fts3Table
*)pVtab
;
592 int rc
= SQLITE_OK
; /* Return code */
593 const char *zDb
= p
->zDb
; /* Name of database (e.g. "main", "temp") */
594 sqlite3
*db
= p
->db
; /* Database handle */
596 /* Drop the shadow tables */
598 "DROP TABLE IF EXISTS %Q.'%q_segments';"
599 "DROP TABLE IF EXISTS %Q.'%q_segdir';"
600 "DROP TABLE IF EXISTS %Q.'%q_docsize';"
601 "DROP TABLE IF EXISTS %Q.'%q_stat';"
602 "%s DROP TABLE IF EXISTS %Q.'%q_content';",
607 (p
->zContentTbl
? "--" : ""), zDb
,p
->zName
610 /* If everything has worked, invoke fts3DisconnectMethod() to free the
611 ** memory associated with the Fts3Table structure and return SQLITE_OK.
612 ** Otherwise, return an SQLite error code.
614 return (rc
==SQLITE_OK
? fts3DisconnectMethod(pVtab
) : rc
);
619 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
620 ** passed as the first argument. This is done as part of the xConnect()
621 ** and xCreate() methods.
623 ** If *pRc is non-zero when this function is called, it is a no-op.
624 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
627 static void fts3DeclareVtab(int *pRc
, Fts3Table
*p
){
628 if( *pRc
==SQLITE_OK
){
629 int i
; /* Iterator variable */
630 int rc
; /* Return code */
631 char *zSql
; /* SQL statement passed to declare_vtab() */
632 char *zCols
; /* List of user defined columns */
633 const char *zLanguageid
;
635 zLanguageid
= (p
->zLanguageid
? p
->zLanguageid
: "__langid");
636 sqlite3_vtab_config(p
->db
, SQLITE_VTAB_CONSTRAINT_SUPPORT
, 1);
638 /* Create a list of user columns for the virtual table */
639 zCols
= sqlite3_mprintf("%Q, ", p
->azColumn
[0]);
640 for(i
=1; zCols
&& i
<p
->nColumn
; i
++){
641 zCols
= sqlite3_mprintf("%z%Q, ", zCols
, p
->azColumn
[i
]);
644 /* Create the whole "CREATE TABLE" statement to pass to SQLite */
645 zSql
= sqlite3_mprintf(
646 "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
647 zCols
, p
->zName
, zLanguageid
649 if( !zCols
|| !zSql
){
652 rc
= sqlite3_declare_vtab(p
->db
, zSql
);
662 ** Create the %_stat table if it does not already exist.
664 void sqlite3Fts3CreateStatTable(int *pRc
, Fts3Table
*p
){
665 fts3DbExec(pRc
, p
->db
,
666 "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
667 "(id INTEGER PRIMARY KEY, value BLOB);",
670 if( (*pRc
)==SQLITE_OK
) p
->bHasStat
= 1;
674 ** Create the backing store tables (%_content, %_segments and %_segdir)
675 ** required by the FTS3 table passed as the only argument. This is done
676 ** as part of the vtab xCreate() method.
678 ** If the p->bHasDocsize boolean is true (indicating that this is an
679 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
680 ** %_stat tables required by FTS4.
682 static int fts3CreateTables(Fts3Table
*p
){
683 int rc
= SQLITE_OK
; /* Return code */
684 int i
; /* Iterator variable */
685 sqlite3
*db
= p
->db
; /* The database connection */
687 if( p
->zContentTbl
==0 ){
688 const char *zLanguageid
= p
->zLanguageid
;
689 char *zContentCols
; /* Columns of %_content table */
691 /* Create a list of user columns for the content table */
692 zContentCols
= sqlite3_mprintf("docid INTEGER PRIMARY KEY");
693 for(i
=0; zContentCols
&& i
<p
->nColumn
; i
++){
694 char *z
= p
->azColumn
[i
];
695 zContentCols
= sqlite3_mprintf("%z, 'c%d%q'", zContentCols
, i
, z
);
697 if( zLanguageid
&& zContentCols
){
698 zContentCols
= sqlite3_mprintf("%z, langid", zContentCols
, zLanguageid
);
700 if( zContentCols
==0 ) rc
= SQLITE_NOMEM
;
702 /* Create the content table */
704 "CREATE TABLE %Q.'%q_content'(%s)",
705 p
->zDb
, p
->zName
, zContentCols
707 sqlite3_free(zContentCols
);
710 /* Create other tables */
712 "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
716 "CREATE TABLE %Q.'%q_segdir'("
719 "start_block INTEGER,"
720 "leaves_end_block INTEGER,"
723 "PRIMARY KEY(level, idx)"
727 if( p
->bHasDocsize
){
729 "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
733 assert( p
->bHasStat
==p
->bFts4
);
735 sqlite3Fts3CreateStatTable(&rc
, p
);
741 ** Store the current database page-size in bytes in p->nPgsz.
743 ** If *pRc is non-zero when this function is called, it is a no-op.
744 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
747 static void fts3DatabasePageSize(int *pRc
, Fts3Table
*p
){
748 if( *pRc
==SQLITE_OK
){
749 int rc
; /* Return code */
750 char *zSql
; /* SQL text "PRAGMA %Q.page_size" */
751 sqlite3_stmt
*pStmt
; /* Compiled "PRAGMA %Q.page_size" statement */
753 zSql
= sqlite3_mprintf("PRAGMA %Q.page_size", p
->zDb
);
757 rc
= sqlite3_prepare(p
->db
, zSql
, -1, &pStmt
, 0);
760 p
->nPgsz
= sqlite3_column_int(pStmt
, 0);
761 rc
= sqlite3_finalize(pStmt
);
762 }else if( rc
==SQLITE_AUTH
){
767 assert( p
->nPgsz
>0 || rc
!=SQLITE_OK
);
774 ** "Special" FTS4 arguments are column specifications of the following form:
778 ** There may not be whitespace surrounding the "=" character. The <value>
779 ** term may be quoted, but the <key> may not.
781 static int fts3IsSpecialColumn(
787 const char *zCsr
= z
;
790 if( *zCsr
=='\0' ) return 0;
794 *pnKey
= (int)(zCsr
-z
);
795 zValue
= sqlite3_mprintf("%s", &zCsr
[1]);
797 sqlite3Fts3Dequote(zValue
);
804 ** Append the output of a printf() style formatting to an existing string.
806 static void fts3Appendf(
807 int *pRc
, /* IN/OUT: Error code */
808 char **pz
, /* IN/OUT: Pointer to string buffer */
809 const char *zFormat
, /* Printf format string to append */
810 ... /* Arguments for printf format string */
812 if( *pRc
==SQLITE_OK
){
815 va_start(ap
, zFormat
);
816 z
= sqlite3_vmprintf(zFormat
, ap
);
819 char *z2
= sqlite3_mprintf("%s%s", *pz
, z
);
823 if( z
==0 ) *pRc
= SQLITE_NOMEM
;
830 ** Return a copy of input string zInput enclosed in double-quotes (") and
831 ** with all double quote characters escaped. For example:
833 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
835 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
836 ** is the callers responsibility to call sqlite3_free() to release this
839 static char *fts3QuoteId(char const *zInput
){
842 nRet
= 2 + (int)strlen(zInput
)*2 + 1;
843 zRet
= sqlite3_malloc64(nRet
);
848 for(i
=0; zInput
[i
]; i
++){
849 if( zInput
[i
]=='"' ) *(z
++) = '"';
859 ** Return a list of comma separated SQL expressions and a FROM clause that
860 ** could be used in a SELECT statement such as the following:
862 ** SELECT <list of expressions> FROM %_content AS x ...
864 ** to return the docid, followed by each column of text data in order
865 ** from left to write. If parameter zFunc is not NULL, then instead of
866 ** being returned directly each column of text data is passed to an SQL
867 ** function named zFunc first. For example, if zFunc is "unzip" and the
868 ** table has the three user-defined columns "a", "b", and "c", the following
869 ** string is returned:
871 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
873 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
874 ** is the responsibility of the caller to eventually free it.
876 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
877 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
878 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
879 ** no error occurs, *pRc is left unmodified.
881 static char *fts3ReadExprList(Fts3Table
*p
, const char *zFunc
, int *pRc
){
887 if( p
->zContentTbl
==0 ){
891 zFree
= zFunction
= fts3QuoteId(zFunc
);
893 fts3Appendf(pRc
, &zRet
, "docid");
894 for(i
=0; i
<p
->nColumn
; i
++){
895 fts3Appendf(pRc
, &zRet
, ",%s(x.'c%d%q')", zFunction
, i
, p
->azColumn
[i
]);
897 if( p
->zLanguageid
){
898 fts3Appendf(pRc
, &zRet
, ", x.%Q", "langid");
902 fts3Appendf(pRc
, &zRet
, "rowid");
903 for(i
=0; i
<p
->nColumn
; i
++){
904 fts3Appendf(pRc
, &zRet
, ", x.'%q'", p
->azColumn
[i
]);
906 if( p
->zLanguageid
){
907 fts3Appendf(pRc
, &zRet
, ", x.%Q", p
->zLanguageid
);
910 fts3Appendf(pRc
, &zRet
, " FROM '%q'.'%q%s' AS x",
912 (p
->zContentTbl
? p
->zContentTbl
: p
->zName
),
913 (p
->zContentTbl
? "" : "_content")
919 ** Return a list of N comma separated question marks, where N is the number
920 ** of columns in the %_content table (one for the docid plus one for each
921 ** user-defined text column).
923 ** If argument zFunc is not NULL, then all but the first question mark
924 ** is preceded by zFunc and an open bracket, and followed by a closed
925 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
926 ** user-defined text columns, the following string is returned:
928 ** "?, zip(?), zip(?), zip(?)"
930 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
931 ** is the responsibility of the caller to eventually free it.
933 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
934 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
935 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
936 ** no error occurs, *pRc is left unmodified.
938 static char *fts3WriteExprList(Fts3Table
*p
, const char *zFunc
, int *pRc
){
947 zFree
= zFunction
= fts3QuoteId(zFunc
);
949 fts3Appendf(pRc
, &zRet
, "?");
950 for(i
=0; i
<p
->nColumn
; i
++){
951 fts3Appendf(pRc
, &zRet
, ",%s(?)", zFunction
);
953 if( p
->zLanguageid
){
954 fts3Appendf(pRc
, &zRet
, ", ?");
961 ** Buffer z contains a positive integer value encoded as utf-8 text.
962 ** Decode this value and store it in *pnOut, returning the number of bytes
963 ** consumed. If an overflow error occurs return a negative value.
965 int sqlite3Fts3ReadInt(const char *z
, int *pnOut
){
968 for(i
=0; z
[i
]>='0' && z
[i
]<='9'; i
++){
969 iVal
= iVal
*10 + (z
[i
] - '0');
970 if( iVal
>0x7FFFFFFF ) return -1;
977 ** This function interprets the string at (*pp) as a non-negative integer
978 ** value. It reads the integer and sets *pnOut to the value read, then
979 ** sets *pp to point to the byte immediately following the last byte of
980 ** the integer value.
982 ** Only decimal digits ('0'..'9') may be part of an integer value.
984 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
985 ** the output value undefined. Otherwise SQLITE_OK is returned.
987 ** This function is used when parsing the "prefix=" FTS4 parameter.
989 static int fts3GobbleInt(const char **pp
, int *pnOut
){
990 const int MAX_NPREFIX
= 10000000;
991 int nInt
= 0; /* Output value */
993 nByte
= sqlite3Fts3ReadInt(*pp
, &nInt
);
994 if( nInt
>MAX_NPREFIX
){
1006 ** This function is called to allocate an array of Fts3Index structures
1007 ** representing the indexes maintained by the current FTS table. FTS tables
1008 ** always maintain the main "terms" index, but may also maintain one or
1009 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
1010 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
1012 ** Argument zParam is passed the value of the "prefix=" option if one was
1013 ** specified, or NULL otherwise.
1015 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
1016 ** the allocated array. *pnIndex is set to the number of elements in the
1017 ** array. If an error does occur, an SQLite error code is returned.
1019 ** Regardless of whether or not an error is returned, it is the responsibility
1020 ** of the caller to call sqlite3_free() on the output array to free it.
1022 static int fts3PrefixParameter(
1023 const char *zParam
, /* ABC in prefix=ABC parameter to parse */
1024 int *pnIndex
, /* OUT: size of *apIndex[] array */
1025 struct Fts3Index
**apIndex
/* OUT: Array of indexes for this table */
1027 struct Fts3Index
*aIndex
; /* Allocated array */
1028 int nIndex
= 1; /* Number of entries in array */
1030 if( zParam
&& zParam
[0] ){
1033 for(p
=zParam
; *p
; p
++){
1034 if( *p
==',' ) nIndex
++;
1038 aIndex
= sqlite3_malloc64(sizeof(struct Fts3Index
) * nIndex
);
1041 return SQLITE_NOMEM
;
1044 memset(aIndex
, 0, sizeof(struct Fts3Index
) * nIndex
);
1046 const char *p
= zParam
;
1048 for(i
=1; i
<nIndex
; i
++){
1050 if( fts3GobbleInt(&p
, &nPrefix
) ) return SQLITE_ERROR
;
1051 assert( nPrefix
>=0 );
1056 aIndex
[i
].nPrefix
= nPrefix
;
1067 ** This function is called when initializing an FTS4 table that uses the
1068 ** content=xxx option. It determines the number of and names of the columns
1069 ** of the new FTS4 table.
1071 ** The third argument passed to this function is the value passed to the
1072 ** config=xxx option (i.e. "xxx"). This function queries the database for
1073 ** a table of that name. If found, the output variables are populated
1076 ** *pnCol: Set to the number of columns table xxx has,
1078 ** *pnStr: Set to the total amount of space required to store a copy
1079 ** of each columns name, including the nul-terminator.
1081 ** *pazCol: Set to point to an array of *pnCol strings. Each string is
1082 ** the name of the corresponding column in table xxx. The array
1083 ** and its contents are allocated using a single allocation. It
1084 ** is the responsibility of the caller to free this allocation
1085 ** by eventually passing the *pazCol value to sqlite3_free().
1087 ** If the table cannot be found, an error code is returned and the output
1088 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
1089 ** returned (and the output variables are undefined).
1091 static int fts3ContentColumns(
1092 sqlite3
*db
, /* Database handle */
1093 const char *zDb
, /* Name of db (i.e. "main", "temp" etc.) */
1094 const char *zTbl
, /* Name of content table */
1095 const char ***pazCol
, /* OUT: Malloc'd array of column names */
1096 int *pnCol
, /* OUT: Size of array *pazCol */
1097 int *pnStr
, /* OUT: Bytes of string content */
1098 char **pzErr
/* OUT: error message */
1100 int rc
= SQLITE_OK
; /* Return code */
1101 char *zSql
; /* "SELECT *" statement on zTbl */
1102 sqlite3_stmt
*pStmt
= 0; /* Compiled version of zSql */
1104 zSql
= sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb
, zTbl
);
1108 rc
= sqlite3_prepare(db
, zSql
, -1, &pStmt
, 0);
1109 if( rc
!=SQLITE_OK
){
1110 sqlite3Fts3ErrMsg(pzErr
, "%s", sqlite3_errmsg(db
));
1115 if( rc
==SQLITE_OK
){
1116 const char **azCol
; /* Output array */
1117 sqlite3_int64 nStr
= 0; /* Size of all column names (incl. 0x00) */
1118 int nCol
; /* Number of table columns */
1119 int i
; /* Used to iterate through columns */
1121 /* Loop through the returned columns. Set nStr to the number of bytes of
1122 ** space required to store a copy of each column name, including the
1123 ** nul-terminator byte. */
1124 nCol
= sqlite3_column_count(pStmt
);
1125 for(i
=0; i
<nCol
; i
++){
1126 const char *zCol
= sqlite3_column_name(pStmt
, i
);
1127 nStr
+= strlen(zCol
) + 1;
1130 /* Allocate and populate the array to return. */
1131 azCol
= (const char **)sqlite3_malloc64(sizeof(char *) * nCol
+ nStr
);
1135 char *p
= (char *)&azCol
[nCol
];
1136 for(i
=0; i
<nCol
; i
++){
1137 const char *zCol
= sqlite3_column_name(pStmt
, i
);
1138 int n
= (int)strlen(zCol
)+1;
1144 sqlite3_finalize(pStmt
);
1146 /* Set the output variables. */
1156 ** This function is the implementation of both the xConnect and xCreate
1157 ** methods of the FTS3 virtual table.
1159 ** The argv[] array contains the following:
1161 ** argv[0] -> module name ("fts3" or "fts4")
1162 ** argv[1] -> database name
1163 ** argv[2] -> table name
1164 ** argv[...] -> "column name" and other module argument fields.
1166 static int fts3InitVtab(
1167 int isCreate
, /* True for xCreate, false for xConnect */
1168 sqlite3
*db
, /* The SQLite database connection */
1169 void *pAux
, /* Hash table containing tokenizers */
1170 int argc
, /* Number of elements in argv array */
1171 const char * const *argv
, /* xCreate/xConnect argument array */
1172 sqlite3_vtab
**ppVTab
, /* Write the resulting vtab structure here */
1173 char **pzErr
/* Write any error message here */
1175 Fts3Hash
*pHash
= (Fts3Hash
*)pAux
;
1176 Fts3Table
*p
= 0; /* Pointer to allocated vtab */
1177 int rc
= SQLITE_OK
; /* Return code */
1178 int i
; /* Iterator variable */
1179 sqlite3_int64 nByte
; /* Size of allocation used for *p */
1180 int iCol
; /* Column index */
1181 int nString
= 0; /* Bytes required to hold all column names */
1182 int nCol
= 0; /* Number of columns in the FTS table */
1183 char *zCsr
; /* Space for holding column names */
1184 int nDb
; /* Bytes required to hold database name */
1185 int nName
; /* Bytes required to hold table name */
1186 int isFts4
= (argv
[0][3]=='4'); /* True for FTS4, false for FTS3 */
1187 const char **aCol
; /* Array of column names */
1188 sqlite3_tokenizer
*pTokenizer
= 0; /* Tokenizer for this table */
1190 int nIndex
= 0; /* Size of aIndex[] array */
1191 struct Fts3Index
*aIndex
= 0; /* Array of indexes for this table */
1193 /* The results of parsing supported FTS4 key=value options: */
1194 int bNoDocsize
= 0; /* True to omit %_docsize table */
1195 int bDescIdx
= 0; /* True to store descending indexes */
1196 char *zPrefix
= 0; /* Prefix parameter value (or NULL) */
1197 char *zCompress
= 0; /* compress=? parameter (or NULL) */
1198 char *zUncompress
= 0; /* uncompress=? parameter (or NULL) */
1199 char *zContent
= 0; /* content=? parameter (or NULL) */
1200 char *zLanguageid
= 0; /* languageid=? parameter (or NULL) */
1201 char **azNotindexed
= 0; /* The set of notindexed= columns */
1202 int nNotindexed
= 0; /* Size of azNotindexed[] array */
1204 assert( strlen(argv
[0])==4 );
1205 assert( (sqlite3_strnicmp(argv
[0], "fts4", 4)==0 && isFts4
)
1206 || (sqlite3_strnicmp(argv
[0], "fts3", 4)==0 && !isFts4
)
1209 nDb
= (int)strlen(argv
[1]) + 1;
1210 nName
= (int)strlen(argv
[2]) + 1;
1212 nByte
= sizeof(const char *) * (argc
-2);
1213 aCol
= (const char **)sqlite3_malloc64(nByte
);
1215 memset((void*)aCol
, 0, nByte
);
1216 azNotindexed
= (char **)sqlite3_malloc64(nByte
);
1219 memset(azNotindexed
, 0, nByte
);
1221 if( !aCol
|| !azNotindexed
){
1226 /* Loop through all of the arguments passed by the user to the FTS3/4
1227 ** module (i.e. all the column names and special arguments). This loop
1228 ** does the following:
1230 ** + Figures out the number of columns the FTSX table will have, and
1231 ** the number of bytes of space that must be allocated to store copies
1232 ** of the column names.
1234 ** + If there is a tokenizer specification included in the arguments,
1235 ** initializes the tokenizer pTokenizer.
1237 for(i
=3; rc
==SQLITE_OK
&& i
<argc
; i
++){
1238 char const *z
= argv
[i
];
1242 /* Check if this is a tokenizer specification */
1245 && 0==sqlite3_strnicmp(z
, "tokenize", 8)
1246 && 0==sqlite3Fts3IsIdChar(z
[8])
1248 rc
= sqlite3Fts3InitTokenizer(pHash
, &z
[9], &pTokenizer
, pzErr
);
1251 /* Check if it is an FTS4 special argument. */
1252 else if( isFts4
&& fts3IsSpecialColumn(z
, &nKey
, &zVal
) ){
1257 { "matchinfo", 9 }, /* 0 -> MATCHINFO */
1258 { "prefix", 6 }, /* 1 -> PREFIX */
1259 { "compress", 8 }, /* 2 -> COMPRESS */
1260 { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
1261 { "order", 5 }, /* 4 -> ORDER */
1262 { "content", 7 }, /* 5 -> CONTENT */
1263 { "languageid", 10 }, /* 6 -> LANGUAGEID */
1264 { "notindexed", 10 } /* 7 -> NOTINDEXED */
1271 for(iOpt
=0; iOpt
<SizeofArray(aFts4Opt
); iOpt
++){
1272 struct Fts4Option
*pOp
= &aFts4Opt
[iOpt
];
1273 if( nKey
==pOp
->nOpt
&& !sqlite3_strnicmp(z
, pOp
->zOpt
, pOp
->nOpt
) ){
1278 case 0: /* MATCHINFO */
1279 if( strlen(zVal
)!=4 || sqlite3_strnicmp(zVal
, "fts3", 4) ){
1280 sqlite3Fts3ErrMsg(pzErr
, "unrecognized matchinfo: %s", zVal
);
1286 case 1: /* PREFIX */
1287 sqlite3_free(zPrefix
);
1292 case 2: /* COMPRESS */
1293 sqlite3_free(zCompress
);
1298 case 3: /* UNCOMPRESS */
1299 sqlite3_free(zUncompress
);
1305 if( (strlen(zVal
)!=3 || sqlite3_strnicmp(zVal
, "asc", 3))
1306 && (strlen(zVal
)!=4 || sqlite3_strnicmp(zVal
, "desc", 4))
1308 sqlite3Fts3ErrMsg(pzErr
, "unrecognized order: %s", zVal
);
1311 bDescIdx
= (zVal
[0]=='d' || zVal
[0]=='D');
1314 case 5: /* CONTENT */
1315 sqlite3_free(zContent
);
1320 case 6: /* LANGUAGEID */
1322 sqlite3_free(zLanguageid
);
1327 case 7: /* NOTINDEXED */
1328 azNotindexed
[nNotindexed
++] = zVal
;
1333 assert( iOpt
==SizeofArray(aFts4Opt
) );
1334 sqlite3Fts3ErrMsg(pzErr
, "unrecognized parameter: %s", z
);
1342 /* Otherwise, the argument is a column name. */
1344 nString
+= (int)(strlen(z
) + 1);
1349 /* If a content=xxx option was specified, the following:
1351 ** 1. Ignore any compress= and uncompress= options.
1353 ** 2. If no column names were specified as part of the CREATE VIRTUAL
1354 ** TABLE statement, use all columns from the content table.
1356 if( rc
==SQLITE_OK
&& zContent
){
1357 sqlite3_free(zCompress
);
1358 sqlite3_free(zUncompress
);
1362 sqlite3_free((void*)aCol
);
1364 rc
= fts3ContentColumns(db
, argv
[1], zContent
,&aCol
,&nCol
,&nString
,pzErr
);
1366 /* If a languageid= option was specified, remove the language id
1367 ** column from the aCol[] array. */
1368 if( rc
==SQLITE_OK
&& zLanguageid
){
1370 for(j
=0; j
<nCol
; j
++){
1371 if( sqlite3_stricmp(zLanguageid
, aCol
[j
])==0 ){
1373 for(k
=j
; k
<nCol
; k
++) aCol
[k
] = aCol
[k
+1];
1381 if( rc
!=SQLITE_OK
) goto fts3_init_out
;
1384 assert( nString
==0 );
1385 aCol
[0] = "content";
1390 if( pTokenizer
==0 ){
1391 rc
= sqlite3Fts3InitTokenizer(pHash
, "simple", &pTokenizer
, pzErr
);
1392 if( rc
!=SQLITE_OK
) goto fts3_init_out
;
1394 assert( pTokenizer
);
1396 rc
= fts3PrefixParameter(zPrefix
, &nIndex
, &aIndex
);
1397 if( rc
==SQLITE_ERROR
){
1399 sqlite3Fts3ErrMsg(pzErr
, "error parsing prefix parameter: %s", zPrefix
);
1401 if( rc
!=SQLITE_OK
) goto fts3_init_out
;
1403 /* Allocate and populate the Fts3Table structure. */
1404 nByte
= sizeof(Fts3Table
) + /* Fts3Table */
1405 nCol
* sizeof(char *) + /* azColumn */
1406 nIndex
* sizeof(struct Fts3Index
) + /* aIndex */
1407 nCol
* sizeof(u8
) + /* abNotindexed */
1410 nString
; /* Space for azColumn strings */
1411 p
= (Fts3Table
*)sqlite3_malloc64(nByte
);
1416 memset(p
, 0, nByte
);
1419 p
->nPendingData
= 0;
1420 p
->azColumn
= (char **)&p
[1];
1421 p
->pTokenizer
= pTokenizer
;
1422 p
->nMaxPendingData
= FTS3_MAX_PENDING_DATA
;
1423 p
->bHasDocsize
= (isFts4
&& bNoDocsize
==0);
1424 p
->bHasStat
= (u8
)isFts4
;
1425 p
->bFts4
= (u8
)isFts4
;
1426 p
->bDescIdx
= (u8
)bDescIdx
;
1427 p
->nAutoincrmerge
= 0xff; /* 0xff means setting unknown */
1428 p
->zContentTbl
= zContent
;
1429 p
->zLanguageid
= zLanguageid
;
1432 TESTONLY( p
->inTransaction
= -1 );
1433 TESTONLY( p
->mxSavepoint
= -1 );
1435 p
->aIndex
= (struct Fts3Index
*)&p
->azColumn
[nCol
];
1436 memcpy(p
->aIndex
, aIndex
, sizeof(struct Fts3Index
) * nIndex
);
1438 for(i
=0; i
<nIndex
; i
++){
1439 fts3HashInit(&p
->aIndex
[i
].hPending
, FTS3_HASH_STRING
, 1);
1441 p
->abNotindexed
= (u8
*)&p
->aIndex
[nIndex
];
1443 /* Fill in the zName and zDb fields of the vtab structure. */
1444 zCsr
= (char *)&p
->abNotindexed
[nCol
];
1446 memcpy(zCsr
, argv
[2], nName
);
1449 memcpy(zCsr
, argv
[1], nDb
);
1452 /* Fill in the azColumn array */
1453 for(iCol
=0; iCol
<nCol
; iCol
++){
1456 z
= (char *)sqlite3Fts3NextToken(aCol
[iCol
], &n
);
1461 sqlite3Fts3Dequote(zCsr
);
1462 p
->azColumn
[iCol
] = zCsr
;
1464 assert( zCsr
<= &((char *)p
)[nByte
] );
1467 /* Fill in the abNotindexed array */
1468 for(iCol
=0; iCol
<nCol
; iCol
++){
1469 int n
= (int)strlen(p
->azColumn
[iCol
]);
1470 for(i
=0; i
<nNotindexed
; i
++){
1471 char *zNot
= azNotindexed
[i
];
1472 if( zNot
&& n
==(int)strlen(zNot
)
1473 && 0==sqlite3_strnicmp(p
->azColumn
[iCol
], zNot
, n
)
1475 p
->abNotindexed
[iCol
] = 1;
1477 azNotindexed
[i
] = 0;
1481 for(i
=0; i
<nNotindexed
; i
++){
1482 if( azNotindexed
[i
] ){
1483 sqlite3Fts3ErrMsg(pzErr
, "no such column: %s", azNotindexed
[i
]);
1488 if( rc
==SQLITE_OK
&& (zCompress
==0)!=(zUncompress
==0) ){
1489 char const *zMiss
= (zCompress
==0 ? "compress" : "uncompress");
1491 sqlite3Fts3ErrMsg(pzErr
, "missing %s parameter in fts4 constructor", zMiss
);
1493 p
->zReadExprlist
= fts3ReadExprList(p
, zUncompress
, &rc
);
1494 p
->zWriteExprlist
= fts3WriteExprList(p
, zCompress
, &rc
);
1495 if( rc
!=SQLITE_OK
) goto fts3_init_out
;
1497 /* If this is an xCreate call, create the underlying tables in the
1498 ** database. TODO: For xConnect(), it could verify that said tables exist.
1501 rc
= fts3CreateTables(p
);
1504 /* Check to see if a legacy fts3 table has been "upgraded" by the
1505 ** addition of a %_stat table so that it can use incremental merge.
1507 if( !isFts4
&& !isCreate
){
1511 /* Figure out the page-size for the database. This is required in order to
1512 ** estimate the cost of loading large doclists from the database. */
1513 fts3DatabasePageSize(&rc
, p
);
1514 p
->nNodeSize
= p
->nPgsz
-35;
1516 #if defined(SQLITE_DEBUG)||defined(SQLITE_TEST)
1517 p
->nMergeCount
= FTS3_MERGE_COUNT
;
1520 /* Declare the table schema to SQLite. */
1521 fts3DeclareVtab(&rc
, p
);
1524 sqlite3_free(zPrefix
);
1525 sqlite3_free(aIndex
);
1526 sqlite3_free(zCompress
);
1527 sqlite3_free(zUncompress
);
1528 sqlite3_free(zContent
);
1529 sqlite3_free(zLanguageid
);
1530 for(i
=0; i
<nNotindexed
; i
++) sqlite3_free(azNotindexed
[i
]);
1531 sqlite3_free((void *)aCol
);
1532 sqlite3_free((void *)azNotindexed
);
1533 if( rc
!=SQLITE_OK
){
1535 fts3DisconnectMethod((sqlite3_vtab
*)p
);
1536 }else if( pTokenizer
){
1537 pTokenizer
->pModule
->xDestroy(pTokenizer
);
1540 assert( p
->pSegments
==0 );
1547 ** The xConnect() and xCreate() methods for the virtual table. All the
1548 ** work is done in function fts3InitVtab().
1550 static int fts3ConnectMethod(
1551 sqlite3
*db
, /* Database connection */
1552 void *pAux
, /* Pointer to tokenizer hash table */
1553 int argc
, /* Number of elements in argv array */
1554 const char * const *argv
, /* xCreate/xConnect argument array */
1555 sqlite3_vtab
**ppVtab
, /* OUT: New sqlite3_vtab object */
1556 char **pzErr
/* OUT: sqlite3_malloc'd error message */
1558 return fts3InitVtab(0, db
, pAux
, argc
, argv
, ppVtab
, pzErr
);
1560 static int fts3CreateMethod(
1561 sqlite3
*db
, /* Database connection */
1562 void *pAux
, /* Pointer to tokenizer hash table */
1563 int argc
, /* Number of elements in argv array */
1564 const char * const *argv
, /* xCreate/xConnect argument array */
1565 sqlite3_vtab
**ppVtab
, /* OUT: New sqlite3_vtab object */
1566 char **pzErr
/* OUT: sqlite3_malloc'd error message */
1568 return fts3InitVtab(1, db
, pAux
, argc
, argv
, ppVtab
, pzErr
);
1572 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
1573 ** extension is currently being used by a version of SQLite too old to
1574 ** support estimatedRows. In that case this function is a no-op.
1576 static void fts3SetEstimatedRows(sqlite3_index_info
*pIdxInfo
, i64 nRow
){
1577 #if SQLITE_VERSION_NUMBER>=3008002
1578 if( sqlite3_libversion_number()>=3008002 ){
1579 pIdxInfo
->estimatedRows
= nRow
;
1585 ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
1586 ** extension is currently being used by a version of SQLite too old to
1587 ** support index-info flags. In that case this function is a no-op.
1589 static void fts3SetUniqueFlag(sqlite3_index_info
*pIdxInfo
){
1590 #if SQLITE_VERSION_NUMBER>=3008012
1591 if( sqlite3_libversion_number()>=3008012 ){
1592 pIdxInfo
->idxFlags
|= SQLITE_INDEX_SCAN_UNIQUE
;
1598 ** Implementation of the xBestIndex method for FTS3 tables. There
1599 ** are three possible strategies, in order of preference:
1601 ** 1. Direct lookup by rowid or docid.
1602 ** 2. Full-text search using a MATCH operator on a non-docid column.
1603 ** 3. Linear scan of %_content table.
1605 static int fts3BestIndexMethod(sqlite3_vtab
*pVTab
, sqlite3_index_info
*pInfo
){
1606 Fts3Table
*p
= (Fts3Table
*)pVTab
;
1607 int i
; /* Iterator variable */
1608 int iCons
= -1; /* Index of constraint to use */
1610 int iLangidCons
= -1; /* Index of langid=x constraint, if present */
1611 int iDocidGe
= -1; /* Index of docid>=x constraint, if present */
1612 int iDocidLe
= -1; /* Index of docid<=x constraint, if present */
1616 return SQLITE_ERROR
;
1619 /* By default use a full table scan. This is an expensive option,
1620 ** so search through the constraints to see if a more efficient
1621 ** strategy is possible.
1623 pInfo
->idxNum
= FTS3_FULLSCAN_SEARCH
;
1624 pInfo
->estimatedCost
= 5000000;
1625 for(i
=0; i
<pInfo
->nConstraint
; i
++){
1626 int bDocid
; /* True if this constraint is on docid */
1627 struct sqlite3_index_constraint
*pCons
= &pInfo
->aConstraint
[i
];
1628 if( pCons
->usable
==0 ){
1629 if( pCons
->op
==SQLITE_INDEX_CONSTRAINT_MATCH
){
1630 /* There exists an unusable MATCH constraint. This means that if
1631 ** the planner does elect to use the results of this call as part
1632 ** of the overall query plan the user will see an "unable to use
1633 ** function MATCH in the requested context" error. To discourage
1634 ** this, return a very high cost here. */
1635 pInfo
->idxNum
= FTS3_FULLSCAN_SEARCH
;
1636 pInfo
->estimatedCost
= 1e50
;
1637 fts3SetEstimatedRows(pInfo
, ((sqlite3_int64
)1) << 50);
1643 bDocid
= (pCons
->iColumn
<0 || pCons
->iColumn
==p
->nColumn
+1);
1645 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
1646 if( iCons
<0 && pCons
->op
==SQLITE_INDEX_CONSTRAINT_EQ
&& bDocid
){
1647 pInfo
->idxNum
= FTS3_DOCID_SEARCH
;
1648 pInfo
->estimatedCost
= 1.0;
1652 /* A MATCH constraint. Use a full-text search.
1654 ** If there is more than one MATCH constraint available, use the first
1655 ** one encountered. If there is both a MATCH constraint and a direct
1656 ** rowid/docid lookup, prefer the MATCH strategy. This is done even
1657 ** though the rowid/docid lookup is faster than a MATCH query, selecting
1658 ** it would lead to an "unable to use function MATCH in the requested
1661 if( pCons
->op
==SQLITE_INDEX_CONSTRAINT_MATCH
1662 && pCons
->iColumn
>=0 && pCons
->iColumn
<=p
->nColumn
1664 pInfo
->idxNum
= FTS3_FULLTEXT_SEARCH
+ pCons
->iColumn
;
1665 pInfo
->estimatedCost
= 2.0;
1669 /* Equality constraint on the langid column */
1670 if( pCons
->op
==SQLITE_INDEX_CONSTRAINT_EQ
1671 && pCons
->iColumn
==p
->nColumn
+ 2
1677 switch( pCons
->op
){
1678 case SQLITE_INDEX_CONSTRAINT_GE
:
1679 case SQLITE_INDEX_CONSTRAINT_GT
:
1683 case SQLITE_INDEX_CONSTRAINT_LE
:
1684 case SQLITE_INDEX_CONSTRAINT_LT
:
1691 /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
1692 if( pInfo
->idxNum
==FTS3_DOCID_SEARCH
) fts3SetUniqueFlag(pInfo
);
1696 pInfo
->aConstraintUsage
[iCons
].argvIndex
= iIdx
++;
1697 pInfo
->aConstraintUsage
[iCons
].omit
= 1;
1699 if( iLangidCons
>=0 ){
1700 pInfo
->idxNum
|= FTS3_HAVE_LANGID
;
1701 pInfo
->aConstraintUsage
[iLangidCons
].argvIndex
= iIdx
++;
1704 pInfo
->idxNum
|= FTS3_HAVE_DOCID_GE
;
1705 pInfo
->aConstraintUsage
[iDocidGe
].argvIndex
= iIdx
++;
1708 pInfo
->idxNum
|= FTS3_HAVE_DOCID_LE
;
1709 pInfo
->aConstraintUsage
[iDocidLe
].argvIndex
= iIdx
++;
1712 /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
1713 ** docid) order. Both ascending and descending are possible.
1715 if( pInfo
->nOrderBy
==1 ){
1716 struct sqlite3_index_orderby
*pOrder
= &pInfo
->aOrderBy
[0];
1717 if( pOrder
->iColumn
<0 || pOrder
->iColumn
==p
->nColumn
+1 ){
1719 pInfo
->idxStr
= "DESC";
1721 pInfo
->idxStr
= "ASC";
1723 pInfo
->orderByConsumed
= 1;
1727 assert( p
->pSegments
==0 );
1732 ** Implementation of xOpen method.
1734 static int fts3OpenMethod(sqlite3_vtab
*pVTab
, sqlite3_vtab_cursor
**ppCsr
){
1735 sqlite3_vtab_cursor
*pCsr
; /* Allocated cursor */
1737 UNUSED_PARAMETER(pVTab
);
1739 /* Allocate a buffer large enough for an Fts3Cursor structure. If the
1740 ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
1741 ** if the allocation fails, return SQLITE_NOMEM.
1743 *ppCsr
= pCsr
= (sqlite3_vtab_cursor
*)sqlite3_malloc(sizeof(Fts3Cursor
));
1745 return SQLITE_NOMEM
;
1747 memset(pCsr
, 0, sizeof(Fts3Cursor
));
1752 ** Finalize the statement handle at pCsr->pStmt.
1754 ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
1755 ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
1756 ** pointer there instead of finalizing it.
1758 static void fts3CursorFinalizeStmt(Fts3Cursor
*pCsr
){
1759 if( pCsr
->bSeekStmt
){
1760 Fts3Table
*p
= (Fts3Table
*)pCsr
->base
.pVtab
;
1761 if( p
->pSeekStmt
==0 ){
1762 p
->pSeekStmt
= pCsr
->pStmt
;
1763 sqlite3_reset(pCsr
->pStmt
);
1766 pCsr
->bSeekStmt
= 0;
1768 sqlite3_finalize(pCsr
->pStmt
);
1772 ** Free all resources currently held by the cursor passed as the only
1775 static void fts3ClearCursor(Fts3Cursor
*pCsr
){
1776 fts3CursorFinalizeStmt(pCsr
);
1777 sqlite3Fts3FreeDeferredTokens(pCsr
);
1778 sqlite3_free(pCsr
->aDoclist
);
1779 sqlite3Fts3MIBufferFree(pCsr
->pMIBuffer
);
1780 sqlite3Fts3ExprFree(pCsr
->pExpr
);
1781 memset(&(&pCsr
->base
)[1], 0, sizeof(Fts3Cursor
)-sizeof(sqlite3_vtab_cursor
));
1785 ** Close the cursor. For additional information see the documentation
1786 ** on the xClose method of the virtual table interface.
1788 static int fts3CloseMethod(sqlite3_vtab_cursor
*pCursor
){
1789 Fts3Cursor
*pCsr
= (Fts3Cursor
*)pCursor
;
1790 assert( ((Fts3Table
*)pCsr
->base
.pVtab
)->pSegments
==0 );
1791 fts3ClearCursor(pCsr
);
1792 assert( ((Fts3Table
*)pCsr
->base
.pVtab
)->pSegments
==0 );
1798 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
1799 ** compose and prepare an SQL statement of the form:
1801 ** "SELECT <columns> FROM %_content WHERE rowid = ?"
1803 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
1804 ** it. If an error occurs, return an SQLite error code.
1806 static int fts3CursorSeekStmt(Fts3Cursor
*pCsr
){
1808 if( pCsr
->pStmt
==0 ){
1809 Fts3Table
*p
= (Fts3Table
*)pCsr
->base
.pVtab
;
1812 pCsr
->pStmt
= p
->pSeekStmt
;
1815 zSql
= sqlite3_mprintf("SELECT %s WHERE rowid = ?", p
->zReadExprlist
);
1816 if( !zSql
) return SQLITE_NOMEM
;
1818 rc
= sqlite3_prepare_v3(
1819 p
->db
, zSql
,-1,SQLITE_PREPARE_PERSISTENT
,&pCsr
->pStmt
,0
1824 if( rc
==SQLITE_OK
) pCsr
->bSeekStmt
= 1;
1830 ** Position the pCsr->pStmt statement so that it is on the row
1831 ** of the %_content table that contains the last match. Return
1832 ** SQLITE_OK on success.
1834 static int fts3CursorSeek(sqlite3_context
*pContext
, Fts3Cursor
*pCsr
){
1836 if( pCsr
->isRequireSeek
){
1837 rc
= fts3CursorSeekStmt(pCsr
);
1838 if( rc
==SQLITE_OK
){
1839 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
1841 sqlite3_bind_int64(pCsr
->pStmt
, 1, pCsr
->iPrevId
);
1842 pCsr
->isRequireSeek
= 0;
1843 if( SQLITE_ROW
==sqlite3_step(pCsr
->pStmt
) ){
1848 rc
= sqlite3_reset(pCsr
->pStmt
);
1849 if( rc
==SQLITE_OK
&& ((Fts3Table
*)pCsr
->base
.pVtab
)->zContentTbl
==0 ){
1850 /* If no row was found and no error has occurred, then the %_content
1851 ** table is missing a row that is present in the full-text index.
1852 ** The data structures are corrupt. */
1853 rc
= FTS_CORRUPT_VTAB
;
1860 if( rc
!=SQLITE_OK
&& pContext
){
1861 sqlite3_result_error_code(pContext
, rc
);
1867 ** This function is used to process a single interior node when searching
1868 ** a b-tree for a term or term prefix. The node data is passed to this
1869 ** function via the zNode/nNode parameters. The term to search for is
1870 ** passed in zTerm/nTerm.
1872 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
1873 ** of the child node that heads the sub-tree that may contain the term.
1875 ** If piLast is not NULL, then *piLast is set to the right-most child node
1876 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
1879 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
1881 static int fts3ScanInteriorNode(
1882 const char *zTerm
, /* Term to select leaves for */
1883 int nTerm
, /* Size of term zTerm in bytes */
1884 const char *zNode
, /* Buffer containing segment interior node */
1885 int nNode
, /* Size of buffer at zNode */
1886 sqlite3_int64
*piFirst
, /* OUT: Selected child node */
1887 sqlite3_int64
*piLast
/* OUT: Selected child node */
1889 int rc
= SQLITE_OK
; /* Return code */
1890 const char *zCsr
= zNode
; /* Cursor to iterate through node */
1891 const char *zEnd
= &zCsr
[nNode
];/* End of interior node buffer */
1892 char *zBuffer
= 0; /* Buffer to load terms into */
1893 i64 nAlloc
= 0; /* Size of allocated buffer */
1894 int isFirstTerm
= 1; /* True when processing first term on page */
1895 u64 iChild
; /* Block id of child node to descend to */
1896 int nBuffer
= 0; /* Total term size */
1898 /* Skip over the 'height' varint that occurs at the start of every
1899 ** interior node. Then load the blockid of the left-child of the b-tree
1900 ** node into variable iChild.
1902 ** Even if the data structure on disk is corrupted, this (reading two
1903 ** varints from the buffer) does not risk an overread. If zNode is a
1904 ** root node, then the buffer comes from a SELECT statement. SQLite does
1905 ** not make this guarantee explicitly, but in practice there are always
1906 ** either more than 20 bytes of allocated space following the nNode bytes of
1907 ** contents, or two zero bytes. Or, if the node is read from the %_segments
1908 ** table, then there are always 20 bytes of zeroed padding following the
1909 ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
1911 zCsr
+= sqlite3Fts3GetVarintU(zCsr
, &iChild
);
1912 zCsr
+= sqlite3Fts3GetVarintU(zCsr
, &iChild
);
1914 return FTS_CORRUPT_VTAB
;
1917 while( zCsr
<zEnd
&& (piFirst
|| piLast
) ){
1918 int cmp
; /* memcmp() result */
1919 int nSuffix
; /* Size of term suffix */
1920 int nPrefix
= 0; /* Size of term prefix */
1922 /* Load the next term on the node into zBuffer. Use realloc() to expand
1923 ** the size of zBuffer if required. */
1925 zCsr
+= fts3GetVarint32(zCsr
, &nPrefix
);
1926 if( nPrefix
>nBuffer
){
1927 rc
= FTS_CORRUPT_VTAB
;
1932 zCsr
+= fts3GetVarint32(zCsr
, &nSuffix
);
1934 assert( nPrefix
>=0 && nSuffix
>=0 );
1935 if( nPrefix
>zCsr
-zNode
|| nSuffix
>zEnd
-zCsr
|| nSuffix
==0 ){
1936 rc
= FTS_CORRUPT_VTAB
;
1939 if( (i64
)nPrefix
+nSuffix
>nAlloc
){
1941 nAlloc
= ((i64
)nPrefix
+nSuffix
) * 2;
1942 zNew
= (char *)sqlite3_realloc64(zBuffer
, nAlloc
);
1950 memcpy(&zBuffer
[nPrefix
], zCsr
, nSuffix
);
1951 nBuffer
= nPrefix
+ nSuffix
;
1954 /* Compare the term we are searching for with the term just loaded from
1955 ** the interior node. If the specified term is greater than or equal
1956 ** to the term from the interior node, then all terms on the sub-tree
1957 ** headed by node iChild are smaller than zTerm. No need to search
1960 ** If the interior node term is larger than the specified term, then
1961 ** the tree headed by iChild may contain the specified term.
1963 cmp
= memcmp(zTerm
, zBuffer
, (nBuffer
>nTerm
? nTerm
: nBuffer
));
1964 if( piFirst
&& (cmp
<0 || (cmp
==0 && nBuffer
>nTerm
)) ){
1965 *piFirst
= (i64
)iChild
;
1969 if( piLast
&& cmp
<0 ){
1970 *piLast
= (i64
)iChild
;
1977 if( piFirst
) *piFirst
= (i64
)iChild
;
1978 if( piLast
) *piLast
= (i64
)iChild
;
1981 sqlite3_free(zBuffer
);
1987 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
1988 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
1989 ** contains a term. This function searches the sub-tree headed by the zNode
1990 ** node for the range of leaf nodes that may contain the specified term
1991 ** or terms for which the specified term is a prefix.
1993 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
1994 ** left-most leaf node in the tree that may contain the specified term.
1995 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
1996 ** right-most leaf node that may contain a term for which the specified
1997 ** term is a prefix.
1999 ** It is possible that the range of returned leaf nodes does not contain
2000 ** the specified term or any terms for which it is a prefix. However, if the
2001 ** segment does contain any such terms, they are stored within the identified
2002 ** range. Because this function only inspects interior segment nodes (and
2003 ** never loads leaf nodes into memory), it is not possible to be sure.
2005 ** If an error occurs, an error code other than SQLITE_OK is returned.
2007 static int fts3SelectLeaf(
2008 Fts3Table
*p
, /* Virtual table handle */
2009 const char *zTerm
, /* Term to select leaves for */
2010 int nTerm
, /* Size of term zTerm in bytes */
2011 const char *zNode
, /* Buffer containing segment interior node */
2012 int nNode
, /* Size of buffer at zNode */
2013 sqlite3_int64
*piLeaf
, /* Selected leaf node */
2014 sqlite3_int64
*piLeaf2
/* Selected leaf node */
2016 int rc
= SQLITE_OK
; /* Return code */
2017 int iHeight
; /* Height of this node in tree */
2019 assert( piLeaf
|| piLeaf2
);
2021 fts3GetVarint32(zNode
, &iHeight
);
2022 rc
= fts3ScanInteriorNode(zTerm
, nTerm
, zNode
, nNode
, piLeaf
, piLeaf2
);
2023 assert_fts3_nc( !piLeaf2
|| !piLeaf
|| rc
!=SQLITE_OK
|| (*piLeaf
<=*piLeaf2
) );
2025 if( rc
==SQLITE_OK
&& iHeight
>1 ){
2026 char *zBlob
= 0; /* Blob read from %_segments table */
2027 int nBlob
= 0; /* Size of zBlob in bytes */
2029 if( piLeaf
&& piLeaf2
&& (*piLeaf
!=*piLeaf2
) ){
2030 rc
= sqlite3Fts3ReadBlock(p
, *piLeaf
, &zBlob
, &nBlob
, 0);
2031 if( rc
==SQLITE_OK
){
2032 rc
= fts3SelectLeaf(p
, zTerm
, nTerm
, zBlob
, nBlob
, piLeaf
, 0);
2034 sqlite3_free(zBlob
);
2039 if( rc
==SQLITE_OK
){
2040 rc
= sqlite3Fts3ReadBlock(p
, piLeaf
?*piLeaf
:*piLeaf2
, &zBlob
, &nBlob
, 0);
2042 if( rc
==SQLITE_OK
){
2044 fts3GetVarint32(zBlob
, &iNewHeight
);
2045 if( iNewHeight
>=iHeight
){
2046 rc
= FTS_CORRUPT_VTAB
;
2048 rc
= fts3SelectLeaf(p
, zTerm
, nTerm
, zBlob
, nBlob
, piLeaf
, piLeaf2
);
2051 sqlite3_free(zBlob
);
2058 ** This function is used to create delta-encoded serialized lists of FTS3
2059 ** varints. Each call to this function appends a single varint to a list.
2061 static void fts3PutDeltaVarint(
2062 char **pp
, /* IN/OUT: Output pointer */
2063 sqlite3_int64
*piPrev
, /* IN/OUT: Previous value written to list */
2064 sqlite3_int64 iVal
/* Write this value to the list */
2066 assert_fts3_nc( iVal
-*piPrev
> 0 || (*piPrev
==0 && iVal
==0) );
2067 *pp
+= sqlite3Fts3PutVarint(*pp
, iVal
-*piPrev
);
2072 ** When this function is called, *ppPoslist is assumed to point to the
2073 ** start of a position-list. After it returns, *ppPoslist points to the
2074 ** first byte after the position-list.
2076 ** A position list is list of positions (delta encoded) and columns for
2077 ** a single document record of a doclist. So, in other words, this
2078 ** routine advances *ppPoslist so that it points to the next docid in
2079 ** the doclist, or to the first byte past the end of the doclist.
2081 ** If pp is not NULL, then the contents of the position list are copied
2082 ** to *pp. *pp is set to point to the first byte past the last byte copied
2083 ** before this function returns.
2085 static void fts3PoslistCopy(char **pp
, char **ppPoslist
){
2086 char *pEnd
= *ppPoslist
;
2089 /* The end of a position list is marked by a zero encoded as an FTS3
2090 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
2091 ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
2092 ** of some other, multi-byte, value.
2094 ** The following while-loop moves pEnd to point to the first byte that is not
2095 ** immediately preceded by a byte with the 0x80 bit set. Then increments
2096 ** pEnd once more so that it points to the byte immediately following the
2097 ** last byte in the position-list.
2101 testcase( c
!=0 && (*pEnd
)==0 );
2103 pEnd
++; /* Advance past the POS_END terminator byte */
2106 int n
= (int)(pEnd
- *ppPoslist
);
2108 memcpy(p
, *ppPoslist
, n
);
2116 ** When this function is called, *ppPoslist is assumed to point to the
2117 ** start of a column-list. After it returns, *ppPoslist points to the
2118 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
2120 ** A column-list is list of delta-encoded positions for a single column
2121 ** within a single document within a doclist.
2123 ** The column-list is terminated either by a POS_COLUMN varint (1) or
2124 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
2125 ** the POS_COLUMN or POS_END that terminates the column-list.
2127 ** If pp is not NULL, then the contents of the column-list are copied
2128 ** to *pp. *pp is set to point to the first byte past the last byte copied
2129 ** before this function returns. The POS_COLUMN or POS_END terminator
2130 ** is not copied into *pp.
2132 static void fts3ColumnlistCopy(char **pp
, char **ppPoslist
){
2133 char *pEnd
= *ppPoslist
;
2136 /* A column-list is terminated by either a 0x01 or 0x00 byte that is
2137 ** not part of a multi-byte varint.
2139 while( 0xFE & (*pEnd
| c
) ){
2141 testcase( c
!=0 && ((*pEnd
)&0xfe)==0 );
2144 int n
= (int)(pEnd
- *ppPoslist
);
2146 memcpy(p
, *ppPoslist
, n
);
2154 ** Value used to signify the end of an position-list. This must be
2155 ** as large or larger than any value that might appear on the
2156 ** position-list, even a position list that has been corrupted.
2158 #define POSITION_LIST_END LARGEST_INT64
2161 ** This function is used to help parse position-lists. When this function is
2162 ** called, *pp may point to the start of the next varint in the position-list
2163 ** being parsed, or it may point to 1 byte past the end of the position-list
2164 ** (in which case **pp will be a terminator bytes POS_END (0) or
2167 ** If *pp points past the end of the current position-list, set *pi to
2168 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
2169 ** increment the current value of *pi by the value read, and set *pp to
2170 ** point to the next value before returning.
2172 ** Before calling this routine *pi must be initialized to the value of
2173 ** the previous position, or zero if we are reading the first position
2174 ** in the position-list. Because positions are delta-encoded, the value
2175 ** of the previous position is needed in order to compute the value of
2176 ** the next position.
2178 static void fts3ReadNextPos(
2179 char **pp
, /* IN/OUT: Pointer into position-list buffer */
2180 sqlite3_int64
*pi
/* IN/OUT: Value read from position-list */
2184 *pp
+= fts3GetVarint32((*pp
), &iVal
);
2188 *pi
= POSITION_LIST_END
;
2193 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
2194 ** the value of iCol encoded as a varint to *pp. This will start a new
2197 ** Set *pp to point to the byte just after the last byte written before
2198 ** returning (do not modify it if iCol==0). Return the total number of bytes
2199 ** written (0 if iCol==0).
2201 static int fts3PutColNumber(char **pp
, int iCol
){
2202 int n
= 0; /* Number of bytes written */
2204 char *p
= *pp
; /* Output pointer */
2205 n
= 1 + sqlite3Fts3PutVarint(&p
[1], iCol
);
2213 ** Compute the union of two position lists. The output written
2214 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
2215 ** order and with any duplicates removed. All pointers are
2216 ** updated appropriately. The caller is responsible for insuring
2217 ** that there is enough space in *pp to hold the complete output.
2219 static int fts3PoslistMerge(
2220 char **pp
, /* Output buffer */
2221 char **pp1
, /* Left input list */
2222 char **pp2
/* Right input list */
2228 while( *p1
|| *p2
){
2229 int iCol1
; /* The current column index in pp1 */
2230 int iCol2
; /* The current column index in pp2 */
2232 if( *p1
==POS_COLUMN
){
2233 fts3GetVarint32(&p1
[1], &iCol1
);
2234 if( iCol1
==0 ) return FTS_CORRUPT_VTAB
;
2236 else if( *p1
==POS_END
) iCol1
= 0x7fffffff;
2239 if( *p2
==POS_COLUMN
){
2240 fts3GetVarint32(&p2
[1], &iCol2
);
2241 if( iCol2
==0 ) return FTS_CORRUPT_VTAB
;
2243 else if( *p2
==POS_END
) iCol2
= 0x7fffffff;
2247 sqlite3_int64 i1
= 0; /* Last position from pp1 */
2248 sqlite3_int64 i2
= 0; /* Last position from pp2 */
2249 sqlite3_int64 iPrev
= 0;
2250 int n
= fts3PutColNumber(&p
, iCol1
);
2254 /* At this point, both p1 and p2 point to the start of column-lists
2255 ** for the same column (the column with index iCol1 and iCol2).
2256 ** A column-list is a list of non-negative delta-encoded varints, each
2257 ** incremented by 2 before being stored. Each list is terminated by a
2258 ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
2259 ** and writes the results to buffer p. p is left pointing to the byte
2260 ** after the list written. No terminator (POS_END or POS_COLUMN) is
2261 ** written to the output.
2263 fts3GetDeltaVarint(&p1
, &i1
);
2264 fts3GetDeltaVarint(&p2
, &i2
);
2269 fts3PutDeltaVarint(&p
, &iPrev
, (i1
<i2
) ? i1
: i2
);
2272 fts3ReadNextPos(&p1
, &i1
);
2273 fts3ReadNextPos(&p2
, &i2
);
2275 fts3ReadNextPos(&p1
, &i1
);
2277 fts3ReadNextPos(&p2
, &i2
);
2279 }while( i1
!=POSITION_LIST_END
|| i2
!=POSITION_LIST_END
);
2280 }else if( iCol1
<iCol2
){
2281 p1
+= fts3PutColNumber(&p
, iCol1
);
2282 fts3ColumnlistCopy(&p
, &p1
);
2284 p2
+= fts3PutColNumber(&p
, iCol2
);
2285 fts3ColumnlistCopy(&p
, &p2
);
2297 ** This function is used to merge two position lists into one. When it is
2298 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
2299 ** the part of a doclist that follows each document id. For example, if a row
2302 ** 'a b c'|'x y z'|'a b b a'
2304 ** Then the position list for this row for token 'b' would consist of:
2306 ** 0x02 0x01 0x02 0x03 0x03 0x00
2308 ** When this function returns, both *pp1 and *pp2 are left pointing to the
2309 ** byte following the 0x00 terminator of their respective position lists.
2311 ** If isSaveLeft is 0, an entry is added to the output position list for
2312 ** each position in *pp2 for which there exists one or more positions in
2313 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
2314 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
2317 ** e.g. nToken==1 searches for adjacent positions.
2319 static int fts3PoslistPhraseMerge(
2320 char **pp
, /* IN/OUT: Preallocated output buffer */
2321 int nToken
, /* Maximum difference in token positions */
2322 int isSaveLeft
, /* Save the left position */
2323 int isExact
, /* If *pp1 is exactly nTokens before *pp2 */
2324 char **pp1
, /* IN/OUT: Left input list */
2325 char **pp2
/* IN/OUT: Right input list */
2333 /* Never set both isSaveLeft and isExact for the same invocation. */
2334 assert( isSaveLeft
==0 || isExact
==0 );
2336 assert_fts3_nc( p
!=0 && *p1
!=0 && *p2
!=0 );
2337 if( *p1
==POS_COLUMN
){
2339 p1
+= fts3GetVarint32(p1
, &iCol1
);
2341 if( *p2
==POS_COLUMN
){
2343 p2
+= fts3GetVarint32(p2
, &iCol2
);
2349 sqlite3_int64 iPrev
= 0;
2350 sqlite3_int64 iPos1
= 0;
2351 sqlite3_int64 iPos2
= 0;
2355 p
+= sqlite3Fts3PutVarint(p
, iCol1
);
2358 fts3GetDeltaVarint(&p1
, &iPos1
); iPos1
-= 2;
2359 fts3GetDeltaVarint(&p2
, &iPos2
); iPos2
-= 2;
2360 if( iPos1
<0 || iPos2
<0 ) break;
2363 if( iPos2
==iPos1
+nToken
2364 || (isExact
==0 && iPos2
>iPos1
&& iPos2
<=iPos1
+nToken
)
2366 sqlite3_int64 iSave
;
2367 iSave
= isSaveLeft
? iPos1
: iPos2
;
2368 fts3PutDeltaVarint(&p
, &iPrev
, iSave
+2); iPrev
-= 2;
2372 if( (!isSaveLeft
&& iPos2
<=(iPos1
+nToken
)) || iPos2
<=iPos1
){
2373 if( (*p2
&0xFE)==0 ) break;
2374 fts3GetDeltaVarint(&p2
, &iPos2
); iPos2
-= 2;
2376 if( (*p1
&0xFE)==0 ) break;
2377 fts3GetDeltaVarint(&p1
, &iPos1
); iPos1
-= 2;
2386 fts3ColumnlistCopy(0, &p1
);
2387 fts3ColumnlistCopy(0, &p2
);
2388 assert( (*p1
&0xFE)==0 && (*p2
&0xFE)==0 );
2389 if( 0==*p1
|| 0==*p2
) break;
2392 p1
+= fts3GetVarint32(p1
, &iCol1
);
2394 p2
+= fts3GetVarint32(p2
, &iCol2
);
2397 /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
2398 ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
2399 ** end of the position list, or the 0x01 that precedes the next
2400 ** column-number in the position list.
2402 else if( iCol1
<iCol2
){
2403 fts3ColumnlistCopy(0, &p1
);
2406 p1
+= fts3GetVarint32(p1
, &iCol1
);
2408 fts3ColumnlistCopy(0, &p2
);
2411 p2
+= fts3GetVarint32(p2
, &iCol2
);
2415 fts3PoslistCopy(0, &p2
);
2416 fts3PoslistCopy(0, &p1
);
2428 ** Merge two position-lists as required by the NEAR operator. The argument
2429 ** position lists correspond to the left and right phrases of an expression
2432 ** "phrase 1" NEAR "phrase number 2"
2434 ** Position list *pp1 corresponds to the left-hand side of the NEAR
2435 ** expression and *pp2 to the right. As usual, the indexes in the position
2436 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
2437 ** in the example above).
2439 ** The output position list - written to *pp - is a copy of *pp2 with those
2440 ** entries that are not sufficiently NEAR entries in *pp1 removed.
2442 static int fts3PoslistNearMerge(
2443 char **pp
, /* Output buffer */
2444 char *aTmp
, /* Temporary buffer space */
2445 int nRight
, /* Maximum difference in token positions */
2446 int nLeft
, /* Maximum difference in token positions */
2447 char **pp1
, /* IN/OUT: Left input list */
2448 char **pp2
/* IN/OUT: Right input list */
2458 fts3PoslistPhraseMerge(&pTmp1
, nRight
, 0, 0, pp1
, pp2
);
2459 aTmp2
= pTmp2
= pTmp1
;
2462 fts3PoslistPhraseMerge(&pTmp2
, nLeft
, 1, 0, pp2
, pp1
);
2463 if( pTmp1
!=aTmp
&& pTmp2
!=aTmp2
){
2464 fts3PoslistMerge(pp
, &aTmp
, &aTmp2
);
2465 }else if( pTmp1
!=aTmp
){
2466 fts3PoslistCopy(pp
, &aTmp
);
2467 }else if( pTmp2
!=aTmp2
){
2468 fts3PoslistCopy(pp
, &aTmp2
);
2477 ** An instance of this function is used to merge together the (potentially
2478 ** large number of) doclists for each term that matches a prefix query.
2479 ** See function fts3TermSelectMerge() for details.
2481 typedef struct TermSelect TermSelect
;
2483 char *aaOutput
[16]; /* Malloc'd output buffers */
2484 int anOutput
[16]; /* Size each output buffer in bytes */
2488 ** This function is used to read a single varint from a buffer. Parameter
2489 ** pEnd points 1 byte past the end of the buffer. When this function is
2490 ** called, if *pp points to pEnd or greater, then the end of the buffer
2491 ** has been reached. In this case *pp is set to 0 and the function returns.
2493 ** If *pp does not point to or past pEnd, then a single varint is read
2494 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
2496 ** If bDescIdx is false, the value read is added to *pVal before returning.
2497 ** If it is true, the value read is subtracted from *pVal before this
2498 ** function returns.
2500 static void fts3GetDeltaVarint3(
2501 char **pp
, /* IN/OUT: Point to read varint from */
2502 char *pEnd
, /* End of buffer */
2503 int bDescIdx
, /* True if docids are descending */
2504 sqlite3_int64
*pVal
/* IN/OUT: Integer value */
2510 *pp
+= sqlite3Fts3GetVarintU(*pp
, &iVal
);
2512 *pVal
= (i64
)((u64
)*pVal
- iVal
);
2514 *pVal
= (i64
)((u64
)*pVal
+ iVal
);
2520 ** This function is used to write a single varint to a buffer. The varint
2521 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
2522 ** end of the value written.
2524 ** If *pbFirst is zero when this function is called, the value written to
2525 ** the buffer is that of parameter iVal.
2527 ** If *pbFirst is non-zero when this function is called, then the value
2528 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
2529 ** (if bDescIdx is non-zero).
2531 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
2532 ** to the value of parameter iVal.
2534 static void fts3PutDeltaVarint3(
2535 char **pp
, /* IN/OUT: Output pointer */
2536 int bDescIdx
, /* True for descending docids */
2537 sqlite3_int64
*piPrev
, /* IN/OUT: Previous value written to list */
2538 int *pbFirst
, /* IN/OUT: True after first int written */
2539 sqlite3_int64 iVal
/* Write this value to the list */
2541 sqlite3_uint64 iWrite
;
2542 if( bDescIdx
==0 || *pbFirst
==0 ){
2543 assert_fts3_nc( *pbFirst
==0 || iVal
>=*piPrev
);
2544 iWrite
= (u64
)iVal
- (u64
)*piPrev
;
2546 assert_fts3_nc( *piPrev
>=iVal
);
2547 iWrite
= (u64
)*piPrev
- (u64
)iVal
;
2549 assert( *pbFirst
|| *piPrev
==0 );
2550 assert_fts3_nc( *pbFirst
==0 || iWrite
>0 );
2551 *pp
+= sqlite3Fts3PutVarint(*pp
, iWrite
);
2558 ** This macro is used by various functions that merge doclists. The two
2559 ** arguments are 64-bit docid values. If the value of the stack variable
2560 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
2561 ** Otherwise, (i2-i1).
2563 ** Using this makes it easier to write code that can merge doclists that are
2564 ** sorted in either ascending or descending order.
2566 /* #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i64)((u64)i1-i2)) */
2567 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1>i2?1:((i1==i2)?0:-1)))
2570 ** This function does an "OR" merge of two doclists (output contains all
2571 ** positions contained in either argument doclist). If the docids in the
2572 ** input doclists are sorted in ascending order, parameter bDescDoclist
2573 ** should be false. If they are sorted in ascending order, it should be
2574 ** passed a non-zero value.
2576 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
2577 ** containing the output doclist and SQLITE_OK is returned. In this case
2578 ** *pnOut is set to the number of bytes in the output doclist.
2580 ** If an error occurs, an SQLite error code is returned. The output values
2581 ** are undefined in this case.
2583 static int fts3DoclistOrMerge(
2584 int bDescDoclist
, /* True if arguments are desc */
2585 char *a1
, int n1
, /* First doclist */
2586 char *a2
, int n2
, /* Second doclist */
2587 char **paOut
, int *pnOut
/* OUT: Malloc'd doclist */
2590 sqlite3_int64 i1
= 0;
2591 sqlite3_int64 i2
= 0;
2592 sqlite3_int64 iPrev
= 0;
2593 char *pEnd1
= &a1
[n1
];
2594 char *pEnd2
= &a2
[n2
];
2604 /* Allocate space for the output. Both the input and output doclists
2605 ** are delta encoded. If they are in ascending order (bDescDoclist==0),
2606 ** then the first docid in each list is simply encoded as a varint. For
2607 ** each subsequent docid, the varint stored is the difference between the
2608 ** current and previous docid (a positive number - since the list is in
2609 ** ascending order).
2611 ** The first docid written to the output is therefore encoded using the
2612 ** same number of bytes as it is in whichever of the input lists it is
2613 ** read from. And each subsequent docid read from the same input list
2614 ** consumes either the same or less bytes as it did in the input (since
2615 ** the difference between it and the previous value in the output must
2616 ** be a positive value less than or equal to the delta value read from
2617 ** the input list). The same argument applies to all but the first docid
2618 ** read from the 'other' list. And to the contents of all position lists
2619 ** that will be copied and merged from the input to the output.
2621 ** However, if the first docid copied to the output is a negative number,
2622 ** then the encoding of the first docid from the 'other' input list may
2623 ** be larger in the output than it was in the input (since the delta value
2624 ** may be a larger positive integer than the actual docid).
2626 ** The space required to store the output is therefore the sum of the
2627 ** sizes of the two inputs, plus enough space for exactly one of the input
2630 ** A symetric argument may be made if the doclists are in descending
2633 aOut
= sqlite3_malloc64((i64
)n1
+n2
+FTS3_VARINT_MAX
-1+FTS3_BUFFER_PADDING
);
2634 if( !aOut
) return SQLITE_NOMEM
;
2637 fts3GetDeltaVarint3(&p1
, pEnd1
, 0, &i1
);
2638 fts3GetDeltaVarint3(&p2
, pEnd2
, 0, &i2
);
2640 sqlite3_int64 iDiff
= DOCID_CMP(i1
, i2
);
2642 if( p2
&& p1
&& iDiff
==0 ){
2643 fts3PutDeltaVarint3(&p
, bDescDoclist
, &iPrev
, &bFirstOut
, i1
);
2644 rc
= fts3PoslistMerge(&p
, &p1
, &p2
);
2646 fts3GetDeltaVarint3(&p1
, pEnd1
, bDescDoclist
, &i1
);
2647 fts3GetDeltaVarint3(&p2
, pEnd2
, bDescDoclist
, &i2
);
2648 }else if( !p2
|| (p1
&& iDiff
<0) ){
2649 fts3PutDeltaVarint3(&p
, bDescDoclist
, &iPrev
, &bFirstOut
, i1
);
2650 fts3PoslistCopy(&p
, &p1
);
2651 fts3GetDeltaVarint3(&p1
, pEnd1
, bDescDoclist
, &i1
);
2653 fts3PutDeltaVarint3(&p
, bDescDoclist
, &iPrev
, &bFirstOut
, i2
);
2654 fts3PoslistCopy(&p
, &p2
);
2655 fts3GetDeltaVarint3(&p2
, pEnd2
, bDescDoclist
, &i2
);
2658 assert( (p
-aOut
)<=((p1
?(p1
-a1
):n1
)+(p2
?(p2
-a2
):n2
)+FTS3_VARINT_MAX
-1) );
2661 if( rc
!=SQLITE_OK
){
2665 assert( (p
-aOut
)<=n1
+n2
+FTS3_VARINT_MAX
-1 );
2666 memset(&aOut
[(p
-aOut
)], 0, FTS3_BUFFER_PADDING
);
2669 *pnOut
= (int)(p
-aOut
);
2674 ** This function does a "phrase" merge of two doclists. In a phrase merge,
2675 ** the output contains a copy of each position from the right-hand input
2676 ** doclist for which there is a position in the left-hand input doclist
2677 ** exactly nDist tokens before it.
2679 ** If the docids in the input doclists are sorted in ascending order,
2680 ** parameter bDescDoclist should be false. If they are sorted in ascending
2681 ** order, it should be passed a non-zero value.
2683 ** The right-hand input doclist is overwritten by this function.
2685 static int fts3DoclistPhraseMerge(
2686 int bDescDoclist
, /* True if arguments are desc */
2687 int nDist
, /* Distance from left to right (1=adjacent) */
2688 char *aLeft
, int nLeft
, /* Left doclist */
2689 char **paRight
, int *pnRight
/* IN/OUT: Right/output doclist */
2691 sqlite3_int64 i1
= 0;
2692 sqlite3_int64 i2
= 0;
2693 sqlite3_int64 iPrev
= 0;
2694 char *aRight
= *paRight
;
2695 char *pEnd1
= &aLeft
[nLeft
];
2696 char *pEnd2
= &aRight
[*pnRight
];
2705 aOut
= sqlite3_malloc64((sqlite3_int64
)*pnRight
+ FTS3_VARINT_MAX
);
2706 if( aOut
==0 ) return SQLITE_NOMEM
;
2712 fts3GetDeltaVarint3(&p1
, pEnd1
, 0, &i1
);
2713 fts3GetDeltaVarint3(&p2
, pEnd2
, 0, &i2
);
2716 sqlite3_int64 iDiff
= DOCID_CMP(i1
, i2
);
2719 sqlite3_int64 iPrevSave
= iPrev
;
2720 int bFirstOutSave
= bFirstOut
;
2722 fts3PutDeltaVarint3(&p
, bDescDoclist
, &iPrev
, &bFirstOut
, i1
);
2723 if( 0==fts3PoslistPhraseMerge(&p
, nDist
, 0, 1, &p1
, &p2
) ){
2726 bFirstOut
= bFirstOutSave
;
2728 fts3GetDeltaVarint3(&p1
, pEnd1
, bDescDoclist
, &i1
);
2729 fts3GetDeltaVarint3(&p2
, pEnd2
, bDescDoclist
, &i2
);
2730 }else if( iDiff
<0 ){
2731 fts3PoslistCopy(0, &p1
);
2732 fts3GetDeltaVarint3(&p1
, pEnd1
, bDescDoclist
, &i1
);
2734 fts3PoslistCopy(0, &p2
);
2735 fts3GetDeltaVarint3(&p2
, pEnd2
, bDescDoclist
, &i2
);
2739 *pnRight
= (int)(p
- aOut
);
2741 sqlite3_free(aRight
);
2749 ** Argument pList points to a position list nList bytes in size. This
2750 ** function checks to see if the position list contains any entries for
2751 ** a token in position 0 (of any column). If so, it writes argument iDelta
2752 ** to the output buffer pOut, followed by a position list consisting only
2753 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
2754 ** The value returned is the number of bytes written to pOut (if any).
2756 int sqlite3Fts3FirstFilter(
2757 sqlite3_int64 iDelta
, /* Varint that may be written to pOut */
2758 char *pList
, /* Position list (no 0x00 term) */
2759 int nList
, /* Size of pList in bytes */
2760 char *pOut
/* Write output here */
2763 int bWritten
= 0; /* True once iDelta has been written */
2765 char *pEnd
= &pList
[nList
];
2769 nOut
+= sqlite3Fts3PutVarint(&pOut
[nOut
], iDelta
);
2770 pOut
[nOut
++] = 0x02;
2773 fts3ColumnlistCopy(0, &p
);
2779 p
+= sqlite3Fts3GetVarint(p
, &iCol
);
2782 nOut
+= sqlite3Fts3PutVarint(&pOut
[nOut
], iDelta
);
2785 pOut
[nOut
++] = 0x01;
2786 nOut
+= sqlite3Fts3PutVarint(&pOut
[nOut
], iCol
);
2787 pOut
[nOut
++] = 0x02;
2789 fts3ColumnlistCopy(0, &p
);
2792 pOut
[nOut
++] = 0x00;
2800 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
2801 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
2802 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
2804 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
2805 ** the responsibility of the caller to free any doclists left in the
2806 ** TermSelect.aaOutput[] array.
2808 static int fts3TermSelectFinishMerge(Fts3Table
*p
, TermSelect
*pTS
){
2813 /* Loop through the doclists in the aaOutput[] array. Merge them all
2814 ** into a single doclist.
2816 for(i
=0; i
<SizeofArray(pTS
->aaOutput
); i
++){
2817 if( pTS
->aaOutput
[i
] ){
2819 aOut
= pTS
->aaOutput
[i
];
2820 nOut
= pTS
->anOutput
[i
];
2821 pTS
->aaOutput
[i
] = 0;
2826 int rc
= fts3DoclistOrMerge(p
->bDescIdx
,
2827 pTS
->aaOutput
[i
], pTS
->anOutput
[i
], aOut
, nOut
, &aNew
, &nNew
2829 if( rc
!=SQLITE_OK
){
2834 sqlite3_free(pTS
->aaOutput
[i
]);
2836 pTS
->aaOutput
[i
] = 0;
2843 pTS
->aaOutput
[0] = aOut
;
2844 pTS
->anOutput
[0] = nOut
;
2849 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
2850 ** as the first argument. The merge is an "OR" merge (see function
2851 ** fts3DoclistOrMerge() for details).
2853 ** This function is called with the doclist for each term that matches
2854 ** a queried prefix. It merges all these doclists into one, the doclist
2855 ** for the specified prefix. Since there can be a very large number of
2856 ** doclists to merge, the merging is done pair-wise using the TermSelect
2859 ** This function returns SQLITE_OK if the merge is successful, or an
2860 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
2862 static int fts3TermSelectMerge(
2863 Fts3Table
*p
, /* FTS table handle */
2864 TermSelect
*pTS
, /* TermSelect object to merge into */
2865 char *aDoclist
, /* Pointer to doclist */
2866 int nDoclist
/* Size of aDoclist in bytes */
2868 if( pTS
->aaOutput
[0]==0 ){
2869 /* If this is the first term selected, copy the doclist to the output
2870 ** buffer using memcpy().
2872 ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
2873 ** allocation. This is so as to ensure that the buffer is big enough
2874 ** to hold the current doclist AND'd with any other doclist. If the
2875 ** doclists are stored in order=ASC order, this padding would not be
2876 ** required (since the size of [doclistA AND doclistB] is always less
2877 ** than or equal to the size of [doclistA] in that case). But this is
2878 ** not true for order=DESC. For example, a doclist containing (1, -1)
2879 ** may be smaller than (-1), as in the first example the -1 may be stored
2880 ** as a single-byte delta, whereas in the second it must be stored as a
2881 ** FTS3_VARINT_MAX byte varint.
2883 ** Similar padding is added in the fts3DoclistOrMerge() function.
2885 pTS
->aaOutput
[0] = sqlite3_malloc(nDoclist
+ FTS3_VARINT_MAX
+ 1);
2886 pTS
->anOutput
[0] = nDoclist
;
2887 if( pTS
->aaOutput
[0] ){
2888 memcpy(pTS
->aaOutput
[0], aDoclist
, nDoclist
);
2889 memset(&pTS
->aaOutput
[0][nDoclist
], 0, FTS3_VARINT_MAX
);
2891 return SQLITE_NOMEM
;
2894 char *aMerge
= aDoclist
;
2895 int nMerge
= nDoclist
;
2898 for(iOut
=0; iOut
<SizeofArray(pTS
->aaOutput
); iOut
++){
2899 if( pTS
->aaOutput
[iOut
]==0 ){
2901 pTS
->aaOutput
[iOut
] = aMerge
;
2902 pTS
->anOutput
[iOut
] = nMerge
;
2908 int rc
= fts3DoclistOrMerge(p
->bDescIdx
, aMerge
, nMerge
,
2909 pTS
->aaOutput
[iOut
], pTS
->anOutput
[iOut
], &aNew
, &nNew
2911 if( rc
!=SQLITE_OK
){
2912 if( aMerge
!=aDoclist
) sqlite3_free(aMerge
);
2916 if( aMerge
!=aDoclist
) sqlite3_free(aMerge
);
2917 sqlite3_free(pTS
->aaOutput
[iOut
]);
2918 pTS
->aaOutput
[iOut
] = 0;
2922 if( (iOut
+1)==SizeofArray(pTS
->aaOutput
) ){
2923 pTS
->aaOutput
[iOut
] = aMerge
;
2924 pTS
->anOutput
[iOut
] = nMerge
;
2933 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
2935 static int fts3SegReaderCursorAppend(
2936 Fts3MultiSegReader
*pCsr
,
2939 if( (pCsr
->nSegment
%16)==0 ){
2940 Fts3SegReader
**apNew
;
2941 sqlite3_int64 nByte
= (pCsr
->nSegment
+ 16)*sizeof(Fts3SegReader
*);
2942 apNew
= (Fts3SegReader
**)sqlite3_realloc64(pCsr
->apSegment
, nByte
);
2944 sqlite3Fts3SegReaderFree(pNew
);
2945 return SQLITE_NOMEM
;
2947 pCsr
->apSegment
= apNew
;
2949 pCsr
->apSegment
[pCsr
->nSegment
++] = pNew
;
2954 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
2957 ** This function returns SQLITE_OK if successful, or an SQLite error code
2960 static int fts3SegReaderCursor(
2961 Fts3Table
*p
, /* FTS3 table handle */
2962 int iLangid
, /* Language id */
2963 int iIndex
, /* Index to search (from 0 to p->nIndex-1) */
2964 int iLevel
, /* Level of segments to scan */
2965 const char *zTerm
, /* Term to query for */
2966 int nTerm
, /* Size of zTerm in bytes */
2967 int isPrefix
, /* True for a prefix search */
2968 int isScan
, /* True to scan from zTerm to EOF */
2969 Fts3MultiSegReader
*pCsr
/* Cursor object to populate */
2971 int rc
= SQLITE_OK
; /* Error code */
2972 sqlite3_stmt
*pStmt
= 0; /* Statement to iterate through segments */
2973 int rc2
; /* Result of sqlite3_reset() */
2975 /* If iLevel is less than 0 and this is not a scan, include a seg-reader
2976 ** for the pending-terms. If this is a scan, then this call must be being
2977 ** made by an fts4aux module, not an FTS table. In this case calling
2978 ** Fts3SegReaderPending might segfault, as the data structures used by
2979 ** fts4aux are not completely populated. So it's easiest to filter these
2980 ** calls out here. */
2981 if( iLevel
<0 && p
->aIndex
&& p
->iPrevLangid
==iLangid
){
2982 Fts3SegReader
*pSeg
= 0;
2983 rc
= sqlite3Fts3SegReaderPending(p
, iIndex
, zTerm
, nTerm
, isPrefix
||isScan
, &pSeg
);
2984 if( rc
==SQLITE_OK
&& pSeg
){
2985 rc
= fts3SegReaderCursorAppend(pCsr
, pSeg
);
2989 if( iLevel
!=FTS3_SEGCURSOR_PENDING
){
2990 if( rc
==SQLITE_OK
){
2991 rc
= sqlite3Fts3AllSegdirs(p
, iLangid
, iIndex
, iLevel
, &pStmt
);
2994 while( rc
==SQLITE_OK
&& SQLITE_ROW
==(rc
= sqlite3_step(pStmt
)) ){
2995 Fts3SegReader
*pSeg
= 0;
2997 /* Read the values returned by the SELECT into local variables. */
2998 sqlite3_int64 iStartBlock
= sqlite3_column_int64(pStmt
, 1);
2999 sqlite3_int64 iLeavesEndBlock
= sqlite3_column_int64(pStmt
, 2);
3000 sqlite3_int64 iEndBlock
= sqlite3_column_int64(pStmt
, 3);
3001 int nRoot
= sqlite3_column_bytes(pStmt
, 4);
3002 char const *zRoot
= sqlite3_column_blob(pStmt
, 4);
3004 /* If zTerm is not NULL, and this segment is not stored entirely on its
3005 ** root node, the range of leaves scanned can be reduced. Do this. */
3006 if( iStartBlock
&& zTerm
&& zRoot
){
3007 sqlite3_int64
*pi
= (isPrefix
? &iLeavesEndBlock
: 0);
3008 rc
= fts3SelectLeaf(p
, zTerm
, nTerm
, zRoot
, nRoot
, &iStartBlock
, pi
);
3009 if( rc
!=SQLITE_OK
) goto finished
;
3010 if( isPrefix
==0 && isScan
==0 ) iLeavesEndBlock
= iStartBlock
;
3013 rc
= sqlite3Fts3SegReaderNew(pCsr
->nSegment
+1,
3014 (isPrefix
==0 && isScan
==0),
3015 iStartBlock
, iLeavesEndBlock
,
3016 iEndBlock
, zRoot
, nRoot
, &pSeg
3018 if( rc
!=SQLITE_OK
) goto finished
;
3019 rc
= fts3SegReaderCursorAppend(pCsr
, pSeg
);
3024 rc2
= sqlite3_reset(pStmt
);
3025 if( rc
==SQLITE_DONE
) rc
= rc2
;
3031 ** Set up a cursor object for iterating through a full-text index or a
3032 ** single level therein.
3034 int sqlite3Fts3SegReaderCursor(
3035 Fts3Table
*p
, /* FTS3 table handle */
3036 int iLangid
, /* Language-id to search */
3037 int iIndex
, /* Index to search (from 0 to p->nIndex-1) */
3038 int iLevel
, /* Level of segments to scan */
3039 const char *zTerm
, /* Term to query for */
3040 int nTerm
, /* Size of zTerm in bytes */
3041 int isPrefix
, /* True for a prefix search */
3042 int isScan
, /* True to scan from zTerm to EOF */
3043 Fts3MultiSegReader
*pCsr
/* Cursor object to populate */
3045 assert( iIndex
>=0 && iIndex
<p
->nIndex
);
3046 assert( iLevel
==FTS3_SEGCURSOR_ALL
3047 || iLevel
==FTS3_SEGCURSOR_PENDING
3050 assert( iLevel
<FTS3_SEGDIR_MAXLEVEL
);
3051 assert( FTS3_SEGCURSOR_ALL
<0 && FTS3_SEGCURSOR_PENDING
<0 );
3052 assert( isPrefix
==0 || isScan
==0 );
3054 memset(pCsr
, 0, sizeof(Fts3MultiSegReader
));
3055 return fts3SegReaderCursor(
3056 p
, iLangid
, iIndex
, iLevel
, zTerm
, nTerm
, isPrefix
, isScan
, pCsr
3061 ** In addition to its current configuration, have the Fts3MultiSegReader
3062 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
3064 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
3066 static int fts3SegReaderCursorAddZero(
3067 Fts3Table
*p
, /* FTS virtual table handle */
3069 const char *zTerm
, /* Term to scan doclist of */
3070 int nTerm
, /* Number of bytes in zTerm */
3071 Fts3MultiSegReader
*pCsr
/* Fts3MultiSegReader to modify */
3073 return fts3SegReaderCursor(p
,
3074 iLangid
, 0, FTS3_SEGCURSOR_ALL
, zTerm
, nTerm
, 0, 0,pCsr
3079 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
3080 ** if isPrefix is true, to scan the doclist for all terms for which
3081 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
3082 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
3083 ** an SQLite error code.
3085 ** It is the responsibility of the caller to free this object by eventually
3086 ** passing it to fts3SegReaderCursorFree()
3088 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
3089 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
3091 static int fts3TermSegReaderCursor(
3092 Fts3Cursor
*pCsr
, /* Virtual table cursor handle */
3093 const char *zTerm
, /* Term to query for */
3094 int nTerm
, /* Size of zTerm in bytes */
3095 int isPrefix
, /* True for a prefix search */
3096 Fts3MultiSegReader
**ppSegcsr
/* OUT: Allocated seg-reader cursor */
3098 Fts3MultiSegReader
*pSegcsr
; /* Object to allocate and return */
3099 int rc
= SQLITE_NOMEM
; /* Return code */
3101 pSegcsr
= sqlite3_malloc(sizeof(Fts3MultiSegReader
));
3104 int bFound
= 0; /* True once an index has been found */
3105 Fts3Table
*p
= (Fts3Table
*)pCsr
->base
.pVtab
;
3108 for(i
=1; bFound
==0 && i
<p
->nIndex
; i
++){
3109 if( p
->aIndex
[i
].nPrefix
==nTerm
){
3111 rc
= sqlite3Fts3SegReaderCursor(p
, pCsr
->iLangid
,
3112 i
, FTS3_SEGCURSOR_ALL
, zTerm
, nTerm
, 0, 0, pSegcsr
3114 pSegcsr
->bLookup
= 1;
3118 for(i
=1; bFound
==0 && i
<p
->nIndex
; i
++){
3119 if( p
->aIndex
[i
].nPrefix
==nTerm
+1 ){
3121 rc
= sqlite3Fts3SegReaderCursor(p
, pCsr
->iLangid
,
3122 i
, FTS3_SEGCURSOR_ALL
, zTerm
, nTerm
, 1, 0, pSegcsr
3124 if( rc
==SQLITE_OK
){
3125 rc
= fts3SegReaderCursorAddZero(
3126 p
, pCsr
->iLangid
, zTerm
, nTerm
, pSegcsr
3134 rc
= sqlite3Fts3SegReaderCursor(p
, pCsr
->iLangid
,
3135 0, FTS3_SEGCURSOR_ALL
, zTerm
, nTerm
, isPrefix
, 0, pSegcsr
3137 pSegcsr
->bLookup
= !isPrefix
;
3141 *ppSegcsr
= pSegcsr
;
3146 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
3148 static void fts3SegReaderCursorFree(Fts3MultiSegReader
*pSegcsr
){
3149 sqlite3Fts3SegReaderFinish(pSegcsr
);
3150 sqlite3_free(pSegcsr
);
3154 ** This function retrieves the doclist for the specified term (or term
3155 ** prefix) from the database.
3157 static int fts3TermSelect(
3158 Fts3Table
*p
, /* Virtual table handle */
3159 Fts3PhraseToken
*pTok
, /* Token to query for */
3160 int iColumn
, /* Column to query (or -ve for all columns) */
3161 int *pnOut
, /* OUT: Size of buffer at *ppOut */
3162 char **ppOut
/* OUT: Malloced result buffer */
3164 int rc
; /* Return code */
3165 Fts3MultiSegReader
*pSegcsr
; /* Seg-reader cursor for this term */
3166 TermSelect tsc
; /* Object for pair-wise doclist merging */
3167 Fts3SegFilter filter
; /* Segment term filter configuration */
3169 pSegcsr
= pTok
->pSegcsr
;
3170 memset(&tsc
, 0, sizeof(TermSelect
));
3172 filter
.flags
= FTS3_SEGMENT_IGNORE_EMPTY
| FTS3_SEGMENT_REQUIRE_POS
3173 | (pTok
->isPrefix
? FTS3_SEGMENT_PREFIX
: 0)
3174 | (pTok
->bFirst
? FTS3_SEGMENT_FIRST
: 0)
3175 | (iColumn
<p
->nColumn
? FTS3_SEGMENT_COLUMN_FILTER
: 0);
3176 filter
.iCol
= iColumn
;
3177 filter
.zTerm
= pTok
->z
;
3178 filter
.nTerm
= pTok
->n
;
3180 rc
= sqlite3Fts3SegReaderStart(p
, pSegcsr
, &filter
);
3181 while( SQLITE_OK
==rc
3182 && SQLITE_ROW
==(rc
= sqlite3Fts3SegReaderStep(p
, pSegcsr
))
3184 rc
= fts3TermSelectMerge(p
, &tsc
, pSegcsr
->aDoclist
, pSegcsr
->nDoclist
);
3187 if( rc
==SQLITE_OK
){
3188 rc
= fts3TermSelectFinishMerge(p
, &tsc
);
3190 if( rc
==SQLITE_OK
){
3191 *ppOut
= tsc
.aaOutput
[0];
3192 *pnOut
= tsc
.anOutput
[0];
3195 for(i
=0; i
<SizeofArray(tsc
.aaOutput
); i
++){
3196 sqlite3_free(tsc
.aaOutput
[i
]);
3200 fts3SegReaderCursorFree(pSegcsr
);
3206 ** This function counts the total number of docids in the doclist stored
3207 ** in buffer aList[], size nList bytes.
3209 ** If the isPoslist argument is true, then it is assumed that the doclist
3210 ** contains a position-list following each docid. Otherwise, it is assumed
3211 ** that the doclist is simply a list of docids stored as delta encoded
3214 static int fts3DoclistCountDocids(char *aList
, int nList
){
3215 int nDoc
= 0; /* Return value */
3217 char *aEnd
= &aList
[nList
]; /* Pointer to one byte after EOF */
3218 char *p
= aList
; /* Cursor */
3221 while( (*p
++)&0x80 ); /* Skip docid varint */
3222 fts3PoslistCopy(0, &p
); /* Skip over position list */
3230 ** Advance the cursor to the next row in the %_content table that
3231 ** matches the search criteria. For a MATCH search, this will be
3232 ** the next row that matches. For a full-table scan, this will be
3233 ** simply the next row in the %_content table. For a docid lookup,
3234 ** this routine simply sets the EOF flag.
3236 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
3237 ** even if we reach end-of-file. The fts3EofMethod() will be called
3238 ** subsequently to determine whether or not an EOF was hit.
3240 static int fts3NextMethod(sqlite3_vtab_cursor
*pCursor
){
3242 Fts3Cursor
*pCsr
= (Fts3Cursor
*)pCursor
;
3243 if( pCsr
->eSearch
==FTS3_DOCID_SEARCH
|| pCsr
->eSearch
==FTS3_FULLSCAN_SEARCH
){
3244 Fts3Table
*pTab
= (Fts3Table
*)pCursor
->pVtab
;
3246 if( SQLITE_ROW
!=sqlite3_step(pCsr
->pStmt
) ){
3248 rc
= sqlite3_reset(pCsr
->pStmt
);
3250 pCsr
->iPrevId
= sqlite3_column_int64(pCsr
->pStmt
, 0);
3255 rc
= fts3EvalNext((Fts3Cursor
*)pCursor
);
3257 assert( ((Fts3Table
*)pCsr
->base
.pVtab
)->pSegments
==0 );
3262 ** If the numeric type of argument pVal is "integer", then return it
3263 ** converted to a 64-bit signed integer. Otherwise, return a copy of
3264 ** the second parameter, iDefault.
3266 static sqlite3_int64
fts3DocidRange(sqlite3_value
*pVal
, i64 iDefault
){
3268 int eType
= sqlite3_value_numeric_type(pVal
);
3269 if( eType
==SQLITE_INTEGER
){
3270 return sqlite3_value_int64(pVal
);
3277 ** This is the xFilter interface for the virtual table. See
3278 ** the virtual table xFilter method documentation for additional
3281 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
3282 ** the %_content table.
3284 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
3285 ** in the %_content table.
3287 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
3288 ** column on the left-hand side of the MATCH operator is column
3289 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
3290 ** side of the MATCH operator.
3292 static int fts3FilterMethod(
3293 sqlite3_vtab_cursor
*pCursor
, /* The cursor used for this query */
3294 int idxNum
, /* Strategy index */
3295 const char *idxStr
, /* Unused */
3296 int nVal
, /* Number of elements in apVal */
3297 sqlite3_value
**apVal
/* Arguments for the indexing scheme */
3300 char *zSql
; /* SQL statement used to access %_content */
3302 Fts3Table
*p
= (Fts3Table
*)pCursor
->pVtab
;
3303 Fts3Cursor
*pCsr
= (Fts3Cursor
*)pCursor
;
3305 sqlite3_value
*pCons
= 0; /* The MATCH or rowid constraint, if any */
3306 sqlite3_value
*pLangid
= 0; /* The "langid = ?" constraint, if any */
3307 sqlite3_value
*pDocidGe
= 0; /* The "docid >= ?" constraint, if any */
3308 sqlite3_value
*pDocidLe
= 0; /* The "docid <= ?" constraint, if any */
3311 UNUSED_PARAMETER(idxStr
);
3312 UNUSED_PARAMETER(nVal
);
3315 return SQLITE_ERROR
;
3318 eSearch
= (idxNum
& 0x0000FFFF);
3319 assert( eSearch
>=0 && eSearch
<=(FTS3_FULLTEXT_SEARCH
+p
->nColumn
) );
3320 assert( p
->pSegments
==0 );
3322 /* Collect arguments into local variables */
3324 if( eSearch
!=FTS3_FULLSCAN_SEARCH
) pCons
= apVal
[iIdx
++];
3325 if( idxNum
& FTS3_HAVE_LANGID
) pLangid
= apVal
[iIdx
++];
3326 if( idxNum
& FTS3_HAVE_DOCID_GE
) pDocidGe
= apVal
[iIdx
++];
3327 if( idxNum
& FTS3_HAVE_DOCID_LE
) pDocidLe
= apVal
[iIdx
++];
3328 assert( iIdx
==nVal
);
3330 /* In case the cursor has been used before, clear it now. */
3331 fts3ClearCursor(pCsr
);
3333 /* Set the lower and upper bounds on docids to return */
3334 pCsr
->iMinDocid
= fts3DocidRange(pDocidGe
, SMALLEST_INT64
);
3335 pCsr
->iMaxDocid
= fts3DocidRange(pDocidLe
, LARGEST_INT64
);
3338 pCsr
->bDesc
= (idxStr
[0]=='D');
3340 pCsr
->bDesc
= p
->bDescIdx
;
3342 pCsr
->eSearch
= (i16
)eSearch
;
3344 if( eSearch
!=FTS3_DOCID_SEARCH
&& eSearch
!=FTS3_FULLSCAN_SEARCH
){
3345 int iCol
= eSearch
-FTS3_FULLTEXT_SEARCH
;
3346 const char *zQuery
= (const char *)sqlite3_value_text(pCons
);
3348 if( zQuery
==0 && sqlite3_value_type(pCons
)!=SQLITE_NULL
){
3349 return SQLITE_NOMEM
;
3353 if( pLangid
) pCsr
->iLangid
= sqlite3_value_int(pLangid
);
3355 assert( p
->base
.zErrMsg
==0 );
3356 rc
= sqlite3Fts3ExprParse(p
->pTokenizer
, pCsr
->iLangid
,
3357 p
->azColumn
, p
->bFts4
, p
->nColumn
, iCol
, zQuery
, -1, &pCsr
->pExpr
,
3360 if( rc
!=SQLITE_OK
){
3364 rc
= fts3EvalStart(pCsr
);
3365 sqlite3Fts3SegmentsClose(p
);
3366 if( rc
!=SQLITE_OK
) return rc
;
3367 pCsr
->pNextId
= pCsr
->aDoclist
;
3371 /* Compile a SELECT statement for this cursor. For a full-table-scan, the
3372 ** statement loops through all rows of the %_content table. For a
3373 ** full-text query or docid lookup, the statement retrieves a single
3376 if( eSearch
==FTS3_FULLSCAN_SEARCH
){
3377 if( pDocidGe
|| pDocidLe
){
3378 zSql
= sqlite3_mprintf(
3379 "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
3380 p
->zReadExprlist
, pCsr
->iMinDocid
, pCsr
->iMaxDocid
,
3381 (pCsr
->bDesc
? "DESC" : "ASC")
3384 zSql
= sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
3385 p
->zReadExprlist
, (pCsr
->bDesc
? "DESC" : "ASC")
3390 rc
= sqlite3_prepare_v3(
3391 p
->db
,zSql
,-1,SQLITE_PREPARE_PERSISTENT
,&pCsr
->pStmt
,0
3398 }else if( eSearch
==FTS3_DOCID_SEARCH
){
3399 rc
= fts3CursorSeekStmt(pCsr
);
3400 if( rc
==SQLITE_OK
){
3401 rc
= sqlite3_bind_value(pCsr
->pStmt
, 1, pCons
);
3404 if( rc
!=SQLITE_OK
) return rc
;
3406 return fts3NextMethod(pCursor
);
3410 ** This is the xEof method of the virtual table. SQLite calls this
3411 ** routine to find out if it has reached the end of a result set.
3413 static int fts3EofMethod(sqlite3_vtab_cursor
*pCursor
){
3414 Fts3Cursor
*pCsr
= (Fts3Cursor
*)pCursor
;
3416 fts3ClearCursor(pCsr
);
3423 ** This is the xRowid method. The SQLite core calls this routine to
3424 ** retrieve the rowid for the current row of the result set. fts3
3425 ** exposes %_content.docid as the rowid for the virtual table. The
3426 ** rowid should be written to *pRowid.
3428 static int fts3RowidMethod(sqlite3_vtab_cursor
*pCursor
, sqlite_int64
*pRowid
){
3429 Fts3Cursor
*pCsr
= (Fts3Cursor
*) pCursor
;
3430 *pRowid
= pCsr
->iPrevId
;
3435 ** This is the xColumn method, called by SQLite to request a value from
3436 ** the row that the supplied cursor currently points to.
3440 ** (iCol < p->nColumn) -> The value of the iCol'th user column.
3441 ** (iCol == p->nColumn) -> Magic column with the same name as the table.
3442 ** (iCol == p->nColumn+1) -> Docid column
3443 ** (iCol == p->nColumn+2) -> Langid column
3445 static int fts3ColumnMethod(
3446 sqlite3_vtab_cursor
*pCursor
, /* Cursor to retrieve value from */
3447 sqlite3_context
*pCtx
, /* Context for sqlite3_result_xxx() calls */
3448 int iCol
/* Index of column to read value from */
3450 int rc
= SQLITE_OK
; /* Return Code */
3451 Fts3Cursor
*pCsr
= (Fts3Cursor
*) pCursor
;
3452 Fts3Table
*p
= (Fts3Table
*)pCursor
->pVtab
;
3454 /* The column value supplied by SQLite must be in range. */
3455 assert( iCol
>=0 && iCol
<=p
->nColumn
+2 );
3457 switch( iCol
-p
->nColumn
){
3459 /* The special 'table-name' column */
3460 sqlite3_result_pointer(pCtx
, pCsr
, "fts3cursor", 0);
3464 /* The docid column */
3465 sqlite3_result_int64(pCtx
, pCsr
->iPrevId
);
3470 sqlite3_result_int64(pCtx
, pCsr
->iLangid
);
3472 }else if( p
->zLanguageid
==0 ){
3473 sqlite3_result_int(pCtx
, 0);
3477 /* no break */ deliberate_fall_through
3481 /* A user column. Or, if this is a full-table scan, possibly the
3482 ** language-id column. Seek the cursor. */
3483 rc
= fts3CursorSeek(0, pCsr
);
3484 if( rc
==SQLITE_OK
&& sqlite3_data_count(pCsr
->pStmt
)-1>iCol
){
3485 sqlite3_result_value(pCtx
, sqlite3_column_value(pCsr
->pStmt
, iCol
+1));
3490 assert( ((Fts3Table
*)pCsr
->base
.pVtab
)->pSegments
==0 );
3495 ** This function is the implementation of the xUpdate callback used by
3496 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
3497 ** inserted, updated or deleted.
3499 static int fts3UpdateMethod(
3500 sqlite3_vtab
*pVtab
, /* Virtual table handle */
3501 int nArg
, /* Size of argument array */
3502 sqlite3_value
**apVal
, /* Array of arguments */
3503 sqlite_int64
*pRowid
/* OUT: The affected (or effected) rowid */
3505 return sqlite3Fts3UpdateMethod(pVtab
, nArg
, apVal
, pRowid
);
3509 ** Implementation of xSync() method. Flush the contents of the pending-terms
3510 ** hash-table to the database.
3512 static int fts3SyncMethod(sqlite3_vtab
*pVtab
){
3514 /* Following an incremental-merge operation, assuming that the input
3515 ** segments are not completely consumed (the usual case), they are updated
3516 ** in place to remove the entries that have already been merged. This
3517 ** involves updating the leaf block that contains the smallest unmerged
3518 ** entry and each block (if any) between the leaf and the root node. So
3519 ** if the height of the input segment b-trees is N, and input segments
3520 ** are merged eight at a time, updating the input segments at the end
3521 ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
3522 ** small - often between 0 and 2. So the overhead of the incremental
3523 ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
3524 ** dwarfing the actual productive work accomplished, the incremental merge
3525 ** is only attempted if it will write at least 64 leaf blocks. Hence
3528 ** Of course, updating the input segments also involves deleting a bunch
3529 ** of blocks from the segments table. But this is not considered overhead
3530 ** as it would also be required by a crisis-merge that used the same input
3533 const u32 nMinMerge
= 64; /* Minimum amount of incr-merge work to do */
3535 Fts3Table
*p
= (Fts3Table
*)pVtab
;
3537 i64 iLastRowid
= sqlite3_last_insert_rowid(p
->db
);
3539 rc
= sqlite3Fts3PendingTermsFlush(p
);
3541 && p
->nLeafAdd
>(nMinMerge
/16)
3542 && p
->nAutoincrmerge
&& p
->nAutoincrmerge
!=0xff
3544 int mxLevel
= 0; /* Maximum relative level value in db */
3545 int A
; /* Incr-merge parameter A */
3547 rc
= sqlite3Fts3MaxLevel(p
, &mxLevel
);
3548 assert( rc
==SQLITE_OK
|| mxLevel
==0 );
3549 A
= p
->nLeafAdd
* mxLevel
;
3551 if( A
>(int)nMinMerge
) rc
= sqlite3Fts3Incrmerge(p
, A
, p
->nAutoincrmerge
);
3553 sqlite3Fts3SegmentsClose(p
);
3554 sqlite3_set_last_insert_rowid(p
->db
, iLastRowid
);
3559 ** If it is currently unknown whether or not the FTS table has an %_stat
3560 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
3561 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
3562 ** if an error occurs.
3564 static int fts3SetHasStat(Fts3Table
*p
){
3566 if( p
->bHasStat
==2 ){
3567 char *zTbl
= sqlite3_mprintf("%s_stat", p
->zName
);
3569 int res
= sqlite3_table_column_metadata(p
->db
, p
->zDb
, zTbl
, 0,0,0,0,0,0);
3571 p
->bHasStat
= (res
==SQLITE_OK
);
3580 ** Implementation of xBegin() method.
3582 static int fts3BeginMethod(sqlite3_vtab
*pVtab
){
3583 Fts3Table
*p
= (Fts3Table
*)pVtab
;
3585 UNUSED_PARAMETER(pVtab
);
3586 assert( p
->pSegments
==0 );
3587 assert( p
->nPendingData
==0 );
3588 assert( p
->inTransaction
!=1 );
3590 rc
= fts3SetHasStat(p
);
3592 if( rc
==SQLITE_OK
){
3593 p
->inTransaction
= 1;
3594 p
->mxSavepoint
= -1;
3601 ** Implementation of xCommit() method. This is a no-op. The contents of
3602 ** the pending-terms hash-table have already been flushed into the database
3603 ** by fts3SyncMethod().
3605 static int fts3CommitMethod(sqlite3_vtab
*pVtab
){
3606 TESTONLY( Fts3Table
*p
= (Fts3Table
*)pVtab
);
3607 UNUSED_PARAMETER(pVtab
);
3608 assert( p
->nPendingData
==0 );
3609 assert( p
->inTransaction
!=0 );
3610 assert( p
->pSegments
==0 );
3611 TESTONLY( p
->inTransaction
= 0 );
3612 TESTONLY( p
->mxSavepoint
= -1; );
3617 ** Implementation of xRollback(). Discard the contents of the pending-terms
3618 ** hash-table. Any changes made to the database are reverted by SQLite.
3620 static int fts3RollbackMethod(sqlite3_vtab
*pVtab
){
3621 Fts3Table
*p
= (Fts3Table
*)pVtab
;
3622 sqlite3Fts3PendingTermsClear(p
);
3623 assert( p
->inTransaction
!=0 );
3624 TESTONLY( p
->inTransaction
= 0 );
3625 TESTONLY( p
->mxSavepoint
= -1; );
3630 ** When called, *ppPoslist must point to the byte immediately following the
3631 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
3632 ** moves *ppPoslist so that it instead points to the first byte of the
3633 ** same position list.
3635 static void fts3ReversePoslist(char *pStart
, char **ppPoslist
){
3636 char *p
= &(*ppPoslist
)[-2];
3639 /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
3640 while( p
>pStart
&& (c
=*p
--)==0 );
3642 /* Search backwards for a varint with value zero (the end of the previous
3643 ** poslist). This is an 0x00 byte preceded by some byte that does not
3644 ** have the 0x80 bit set. */
3645 while( p
>pStart
&& (*p
& 0x80) | c
){
3648 assert( p
==pStart
|| c
==0 );
3650 /* At this point p points to that preceding byte without the 0x80 bit
3651 ** set. So to find the start of the poslist, skip forward 2 bytes then
3654 ** Normally. The other case is that p==pStart and the poslist to return
3655 ** is the first in the doclist. In this case do not skip forward 2 bytes.
3656 ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
3657 ** is required for cases where the first byte of a doclist and the
3658 ** doclist is empty. For example, if the first docid is 10, a doclist
3659 ** that begins with:
3661 ** 0x0A 0x00 <next docid delta varint>
3663 if( p
>pStart
|| (c
==0 && *ppPoslist
>&p
[2]) ){ p
= &p
[2]; }
3669 ** Helper function used by the implementation of the overloaded snippet(),
3670 ** offsets() and optimize() SQL functions.
3672 ** If the value passed as the third argument is a blob of size
3673 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
3674 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
3675 ** message is written to context pContext and SQLITE_ERROR returned. The
3676 ** string passed via zFunc is used as part of the error message.
3678 static int fts3FunctionArg(
3679 sqlite3_context
*pContext
, /* SQL function call context */
3680 const char *zFunc
, /* Function name */
3681 sqlite3_value
*pVal
, /* argv[0] passed to function */
3682 Fts3Cursor
**ppCsr
/* OUT: Store cursor handle here */
3685 *ppCsr
= (Fts3Cursor
*)sqlite3_value_pointer(pVal
, "fts3cursor");
3689 char *zErr
= sqlite3_mprintf("illegal first argument to %s", zFunc
);
3690 sqlite3_result_error(pContext
, zErr
, -1);
3698 ** Implementation of the snippet() function for FTS3
3700 static void fts3SnippetFunc(
3701 sqlite3_context
*pContext
, /* SQLite function call context */
3702 int nVal
, /* Size of apVal[] array */
3703 sqlite3_value
**apVal
/* Array of arguments */
3705 Fts3Cursor
*pCsr
; /* Cursor handle passed through apVal[0] */
3706 const char *zStart
= "<b>";
3707 const char *zEnd
= "</b>";
3708 const char *zEllipsis
= "<b>...</b>";
3710 int nToken
= 15; /* Default number of tokens in snippet */
3712 /* There must be at least one argument passed to this function (otherwise
3713 ** the non-overloaded version would have been called instead of this one).
3718 sqlite3_result_error(pContext
,
3719 "wrong number of arguments to function snippet()", -1);
3722 if( fts3FunctionArg(pContext
, "snippet", apVal
[0], &pCsr
) ) return;
3725 case 6: nToken
= sqlite3_value_int(apVal
[5]);
3726 /* no break */ deliberate_fall_through
3727 case 5: iCol
= sqlite3_value_int(apVal
[4]);
3728 /* no break */ deliberate_fall_through
3729 case 4: zEllipsis
= (const char*)sqlite3_value_text(apVal
[3]);
3730 /* no break */ deliberate_fall_through
3731 case 3: zEnd
= (const char*)sqlite3_value_text(apVal
[2]);
3732 /* no break */ deliberate_fall_through
3733 case 2: zStart
= (const char*)sqlite3_value_text(apVal
[1]);
3735 if( !zEllipsis
|| !zEnd
|| !zStart
){
3736 sqlite3_result_error_nomem(pContext
);
3737 }else if( nToken
==0 ){
3738 sqlite3_result_text(pContext
, "", -1, SQLITE_STATIC
);
3739 }else if( SQLITE_OK
==fts3CursorSeek(pContext
, pCsr
) ){
3740 sqlite3Fts3Snippet(pContext
, pCsr
, zStart
, zEnd
, zEllipsis
, iCol
, nToken
);
3745 ** Implementation of the offsets() function for FTS3
3747 static void fts3OffsetsFunc(
3748 sqlite3_context
*pContext
, /* SQLite function call context */
3749 int nVal
, /* Size of argument array */
3750 sqlite3_value
**apVal
/* Array of arguments */
3752 Fts3Cursor
*pCsr
; /* Cursor handle passed through apVal[0] */
3754 UNUSED_PARAMETER(nVal
);
3757 if( fts3FunctionArg(pContext
, "offsets", apVal
[0], &pCsr
) ) return;
3759 if( SQLITE_OK
==fts3CursorSeek(pContext
, pCsr
) ){
3760 sqlite3Fts3Offsets(pContext
, pCsr
);
3765 ** Implementation of the special optimize() function for FTS3. This
3766 ** function merges all segments in the database to a single segment.
3767 ** Example usage is:
3769 ** SELECT optimize(t) FROM t LIMIT 1;
3771 ** where 't' is the name of an FTS3 table.
3773 static void fts3OptimizeFunc(
3774 sqlite3_context
*pContext
, /* SQLite function call context */
3775 int nVal
, /* Size of argument array */
3776 sqlite3_value
**apVal
/* Array of arguments */
3778 int rc
; /* Return code */
3779 Fts3Table
*p
; /* Virtual table handle */
3780 Fts3Cursor
*pCursor
; /* Cursor handle passed through apVal[0] */
3782 UNUSED_PARAMETER(nVal
);
3785 if( fts3FunctionArg(pContext
, "optimize", apVal
[0], &pCursor
) ) return;
3786 p
= (Fts3Table
*)pCursor
->base
.pVtab
;
3789 rc
= sqlite3Fts3Optimize(p
);
3793 sqlite3_result_text(pContext
, "Index optimized", -1, SQLITE_STATIC
);
3796 sqlite3_result_text(pContext
, "Index already optimal", -1, SQLITE_STATIC
);
3799 sqlite3_result_error_code(pContext
, rc
);
3805 ** Implementation of the matchinfo() function for FTS3
3807 static void fts3MatchinfoFunc(
3808 sqlite3_context
*pContext
, /* SQLite function call context */
3809 int nVal
, /* Size of argument array */
3810 sqlite3_value
**apVal
/* Array of arguments */
3812 Fts3Cursor
*pCsr
; /* Cursor handle passed through apVal[0] */
3813 assert( nVal
==1 || nVal
==2 );
3814 if( SQLITE_OK
==fts3FunctionArg(pContext
, "matchinfo", apVal
[0], &pCsr
) ){
3815 const char *zArg
= 0;
3817 zArg
= (const char *)sqlite3_value_text(apVal
[1]);
3819 sqlite3Fts3Matchinfo(pContext
, pCsr
, zArg
);
3824 ** This routine implements the xFindFunction method for the FTS3
3827 static int fts3FindFunctionMethod(
3828 sqlite3_vtab
*pVtab
, /* Virtual table handle */
3829 int nArg
, /* Number of SQL function arguments */
3830 const char *zName
, /* Name of SQL function */
3831 void (**pxFunc
)(sqlite3_context
*,int,sqlite3_value
**), /* OUT: Result */
3832 void **ppArg
/* Unused */
3836 void (*xFunc
)(sqlite3_context
*,int,sqlite3_value
**);
3838 { "snippet", fts3SnippetFunc
},
3839 { "offsets", fts3OffsetsFunc
},
3840 { "optimize", fts3OptimizeFunc
},
3841 { "matchinfo", fts3MatchinfoFunc
},
3843 int i
; /* Iterator variable */
3845 UNUSED_PARAMETER(pVtab
);
3846 UNUSED_PARAMETER(nArg
);
3847 UNUSED_PARAMETER(ppArg
);
3849 for(i
=0; i
<SizeofArray(aOverload
); i
++){
3850 if( strcmp(zName
, aOverload
[i
].zName
)==0 ){
3851 *pxFunc
= aOverload
[i
].xFunc
;
3856 /* No function of the specified name was found. Return 0. */
3861 ** Implementation of FTS3 xRename method. Rename an fts3 table.
3863 static int fts3RenameMethod(
3864 sqlite3_vtab
*pVtab
, /* Virtual table handle */
3865 const char *zName
/* New name of table */
3867 Fts3Table
*p
= (Fts3Table
*)pVtab
;
3868 sqlite3
*db
= p
->db
; /* Database connection */
3869 int rc
; /* Return Code */
3871 /* At this point it must be known if the %_stat table exists or not.
3872 ** So bHasStat may not be 2. */
3873 rc
= fts3SetHasStat(p
);
3875 /* As it happens, the pending terms table is always empty here. This is
3876 ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
3877 ** always opens a savepoint transaction. And the xSavepoint() method
3878 ** flushes the pending terms table. But leave the (no-op) call to
3879 ** PendingTermsFlush() in in case that changes.
3881 assert( p
->nPendingData
==0 );
3882 if( rc
==SQLITE_OK
){
3883 rc
= sqlite3Fts3PendingTermsFlush(p
);
3886 if( p
->zContentTbl
==0 ){
3888 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
3889 p
->zDb
, p
->zName
, zName
3893 if( p
->bHasDocsize
){
3895 "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
3896 p
->zDb
, p
->zName
, zName
3901 "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
3902 p
->zDb
, p
->zName
, zName
3906 "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
3907 p
->zDb
, p
->zName
, zName
3910 "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
3911 p
->zDb
, p
->zName
, zName
3917 ** The xSavepoint() method.
3919 ** Flush the contents of the pending-terms table to disk.
3921 static int fts3SavepointMethod(sqlite3_vtab
*pVtab
, int iSavepoint
){
3923 UNUSED_PARAMETER(iSavepoint
);
3924 assert( ((Fts3Table
*)pVtab
)->inTransaction
);
3925 assert( ((Fts3Table
*)pVtab
)->mxSavepoint
<= iSavepoint
);
3926 TESTONLY( ((Fts3Table
*)pVtab
)->mxSavepoint
= iSavepoint
);
3927 if( ((Fts3Table
*)pVtab
)->bIgnoreSavepoint
==0 ){
3928 rc
= fts3SyncMethod(pVtab
);
3934 ** The xRelease() method.
3938 static int fts3ReleaseMethod(sqlite3_vtab
*pVtab
, int iSavepoint
){
3939 TESTONLY( Fts3Table
*p
= (Fts3Table
*)pVtab
);
3940 UNUSED_PARAMETER(iSavepoint
);
3941 UNUSED_PARAMETER(pVtab
);
3942 assert( p
->inTransaction
);
3943 assert( p
->mxSavepoint
>= iSavepoint
);
3944 TESTONLY( p
->mxSavepoint
= iSavepoint
-1 );
3949 ** The xRollbackTo() method.
3951 ** Discard the contents of the pending terms table.
3953 static int fts3RollbackToMethod(sqlite3_vtab
*pVtab
, int iSavepoint
){
3954 Fts3Table
*p
= (Fts3Table
*)pVtab
;
3955 UNUSED_PARAMETER(iSavepoint
);
3956 assert( p
->inTransaction
);
3957 TESTONLY( p
->mxSavepoint
= iSavepoint
);
3958 sqlite3Fts3PendingTermsClear(p
);
3963 ** Return true if zName is the extension on one of the shadow tables used
3966 static int fts3ShadowName(const char *zName
){
3967 static const char *azName
[] = {
3968 "content", "docsize", "segdir", "segments", "stat",
3971 for(i
=0; i
<sizeof(azName
)/sizeof(azName
[0]); i
++){
3972 if( sqlite3_stricmp(zName
, azName
[i
])==0 ) return 1;
3977 static const sqlite3_module fts3Module
= {
3979 /* xCreate */ fts3CreateMethod
,
3980 /* xConnect */ fts3ConnectMethod
,
3981 /* xBestIndex */ fts3BestIndexMethod
,
3982 /* xDisconnect */ fts3DisconnectMethod
,
3983 /* xDestroy */ fts3DestroyMethod
,
3984 /* xOpen */ fts3OpenMethod
,
3985 /* xClose */ fts3CloseMethod
,
3986 /* xFilter */ fts3FilterMethod
,
3987 /* xNext */ fts3NextMethod
,
3988 /* xEof */ fts3EofMethod
,
3989 /* xColumn */ fts3ColumnMethod
,
3990 /* xRowid */ fts3RowidMethod
,
3991 /* xUpdate */ fts3UpdateMethod
,
3992 /* xBegin */ fts3BeginMethod
,
3993 /* xSync */ fts3SyncMethod
,
3994 /* xCommit */ fts3CommitMethod
,
3995 /* xRollback */ fts3RollbackMethod
,
3996 /* xFindFunction */ fts3FindFunctionMethod
,
3997 /* xRename */ fts3RenameMethod
,
3998 /* xSavepoint */ fts3SavepointMethod
,
3999 /* xRelease */ fts3ReleaseMethod
,
4000 /* xRollbackTo */ fts3RollbackToMethod
,
4001 /* xShadowName */ fts3ShadowName
,
4005 ** This function is registered as the module destructor (called when an
4006 ** FTS3 enabled database connection is closed). It frees the memory
4007 ** allocated for the tokenizer hash table.
4009 static void hashDestroy(void *p
){
4010 Fts3Hash
*pHash
= (Fts3Hash
*)p
;
4011 sqlite3Fts3HashClear(pHash
);
4012 sqlite3_free(pHash
);
4016 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
4017 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
4018 ** respectively. The following three forward declarations are for functions
4019 ** declared in these files used to retrieve the respective implementations.
4021 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
4022 ** to by the argument to point to the "simple" tokenizer implementation.
4025 void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module
const**ppModule
);
4026 void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module
const**ppModule
);
4027 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4028 void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module
const**ppModule
);
4030 #ifdef SQLITE_ENABLE_ICU
4031 void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module
const**ppModule
);
4035 ** Initialize the fts3 extension. If this extension is built as part
4036 ** of the sqlite library, then this function is called directly by
4037 ** SQLite. If fts3 is built as a dynamically loadable extension, this
4038 ** function is called by the sqlite3_extension_init() entry point.
4040 int sqlite3Fts3Init(sqlite3
*db
){
4042 Fts3Hash
*pHash
= 0;
4043 const sqlite3_tokenizer_module
*pSimple
= 0;
4044 const sqlite3_tokenizer_module
*pPorter
= 0;
4045 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4046 const sqlite3_tokenizer_module
*pUnicode
= 0;
4049 #ifdef SQLITE_ENABLE_ICU
4050 const sqlite3_tokenizer_module
*pIcu
= 0;
4051 sqlite3Fts3IcuTokenizerModule(&pIcu
);
4054 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4055 sqlite3Fts3UnicodeTokenizer(&pUnicode
);
4059 rc
= sqlite3Fts3InitTerm(db
);
4060 if( rc
!=SQLITE_OK
) return rc
;
4063 rc
= sqlite3Fts3InitAux(db
);
4064 if( rc
!=SQLITE_OK
) return rc
;
4066 sqlite3Fts3SimpleTokenizerModule(&pSimple
);
4067 sqlite3Fts3PorterTokenizerModule(&pPorter
);
4069 /* Allocate and initialize the hash-table used to store tokenizers. */
4070 pHash
= sqlite3_malloc(sizeof(Fts3Hash
));
4074 sqlite3Fts3HashInit(pHash
, FTS3_HASH_STRING
, 1);
4077 /* Load the built-in tokenizers into the hash table */
4078 if( rc
==SQLITE_OK
){
4079 if( sqlite3Fts3HashInsert(pHash
, "simple", 7, (void *)pSimple
)
4080 || sqlite3Fts3HashInsert(pHash
, "porter", 7, (void *)pPorter
)
4082 #ifndef SQLITE_DISABLE_FTS3_UNICODE
4083 || sqlite3Fts3HashInsert(pHash
, "unicode61", 10, (void *)pUnicode
)
4085 #ifdef SQLITE_ENABLE_ICU
4086 || (pIcu
&& sqlite3Fts3HashInsert(pHash
, "icu", 4, (void *)pIcu
))
4094 if( rc
==SQLITE_OK
){
4095 rc
= sqlite3Fts3ExprInitTestInterface(db
, pHash
);
4099 /* Create the virtual table wrapper around the hash-table and overload
4100 ** the four scalar functions. If this is successful, register the
4101 ** module with sqlite.
4104 && SQLITE_OK
==(rc
= sqlite3Fts3InitHashTable(db
, pHash
, "fts3_tokenizer"))
4105 && SQLITE_OK
==(rc
= sqlite3_overload_function(db
, "snippet", -1))
4106 && SQLITE_OK
==(rc
= sqlite3_overload_function(db
, "offsets", 1))
4107 && SQLITE_OK
==(rc
= sqlite3_overload_function(db
, "matchinfo", 1))
4108 && SQLITE_OK
==(rc
= sqlite3_overload_function(db
, "matchinfo", 2))
4109 && SQLITE_OK
==(rc
= sqlite3_overload_function(db
, "optimize", 1))
4111 rc
= sqlite3_create_module_v2(
4112 db
, "fts3", &fts3Module
, (void *)pHash
, hashDestroy
4114 if( rc
==SQLITE_OK
){
4115 rc
= sqlite3_create_module_v2(
4116 db
, "fts4", &fts3Module
, (void *)pHash
, 0
4119 if( rc
==SQLITE_OK
){
4120 rc
= sqlite3Fts3InitTok(db
, (void *)pHash
);
4126 /* An error has occurred. Delete the hash table and return the error code. */
4127 assert( rc
!=SQLITE_OK
);
4129 sqlite3Fts3HashClear(pHash
);
4130 sqlite3_free(pHash
);
4136 ** Allocate an Fts3MultiSegReader for each token in the expression headed
4139 ** An Fts3SegReader object is a cursor that can seek or scan a range of
4140 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
4141 ** Fts3SegReader objects internally to provide an interface to seek or scan
4142 ** within the union of all segments of a b-tree. Hence the name.
4144 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
4145 ** segment b-tree (if the term is not a prefix or it is a prefix for which
4146 ** there exists prefix b-tree of the right length) then it may be traversed
4147 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
4148 ** doclist and then traversed.
4150 static void fts3EvalAllocateReaders(
4151 Fts3Cursor
*pCsr
, /* FTS cursor handle */
4152 Fts3Expr
*pExpr
, /* Allocate readers for this expression */
4153 int *pnToken
, /* OUT: Total number of tokens in phrase. */
4154 int *pnOr
, /* OUT: Total number of OR nodes in expr. */
4155 int *pRc
/* IN/OUT: Error code */
4157 if( pExpr
&& SQLITE_OK
==*pRc
){
4158 if( pExpr
->eType
==FTSQUERY_PHRASE
){
4160 int nToken
= pExpr
->pPhrase
->nToken
;
4162 for(i
=0; i
<nToken
; i
++){
4163 Fts3PhraseToken
*pToken
= &pExpr
->pPhrase
->aToken
[i
];
4164 int rc
= fts3TermSegReaderCursor(pCsr
,
4165 pToken
->z
, pToken
->n
, pToken
->isPrefix
, &pToken
->pSegcsr
4167 if( rc
!=SQLITE_OK
){
4172 assert( pExpr
->pPhrase
->iDoclistToken
==0 );
4173 pExpr
->pPhrase
->iDoclistToken
= -1;
4175 *pnOr
+= (pExpr
->eType
==FTSQUERY_OR
);
4176 fts3EvalAllocateReaders(pCsr
, pExpr
->pLeft
, pnToken
, pnOr
, pRc
);
4177 fts3EvalAllocateReaders(pCsr
, pExpr
->pRight
, pnToken
, pnOr
, pRc
);
4183 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
4184 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
4186 ** This function assumes that pList points to a buffer allocated using
4187 ** sqlite3_malloc(). This function takes responsibility for eventually
4188 ** freeing the buffer.
4190 ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
4192 static int fts3EvalPhraseMergeToken(
4193 Fts3Table
*pTab
, /* FTS Table pointer */
4194 Fts3Phrase
*p
, /* Phrase to merge pList/nList into */
4195 int iToken
, /* Token pList/nList corresponds to */
4196 char *pList
, /* Pointer to doclist */
4197 int nList
/* Number of bytes in pList */
4200 assert( iToken
!=p
->iDoclistToken
);
4203 sqlite3_free(p
->doclist
.aAll
);
4204 p
->doclist
.aAll
= 0;
4205 p
->doclist
.nAll
= 0;
4208 else if( p
->iDoclistToken
<0 ){
4209 p
->doclist
.aAll
= pList
;
4210 p
->doclist
.nAll
= nList
;
4213 else if( p
->doclist
.aAll
==0 ){
4214 sqlite3_free(pList
);
4224 if( p
->iDoclistToken
<iToken
){
4225 pLeft
= p
->doclist
.aAll
;
4226 nLeft
= p
->doclist
.nAll
;
4229 nDiff
= iToken
- p
->iDoclistToken
;
4231 pRight
= p
->doclist
.aAll
;
4232 nRight
= p
->doclist
.nAll
;
4235 nDiff
= p
->iDoclistToken
- iToken
;
4238 rc
= fts3DoclistPhraseMerge(
4239 pTab
->bDescIdx
, nDiff
, pLeft
, nLeft
, &pRight
, &nRight
4241 sqlite3_free(pLeft
);
4242 p
->doclist
.aAll
= pRight
;
4243 p
->doclist
.nAll
= nRight
;
4246 if( iToken
>p
->iDoclistToken
) p
->iDoclistToken
= iToken
;
4251 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
4252 ** does not take deferred tokens into account.
4254 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
4256 static int fts3EvalPhraseLoad(
4257 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4258 Fts3Phrase
*p
/* Phrase object */
4260 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
4264 for(iToken
=0; rc
==SQLITE_OK
&& iToken
<p
->nToken
; iToken
++){
4265 Fts3PhraseToken
*pToken
= &p
->aToken
[iToken
];
4266 assert( pToken
->pDeferred
==0 || pToken
->pSegcsr
==0 );
4268 if( pToken
->pSegcsr
){
4271 rc
= fts3TermSelect(pTab
, pToken
, p
->iColumn
, &nThis
, &pThis
);
4272 if( rc
==SQLITE_OK
){
4273 rc
= fts3EvalPhraseMergeToken(pTab
, p
, iToken
, pThis
, nThis
);
4276 assert( pToken
->pSegcsr
==0 );
4282 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
4284 ** This function is called on each phrase after the position lists for
4285 ** any deferred tokens have been loaded into memory. It updates the phrases
4286 ** current position list to include only those positions that are really
4287 ** instances of the phrase (after considering deferred tokens). If this
4288 ** means that the phrase does not appear in the current row, doclist.pList
4289 ** and doclist.nList are both zeroed.
4291 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
4293 static int fts3EvalDeferredPhrase(Fts3Cursor
*pCsr
, Fts3Phrase
*pPhrase
){
4294 int iToken
; /* Used to iterate through phrase tokens */
4295 char *aPoslist
= 0; /* Position list for deferred tokens */
4296 int nPoslist
= 0; /* Number of bytes in aPoslist */
4297 int iPrev
= -1; /* Token number of previous deferred token */
4299 assert( pPhrase
->doclist
.bFreeList
==0 );
4301 for(iToken
=0; iToken
<pPhrase
->nToken
; iToken
++){
4302 Fts3PhraseToken
*pToken
= &pPhrase
->aToken
[iToken
];
4303 Fts3DeferredToken
*pDeferred
= pToken
->pDeferred
;
4308 int rc
= sqlite3Fts3DeferredTokenList(pDeferred
, &pList
, &nList
);
4309 if( rc
!=SQLITE_OK
) return rc
;
4312 sqlite3_free(aPoslist
);
4313 pPhrase
->doclist
.pList
= 0;
4314 pPhrase
->doclist
.nList
= 0;
4317 }else if( aPoslist
==0 ){
4323 char *p1
= aPoslist
;
4327 fts3PoslistPhraseMerge(&aOut
, iToken
-iPrev
, 0, 1, &p1
, &p2
);
4328 sqlite3_free(aPoslist
);
4330 nPoslist
= (int)(aOut
- aPoslist
);
4332 sqlite3_free(aPoslist
);
4333 pPhrase
->doclist
.pList
= 0;
4334 pPhrase
->doclist
.nList
= 0;
4343 int nMaxUndeferred
= pPhrase
->iDoclistToken
;
4344 if( nMaxUndeferred
<0 ){
4345 pPhrase
->doclist
.pList
= aPoslist
;
4346 pPhrase
->doclist
.nList
= nPoslist
;
4347 pPhrase
->doclist
.iDocid
= pCsr
->iPrevId
;
4348 pPhrase
->doclist
.bFreeList
= 1;
4355 if( nMaxUndeferred
>iPrev
){
4357 p2
= pPhrase
->doclist
.pList
;
4358 nDistance
= nMaxUndeferred
- iPrev
;
4360 p1
= pPhrase
->doclist
.pList
;
4362 nDistance
= iPrev
- nMaxUndeferred
;
4365 aOut
= (char *)sqlite3_malloc(nPoslist
+8);
4367 sqlite3_free(aPoslist
);
4368 return SQLITE_NOMEM
;
4371 pPhrase
->doclist
.pList
= aOut
;
4372 if( fts3PoslistPhraseMerge(&aOut
, nDistance
, 0, 1, &p1
, &p2
) ){
4373 pPhrase
->doclist
.bFreeList
= 1;
4374 pPhrase
->doclist
.nList
= (int)(aOut
- pPhrase
->doclist
.pList
);
4377 pPhrase
->doclist
.pList
= 0;
4378 pPhrase
->doclist
.nList
= 0;
4380 sqlite3_free(aPoslist
);
4386 #endif /* SQLITE_DISABLE_FTS4_DEFERRED */
4389 ** Maximum number of tokens a phrase may have to be considered for the
4390 ** incremental doclists strategy.
4392 #define MAX_INCR_PHRASE_TOKENS 4
4395 ** This function is called for each Fts3Phrase in a full-text query
4396 ** expression to initialize the mechanism for returning rows. Once this
4397 ** function has been called successfully on an Fts3Phrase, it may be
4398 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
4400 ** If parameter bOptOk is true, then the phrase may (or may not) use the
4401 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
4402 ** memory within this call.
4404 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
4406 static int fts3EvalPhraseStart(Fts3Cursor
*pCsr
, int bOptOk
, Fts3Phrase
*p
){
4407 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
4408 int rc
= SQLITE_OK
; /* Error code */
4411 /* Determine if doclists may be loaded from disk incrementally. This is
4412 ** possible if the bOptOk argument is true, the FTS doclists will be
4413 ** scanned in forward order, and the phrase consists of
4414 ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
4415 ** tokens or prefix tokens that cannot use a prefix-index. */
4417 int bIncrOk
= (bOptOk
4418 && pCsr
->bDesc
==pTab
->bDescIdx
4419 && p
->nToken
<=MAX_INCR_PHRASE_TOKENS
&& p
->nToken
>0
4420 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
4421 && pTab
->bNoIncrDoclist
==0
4424 for(i
=0; bIncrOk
==1 && i
<p
->nToken
; i
++){
4425 Fts3PhraseToken
*pToken
= &p
->aToken
[i
];
4426 if( pToken
->bFirst
|| (pToken
->pSegcsr
!=0 && !pToken
->pSegcsr
->bLookup
) ){
4429 if( pToken
->pSegcsr
) bHaveIncr
= 1;
4432 if( bIncrOk
&& bHaveIncr
){
4433 /* Use the incremental approach. */
4434 int iCol
= (p
->iColumn
>= pTab
->nColumn
? -1 : p
->iColumn
);
4435 for(i
=0; rc
==SQLITE_OK
&& i
<p
->nToken
; i
++){
4436 Fts3PhraseToken
*pToken
= &p
->aToken
[i
];
4437 Fts3MultiSegReader
*pSegcsr
= pToken
->pSegcsr
;
4439 rc
= sqlite3Fts3MsrIncrStart(pTab
, pSegcsr
, iCol
, pToken
->z
, pToken
->n
);
4444 /* Load the full doclist for the phrase into memory. */
4445 rc
= fts3EvalPhraseLoad(pCsr
, p
);
4449 assert( rc
!=SQLITE_OK
|| p
->nToken
<1 || p
->aToken
[0].pSegcsr
==0 || p
->bIncr
);
4454 ** This function is used to iterate backwards (from the end to start)
4455 ** through doclists. It is used by this module to iterate through phrase
4456 ** doclists in reverse and by the fts3_write.c module to iterate through
4457 ** pending-terms lists when writing to databases with "order=desc".
4459 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
4460 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
4461 ** function iterates from the end of the doclist to the beginning.
4463 void sqlite3Fts3DoclistPrev(
4464 int bDescIdx
, /* True if the doclist is desc */
4465 char *aDoclist
, /* Pointer to entire doclist */
4466 int nDoclist
, /* Length of aDoclist in bytes */
4467 char **ppIter
, /* IN/OUT: Iterator pointer */
4468 sqlite3_int64
*piDocid
, /* IN/OUT: Docid pointer */
4469 int *pnList
, /* OUT: List length pointer */
4470 u8
*pbEof
/* OUT: End-of-file flag */
4474 assert( nDoclist
>0 );
4475 assert( *pbEof
==0 );
4476 assert_fts3_nc( p
|| *piDocid
==0 );
4477 assert( !p
|| (p
>aDoclist
&& p
<&aDoclist
[nDoclist
]) );
4480 sqlite3_int64 iDocid
= 0;
4482 char *pDocid
= aDoclist
;
4483 char *pEnd
= &aDoclist
[nDoclist
];
4486 while( pDocid
<pEnd
){
4487 sqlite3_int64 iDelta
;
4488 pDocid
+= sqlite3Fts3GetVarint(pDocid
, &iDelta
);
4489 iDocid
+= (iMul
* iDelta
);
4491 fts3PoslistCopy(0, &pDocid
);
4492 while( pDocid
<pEnd
&& *pDocid
==0 ) pDocid
++;
4493 iMul
= (bDescIdx
? -1 : 1);
4496 *pnList
= (int)(pEnd
- pNext
);
4500 int iMul
= (bDescIdx
? -1 : 1);
4501 sqlite3_int64 iDelta
;
4502 fts3GetReverseVarint(&p
, aDoclist
, &iDelta
);
4503 *piDocid
-= (iMul
* iDelta
);
4509 fts3ReversePoslist(aDoclist
, &p
);
4510 *pnList
= (int)(pSave
- p
);
4517 ** Iterate forwards through a doclist.
4519 void sqlite3Fts3DoclistNext(
4520 int bDescIdx
, /* True if the doclist is desc */
4521 char *aDoclist
, /* Pointer to entire doclist */
4522 int nDoclist
, /* Length of aDoclist in bytes */
4523 char **ppIter
, /* IN/OUT: Iterator pointer */
4524 sqlite3_int64
*piDocid
, /* IN/OUT: Docid pointer */
4525 u8
*pbEof
/* OUT: End-of-file flag */
4529 assert( nDoclist
>0 );
4530 assert( *pbEof
==0 );
4531 assert_fts3_nc( p
|| *piDocid
==0 );
4532 assert( !p
|| (p
>=aDoclist
&& p
<=&aDoclist
[nDoclist
]) );
4536 p
+= sqlite3Fts3GetVarint(p
, piDocid
);
4538 fts3PoslistCopy(0, &p
);
4539 while( p
<&aDoclist
[nDoclist
] && *p
==0 ) p
++;
4540 if( p
>=&aDoclist
[nDoclist
] ){
4544 p
+= sqlite3Fts3GetVarint(p
, &iVar
);
4545 *piDocid
+= ((bDescIdx
? -1 : 1) * iVar
);
4553 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
4554 ** to true if EOF is reached.
4556 static void fts3EvalDlPhraseNext(
4561 char *pIter
; /* Used to iterate through aAll */
4562 char *pEnd
; /* 1 byte past end of aAll */
4564 if( pDL
->pNextDocid
){
4565 pIter
= pDL
->pNextDocid
;
4566 assert( pDL
->aAll
!=0 || pIter
==0 );
4571 if( pIter
==0 || pIter
>=(pEnd
= pDL
->aAll
+ pDL
->nAll
) ){
4572 /* We have already reached the end of this doclist. EOF. */
4575 sqlite3_int64 iDelta
;
4576 pIter
+= sqlite3Fts3GetVarint(pIter
, &iDelta
);
4577 if( pTab
->bDescIdx
==0 || pDL
->pNextDocid
==0 ){
4578 pDL
->iDocid
+= iDelta
;
4580 pDL
->iDocid
-= iDelta
;
4583 fts3PoslistCopy(0, &pIter
);
4584 pDL
->nList
= (int)(pIter
- pDL
->pList
);
4586 /* pIter now points just past the 0x00 that terminates the position-
4587 ** list for document pDL->iDocid. However, if this position-list was
4588 ** edited in place by fts3EvalNearTrim(), then pIter may not actually
4589 ** point to the start of the next docid value. The following line deals
4590 ** with this case by advancing pIter past the zero-padding added by
4591 ** fts3EvalNearTrim(). */
4592 while( pIter
<pEnd
&& *pIter
==0 ) pIter
++;
4594 pDL
->pNextDocid
= pIter
;
4595 assert( pIter
>=&pDL
->aAll
[pDL
->nAll
] || *pIter
);
4601 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
4603 typedef struct TokenDoclist TokenDoclist
;
4604 struct TokenDoclist
{
4606 sqlite3_int64 iDocid
;
4612 ** Token pToken is an incrementally loaded token that is part of a
4613 ** multi-token phrase. Advance it to the next matching document in the
4614 ** database and populate output variable *p with the details of the new
4615 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
4617 ** If an error occurs, return an SQLite error code. Otherwise, return
4620 static int incrPhraseTokenNext(
4621 Fts3Table
*pTab
, /* Virtual table handle */
4622 Fts3Phrase
*pPhrase
, /* Phrase to advance token of */
4623 int iToken
, /* Specific token to advance */
4624 TokenDoclist
*p
, /* OUT: Docid and doclist for new entry */
4625 u8
*pbEof
/* OUT: True if iterator is at EOF */
4629 if( pPhrase
->iDoclistToken
==iToken
){
4630 assert( p
->bIgnore
==0 );
4631 assert( pPhrase
->aToken
[iToken
].pSegcsr
==0 );
4632 fts3EvalDlPhraseNext(pTab
, &pPhrase
->doclist
, pbEof
);
4633 p
->pList
= pPhrase
->doclist
.pList
;
4634 p
->nList
= pPhrase
->doclist
.nList
;
4635 p
->iDocid
= pPhrase
->doclist
.iDocid
;
4637 Fts3PhraseToken
*pToken
= &pPhrase
->aToken
[iToken
];
4638 assert( pToken
->pDeferred
==0 );
4639 assert( pToken
->pSegcsr
|| pPhrase
->iDoclistToken
>=0 );
4640 if( pToken
->pSegcsr
){
4641 assert( p
->bIgnore
==0 );
4642 rc
= sqlite3Fts3MsrIncrNext(
4643 pTab
, pToken
->pSegcsr
, &p
->iDocid
, &p
->pList
, &p
->nList
4645 if( p
->pList
==0 ) *pbEof
= 1;
4656 ** The phrase iterator passed as the second argument:
4658 ** * features at least one token that uses an incremental doclist, and
4660 ** * does not contain any deferred tokens.
4662 ** Advance it to the next matching documnent in the database and populate
4663 ** the Fts3Doclist.pList and nList fields.
4665 ** If there is no "next" entry and no error occurs, then *pbEof is set to
4666 ** 1 before returning. Otherwise, if no error occurs and the iterator is
4667 ** successfully advanced, *pbEof is set to 0.
4669 ** If an error occurs, return an SQLite error code. Otherwise, return
4672 static int fts3EvalIncrPhraseNext(
4673 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4674 Fts3Phrase
*p
, /* Phrase object to advance to next docid */
4675 u8
*pbEof
/* OUT: Set to 1 if EOF */
4678 Fts3Doclist
*pDL
= &p
->doclist
;
4679 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
4682 /* This is only called if it is guaranteed that the phrase has at least
4683 ** one incremental token. In which case the bIncr flag is set. */
4684 assert( p
->bIncr
==1 );
4687 rc
= sqlite3Fts3MsrIncrNext(pTab
, p
->aToken
[0].pSegcsr
,
4688 &pDL
->iDocid
, &pDL
->pList
, &pDL
->nList
4690 if( pDL
->pList
==0 ) bEof
= 1;
4692 int bDescDoclist
= pCsr
->bDesc
;
4693 struct TokenDoclist a
[MAX_INCR_PHRASE_TOKENS
];
4695 memset(a
, 0, sizeof(a
));
4696 assert( p
->nToken
<=MAX_INCR_PHRASE_TOKENS
);
4697 assert( p
->iDoclistToken
<MAX_INCR_PHRASE_TOKENS
);
4701 sqlite3_int64 iMax
= 0; /* Largest docid for all iterators */
4702 int i
; /* Used to iterate through tokens */
4704 /* Advance the iterator for each token in the phrase once. */
4705 for(i
=0; rc
==SQLITE_OK
&& i
<p
->nToken
&& bEof
==0; i
++){
4706 rc
= incrPhraseTokenNext(pTab
, p
, i
, &a
[i
], &bEof
);
4707 if( a
[i
].bIgnore
==0 && (bMaxSet
==0 || DOCID_CMP(iMax
, a
[i
].iDocid
)<0) ){
4712 assert( rc
!=SQLITE_OK
|| (p
->nToken
>=1 && a
[p
->nToken
-1].bIgnore
==0) );
4713 assert( rc
!=SQLITE_OK
|| bMaxSet
);
4715 /* Keep advancing iterators until they all point to the same document */
4716 for(i
=0; i
<p
->nToken
; i
++){
4717 while( rc
==SQLITE_OK
&& bEof
==0
4718 && a
[i
].bIgnore
==0 && DOCID_CMP(a
[i
].iDocid
, iMax
)<0
4720 rc
= incrPhraseTokenNext(pTab
, p
, i
, &a
[i
], &bEof
);
4721 if( DOCID_CMP(a
[i
].iDocid
, iMax
)>0 ){
4728 /* Check if the current entries really are a phrase match */
4731 int nByte
= a
[p
->nToken
-1].nList
;
4732 char *aDoclist
= sqlite3_malloc(nByte
+FTS3_BUFFER_PADDING
);
4733 if( !aDoclist
) return SQLITE_NOMEM
;
4734 memcpy(aDoclist
, a
[p
->nToken
-1].pList
, nByte
+1);
4735 memset(&aDoclist
[nByte
], 0, FTS3_BUFFER_PADDING
);
4737 for(i
=0; i
<(p
->nToken
-1); i
++){
4738 if( a
[i
].bIgnore
==0 ){
4739 char *pL
= a
[i
].pList
;
4740 char *pR
= aDoclist
;
4741 char *pOut
= aDoclist
;
4742 int nDist
= p
->nToken
-1-i
;
4743 int res
= fts3PoslistPhraseMerge(&pOut
, nDist
, 0, 1, &pL
, &pR
);
4745 nList
= (int)(pOut
- aDoclist
);
4748 if( i
==(p
->nToken
-1) ){
4750 pDL
->pList
= aDoclist
;
4755 sqlite3_free(aDoclist
);
4765 ** Attempt to move the phrase iterator to point to the next matching docid.
4766 ** If an error occurs, return an SQLite error code. Otherwise, return
4769 ** If there is no "next" entry and no error occurs, then *pbEof is set to
4770 ** 1 before returning. Otherwise, if no error occurs and the iterator is
4771 ** successfully advanced, *pbEof is set to 0.
4773 static int fts3EvalPhraseNext(
4774 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4775 Fts3Phrase
*p
, /* Phrase object to advance to next docid */
4776 u8
*pbEof
/* OUT: Set to 1 if EOF */
4779 Fts3Doclist
*pDL
= &p
->doclist
;
4780 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
4783 rc
= fts3EvalIncrPhraseNext(pCsr
, p
, pbEof
);
4784 }else if( pCsr
->bDesc
!=pTab
->bDescIdx
&& pDL
->nAll
){
4785 sqlite3Fts3DoclistPrev(pTab
->bDescIdx
, pDL
->aAll
, pDL
->nAll
,
4786 &pDL
->pNextDocid
, &pDL
->iDocid
, &pDL
->nList
, pbEof
4788 pDL
->pList
= pDL
->pNextDocid
;
4790 fts3EvalDlPhraseNext(pTab
, pDL
, pbEof
);
4798 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
4799 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
4800 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
4801 ** expressions for which all descendent tokens are deferred.
4803 ** If parameter bOptOk is zero, then it is guaranteed that the
4804 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
4805 ** each phrase in the expression (subject to deferred token processing).
4806 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
4807 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
4809 ** If an error occurs within this function, *pRc is set to an SQLite error
4810 ** code before returning.
4812 static void fts3EvalStartReaders(
4813 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4814 Fts3Expr
*pExpr
, /* Expression to initialize phrases in */
4815 int *pRc
/* IN/OUT: Error code */
4817 if( pExpr
&& SQLITE_OK
==*pRc
){
4818 if( pExpr
->eType
==FTSQUERY_PHRASE
){
4819 int nToken
= pExpr
->pPhrase
->nToken
;
4822 for(i
=0; i
<nToken
; i
++){
4823 if( pExpr
->pPhrase
->aToken
[i
].pDeferred
==0 ) break;
4825 pExpr
->bDeferred
= (i
==nToken
);
4827 *pRc
= fts3EvalPhraseStart(pCsr
, 1, pExpr
->pPhrase
);
4829 fts3EvalStartReaders(pCsr
, pExpr
->pLeft
, pRc
);
4830 fts3EvalStartReaders(pCsr
, pExpr
->pRight
, pRc
);
4831 pExpr
->bDeferred
= (pExpr
->pLeft
->bDeferred
&& pExpr
->pRight
->bDeferred
);
4837 ** An array of the following structures is assembled as part of the process
4838 ** of selecting tokens to defer before the query starts executing (as part
4839 ** of the xFilter() method). There is one element in the array for each
4840 ** token in the FTS expression.
4842 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
4843 ** to phrases that are connected only by AND and NEAR operators (not OR or
4844 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
4845 ** separately. The root of a tokens AND/NEAR cluster is stored in
4846 ** Fts3TokenAndCost.pRoot.
4848 typedef struct Fts3TokenAndCost Fts3TokenAndCost
;
4849 struct Fts3TokenAndCost
{
4850 Fts3Phrase
*pPhrase
; /* The phrase the token belongs to */
4851 int iToken
; /* Position of token in phrase */
4852 Fts3PhraseToken
*pToken
; /* The token itself */
4853 Fts3Expr
*pRoot
; /* Root of NEAR/AND cluster */
4854 int nOvfl
; /* Number of overflow pages to load doclist */
4855 int iCol
; /* The column the token must match */
4859 ** This function is used to populate an allocated Fts3TokenAndCost array.
4861 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
4862 ** Otherwise, if an error occurs during execution, *pRc is set to an
4863 ** SQLite error code.
4865 static void fts3EvalTokenCosts(
4866 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4867 Fts3Expr
*pRoot
, /* Root of current AND/NEAR cluster */
4868 Fts3Expr
*pExpr
, /* Expression to consider */
4869 Fts3TokenAndCost
**ppTC
, /* Write new entries to *(*ppTC)++ */
4870 Fts3Expr
***ppOr
, /* Write new OR root to *(*ppOr)++ */
4871 int *pRc
/* IN/OUT: Error code */
4873 if( *pRc
==SQLITE_OK
){
4874 if( pExpr
->eType
==FTSQUERY_PHRASE
){
4875 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
4877 for(i
=0; *pRc
==SQLITE_OK
&& i
<pPhrase
->nToken
; i
++){
4878 Fts3TokenAndCost
*pTC
= (*ppTC
)++;
4879 pTC
->pPhrase
= pPhrase
;
4882 pTC
->pToken
= &pPhrase
->aToken
[i
];
4883 pTC
->iCol
= pPhrase
->iColumn
;
4884 *pRc
= sqlite3Fts3MsrOvfl(pCsr
, pTC
->pToken
->pSegcsr
, &pTC
->nOvfl
);
4886 }else if( pExpr
->eType
!=FTSQUERY_NOT
){
4887 assert( pExpr
->eType
==FTSQUERY_OR
4888 || pExpr
->eType
==FTSQUERY_AND
4889 || pExpr
->eType
==FTSQUERY_NEAR
4891 assert( pExpr
->pLeft
&& pExpr
->pRight
);
4892 if( pExpr
->eType
==FTSQUERY_OR
){
4893 pRoot
= pExpr
->pLeft
;
4897 fts3EvalTokenCosts(pCsr
, pRoot
, pExpr
->pLeft
, ppTC
, ppOr
, pRc
);
4898 if( pExpr
->eType
==FTSQUERY_OR
){
4899 pRoot
= pExpr
->pRight
;
4903 fts3EvalTokenCosts(pCsr
, pRoot
, pExpr
->pRight
, ppTC
, ppOr
, pRc
);
4909 ** Determine the average document (row) size in pages. If successful,
4910 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
4911 ** an SQLite error code.
4913 ** The average document size in pages is calculated by first calculating
4914 ** determining the average size in bytes, B. If B is less than the amount
4915 ** of data that will fit on a single leaf page of an intkey table in
4916 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
4917 ** the number of overflow pages consumed by a record B bytes in size.
4919 static int fts3EvalAverageDocsize(Fts3Cursor
*pCsr
, int *pnPage
){
4921 if( pCsr
->nRowAvg
==0 ){
4922 /* The average document size, which is required to calculate the cost
4923 ** of each doclist, has not yet been determined. Read the required
4924 ** data from the %_stat table to calculate it.
4926 ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
4927 ** varints, where nCol is the number of columns in the FTS3 table.
4928 ** The first varint is the number of documents currently stored in
4929 ** the table. The following nCol varints contain the total amount of
4930 ** data stored in all rows of each column of the table, from left
4933 Fts3Table
*p
= (Fts3Table
*)pCsr
->base
.pVtab
;
4934 sqlite3_stmt
*pStmt
;
4935 sqlite3_int64 nDoc
= 0;
4936 sqlite3_int64 nByte
= 0;
4940 rc
= sqlite3Fts3SelectDoctotal(p
, &pStmt
);
4941 if( rc
!=SQLITE_OK
) return rc
;
4942 a
= sqlite3_column_blob(pStmt
, 0);
4943 testcase( a
==0 ); /* If %_stat.value set to X'' */
4945 pEnd
= &a
[sqlite3_column_bytes(pStmt
, 0)];
4946 a
+= sqlite3Fts3GetVarintBounded(a
, pEnd
, &nDoc
);
4948 a
+= sqlite3Fts3GetVarintBounded(a
, pEnd
, &nByte
);
4951 if( nDoc
==0 || nByte
==0 ){
4952 sqlite3_reset(pStmt
);
4953 return FTS_CORRUPT_VTAB
;
4957 pCsr
->nRowAvg
= (int)(((nByte
/ nDoc
) + p
->nPgsz
) / p
->nPgsz
);
4958 assert( pCsr
->nRowAvg
>0 );
4959 rc
= sqlite3_reset(pStmt
);
4962 *pnPage
= pCsr
->nRowAvg
;
4967 ** This function is called to select the tokens (if any) that will be
4968 ** deferred. The array aTC[] has already been populated when this is
4971 ** This function is called once for each AND/NEAR cluster in the
4972 ** expression. Each invocation determines which tokens to defer within
4973 ** the cluster with root node pRoot. See comments above the definition
4974 ** of struct Fts3TokenAndCost for more details.
4976 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
4977 ** called on each token to defer. Otherwise, an SQLite error code is
4980 static int fts3EvalSelectDeferred(
4981 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4982 Fts3Expr
*pRoot
, /* Consider tokens with this root node */
4983 Fts3TokenAndCost
*aTC
, /* Array of expression tokens and costs */
4984 int nTC
/* Number of entries in aTC[] */
4986 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
4987 int nDocSize
= 0; /* Number of pages per doc loaded */
4988 int rc
= SQLITE_OK
; /* Return code */
4989 int ii
; /* Iterator variable for various purposes */
4990 int nOvfl
= 0; /* Total overflow pages used by doclists */
4991 int nToken
= 0; /* Total number of tokens in cluster */
4993 int nMinEst
= 0; /* The minimum count for any phrase so far. */
4994 int nLoad4
= 1; /* (Phrases that will be loaded)^4. */
4996 /* Tokens are never deferred for FTS tables created using the content=xxx
4997 ** option. The reason being that it is not guaranteed that the content
4998 ** table actually contains the same data as the index. To prevent this from
4999 ** causing any problems, the deferred token optimization is completely
5000 ** disabled for content=xxx tables. */
5001 if( pTab
->zContentTbl
){
5005 /* Count the tokens in this AND/NEAR cluster. If none of the doclists
5006 ** associated with the tokens spill onto overflow pages, or if there is
5007 ** only 1 token, exit early. No tokens to defer in this case. */
5008 for(ii
=0; ii
<nTC
; ii
++){
5009 if( aTC
[ii
].pRoot
==pRoot
){
5010 nOvfl
+= aTC
[ii
].nOvfl
;
5014 if( nOvfl
==0 || nToken
<2 ) return SQLITE_OK
;
5016 /* Obtain the average docsize (in pages). */
5017 rc
= fts3EvalAverageDocsize(pCsr
, &nDocSize
);
5018 assert( rc
!=SQLITE_OK
|| nDocSize
>0 );
5021 /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
5022 ** of the number of overflow pages that will be loaded by the pager layer
5023 ** to retrieve the entire doclist for the token from the full-text index.
5024 ** Load the doclists for tokens that are either:
5026 ** a. The cheapest token in the entire query (i.e. the one visited by the
5027 ** first iteration of this loop), or
5029 ** b. Part of a multi-token phrase.
5031 ** After each token doclist is loaded, merge it with the others from the
5032 ** same phrase and count the number of documents that the merged doclist
5033 ** contains. Set variable "nMinEst" to the smallest number of documents in
5034 ** any phrase doclist for which 1 or more token doclists have been loaded.
5035 ** Let nOther be the number of other phrases for which it is certain that
5036 ** one or more tokens will not be deferred.
5038 ** Then, for each token, defer it if loading the doclist would result in
5039 ** loading N or more overflow pages into memory, where N is computed as:
5041 ** (nMinEst + 4^nOther - 1) / (4^nOther)
5043 for(ii
=0; ii
<nToken
&& rc
==SQLITE_OK
; ii
++){
5044 int iTC
; /* Used to iterate through aTC[] array. */
5045 Fts3TokenAndCost
*pTC
= 0; /* Set to cheapest remaining token. */
5047 /* Set pTC to point to the cheapest remaining token. */
5048 for(iTC
=0; iTC
<nTC
; iTC
++){
5049 if( aTC
[iTC
].pToken
&& aTC
[iTC
].pRoot
==pRoot
5050 && (!pTC
|| aTC
[iTC
].nOvfl
<pTC
->nOvfl
)
5057 if( ii
&& pTC
->nOvfl
>=((nMinEst
+(nLoad4
/4)-1)/(nLoad4
/4))*nDocSize
){
5058 /* The number of overflow pages to load for this (and therefore all
5059 ** subsequent) tokens is greater than the estimated number of pages
5060 ** that will be loaded if all subsequent tokens are deferred.
5062 Fts3PhraseToken
*pToken
= pTC
->pToken
;
5063 rc
= sqlite3Fts3DeferToken(pCsr
, pToken
, pTC
->iCol
);
5064 fts3SegReaderCursorFree(pToken
->pSegcsr
);
5065 pToken
->pSegcsr
= 0;
5067 /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
5068 ** for-loop. Except, limit the value to 2^24 to prevent it from
5069 ** overflowing the 32-bit integer it is stored in. */
5070 if( ii
<12 ) nLoad4
= nLoad4
*4;
5072 if( ii
==0 || (pTC
->pPhrase
->nToken
>1 && ii
!=nToken
-1) ){
5073 /* Either this is the cheapest token in the entire query, or it is
5074 ** part of a multi-token phrase. Either way, the entire doclist will
5075 ** (eventually) be loaded into memory. It may as well be now. */
5076 Fts3PhraseToken
*pToken
= pTC
->pToken
;
5079 rc
= fts3TermSelect(pTab
, pToken
, pTC
->iCol
, &nList
, &pList
);
5080 assert( rc
==SQLITE_OK
|| pList
==0 );
5081 if( rc
==SQLITE_OK
){
5082 rc
= fts3EvalPhraseMergeToken(
5083 pTab
, pTC
->pPhrase
, pTC
->iToken
,pList
,nList
5086 if( rc
==SQLITE_OK
){
5088 nCount
= fts3DoclistCountDocids(
5089 pTC
->pPhrase
->doclist
.aAll
, pTC
->pPhrase
->doclist
.nAll
5091 if( ii
==0 || nCount
<nMinEst
) nMinEst
= nCount
;
5102 ** This function is called from within the xFilter method. It initializes
5103 ** the full-text query currently stored in pCsr->pExpr. To iterate through
5104 ** the results of a query, the caller does:
5106 ** fts3EvalStart(pCsr);
5108 ** fts3EvalNext(pCsr);
5109 ** if( pCsr->bEof ) break;
5110 ** ... return row pCsr->iPrevId to the caller ...
5113 static int fts3EvalStart(Fts3Cursor
*pCsr
){
5114 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
5119 /* Allocate a MultiSegReader for each token in the expression. */
5120 fts3EvalAllocateReaders(pCsr
, pCsr
->pExpr
, &nToken
, &nOr
, &rc
);
5122 /* Determine which, if any, tokens in the expression should be deferred. */
5123 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
5124 if( rc
==SQLITE_OK
&& nToken
>1 && pTab
->bFts4
){
5125 Fts3TokenAndCost
*aTC
;
5126 aTC
= (Fts3TokenAndCost
*)sqlite3_malloc64(
5127 sizeof(Fts3TokenAndCost
) * nToken
5128 + sizeof(Fts3Expr
*) * nOr
* 2
5134 Fts3Expr
**apOr
= (Fts3Expr
**)&aTC
[nToken
];
5136 Fts3TokenAndCost
*pTC
= aTC
;
5137 Fts3Expr
**ppOr
= apOr
;
5139 fts3EvalTokenCosts(pCsr
, 0, pCsr
->pExpr
, &pTC
, &ppOr
, &rc
);
5140 nToken
= (int)(pTC
-aTC
);
5141 nOr
= (int)(ppOr
-apOr
);
5143 if( rc
==SQLITE_OK
){
5144 rc
= fts3EvalSelectDeferred(pCsr
, 0, aTC
, nToken
);
5145 for(ii
=0; rc
==SQLITE_OK
&& ii
<nOr
; ii
++){
5146 rc
= fts3EvalSelectDeferred(pCsr
, apOr
[ii
], aTC
, nToken
);
5155 fts3EvalStartReaders(pCsr
, pCsr
->pExpr
, &rc
);
5160 ** Invalidate the current position list for phrase pPhrase.
5162 static void fts3EvalInvalidatePoslist(Fts3Phrase
*pPhrase
){
5163 if( pPhrase
->doclist
.bFreeList
){
5164 sqlite3_free(pPhrase
->doclist
.pList
);
5166 pPhrase
->doclist
.pList
= 0;
5167 pPhrase
->doclist
.nList
= 0;
5168 pPhrase
->doclist
.bFreeList
= 0;
5172 ** This function is called to edit the position list associated with
5173 ** the phrase object passed as the fifth argument according to a NEAR
5174 ** condition. For example:
5176 ** abc NEAR/5 "def ghi"
5178 ** Parameter nNear is passed the NEAR distance of the expression (5 in
5179 ** the example above). When this function is called, *paPoslist points to
5180 ** the position list, and *pnToken is the number of phrase tokens in the
5181 ** phrase on the other side of the NEAR operator to pPhrase. For example,
5182 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
5183 ** the position list associated with phrase "abc".
5185 ** All positions in the pPhrase position list that are not sufficiently
5186 ** close to a position in the *paPoslist position list are removed. If this
5187 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
5189 ** Before returning, *paPoslist is set to point to the position lsit
5190 ** associated with pPhrase. And *pnToken is set to the number of tokens in
5193 static int fts3EvalNearTrim(
5194 int nNear
, /* NEAR distance. As in "NEAR/nNear". */
5195 char *aTmp
, /* Temporary space to use */
5196 char **paPoslist
, /* IN/OUT: Position list */
5197 int *pnToken
, /* IN/OUT: Tokens in phrase of *paPoslist */
5198 Fts3Phrase
*pPhrase
/* The phrase object to trim the doclist of */
5200 int nParam1
= nNear
+ pPhrase
->nToken
;
5201 int nParam2
= nNear
+ *pnToken
;
5207 assert( pPhrase
->doclist
.pList
);
5209 p2
= pOut
= pPhrase
->doclist
.pList
;
5210 res
= fts3PoslistNearMerge(
5211 &pOut
, aTmp
, nParam1
, nParam2
, paPoslist
, &p2
5214 nNew
= (int)(pOut
- pPhrase
->doclist
.pList
) - 1;
5215 assert_fts3_nc( nNew
<=pPhrase
->doclist
.nList
&& nNew
>0 );
5216 if( nNew
>=0 && nNew
<=pPhrase
->doclist
.nList
){
5217 assert( pPhrase
->doclist
.pList
[nNew
]=='\0' );
5218 memset(&pPhrase
->doclist
.pList
[nNew
], 0, pPhrase
->doclist
.nList
- nNew
);
5219 pPhrase
->doclist
.nList
= nNew
;
5221 *paPoslist
= pPhrase
->doclist
.pList
;
5222 *pnToken
= pPhrase
->nToken
;
5229 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
5230 ** Otherwise, it advances the expression passed as the second argument to
5231 ** point to the next matching row in the database. Expressions iterate through
5232 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
5233 ** or descending if it is non-zero.
5235 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
5236 ** successful, the following variables in pExpr are set:
5238 ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
5239 ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
5241 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
5242 ** at EOF, then the following variables are populated with the position list
5243 ** for the phrase for the visited row:
5245 ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
5246 ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
5248 ** It says above that this function advances the expression to the next
5249 ** matching row. This is usually true, but there are the following exceptions:
5251 ** 1. Deferred tokens are not taken into account. If a phrase consists
5252 ** entirely of deferred tokens, it is assumed to match every row in
5253 ** the db. In this case the position-list is not populated at all.
5255 ** Or, if a phrase contains one or more deferred tokens and one or
5256 ** more non-deferred tokens, then the expression is advanced to the
5257 ** next possible match, considering only non-deferred tokens. In other
5258 ** words, if the phrase is "A B C", and "B" is deferred, the expression
5259 ** is advanced to the next row that contains an instance of "A * C",
5260 ** where "*" may match any single token. The position list in this case
5261 ** is populated as for "A * C" before returning.
5263 ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
5264 ** advanced to point to the next row that matches "x AND y".
5266 ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
5267 ** really a match, taking into account deferred tokens and NEAR operators.
5269 static void fts3EvalNextRow(
5270 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
5271 Fts3Expr
*pExpr
, /* Expr. to advance to next matching row */
5272 int *pRc
/* IN/OUT: Error code */
5274 if( *pRc
==SQLITE_OK
){
5275 int bDescDoclist
= pCsr
->bDesc
; /* Used by DOCID_CMP() macro */
5276 assert( pExpr
->bEof
==0 );
5279 switch( pExpr
->eType
){
5281 case FTSQUERY_AND
: {
5282 Fts3Expr
*pLeft
= pExpr
->pLeft
;
5283 Fts3Expr
*pRight
= pExpr
->pRight
;
5284 assert( !pLeft
->bDeferred
|| !pRight
->bDeferred
);
5286 if( pLeft
->bDeferred
){
5287 /* LHS is entirely deferred. So we assume it matches every row.
5288 ** Advance the RHS iterator to find the next row visited. */
5289 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5290 pExpr
->iDocid
= pRight
->iDocid
;
5291 pExpr
->bEof
= pRight
->bEof
;
5292 }else if( pRight
->bDeferred
){
5293 /* RHS is entirely deferred. So we assume it matches every row.
5294 ** Advance the LHS iterator to find the next row visited. */
5295 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5296 pExpr
->iDocid
= pLeft
->iDocid
;
5297 pExpr
->bEof
= pLeft
->bEof
;
5299 /* Neither the RHS or LHS are deferred. */
5300 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5301 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5302 while( !pLeft
->bEof
&& !pRight
->bEof
&& *pRc
==SQLITE_OK
){
5303 sqlite3_int64 iDiff
= DOCID_CMP(pLeft
->iDocid
, pRight
->iDocid
);
5304 if( iDiff
==0 ) break;
5306 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5308 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5311 pExpr
->iDocid
= pLeft
->iDocid
;
5312 pExpr
->bEof
= (pLeft
->bEof
|| pRight
->bEof
);
5313 if( pExpr
->eType
==FTSQUERY_NEAR
&& pExpr
->bEof
){
5314 assert( pRight
->eType
==FTSQUERY_PHRASE
);
5315 if( pRight
->pPhrase
->doclist
.aAll
){
5316 Fts3Doclist
*pDl
= &pRight
->pPhrase
->doclist
;
5317 while( *pRc
==SQLITE_OK
&& pRight
->bEof
==0 ){
5318 memset(pDl
->pList
, 0, pDl
->nList
);
5319 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5322 if( pLeft
->pPhrase
&& pLeft
->pPhrase
->doclist
.aAll
){
5323 Fts3Doclist
*pDl
= &pLeft
->pPhrase
->doclist
;
5324 while( *pRc
==SQLITE_OK
&& pLeft
->bEof
==0 ){
5325 memset(pDl
->pList
, 0, pDl
->nList
);
5326 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5329 pRight
->bEof
= pLeft
->bEof
= 1;
5336 Fts3Expr
*pLeft
= pExpr
->pLeft
;
5337 Fts3Expr
*pRight
= pExpr
->pRight
;
5338 sqlite3_int64 iCmp
= DOCID_CMP(pLeft
->iDocid
, pRight
->iDocid
);
5340 assert_fts3_nc( pLeft
->bStart
|| pLeft
->iDocid
==pRight
->iDocid
);
5341 assert_fts3_nc( pRight
->bStart
|| pLeft
->iDocid
==pRight
->iDocid
);
5343 if( pRight
->bEof
|| (pLeft
->bEof
==0 && iCmp
<0) ){
5344 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5345 }else if( pLeft
->bEof
|| iCmp
>0 ){
5346 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5348 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5349 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5352 pExpr
->bEof
= (pLeft
->bEof
&& pRight
->bEof
);
5353 iCmp
= DOCID_CMP(pLeft
->iDocid
, pRight
->iDocid
);
5354 if( pRight
->bEof
|| (pLeft
->bEof
==0 && iCmp
<0) ){
5355 pExpr
->iDocid
= pLeft
->iDocid
;
5357 pExpr
->iDocid
= pRight
->iDocid
;
5363 case FTSQUERY_NOT
: {
5364 Fts3Expr
*pLeft
= pExpr
->pLeft
;
5365 Fts3Expr
*pRight
= pExpr
->pRight
;
5367 if( pRight
->bStart
==0 ){
5368 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5369 assert( *pRc
!=SQLITE_OK
|| pRight
->bStart
);
5372 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5373 if( pLeft
->bEof
==0 ){
5376 && DOCID_CMP(pLeft
->iDocid
, pRight
->iDocid
)>0
5378 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5381 pExpr
->iDocid
= pLeft
->iDocid
;
5382 pExpr
->bEof
= pLeft
->bEof
;
5387 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
5388 fts3EvalInvalidatePoslist(pPhrase
);
5389 *pRc
= fts3EvalPhraseNext(pCsr
, pPhrase
, &pExpr
->bEof
);
5390 pExpr
->iDocid
= pPhrase
->doclist
.iDocid
;
5398 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
5399 ** cluster, then this function returns 1 immediately.
5401 ** Otherwise, it checks if the current row really does match the NEAR
5402 ** expression, using the data currently stored in the position lists
5403 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
5405 ** If the current row is a match, the position list associated with each
5406 ** phrase in the NEAR expression is edited in place to contain only those
5407 ** phrase instances sufficiently close to their peers to satisfy all NEAR
5408 ** constraints. In this case it returns 1. If the NEAR expression does not
5409 ** match the current row, 0 is returned. The position lists may or may not
5410 ** be edited if 0 is returned.
5412 static int fts3EvalNearTest(Fts3Expr
*pExpr
, int *pRc
){
5415 /* The following block runs if pExpr is the root of a NEAR query.
5416 ** For example, the query:
5418 ** "w" NEAR "x" NEAR "y" NEAR "z"
5420 ** which is represented in tree form as:
5423 ** +--NEAR--+ <-- root of NEAR query
5431 ** The right-hand child of a NEAR node is always a phrase. The
5432 ** left-hand child may be either a phrase or a NEAR node. There are
5433 ** no exceptions to this - it's the way the parser in fts3_expr.c works.
5436 && pExpr
->eType
==FTSQUERY_NEAR
5437 && (pExpr
->pParent
==0 || pExpr
->pParent
->eType
!=FTSQUERY_NEAR
)
5440 sqlite3_int64 nTmp
= 0; /* Bytes of temp space */
5441 char *aTmp
; /* Temp space for PoslistNearMerge() */
5443 /* Allocate temporary working space. */
5444 for(p
=pExpr
; p
->pLeft
; p
=p
->pLeft
){
5445 assert( p
->pRight
->pPhrase
->doclist
.nList
>0 );
5446 nTmp
+= p
->pRight
->pPhrase
->doclist
.nList
;
5448 nTmp
+= p
->pPhrase
->doclist
.nList
;
5449 aTmp
= sqlite3_malloc64(nTmp
*2);
5451 *pRc
= SQLITE_NOMEM
;
5454 char *aPoslist
= p
->pPhrase
->doclist
.pList
;
5455 int nToken
= p
->pPhrase
->nToken
;
5457 for(p
=p
->pParent
;res
&& p
&& p
->eType
==FTSQUERY_NEAR
; p
=p
->pParent
){
5458 Fts3Phrase
*pPhrase
= p
->pRight
->pPhrase
;
5459 int nNear
= p
->nNear
;
5460 res
= fts3EvalNearTrim(nNear
, aTmp
, &aPoslist
, &nToken
, pPhrase
);
5463 aPoslist
= pExpr
->pRight
->pPhrase
->doclist
.pList
;
5464 nToken
= pExpr
->pRight
->pPhrase
->nToken
;
5465 for(p
=pExpr
->pLeft
; p
&& res
; p
=p
->pLeft
){
5467 Fts3Phrase
*pPhrase
;
5468 assert( p
->pParent
&& p
->pParent
->pLeft
==p
);
5469 nNear
= p
->pParent
->nNear
;
5471 p
->eType
==FTSQUERY_NEAR
? p
->pRight
->pPhrase
: p
->pPhrase
5473 res
= fts3EvalNearTrim(nNear
, aTmp
, &aPoslist
, &nToken
, pPhrase
);
5484 ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
5485 ** Assuming no error occurs or has occurred, It returns non-zero if the
5486 ** expression passed as the second argument matches the row that pCsr
5487 ** currently points to, or zero if it does not.
5489 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
5490 ** If an error occurs during execution of this function, *pRc is set to
5491 ** the appropriate SQLite error code. In this case the returned value is
5494 static int fts3EvalTestExpr(
5495 Fts3Cursor
*pCsr
, /* FTS cursor handle */
5496 Fts3Expr
*pExpr
, /* Expr to test. May or may not be root. */
5497 int *pRc
/* IN/OUT: Error code */
5499 int bHit
= 1; /* Return value */
5500 if( *pRc
==SQLITE_OK
){
5501 switch( pExpr
->eType
){
5505 fts3EvalTestExpr(pCsr
, pExpr
->pLeft
, pRc
)
5506 && fts3EvalTestExpr(pCsr
, pExpr
->pRight
, pRc
)
5507 && fts3EvalNearTest(pExpr
, pRc
)
5510 /* If the NEAR expression does not match any rows, zero the doclist for
5511 ** all phrases involved in the NEAR. This is because the snippet(),
5512 ** offsets() and matchinfo() functions are not supposed to recognize
5513 ** any instances of phrases that are part of unmatched NEAR queries.
5514 ** For example if this expression:
5516 ** ... MATCH 'a OR (b NEAR c)'
5518 ** is matched against a row containing:
5522 ** then any snippet() should ony highlight the "a" term, not the "b"
5523 ** (as "b" is part of a non-matching NEAR clause).
5526 && pExpr
->eType
==FTSQUERY_NEAR
5527 && (pExpr
->pParent
==0 || pExpr
->pParent
->eType
!=FTSQUERY_NEAR
)
5530 for(p
=pExpr
; p
->pPhrase
==0; p
=p
->pLeft
){
5531 if( p
->pRight
->iDocid
==pCsr
->iPrevId
){
5532 fts3EvalInvalidatePoslist(p
->pRight
->pPhrase
);
5535 if( p
->iDocid
==pCsr
->iPrevId
){
5536 fts3EvalInvalidatePoslist(p
->pPhrase
);
5543 int bHit1
= fts3EvalTestExpr(pCsr
, pExpr
->pLeft
, pRc
);
5544 int bHit2
= fts3EvalTestExpr(pCsr
, pExpr
->pRight
, pRc
);
5545 bHit
= bHit1
|| bHit2
;
5551 fts3EvalTestExpr(pCsr
, pExpr
->pLeft
, pRc
)
5552 && !fts3EvalTestExpr(pCsr
, pExpr
->pRight
, pRc
)
5557 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
5559 && (pExpr
->iDocid
==pCsr
->iPrevId
|| pExpr
->bDeferred
)
5561 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
5562 assert( pExpr
->bDeferred
|| pPhrase
->doclist
.bFreeList
==0 );
5563 if( pExpr
->bDeferred
){
5564 fts3EvalInvalidatePoslist(pPhrase
);
5566 *pRc
= fts3EvalDeferredPhrase(pCsr
, pPhrase
);
5567 bHit
= (pPhrase
->doclist
.pList
!=0);
5568 pExpr
->iDocid
= pCsr
->iPrevId
;
5573 pExpr
->bEof
==0 && pExpr
->iDocid
==pCsr
->iPrevId
5574 && pExpr
->pPhrase
->doclist
.nList
>0
5585 ** This function is called as the second part of each xNext operation when
5586 ** iterating through the results of a full-text query. At this point the
5587 ** cursor points to a row that matches the query expression, with the
5588 ** following caveats:
5590 ** * Up until this point, "NEAR" operators in the expression have been
5591 ** treated as "AND".
5593 ** * Deferred tokens have not yet been considered.
5595 ** If *pRc is not SQLITE_OK when this function is called, it immediately
5596 ** returns 0. Otherwise, it tests whether or not after considering NEAR
5597 ** operators and deferred tokens the current row is still a match for the
5598 ** expression. It returns 1 if both of the following are true:
5600 ** 1. *pRc is SQLITE_OK when this function returns, and
5602 ** 2. After scanning the current FTS table row for the deferred tokens,
5603 ** it is determined that the row does *not* match the query.
5605 ** Or, if no error occurs and it seems the current row does match the FTS
5608 int sqlite3Fts3EvalTestDeferred(Fts3Cursor
*pCsr
, int *pRc
){
5611 if( rc
==SQLITE_OK
){
5613 /* If there are one or more deferred tokens, load the current row into
5614 ** memory and scan it to determine the position list for each deferred
5615 ** token. Then, see if this row is really a match, considering deferred
5616 ** tokens and NEAR operators (neither of which were taken into account
5617 ** earlier, by fts3EvalNextRow()).
5619 if( pCsr
->pDeferred
){
5620 rc
= fts3CursorSeek(0, pCsr
);
5621 if( rc
==SQLITE_OK
){
5622 rc
= sqlite3Fts3CacheDeferredDoclists(pCsr
);
5625 bMiss
= (0==fts3EvalTestExpr(pCsr
, pCsr
->pExpr
, &rc
));
5627 /* Free the position-lists accumulated for each deferred token above. */
5628 sqlite3Fts3FreeDeferredDoclists(pCsr
);
5631 return (rc
==SQLITE_OK
&& bMiss
);
5635 ** Advance to the next document that matches the FTS expression in
5636 ** Fts3Cursor.pExpr.
5638 static int fts3EvalNext(Fts3Cursor
*pCsr
){
5639 int rc
= SQLITE_OK
; /* Return Code */
5640 Fts3Expr
*pExpr
= pCsr
->pExpr
;
5641 assert( pCsr
->isEof
==0 );
5646 if( pCsr
->isRequireSeek
==0 ){
5647 sqlite3_reset(pCsr
->pStmt
);
5649 assert( sqlite3_data_count(pCsr
->pStmt
)==0 );
5650 fts3EvalNextRow(pCsr
, pExpr
, &rc
);
5651 pCsr
->isEof
= pExpr
->bEof
;
5652 pCsr
->isRequireSeek
= 1;
5653 pCsr
->isMatchinfoNeeded
= 1;
5654 pCsr
->iPrevId
= pExpr
->iDocid
;
5655 }while( pCsr
->isEof
==0 && sqlite3Fts3EvalTestDeferred(pCsr
, &rc
) );
5658 /* Check if the cursor is past the end of the docid range specified
5659 ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
5660 if( rc
==SQLITE_OK
&& (
5661 (pCsr
->bDesc
==0 && pCsr
->iPrevId
>pCsr
->iMaxDocid
)
5662 || (pCsr
->bDesc
!=0 && pCsr
->iPrevId
<pCsr
->iMinDocid
)
5671 ** Restart interation for expression pExpr so that the next call to
5672 ** fts3EvalNext() visits the first row. Do not allow incremental
5673 ** loading or merging of phrase doclists for this iteration.
5675 ** If *pRc is other than SQLITE_OK when this function is called, it is
5676 ** a no-op. If an error occurs within this function, *pRc is set to an
5677 ** SQLite error code before returning.
5679 static void fts3EvalRestart(
5684 if( pExpr
&& *pRc
==SQLITE_OK
){
5685 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
5688 fts3EvalInvalidatePoslist(pPhrase
);
5689 if( pPhrase
->bIncr
){
5691 for(i
=0; i
<pPhrase
->nToken
; i
++){
5692 Fts3PhraseToken
*pToken
= &pPhrase
->aToken
[i
];
5693 assert( pToken
->pDeferred
==0 );
5694 if( pToken
->pSegcsr
){
5695 sqlite3Fts3MsrIncrRestart(pToken
->pSegcsr
);
5698 *pRc
= fts3EvalPhraseStart(pCsr
, 0, pPhrase
);
5700 pPhrase
->doclist
.pNextDocid
= 0;
5701 pPhrase
->doclist
.iDocid
= 0;
5702 pPhrase
->pOrPoslist
= 0;
5709 fts3EvalRestart(pCsr
, pExpr
->pLeft
, pRc
);
5710 fts3EvalRestart(pCsr
, pExpr
->pRight
, pRc
);
5715 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
5716 ** expression rooted at pExpr, the cursor iterates through all rows matched
5717 ** by pExpr, calling this function for each row. This function increments
5718 ** the values in Fts3Expr.aMI[] according to the position-list currently
5719 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
5720 ** expression nodes.
5722 static void fts3EvalUpdateCounts(Fts3Expr
*pExpr
, int nCol
){
5724 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
5725 if( pPhrase
&& pPhrase
->doclist
.pList
){
5727 char *p
= pPhrase
->doclist
.pList
;
5732 while( 0xFE & (*p
| c
) ){
5733 if( (c
&0x80)==0 ) iCnt
++;
5737 /* aMI[iCol*3 + 1] = Number of occurrences
5738 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
5740 pExpr
->aMI
[iCol
*3 + 1] += iCnt
;
5741 pExpr
->aMI
[iCol
*3 + 2] += (iCnt
>0);
5742 if( *p
==0x00 ) break;
5744 p
+= fts3GetVarint32(p
, &iCol
);
5745 }while( iCol
<nCol
);
5748 fts3EvalUpdateCounts(pExpr
->pLeft
, nCol
);
5749 fts3EvalUpdateCounts(pExpr
->pRight
, nCol
);
5754 ** Expression pExpr must be of type FTSQUERY_PHRASE.
5756 ** If it is not already allocated and populated, this function allocates and
5757 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
5758 ** of a NEAR expression, then it also allocates and populates the same array
5759 ** for all other phrases that are part of the NEAR expression.
5761 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
5762 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
5764 static int fts3EvalGatherStats(
5765 Fts3Cursor
*pCsr
, /* Cursor object */
5766 Fts3Expr
*pExpr
/* FTSQUERY_PHRASE expression */
5768 int rc
= SQLITE_OK
; /* Return code */
5770 assert( pExpr
->eType
==FTSQUERY_PHRASE
);
5771 if( pExpr
->aMI
==0 ){
5772 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
5773 Fts3Expr
*pRoot
; /* Root of NEAR expression */
5774 Fts3Expr
*p
; /* Iterator used for several purposes */
5776 sqlite3_int64 iPrevId
= pCsr
->iPrevId
;
5777 sqlite3_int64 iDocid
;
5780 /* Find the root of the NEAR expression */
5782 while( pRoot
->pParent
&& pRoot
->pParent
->eType
==FTSQUERY_NEAR
){
5783 pRoot
= pRoot
->pParent
;
5785 iDocid
= pRoot
->iDocid
;
5787 assert( pRoot
->bStart
);
5789 /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
5790 for(p
=pRoot
; p
; p
=p
->pLeft
){
5791 Fts3Expr
*pE
= (p
->eType
==FTSQUERY_PHRASE
?p
:p
->pRight
);
5792 assert( pE
->aMI
==0 );
5793 pE
->aMI
= (u32
*)sqlite3_malloc64(pTab
->nColumn
* 3 * sizeof(u32
));
5794 if( !pE
->aMI
) return SQLITE_NOMEM
;
5795 memset(pE
->aMI
, 0, pTab
->nColumn
* 3 * sizeof(u32
));
5798 fts3EvalRestart(pCsr
, pRoot
, &rc
);
5800 while( pCsr
->isEof
==0 && rc
==SQLITE_OK
){
5803 /* Ensure the %_content statement is reset. */
5804 if( pCsr
->isRequireSeek
==0 ) sqlite3_reset(pCsr
->pStmt
);
5805 assert( sqlite3_data_count(pCsr
->pStmt
)==0 );
5807 /* Advance to the next document */
5808 fts3EvalNextRow(pCsr
, pRoot
, &rc
);
5809 pCsr
->isEof
= pRoot
->bEof
;
5810 pCsr
->isRequireSeek
= 1;
5811 pCsr
->isMatchinfoNeeded
= 1;
5812 pCsr
->iPrevId
= pRoot
->iDocid
;
5813 }while( pCsr
->isEof
==0
5814 && pRoot
->eType
==FTSQUERY_NEAR
5815 && sqlite3Fts3EvalTestDeferred(pCsr
, &rc
)
5818 if( rc
==SQLITE_OK
&& pCsr
->isEof
==0 ){
5819 fts3EvalUpdateCounts(pRoot
, pTab
->nColumn
);
5824 pCsr
->iPrevId
= iPrevId
;
5829 /* Caution: pRoot may iterate through docids in ascending or descending
5830 ** order. For this reason, even though it seems more defensive, the
5831 ** do loop can not be written:
5833 ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
5835 fts3EvalRestart(pCsr
, pRoot
, &rc
);
5837 fts3EvalNextRow(pCsr
, pRoot
, &rc
);
5838 assert_fts3_nc( pRoot
->bEof
==0 );
5839 if( pRoot
->bEof
) rc
= FTS_CORRUPT_VTAB
;
5840 }while( pRoot
->iDocid
!=iDocid
&& rc
==SQLITE_OK
);
5847 ** This function is used by the matchinfo() module to query a phrase
5848 ** expression node for the following information:
5850 ** 1. The total number of occurrences of the phrase in each column of
5851 ** the FTS table (considering all rows), and
5853 ** 2. For each column, the number of rows in the table for which the
5854 ** column contains at least one instance of the phrase.
5856 ** If no error occurs, SQLITE_OK is returned and the values for each column
5857 ** written into the array aiOut as follows:
5859 ** aiOut[iCol*3 + 1] = Number of occurrences
5860 ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
5864 ** * If a phrase consists entirely of deferred tokens, then all output
5865 ** values are set to the number of documents in the table. In other
5866 ** words we assume that very common tokens occur exactly once in each
5867 ** column of each row of the table.
5869 ** * If a phrase contains some deferred tokens (and some non-deferred
5870 ** tokens), count the potential occurrence identified by considering
5871 ** the non-deferred tokens instead of actual phrase occurrences.
5873 ** * If the phrase is part of a NEAR expression, then only phrase instances
5874 ** that meet the NEAR constraint are included in the counts.
5876 int sqlite3Fts3EvalPhraseStats(
5877 Fts3Cursor
*pCsr
, /* FTS cursor handle */
5878 Fts3Expr
*pExpr
, /* Phrase expression */
5879 u32
*aiOut
/* Array to write results into (see above) */
5881 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
5885 if( pExpr
->bDeferred
&& pExpr
->pParent
->eType
!=FTSQUERY_NEAR
){
5886 assert( pCsr
->nDoc
>0 );
5887 for(iCol
=0; iCol
<pTab
->nColumn
; iCol
++){
5888 aiOut
[iCol
*3 + 1] = (u32
)pCsr
->nDoc
;
5889 aiOut
[iCol
*3 + 2] = (u32
)pCsr
->nDoc
;
5892 rc
= fts3EvalGatherStats(pCsr
, pExpr
);
5893 if( rc
==SQLITE_OK
){
5894 assert( pExpr
->aMI
);
5895 for(iCol
=0; iCol
<pTab
->nColumn
; iCol
++){
5896 aiOut
[iCol
*3 + 1] = pExpr
->aMI
[iCol
*3 + 1];
5897 aiOut
[iCol
*3 + 2] = pExpr
->aMI
[iCol
*3 + 2];
5906 ** The expression pExpr passed as the second argument to this function
5907 ** must be of type FTSQUERY_PHRASE.
5909 ** The returned value is either NULL or a pointer to a buffer containing
5910 ** a position-list indicating the occurrences of the phrase in column iCol
5911 ** of the current row.
5913 ** More specifically, the returned buffer contains 1 varint for each
5914 ** occurrence of the phrase in the column, stored using the normal (delta+2)
5915 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
5916 ** if the requested column contains "a b X c d X X" and the position-list
5917 ** for 'X' is requested, the buffer returned may contain:
5919 ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
5921 ** This function works regardless of whether or not the phrase is deferred,
5922 ** incremental, or neither.
5924 int sqlite3Fts3EvalPhrasePoslist(
5925 Fts3Cursor
*pCsr
, /* FTS3 cursor object */
5926 Fts3Expr
*pExpr
, /* Phrase to return doclist for */
5927 int iCol
, /* Column to return position list for */
5928 char **ppOut
/* OUT: Pointer to position list */
5930 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
5931 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
5934 sqlite3_int64 iDocid
;
5936 /* If this phrase is applies specifically to some column other than
5937 ** column iCol, return a NULL pointer. */
5939 assert( iCol
>=0 && iCol
<pTab
->nColumn
);
5940 if( (pPhrase
->iColumn
<pTab
->nColumn
&& pPhrase
->iColumn
!=iCol
) ){
5944 iDocid
= pExpr
->iDocid
;
5945 pIter
= pPhrase
->doclist
.pList
;
5946 if( iDocid
!=pCsr
->iPrevId
|| pExpr
->bEof
){
5948 int bDescDoclist
= pTab
->bDescIdx
; /* For DOCID_CMP macro */
5951 Fts3Expr
*p
; /* Used to iterate from pExpr to root */
5952 Fts3Expr
*pNear
; /* Most senior NEAR ancestor (or pExpr) */
5955 /* Check if this phrase descends from an OR expression node. If not,
5956 ** return NULL. Otherwise, the entry that corresponds to docid
5957 ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
5958 ** tree that the node is part of has been marked as EOF, but the node
5959 ** itself is not EOF, then it may point to an earlier entry. */
5961 for(p
=pExpr
->pParent
; p
; p
=p
->pParent
){
5962 if( p
->eType
==FTSQUERY_OR
) bOr
= 1;
5963 if( p
->eType
==FTSQUERY_NEAR
) pNear
= p
;
5964 if( p
->bEof
) bTreeEof
= 1;
5966 if( bOr
==0 ) return SQLITE_OK
;
5968 /* This is the descendent of an OR node. In this case we cannot use
5969 ** an incremental phrase. Load the entire doclist for the phrase
5970 ** into memory in this case. */
5971 if( pPhrase
->bIncr
){
5972 int bEofSave
= pNear
->bEof
;
5973 fts3EvalRestart(pCsr
, pNear
, &rc
);
5974 while( rc
==SQLITE_OK
&& !pNear
->bEof
){
5975 fts3EvalNextRow(pCsr
, pNear
, &rc
);
5976 if( bEofSave
==0 && pNear
->iDocid
==iDocid
) break;
5978 assert( rc
!=SQLITE_OK
|| pPhrase
->bIncr
==0 );
5979 if( rc
==SQLITE_OK
&& pNear
->bEof
!=bEofSave
){
5980 rc
= FTS_CORRUPT_VTAB
;
5984 while( rc
==SQLITE_OK
&& !pNear
->bEof
){
5985 fts3EvalNextRow(pCsr
, pNear
, &rc
);
5988 if( rc
!=SQLITE_OK
) return rc
;
5991 for(p
=pNear
; p
; p
=p
->pLeft
){
5993 Fts3Expr
*pTest
= p
;
5995 assert( pTest
->eType
==FTSQUERY_NEAR
|| pTest
->eType
==FTSQUERY_PHRASE
);
5996 if( pTest
->eType
==FTSQUERY_NEAR
) pTest
= pTest
->pRight
;
5997 assert( pTest
->eType
==FTSQUERY_PHRASE
);
5998 pPh
= pTest
->pPhrase
;
6000 pIter
= pPh
->pOrPoslist
;
6001 iDocid
= pPh
->iOrDocid
;
6002 if( pCsr
->bDesc
==bDescDoclist
){
6003 bEof
= !pPh
->doclist
.nAll
||
6004 (pIter
>= (pPh
->doclist
.aAll
+ pPh
->doclist
.nAll
));
6005 while( (pIter
==0 || DOCID_CMP(iDocid
, pCsr
->iPrevId
)<0 ) && bEof
==0 ){
6006 sqlite3Fts3DoclistNext(
6007 bDescDoclist
, pPh
->doclist
.aAll
, pPh
->doclist
.nAll
,
6008 &pIter
, &iDocid
, &bEof
6012 bEof
= !pPh
->doclist
.nAll
|| (pIter
&& pIter
<=pPh
->doclist
.aAll
);
6013 while( (pIter
==0 || DOCID_CMP(iDocid
, pCsr
->iPrevId
)>0 ) && bEof
==0 ){
6015 sqlite3Fts3DoclistPrev(
6016 bDescDoclist
, pPh
->doclist
.aAll
, pPh
->doclist
.nAll
,
6017 &pIter
, &iDocid
, &dummy
, &bEof
6021 pPh
->pOrPoslist
= pIter
;
6022 pPh
->iOrDocid
= iDocid
;
6023 if( bEof
|| iDocid
!=pCsr
->iPrevId
) bMatch
= 0;
6027 pIter
= pPhrase
->pOrPoslist
;
6032 if( pIter
==0 ) return SQLITE_OK
;
6036 pIter
+= fts3GetVarint32(pIter
, &iThis
);
6040 while( iThis
<iCol
){
6041 fts3ColumnlistCopy(0, &pIter
);
6042 if( *pIter
==0x00 ) return SQLITE_OK
;
6044 pIter
+= fts3GetVarint32(pIter
, &iThis
);
6050 *ppOut
= ((iCol
==iThis
)?pIter
:0);
6055 ** Free all components of the Fts3Phrase structure that were allocated by
6056 ** the eval module. Specifically, this means to free:
6058 ** * the contents of pPhrase->doclist, and
6059 ** * any Fts3MultiSegReader objects held by phrase tokens.
6061 void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase
*pPhrase
){
6064 sqlite3_free(pPhrase
->doclist
.aAll
);
6065 fts3EvalInvalidatePoslist(pPhrase
);
6066 memset(&pPhrase
->doclist
, 0, sizeof(Fts3Doclist
));
6067 for(i
=0; i
<pPhrase
->nToken
; i
++){
6068 fts3SegReaderCursorFree(pPhrase
->aToken
[i
].pSegcsr
);
6069 pPhrase
->aToken
[i
].pSegcsr
= 0;
6076 ** Return SQLITE_CORRUPT_VTAB.
6079 int sqlite3Fts3Corrupt(){
6080 return SQLITE_CORRUPT_VTAB
;
6086 ** Initialize API pointer table, if required.
6089 __declspec(dllexport
)
6091 int sqlite3_fts3_init(
6094 const sqlite3_api_routines
*pApi
6096 SQLITE_EXTENSION_INIT2(pApi
)
6097 return sqlite3Fts3Init(db
);