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
290 #define CHROMIUM_FTS3_CHANGES 1
293 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
295 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
296 # define SQLITE_CORE 1
308 # include "sqlite3ext.h"
309 SQLITE_EXTENSION_INIT1
312 static int fts3EvalNext(Fts3Cursor
*pCsr
);
313 static int fts3EvalStart(Fts3Cursor
*pCsr
);
314 static int fts3TermSegReaderCursor(
315 Fts3Cursor
*, const char *, int, int, Fts3MultiSegReader
**);
318 ** Write a 64-bit variable-length integer to memory starting at p[0].
319 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
320 ** The number of bytes written is returned.
322 int sqlite3Fts3PutVarint(char *p
, sqlite_int64 v
){
323 unsigned char *q
= (unsigned char *) p
;
324 sqlite_uint64 vu
= v
;
326 *q
++ = (unsigned char) ((vu
& 0x7f) | 0x80);
329 q
[-1] &= 0x7f; /* turn off high bit in final byte */
330 assert( q
- (unsigned char *)p
<= FTS3_VARINT_MAX
);
331 return (int) (q
- (unsigned char *)p
);
334 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
335 v = (v & mask1) | ( (*ptr++) << shift ); \
336 if( (v & mask2)==0 ){ var = v; return ret; }
337 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
339 if( (v & mask2)==0 ){ var = v; return ret; }
342 ** Read a 64-bit variable-length integer from memory starting at p[0].
343 ** Return the number of bytes read, or 0 on error.
344 ** The value is stored in *v.
346 int sqlite3Fts3GetVarint(const char *p
, sqlite_int64
*v
){
347 const char *pStart
= p
;
352 GETVARINT_INIT(a
, p
, 0, 0x00, 0x80, *v
, 1);
353 GETVARINT_STEP(a
, p
, 7, 0x7F, 0x4000, *v
, 2);
354 GETVARINT_STEP(a
, p
, 14, 0x3FFF, 0x200000, *v
, 3);
355 GETVARINT_STEP(a
, p
, 21, 0x1FFFFF, 0x10000000, *v
, 4);
356 b
= (a
& 0x0FFFFFFF );
358 for(shift
=28; shift
<=63; shift
+=7){
360 b
+= (c
&0x7F) << shift
;
361 if( (c
& 0x80)==0 ) break;
364 return (int)(p
- pStart
);
368 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
369 ** 32-bit integer before it is returned.
371 int sqlite3Fts3GetVarint32(const char *p
, int *pi
){
374 #ifndef fts3GetVarint32
375 GETVARINT_INIT(a
, p
, 0, 0x00, 0x80, *pi
, 1);
381 GETVARINT_STEP(a
, p
, 7, 0x7F, 0x4000, *pi
, 2);
382 GETVARINT_STEP(a
, p
, 14, 0x3FFF, 0x200000, *pi
, 3);
383 GETVARINT_STEP(a
, p
, 21, 0x1FFFFF, 0x10000000, *pi
, 4);
384 a
= (a
& 0x0FFFFFFF );
385 *pi
= (int)(a
| ((u32
)(*p
& 0x0F) << 28));
390 ** Return the number of bytes required to encode v as a varint
392 int sqlite3Fts3VarintLen(sqlite3_uint64 v
){
402 ** Convert an SQL-style quoted string into a normal string by removing
403 ** the quote characters. The conversion is done in-place. If the
404 ** input does not begin with a quote character, then this routine
415 void sqlite3Fts3Dequote(char *z
){
416 char quote
; /* Quote character (if any ) */
419 if( quote
=='[' || quote
=='\'' || quote
=='"' || quote
=='`' ){
420 int iIn
= 1; /* Index of next byte to read from input */
421 int iOut
= 0; /* Index of next byte to write to output */
423 /* If the first byte was a '[', then the close-quote character is a ']' */
424 if( quote
=='[' ) quote
= ']';
426 while( ALWAYS(z
[iIn
]) ){
428 if( z
[iIn
+1]!=quote
) break;
432 z
[iOut
++] = z
[iIn
++];
440 ** Read a single varint from the doclist at *pp and advance *pp to point
441 ** to the first byte past the end of the varint. Add the value of the varint
444 static void fts3GetDeltaVarint(char **pp
, sqlite3_int64
*pVal
){
446 *pp
+= sqlite3Fts3GetVarint(*pp
, &iVal
);
451 ** When this function is called, *pp points to the first byte following a
452 ** varint that is part of a doclist (or position-list, or any other list
453 ** of varints). This function moves *pp to point to the start of that varint,
454 ** and sets *pVal by the varint value.
456 ** Argument pStart points to the first byte of the doclist that the
457 ** varint is part of.
459 static void fts3GetReverseVarint(
467 /* Pointer p now points at the first byte past the varint we are
468 ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
469 ** clear on character p[-1]. */
470 for(p
= (*pp
)-2; p
>=pStart
&& *p
&0x80; p
--);
474 sqlite3Fts3GetVarint(p
, &iVal
);
479 ** The xDisconnect() virtual table method.
481 static int fts3DisconnectMethod(sqlite3_vtab
*pVtab
){
482 Fts3Table
*p
= (Fts3Table
*)pVtab
;
485 assert( p
->nPendingData
==0 );
486 assert( p
->pSegments
==0 );
488 /* Free any prepared statements held */
489 for(i
=0; i
<SizeofArray(p
->aStmt
); i
++){
490 sqlite3_finalize(p
->aStmt
[i
]);
492 sqlite3_free(p
->zSegmentsTbl
);
493 sqlite3_free(p
->zReadExprlist
);
494 sqlite3_free(p
->zWriteExprlist
);
495 sqlite3_free(p
->zContentTbl
);
496 sqlite3_free(p
->zLanguageid
);
498 /* Invoke the tokenizer destructor to free the tokenizer. */
499 p
->pTokenizer
->pModule
->xDestroy(p
->pTokenizer
);
506 ** Construct one or more SQL statements from the format string given
507 ** and then evaluate those statements. The success code is written
510 ** If *pRc is initially non-zero then this routine is a no-op.
512 static void fts3DbExec(
513 int *pRc
, /* Success code */
514 sqlite3
*db
, /* Database in which to run SQL */
515 const char *zFormat
, /* Format string for SQL */
516 ... /* Arguments to the format string */
521 va_start(ap
, zFormat
);
522 zSql
= sqlite3_vmprintf(zFormat
, ap
);
527 *pRc
= sqlite3_exec(db
, zSql
, 0, 0, 0);
533 ** The xDestroy() virtual table method.
535 static int fts3DestroyMethod(sqlite3_vtab
*pVtab
){
536 Fts3Table
*p
= (Fts3Table
*)pVtab
;
537 int rc
= SQLITE_OK
; /* Return code */
538 const char *zDb
= p
->zDb
; /* Name of database (e.g. "main", "temp") */
539 sqlite3
*db
= p
->db
; /* Database handle */
541 /* Drop the shadow tables */
542 if( p
->zContentTbl
==0 ){
543 fts3DbExec(&rc
, db
, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb
, p
->zName
);
545 fts3DbExec(&rc
, db
, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb
,p
->zName
);
546 fts3DbExec(&rc
, db
, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb
, p
->zName
);
547 fts3DbExec(&rc
, db
, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb
, p
->zName
);
548 fts3DbExec(&rc
, db
, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb
, p
->zName
);
550 /* If everything has worked, invoke fts3DisconnectMethod() to free the
551 ** memory associated with the Fts3Table structure and return SQLITE_OK.
552 ** Otherwise, return an SQLite error code.
554 return (rc
==SQLITE_OK
? fts3DisconnectMethod(pVtab
) : rc
);
559 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
560 ** passed as the first argument. This is done as part of the xConnect()
561 ** and xCreate() methods.
563 ** If *pRc is non-zero when this function is called, it is a no-op.
564 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
567 static void fts3DeclareVtab(int *pRc
, Fts3Table
*p
){
568 if( *pRc
==SQLITE_OK
){
569 int i
; /* Iterator variable */
570 int rc
; /* Return code */
571 char *zSql
; /* SQL statement passed to declare_vtab() */
572 char *zCols
; /* List of user defined columns */
573 const char *zLanguageid
;
575 zLanguageid
= (p
->zLanguageid
? p
->zLanguageid
: "__langid");
576 sqlite3_vtab_config(p
->db
, SQLITE_VTAB_CONSTRAINT_SUPPORT
, 1);
578 /* Create a list of user columns for the virtual table */
579 zCols
= sqlite3_mprintf("%Q, ", p
->azColumn
[0]);
580 for(i
=1; zCols
&& i
<p
->nColumn
; i
++){
581 zCols
= sqlite3_mprintf("%z%Q, ", zCols
, p
->azColumn
[i
]);
584 /* Create the whole "CREATE TABLE" statement to pass to SQLite */
585 zSql
= sqlite3_mprintf(
586 "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
587 zCols
, p
->zName
, zLanguageid
589 if( !zCols
|| !zSql
){
592 rc
= sqlite3_declare_vtab(p
->db
, zSql
);
602 ** Create the %_stat table if it does not already exist.
604 void sqlite3Fts3CreateStatTable(int *pRc
, Fts3Table
*p
){
605 fts3DbExec(pRc
, p
->db
,
606 "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
607 "(id INTEGER PRIMARY KEY, value BLOB);",
610 if( (*pRc
)==SQLITE_OK
) p
->bHasStat
= 1;
614 ** Create the backing store tables (%_content, %_segments and %_segdir)
615 ** required by the FTS3 table passed as the only argument. This is done
616 ** as part of the vtab xCreate() method.
618 ** If the p->bHasDocsize boolean is true (indicating that this is an
619 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
620 ** %_stat tables required by FTS4.
622 static int fts3CreateTables(Fts3Table
*p
){
623 int rc
= SQLITE_OK
; /* Return code */
624 int i
; /* Iterator variable */
625 sqlite3
*db
= p
->db
; /* The database connection */
627 if( p
->zContentTbl
==0 ){
628 const char *zLanguageid
= p
->zLanguageid
;
629 char *zContentCols
; /* Columns of %_content table */
631 /* Create a list of user columns for the content table */
632 zContentCols
= sqlite3_mprintf("docid INTEGER PRIMARY KEY");
633 for(i
=0; zContentCols
&& i
<p
->nColumn
; i
++){
634 char *z
= p
->azColumn
[i
];
635 zContentCols
= sqlite3_mprintf("%z, 'c%d%q'", zContentCols
, i
, z
);
637 if( zLanguageid
&& zContentCols
){
638 zContentCols
= sqlite3_mprintf("%z, langid", zContentCols
, zLanguageid
);
640 if( zContentCols
==0 ) rc
= SQLITE_NOMEM
;
642 /* Create the content table */
644 "CREATE TABLE %Q.'%q_content'(%s)",
645 p
->zDb
, p
->zName
, zContentCols
647 sqlite3_free(zContentCols
);
650 /* Create other tables */
652 "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
656 "CREATE TABLE %Q.'%q_segdir'("
659 "start_block INTEGER,"
660 "leaves_end_block INTEGER,"
663 "PRIMARY KEY(level, idx)"
667 if( p
->bHasDocsize
){
669 "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
673 assert( p
->bHasStat
==p
->bFts4
);
675 sqlite3Fts3CreateStatTable(&rc
, p
);
681 ** Store the current database page-size in bytes in p->nPgsz.
683 ** If *pRc is non-zero when this function is called, it is a no-op.
684 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
687 static void fts3DatabasePageSize(int *pRc
, Fts3Table
*p
){
688 if( *pRc
==SQLITE_OK
){
689 int rc
; /* Return code */
690 char *zSql
; /* SQL text "PRAGMA %Q.page_size" */
691 sqlite3_stmt
*pStmt
; /* Compiled "PRAGMA %Q.page_size" statement */
693 zSql
= sqlite3_mprintf("PRAGMA %Q.page_size", p
->zDb
);
697 rc
= sqlite3_prepare(p
->db
, zSql
, -1, &pStmt
, 0);
700 p
->nPgsz
= sqlite3_column_int(pStmt
, 0);
701 rc
= sqlite3_finalize(pStmt
);
702 }else if( rc
==SQLITE_AUTH
){
707 assert( p
->nPgsz
>0 || rc
!=SQLITE_OK
);
714 ** "Special" FTS4 arguments are column specifications of the following form:
718 ** There may not be whitespace surrounding the "=" character. The <value>
719 ** term may be quoted, but the <key> may not.
721 static int fts3IsSpecialColumn(
727 const char *zCsr
= z
;
730 if( *zCsr
=='\0' ) return 0;
734 *pnKey
= (int)(zCsr
-z
);
735 zValue
= sqlite3_mprintf("%s", &zCsr
[1]);
737 sqlite3Fts3Dequote(zValue
);
744 ** Append the output of a printf() style formatting to an existing string.
746 static void fts3Appendf(
747 int *pRc
, /* IN/OUT: Error code */
748 char **pz
, /* IN/OUT: Pointer to string buffer */
749 const char *zFormat
, /* Printf format string to append */
750 ... /* Arguments for printf format string */
752 if( *pRc
==SQLITE_OK
){
755 va_start(ap
, zFormat
);
756 z
= sqlite3_vmprintf(zFormat
, ap
);
759 char *z2
= sqlite3_mprintf("%s%s", *pz
, z
);
763 if( z
==0 ) *pRc
= SQLITE_NOMEM
;
770 ** Return a copy of input string zInput enclosed in double-quotes (") and
771 ** with all double quote characters escaped. For example:
773 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
775 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
776 ** is the callers responsibility to call sqlite3_free() to release this
779 static char *fts3QuoteId(char const *zInput
){
782 nRet
= 2 + (int)strlen(zInput
)*2 + 1;
783 zRet
= sqlite3_malloc(nRet
);
788 for(i
=0; zInput
[i
]; i
++){
789 if( zInput
[i
]=='"' ) *(z
++) = '"';
799 ** Return a list of comma separated SQL expressions and a FROM clause that
800 ** could be used in a SELECT statement such as the following:
802 ** SELECT <list of expressions> FROM %_content AS x ...
804 ** to return the docid, followed by each column of text data in order
805 ** from left to write. If parameter zFunc is not NULL, then instead of
806 ** being returned directly each column of text data is passed to an SQL
807 ** function named zFunc first. For example, if zFunc is "unzip" and the
808 ** table has the three user-defined columns "a", "b", and "c", the following
809 ** string is returned:
811 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
813 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
814 ** is the responsibility of the caller to eventually free it.
816 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
817 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
818 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
819 ** no error occurs, *pRc is left unmodified.
821 static char *fts3ReadExprList(Fts3Table
*p
, const char *zFunc
, int *pRc
){
827 if( p
->zContentTbl
==0 ){
831 zFree
= zFunction
= fts3QuoteId(zFunc
);
833 fts3Appendf(pRc
, &zRet
, "docid");
834 for(i
=0; i
<p
->nColumn
; i
++){
835 fts3Appendf(pRc
, &zRet
, ",%s(x.'c%d%q')", zFunction
, i
, p
->azColumn
[i
]);
837 if( p
->zLanguageid
){
838 fts3Appendf(pRc
, &zRet
, ", x.%Q", "langid");
842 fts3Appendf(pRc
, &zRet
, "rowid");
843 for(i
=0; i
<p
->nColumn
; i
++){
844 fts3Appendf(pRc
, &zRet
, ", x.'%q'", p
->azColumn
[i
]);
846 if( p
->zLanguageid
){
847 fts3Appendf(pRc
, &zRet
, ", x.%Q", p
->zLanguageid
);
850 fts3Appendf(pRc
, &zRet
, " FROM '%q'.'%q%s' AS x",
852 (p
->zContentTbl
? p
->zContentTbl
: p
->zName
),
853 (p
->zContentTbl
? "" : "_content")
859 ** Return a list of N comma separated question marks, where N is the number
860 ** of columns in the %_content table (one for the docid plus one for each
861 ** user-defined text column).
863 ** If argument zFunc is not NULL, then all but the first question mark
864 ** is preceded by zFunc and an open bracket, and followed by a closed
865 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
866 ** user-defined text columns, the following string is returned:
868 ** "?, zip(?), zip(?), zip(?)"
870 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
871 ** is the responsibility of the caller to eventually free it.
873 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
874 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
875 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
876 ** no error occurs, *pRc is left unmodified.
878 static char *fts3WriteExprList(Fts3Table
*p
, const char *zFunc
, int *pRc
){
887 zFree
= zFunction
= fts3QuoteId(zFunc
);
889 fts3Appendf(pRc
, &zRet
, "?");
890 for(i
=0; i
<p
->nColumn
; i
++){
891 fts3Appendf(pRc
, &zRet
, ",%s(?)", zFunction
);
893 if( p
->zLanguageid
){
894 fts3Appendf(pRc
, &zRet
, ", ?");
901 ** This function interprets the string at (*pp) as a non-negative integer
902 ** value. It reads the integer and sets *pnOut to the value read, then
903 ** sets *pp to point to the byte immediately following the last byte of
904 ** the integer value.
906 ** Only decimal digits ('0'..'9') may be part of an integer value.
908 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
909 ** the output value undefined. Otherwise SQLITE_OK is returned.
911 ** This function is used when parsing the "prefix=" FTS4 parameter.
913 static int fts3GobbleInt(const char **pp
, int *pnOut
){
914 const char *p
; /* Iterator pointer */
915 int nInt
= 0; /* Output value */
917 for(p
=*pp
; p
[0]>='0' && p
[0]<='9'; p
++){
918 nInt
= nInt
* 10 + (p
[0] - '0');
920 if( p
==*pp
) return SQLITE_ERROR
;
927 ** This function is called to allocate an array of Fts3Index structures
928 ** representing the indexes maintained by the current FTS table. FTS tables
929 ** always maintain the main "terms" index, but may also maintain one or
930 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
931 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
933 ** Argument zParam is passed the value of the "prefix=" option if one was
934 ** specified, or NULL otherwise.
936 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
937 ** the allocated array. *pnIndex is set to the number of elements in the
938 ** array. If an error does occur, an SQLite error code is returned.
940 ** Regardless of whether or not an error is returned, it is the responsibility
941 ** of the caller to call sqlite3_free() on the output array to free it.
943 static int fts3PrefixParameter(
944 const char *zParam
, /* ABC in prefix=ABC parameter to parse */
945 int *pnIndex
, /* OUT: size of *apIndex[] array */
946 struct Fts3Index
**apIndex
/* OUT: Array of indexes for this table */
948 struct Fts3Index
*aIndex
; /* Allocated array */
949 int nIndex
= 1; /* Number of entries in array */
951 if( zParam
&& zParam
[0] ){
954 for(p
=zParam
; *p
; p
++){
955 if( *p
==',' ) nIndex
++;
959 aIndex
= sqlite3_malloc(sizeof(struct Fts3Index
) * nIndex
);
966 memset(aIndex
, 0, sizeof(struct Fts3Index
) * nIndex
);
968 const char *p
= zParam
;
970 for(i
=1; i
<nIndex
; i
++){
972 if( fts3GobbleInt(&p
, &nPrefix
) ) return SQLITE_ERROR
;
973 aIndex
[i
].nPrefix
= nPrefix
;
982 ** This function is called when initializing an FTS4 table that uses the
983 ** content=xxx option. It determines the number of and names of the columns
984 ** of the new FTS4 table.
986 ** The third argument passed to this function is the value passed to the
987 ** config=xxx option (i.e. "xxx"). This function queries the database for
988 ** a table of that name. If found, the output variables are populated
991 ** *pnCol: Set to the number of columns table xxx has,
993 ** *pnStr: Set to the total amount of space required to store a copy
994 ** of each columns name, including the nul-terminator.
996 ** *pazCol: Set to point to an array of *pnCol strings. Each string is
997 ** the name of the corresponding column in table xxx. The array
998 ** and its contents are allocated using a single allocation. It
999 ** is the responsibility of the caller to free this allocation
1000 ** by eventually passing the *pazCol value to sqlite3_free().
1002 ** If the table cannot be found, an error code is returned and the output
1003 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
1004 ** returned (and the output variables are undefined).
1006 static int fts3ContentColumns(
1007 sqlite3
*db
, /* Database handle */
1008 const char *zDb
, /* Name of db (i.e. "main", "temp" etc.) */
1009 const char *zTbl
, /* Name of content table */
1010 const char ***pazCol
, /* OUT: Malloc'd array of column names */
1011 int *pnCol
, /* OUT: Size of array *pazCol */
1012 int *pnStr
/* OUT: Bytes of string content */
1014 int rc
= SQLITE_OK
; /* Return code */
1015 char *zSql
; /* "SELECT *" statement on zTbl */
1016 sqlite3_stmt
*pStmt
= 0; /* Compiled version of zSql */
1018 zSql
= sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb
, zTbl
);
1022 rc
= sqlite3_prepare(db
, zSql
, -1, &pStmt
, 0);
1026 if( rc
==SQLITE_OK
){
1027 const char **azCol
; /* Output array */
1028 int nStr
= 0; /* Size of all column names (incl. 0x00) */
1029 int nCol
; /* Number of table columns */
1030 int i
; /* Used to iterate through columns */
1032 /* Loop through the returned columns. Set nStr to the number of bytes of
1033 ** space required to store a copy of each column name, including the
1034 ** nul-terminator byte. */
1035 nCol
= sqlite3_column_count(pStmt
);
1036 for(i
=0; i
<nCol
; i
++){
1037 const char *zCol
= sqlite3_column_name(pStmt
, i
);
1038 nStr
+= (int)strlen(zCol
) + 1;
1041 /* Allocate and populate the array to return. */
1042 azCol
= (const char **)sqlite3_malloc(sizeof(char *) * nCol
+ nStr
);
1046 char *p
= (char *)&azCol
[nCol
];
1047 for(i
=0; i
<nCol
; i
++){
1048 const char *zCol
= sqlite3_column_name(pStmt
, i
);
1049 int n
= (int)strlen(zCol
)+1;
1055 sqlite3_finalize(pStmt
);
1057 /* Set the output variables. */
1067 ** This function is the implementation of both the xConnect and xCreate
1068 ** methods of the FTS3 virtual table.
1070 ** The argv[] array contains the following:
1072 ** argv[0] -> module name ("fts3" or "fts4")
1073 ** argv[1] -> database name
1074 ** argv[2] -> table name
1075 ** argv[...] -> "column name" and other module argument fields.
1077 static int fts3InitVtab(
1078 int isCreate
, /* True for xCreate, false for xConnect */
1079 sqlite3
*db
, /* The SQLite database connection */
1080 void *pAux
, /* Hash table containing tokenizers */
1081 int argc
, /* Number of elements in argv array */
1082 const char * const *argv
, /* xCreate/xConnect argument array */
1083 sqlite3_vtab
**ppVTab
, /* Write the resulting vtab structure here */
1084 char **pzErr
/* Write any error message here */
1086 Fts3Hash
*pHash
= (Fts3Hash
*)pAux
;
1087 Fts3Table
*p
= 0; /* Pointer to allocated vtab */
1088 int rc
= SQLITE_OK
; /* Return code */
1089 int i
; /* Iterator variable */
1090 int nByte
; /* Size of allocation used for *p */
1091 int iCol
; /* Column index */
1092 int nString
= 0; /* Bytes required to hold all column names */
1093 int nCol
= 0; /* Number of columns in the FTS table */
1094 char *zCsr
; /* Space for holding column names */
1095 int nDb
; /* Bytes required to hold database name */
1096 int nName
; /* Bytes required to hold table name */
1097 int isFts4
= (argv
[0][3]=='4'); /* True for FTS4, false for FTS3 */
1098 const char **aCol
; /* Array of column names */
1099 sqlite3_tokenizer
*pTokenizer
= 0; /* Tokenizer for this table */
1101 int nIndex
; /* Size of aIndex[] array */
1102 struct Fts3Index
*aIndex
= 0; /* Array of indexes for this table */
1104 /* The results of parsing supported FTS4 key=value options: */
1105 int bNoDocsize
= 0; /* True to omit %_docsize table */
1106 int bDescIdx
= 0; /* True to store descending indexes */
1107 char *zPrefix
= 0; /* Prefix parameter value (or NULL) */
1108 char *zCompress
= 0; /* compress=? parameter (or NULL) */
1109 char *zUncompress
= 0; /* uncompress=? parameter (or NULL) */
1110 char *zContent
= 0; /* content=? parameter (or NULL) */
1111 char *zLanguageid
= 0; /* languageid=? parameter (or NULL) */
1112 char **azNotindexed
= 0; /* The set of notindexed= columns */
1113 int nNotindexed
= 0; /* Size of azNotindexed[] array */
1115 assert( strlen(argv
[0])==4 );
1116 assert( (sqlite3_strnicmp(argv
[0], "fts4", 4)==0 && isFts4
)
1117 || (sqlite3_strnicmp(argv
[0], "fts3", 4)==0 && !isFts4
)
1120 nDb
= (int)strlen(argv
[1]) + 1;
1121 nName
= (int)strlen(argv
[2]) + 1;
1123 nByte
= sizeof(const char *) * (argc
-2);
1124 aCol
= (const char **)sqlite3_malloc(nByte
);
1126 memset((void*)aCol
, 0, nByte
);
1127 azNotindexed
= (char **)sqlite3_malloc(nByte
);
1130 memset(azNotindexed
, 0, nByte
);
1132 if( !aCol
|| !azNotindexed
){
1137 /* Loop through all of the arguments passed by the user to the FTS3/4
1138 ** module (i.e. all the column names and special arguments). This loop
1139 ** does the following:
1141 ** + Figures out the number of columns the FTSX table will have, and
1142 ** the number of bytes of space that must be allocated to store copies
1143 ** of the column names.
1145 ** + If there is a tokenizer specification included in the arguments,
1146 ** initializes the tokenizer pTokenizer.
1148 for(i
=3; rc
==SQLITE_OK
&& i
<argc
; i
++){
1149 char const *z
= argv
[i
];
1153 /* Check if this is a tokenizer specification */
1156 && 0==sqlite3_strnicmp(z
, "tokenize", 8)
1157 && 0==sqlite3Fts3IsIdChar(z
[8])
1159 rc
= sqlite3Fts3InitTokenizer(pHash
, &z
[9], &pTokenizer
, pzErr
);
1162 /* Check if it is an FTS4 special argument. */
1163 else if( isFts4
&& fts3IsSpecialColumn(z
, &nKey
, &zVal
) ){
1168 { "matchinfo", 9 }, /* 0 -> MATCHINFO */
1169 { "prefix", 6 }, /* 1 -> PREFIX */
1170 { "compress", 8 }, /* 2 -> COMPRESS */
1171 { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
1172 { "order", 5 }, /* 4 -> ORDER */
1173 { "content", 7 }, /* 5 -> CONTENT */
1174 { "languageid", 10 }, /* 6 -> LANGUAGEID */
1175 { "notindexed", 10 } /* 7 -> NOTINDEXED */
1182 for(iOpt
=0; iOpt
<SizeofArray(aFts4Opt
); iOpt
++){
1183 struct Fts4Option
*pOp
= &aFts4Opt
[iOpt
];
1184 if( nKey
==pOp
->nOpt
&& !sqlite3_strnicmp(z
, pOp
->zOpt
, pOp
->nOpt
) ){
1188 if( iOpt
==SizeofArray(aFts4Opt
) ){
1189 *pzErr
= sqlite3_mprintf("unrecognized parameter: %s", z
);
1193 case 0: /* MATCHINFO */
1194 if( strlen(zVal
)!=4 || sqlite3_strnicmp(zVal
, "fts3", 4) ){
1195 *pzErr
= sqlite3_mprintf("unrecognized matchinfo: %s", zVal
);
1201 case 1: /* PREFIX */
1202 sqlite3_free(zPrefix
);
1207 case 2: /* COMPRESS */
1208 sqlite3_free(zCompress
);
1213 case 3: /* UNCOMPRESS */
1214 sqlite3_free(zUncompress
);
1220 if( (strlen(zVal
)!=3 || sqlite3_strnicmp(zVal
, "asc", 3))
1221 && (strlen(zVal
)!=4 || sqlite3_strnicmp(zVal
, "desc", 4))
1223 *pzErr
= sqlite3_mprintf("unrecognized order: %s", zVal
);
1226 bDescIdx
= (zVal
[0]=='d' || zVal
[0]=='D');
1229 case 5: /* CONTENT */
1230 sqlite3_free(zContent
);
1235 case 6: /* LANGUAGEID */
1237 sqlite3_free(zLanguageid
);
1242 case 7: /* NOTINDEXED */
1243 azNotindexed
[nNotindexed
++] = zVal
;
1252 /* Otherwise, the argument is a column name. */
1254 nString
+= (int)(strlen(z
) + 1);
1259 /* If a content=xxx option was specified, the following:
1261 ** 1. Ignore any compress= and uncompress= options.
1263 ** 2. If no column names were specified as part of the CREATE VIRTUAL
1264 ** TABLE statement, use all columns from the content table.
1266 if( rc
==SQLITE_OK
&& zContent
){
1267 sqlite3_free(zCompress
);
1268 sqlite3_free(zUncompress
);
1272 sqlite3_free((void*)aCol
);
1274 rc
= fts3ContentColumns(db
, argv
[1], zContent
, &aCol
, &nCol
, &nString
);
1276 /* If a languageid= option was specified, remove the language id
1277 ** column from the aCol[] array. */
1278 if( rc
==SQLITE_OK
&& zLanguageid
){
1280 for(j
=0; j
<nCol
; j
++){
1281 if( sqlite3_stricmp(zLanguageid
, aCol
[j
])==0 ){
1283 for(k
=j
; k
<nCol
; k
++) aCol
[k
] = aCol
[k
+1];
1291 if( rc
!=SQLITE_OK
) goto fts3_init_out
;
1294 assert( nString
==0 );
1295 aCol
[0] = "content";
1300 if( pTokenizer
==0 ){
1301 rc
= sqlite3Fts3InitTokenizer(pHash
, "simple", &pTokenizer
, pzErr
);
1302 if( rc
!=SQLITE_OK
) goto fts3_init_out
;
1304 assert( pTokenizer
);
1306 rc
= fts3PrefixParameter(zPrefix
, &nIndex
, &aIndex
);
1307 if( rc
==SQLITE_ERROR
){
1309 *pzErr
= sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix
);
1311 if( rc
!=SQLITE_OK
) goto fts3_init_out
;
1313 /* Allocate and populate the Fts3Table structure. */
1314 nByte
= sizeof(Fts3Table
) + /* Fts3Table */
1315 nCol
* sizeof(char *) + /* azColumn */
1316 nIndex
* sizeof(struct Fts3Index
) + /* aIndex */
1317 nCol
* sizeof(u8
) + /* abNotindexed */
1320 nString
; /* Space for azColumn strings */
1321 p
= (Fts3Table
*)sqlite3_malloc(nByte
);
1326 memset(p
, 0, nByte
);
1329 p
->nPendingData
= 0;
1330 p
->azColumn
= (char **)&p
[1];
1331 p
->pTokenizer
= pTokenizer
;
1332 p
->nMaxPendingData
= FTS3_MAX_PENDING_DATA
;
1333 p
->bHasDocsize
= (isFts4
&& bNoDocsize
==0);
1334 p
->bHasStat
= isFts4
;
1336 p
->bDescIdx
= bDescIdx
;
1337 p
->nAutoincrmerge
= 0xff; /* 0xff means setting unknown */
1338 p
->zContentTbl
= zContent
;
1339 p
->zLanguageid
= zLanguageid
;
1342 TESTONLY( p
->inTransaction
= -1 );
1343 TESTONLY( p
->mxSavepoint
= -1 );
1345 p
->aIndex
= (struct Fts3Index
*)&p
->azColumn
[nCol
];
1346 memcpy(p
->aIndex
, aIndex
, sizeof(struct Fts3Index
) * nIndex
);
1348 for(i
=0; i
<nIndex
; i
++){
1349 fts3HashInit(&p
->aIndex
[i
].hPending
, FTS3_HASH_STRING
, 1);
1351 p
->abNotindexed
= (u8
*)&p
->aIndex
[nIndex
];
1353 /* Fill in the zName and zDb fields of the vtab structure. */
1354 zCsr
= (char *)&p
->abNotindexed
[nCol
];
1356 memcpy(zCsr
, argv
[2], nName
);
1359 memcpy(zCsr
, argv
[1], nDb
);
1362 /* Fill in the azColumn array */
1363 for(iCol
=0; iCol
<nCol
; iCol
++){
1366 z
= (char *)sqlite3Fts3NextToken(aCol
[iCol
], &n
);
1369 sqlite3Fts3Dequote(zCsr
);
1370 p
->azColumn
[iCol
] = zCsr
;
1372 assert( zCsr
<= &((char *)p
)[nByte
] );
1375 /* Fill in the abNotindexed array */
1376 for(iCol
=0; iCol
<nCol
; iCol
++){
1377 int n
= (int)strlen(p
->azColumn
[iCol
]);
1378 for(i
=0; i
<nNotindexed
; i
++){
1379 char *zNot
= azNotindexed
[i
];
1380 if( zNot
&& n
==(int)strlen(zNot
)
1381 && 0==sqlite3_strnicmp(p
->azColumn
[iCol
], zNot
, n
)
1383 p
->abNotindexed
[iCol
] = 1;
1385 azNotindexed
[i
] = 0;
1389 for(i
=0; i
<nNotindexed
; i
++){
1390 if( azNotindexed
[i
] ){
1391 *pzErr
= sqlite3_mprintf("no such column: %s", azNotindexed
[i
]);
1396 if( rc
==SQLITE_OK
&& (zCompress
==0)!=(zUncompress
==0) ){
1397 char const *zMiss
= (zCompress
==0 ? "compress" : "uncompress");
1399 *pzErr
= sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss
);
1401 p
->zReadExprlist
= fts3ReadExprList(p
, zUncompress
, &rc
);
1402 p
->zWriteExprlist
= fts3WriteExprList(p
, zCompress
, &rc
);
1403 if( rc
!=SQLITE_OK
) goto fts3_init_out
;
1405 /* If this is an xCreate call, create the underlying tables in the
1406 ** database. TODO: For xConnect(), it could verify that said tables exist.
1409 rc
= fts3CreateTables(p
);
1412 /* Check to see if a legacy fts3 table has been "upgraded" by the
1413 ** addition of a %_stat table so that it can use incremental merge.
1415 if( !isFts4
&& !isCreate
){
1419 /* Figure out the page-size for the database. This is required in order to
1420 ** estimate the cost of loading large doclists from the database. */
1421 fts3DatabasePageSize(&rc
, p
);
1422 p
->nNodeSize
= p
->nPgsz
-35;
1424 /* Declare the table schema to SQLite. */
1425 fts3DeclareVtab(&rc
, p
);
1428 sqlite3_free(zPrefix
);
1429 sqlite3_free(aIndex
);
1430 sqlite3_free(zCompress
);
1431 sqlite3_free(zUncompress
);
1432 sqlite3_free(zContent
);
1433 sqlite3_free(zLanguageid
);
1434 for(i
=0; i
<nNotindexed
; i
++) sqlite3_free(azNotindexed
[i
]);
1435 sqlite3_free((void *)aCol
);
1436 sqlite3_free((void *)azNotindexed
);
1437 if( rc
!=SQLITE_OK
){
1439 fts3DisconnectMethod((sqlite3_vtab
*)p
);
1440 }else if( pTokenizer
){
1441 pTokenizer
->pModule
->xDestroy(pTokenizer
);
1444 assert( p
->pSegments
==0 );
1451 ** The xConnect() and xCreate() methods for the virtual table. All the
1452 ** work is done in function fts3InitVtab().
1454 static int fts3ConnectMethod(
1455 sqlite3
*db
, /* Database connection */
1456 void *pAux
, /* Pointer to tokenizer hash table */
1457 int argc
, /* Number of elements in argv array */
1458 const char * const *argv
, /* xCreate/xConnect argument array */
1459 sqlite3_vtab
**ppVtab
, /* OUT: New sqlite3_vtab object */
1460 char **pzErr
/* OUT: sqlite3_malloc'd error message */
1462 return fts3InitVtab(0, db
, pAux
, argc
, argv
, ppVtab
, pzErr
);
1464 static int fts3CreateMethod(
1465 sqlite3
*db
, /* Database connection */
1466 void *pAux
, /* Pointer to tokenizer hash table */
1467 int argc
, /* Number of elements in argv array */
1468 const char * const *argv
, /* xCreate/xConnect argument array */
1469 sqlite3_vtab
**ppVtab
, /* OUT: New sqlite3_vtab object */
1470 char **pzErr
/* OUT: sqlite3_malloc'd error message */
1472 return fts3InitVtab(1, db
, pAux
, argc
, argv
, ppVtab
, pzErr
);
1476 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
1477 ** extension is currently being used by a version of SQLite too old to
1478 ** support estimatedRows. In that case this function is a no-op.
1480 static void fts3SetEstimatedRows(sqlite3_index_info
*pIdxInfo
, i64 nRow
){
1481 #if SQLITE_VERSION_NUMBER>=3008002
1482 if( sqlite3_libversion_number()>=3008002 ){
1483 pIdxInfo
->estimatedRows
= nRow
;
1489 ** Implementation of the xBestIndex method for FTS3 tables. There
1490 ** are three possible strategies, in order of preference:
1492 ** 1. Direct lookup by rowid or docid.
1493 ** 2. Full-text search using a MATCH operator on a non-docid column.
1494 ** 3. Linear scan of %_content table.
1496 static int fts3BestIndexMethod(sqlite3_vtab
*pVTab
, sqlite3_index_info
*pInfo
){
1497 Fts3Table
*p
= (Fts3Table
*)pVTab
;
1498 int i
; /* Iterator variable */
1499 int iCons
= -1; /* Index of constraint to use */
1501 int iLangidCons
= -1; /* Index of langid=x constraint, if present */
1502 int iDocidGe
= -1; /* Index of docid>=x constraint, if present */
1503 int iDocidLe
= -1; /* Index of docid<=x constraint, if present */
1506 /* By default use a full table scan. This is an expensive option,
1507 ** so search through the constraints to see if a more efficient
1508 ** strategy is possible.
1510 pInfo
->idxNum
= FTS3_FULLSCAN_SEARCH
;
1511 pInfo
->estimatedCost
= 5000000;
1512 for(i
=0; i
<pInfo
->nConstraint
; i
++){
1513 int bDocid
; /* True if this constraint is on docid */
1514 struct sqlite3_index_constraint
*pCons
= &pInfo
->aConstraint
[i
];
1515 if( pCons
->usable
==0 ){
1516 if( pCons
->op
==SQLITE_INDEX_CONSTRAINT_MATCH
){
1517 /* There exists an unusable MATCH constraint. This means that if
1518 ** the planner does elect to use the results of this call as part
1519 ** of the overall query plan the user will see an "unable to use
1520 ** function MATCH in the requested context" error. To discourage
1521 ** this, return a very high cost here. */
1522 pInfo
->idxNum
= FTS3_FULLSCAN_SEARCH
;
1523 pInfo
->estimatedCost
= 1e50
;
1524 fts3SetEstimatedRows(pInfo
, ((sqlite3_int64
)1) << 50);
1530 bDocid
= (pCons
->iColumn
<0 || pCons
->iColumn
==p
->nColumn
+1);
1532 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
1533 if( iCons
<0 && pCons
->op
==SQLITE_INDEX_CONSTRAINT_EQ
&& bDocid
){
1534 pInfo
->idxNum
= FTS3_DOCID_SEARCH
;
1535 pInfo
->estimatedCost
= 1.0;
1539 /* A MATCH constraint. Use a full-text search.
1541 ** If there is more than one MATCH constraint available, use the first
1542 ** one encountered. If there is both a MATCH constraint and a direct
1543 ** rowid/docid lookup, prefer the MATCH strategy. This is done even
1544 ** though the rowid/docid lookup is faster than a MATCH query, selecting
1545 ** it would lead to an "unable to use function MATCH in the requested
1548 if( pCons
->op
==SQLITE_INDEX_CONSTRAINT_MATCH
1549 && pCons
->iColumn
>=0 && pCons
->iColumn
<=p
->nColumn
1551 pInfo
->idxNum
= FTS3_FULLTEXT_SEARCH
+ pCons
->iColumn
;
1552 pInfo
->estimatedCost
= 2.0;
1556 /* Equality constraint on the langid column */
1557 if( pCons
->op
==SQLITE_INDEX_CONSTRAINT_EQ
1558 && pCons
->iColumn
==p
->nColumn
+ 2
1564 switch( pCons
->op
){
1565 case SQLITE_INDEX_CONSTRAINT_GE
:
1566 case SQLITE_INDEX_CONSTRAINT_GT
:
1570 case SQLITE_INDEX_CONSTRAINT_LE
:
1571 case SQLITE_INDEX_CONSTRAINT_LT
:
1580 pInfo
->aConstraintUsage
[iCons
].argvIndex
= iIdx
++;
1581 pInfo
->aConstraintUsage
[iCons
].omit
= 1;
1583 if( iLangidCons
>=0 ){
1584 pInfo
->idxNum
|= FTS3_HAVE_LANGID
;
1585 pInfo
->aConstraintUsage
[iLangidCons
].argvIndex
= iIdx
++;
1588 pInfo
->idxNum
|= FTS3_HAVE_DOCID_GE
;
1589 pInfo
->aConstraintUsage
[iDocidGe
].argvIndex
= iIdx
++;
1592 pInfo
->idxNum
|= FTS3_HAVE_DOCID_LE
;
1593 pInfo
->aConstraintUsage
[iDocidLe
].argvIndex
= iIdx
++;
1596 /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
1597 ** docid) order. Both ascending and descending are possible.
1599 if( pInfo
->nOrderBy
==1 ){
1600 struct sqlite3_index_orderby
*pOrder
= &pInfo
->aOrderBy
[0];
1601 if( pOrder
->iColumn
<0 || pOrder
->iColumn
==p
->nColumn
+1 ){
1603 pInfo
->idxStr
= "DESC";
1605 pInfo
->idxStr
= "ASC";
1607 pInfo
->orderByConsumed
= 1;
1611 assert( p
->pSegments
==0 );
1616 ** Implementation of xOpen method.
1618 static int fts3OpenMethod(sqlite3_vtab
*pVTab
, sqlite3_vtab_cursor
**ppCsr
){
1619 sqlite3_vtab_cursor
*pCsr
; /* Allocated cursor */
1621 UNUSED_PARAMETER(pVTab
);
1623 /* Allocate a buffer large enough for an Fts3Cursor structure. If the
1624 ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
1625 ** if the allocation fails, return SQLITE_NOMEM.
1627 *ppCsr
= pCsr
= (sqlite3_vtab_cursor
*)sqlite3_malloc(sizeof(Fts3Cursor
));
1629 return SQLITE_NOMEM
;
1631 memset(pCsr
, 0, sizeof(Fts3Cursor
));
1636 ** Close the cursor. For additional information see the documentation
1637 ** on the xClose method of the virtual table interface.
1639 static int fts3CloseMethod(sqlite3_vtab_cursor
*pCursor
){
1640 Fts3Cursor
*pCsr
= (Fts3Cursor
*)pCursor
;
1641 assert( ((Fts3Table
*)pCsr
->base
.pVtab
)->pSegments
==0 );
1642 sqlite3_finalize(pCsr
->pStmt
);
1643 sqlite3Fts3ExprFree(pCsr
->pExpr
);
1644 sqlite3Fts3FreeDeferredTokens(pCsr
);
1645 sqlite3_free(pCsr
->aDoclist
);
1646 sqlite3_free(pCsr
->aMatchinfo
);
1647 assert( ((Fts3Table
*)pCsr
->base
.pVtab
)->pSegments
==0 );
1653 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
1654 ** compose and prepare an SQL statement of the form:
1656 ** "SELECT <columns> FROM %_content WHERE rowid = ?"
1658 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
1659 ** it. If an error occurs, return an SQLite error code.
1661 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
1663 static int fts3CursorSeekStmt(Fts3Cursor
*pCsr
, sqlite3_stmt
**ppStmt
){
1665 if( pCsr
->pStmt
==0 ){
1666 Fts3Table
*p
= (Fts3Table
*)pCsr
->base
.pVtab
;
1668 zSql
= sqlite3_mprintf("SELECT %s WHERE rowid = ?", p
->zReadExprlist
);
1669 if( !zSql
) return SQLITE_NOMEM
;
1670 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pCsr
->pStmt
, 0);
1673 *ppStmt
= pCsr
->pStmt
;
1678 ** Position the pCsr->pStmt statement so that it is on the row
1679 ** of the %_content table that contains the last match. Return
1680 ** SQLITE_OK on success.
1682 static int fts3CursorSeek(sqlite3_context
*pContext
, Fts3Cursor
*pCsr
){
1684 if( pCsr
->isRequireSeek
){
1685 sqlite3_stmt
*pStmt
= 0;
1687 rc
= fts3CursorSeekStmt(pCsr
, &pStmt
);
1688 if( rc
==SQLITE_OK
){
1689 sqlite3_bind_int64(pCsr
->pStmt
, 1, pCsr
->iPrevId
);
1690 pCsr
->isRequireSeek
= 0;
1691 if( SQLITE_ROW
==sqlite3_step(pCsr
->pStmt
) ){
1694 rc
= sqlite3_reset(pCsr
->pStmt
);
1695 if( rc
==SQLITE_OK
&& ((Fts3Table
*)pCsr
->base
.pVtab
)->zContentTbl
==0 ){
1696 /* If no row was found and no error has occurred, then the %_content
1697 ** table is missing a row that is present in the full-text index.
1698 ** The data structures are corrupt. */
1699 rc
= FTS_CORRUPT_VTAB
;
1706 if( rc
!=SQLITE_OK
&& pContext
){
1707 sqlite3_result_error_code(pContext
, rc
);
1713 ** This function is used to process a single interior node when searching
1714 ** a b-tree for a term or term prefix. The node data is passed to this
1715 ** function via the zNode/nNode parameters. The term to search for is
1716 ** passed in zTerm/nTerm.
1718 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
1719 ** of the child node that heads the sub-tree that may contain the term.
1721 ** If piLast is not NULL, then *piLast is set to the right-most child node
1722 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
1725 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
1727 static int fts3ScanInteriorNode(
1728 const char *zTerm
, /* Term to select leaves for */
1729 int nTerm
, /* Size of term zTerm in bytes */
1730 const char *zNode
, /* Buffer containing segment interior node */
1731 int nNode
, /* Size of buffer at zNode */
1732 sqlite3_int64
*piFirst
, /* OUT: Selected child node */
1733 sqlite3_int64
*piLast
/* OUT: Selected child node */
1735 int rc
= SQLITE_OK
; /* Return code */
1736 const char *zCsr
= zNode
; /* Cursor to iterate through node */
1737 const char *zEnd
= &zCsr
[nNode
];/* End of interior node buffer */
1738 char *zBuffer
= 0; /* Buffer to load terms into */
1739 int nAlloc
= 0; /* Size of allocated buffer */
1740 int isFirstTerm
= 1; /* True when processing first term on page */
1741 sqlite3_int64 iChild
; /* Block id of child node to descend to */
1743 /* Skip over the 'height' varint that occurs at the start of every
1744 ** interior node. Then load the blockid of the left-child of the b-tree
1745 ** node into variable iChild.
1747 ** Even if the data structure on disk is corrupted, this (reading two
1748 ** varints from the buffer) does not risk an overread. If zNode is a
1749 ** root node, then the buffer comes from a SELECT statement. SQLite does
1750 ** not make this guarantee explicitly, but in practice there are always
1751 ** either more than 20 bytes of allocated space following the nNode bytes of
1752 ** contents, or two zero bytes. Or, if the node is read from the %_segments
1753 ** table, then there are always 20 bytes of zeroed padding following the
1754 ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
1756 zCsr
+= sqlite3Fts3GetVarint(zCsr
, &iChild
);
1757 zCsr
+= sqlite3Fts3GetVarint(zCsr
, &iChild
);
1759 return FTS_CORRUPT_VTAB
;
1762 while( zCsr
<zEnd
&& (piFirst
|| piLast
) ){
1763 int cmp
; /* memcmp() result */
1764 int nSuffix
; /* Size of term suffix */
1765 int nPrefix
= 0; /* Size of term prefix */
1766 int nBuffer
; /* Total term size */
1768 /* Load the next term on the node into zBuffer. Use realloc() to expand
1769 ** the size of zBuffer if required. */
1771 zCsr
+= fts3GetVarint32(zCsr
, &nPrefix
);
1774 zCsr
+= fts3GetVarint32(zCsr
, &nSuffix
);
1776 /* NOTE(shess): Previous code checked for negative nPrefix and
1777 ** nSuffix and suffix overrunning zEnd. Additionally corrupt if
1778 ** the prefix is longer than the previous term, or if the suffix
1781 if( nPrefix
<0 || nSuffix
<0 /* || nPrefix>nBuffer */
1782 || &zCsr
[nSuffix
]<zCsr
|| &zCsr
[nSuffix
]>zEnd
){
1783 rc
= SQLITE_CORRUPT
;
1786 if( nPrefix
+nSuffix
>nAlloc
){
1788 nAlloc
= (nPrefix
+nSuffix
) * 2;
1789 zNew
= (char *)sqlite3_realloc(zBuffer
, nAlloc
);
1797 memcpy(&zBuffer
[nPrefix
], zCsr
, nSuffix
);
1798 nBuffer
= nPrefix
+ nSuffix
;
1801 /* Compare the term we are searching for with the term just loaded from
1802 ** the interior node. If the specified term is greater than or equal
1803 ** to the term from the interior node, then all terms on the sub-tree
1804 ** headed by node iChild are smaller than zTerm. No need to search
1807 ** If the interior node term is larger than the specified term, then
1808 ** the tree headed by iChild may contain the specified term.
1810 cmp
= memcmp(zTerm
, zBuffer
, (nBuffer
>nTerm
? nTerm
: nBuffer
));
1811 if( piFirst
&& (cmp
<0 || (cmp
==0 && nBuffer
>nTerm
)) ){
1816 if( piLast
&& cmp
<0 ){
1824 if( piFirst
) *piFirst
= iChild
;
1825 if( piLast
) *piLast
= iChild
;
1828 sqlite3_free(zBuffer
);
1834 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
1835 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
1836 ** contains a term. This function searches the sub-tree headed by the zNode
1837 ** node for the range of leaf nodes that may contain the specified term
1838 ** or terms for which the specified term is a prefix.
1840 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
1841 ** left-most leaf node in the tree that may contain the specified term.
1842 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
1843 ** right-most leaf node that may contain a term for which the specified
1844 ** term is a prefix.
1846 ** It is possible that the range of returned leaf nodes does not contain
1847 ** the specified term or any terms for which it is a prefix. However, if the
1848 ** segment does contain any such terms, they are stored within the identified
1849 ** range. Because this function only inspects interior segment nodes (and
1850 ** never loads leaf nodes into memory), it is not possible to be sure.
1852 ** If an error occurs, an error code other than SQLITE_OK is returned.
1854 static int fts3SelectLeaf(
1855 Fts3Table
*p
, /* Virtual table handle */
1856 const char *zTerm
, /* Term to select leaves for */
1857 int nTerm
, /* Size of term zTerm in bytes */
1858 const char *zNode
, /* Buffer containing segment interior node */
1859 int nNode
, /* Size of buffer at zNode */
1860 sqlite3_int64
*piLeaf
, /* Selected leaf node */
1861 sqlite3_int64
*piLeaf2
/* Selected leaf node */
1863 int rc
; /* Return code */
1864 int iHeight
; /* Height of this node in tree */
1866 assert( piLeaf
|| piLeaf2
);
1868 fts3GetVarint32(zNode
, &iHeight
);
1869 rc
= fts3ScanInteriorNode(zTerm
, nTerm
, zNode
, nNode
, piLeaf
, piLeaf2
);
1870 assert( !piLeaf2
|| !piLeaf
|| rc
!=SQLITE_OK
|| (*piLeaf
<=*piLeaf2
) );
1872 if( rc
==SQLITE_OK
&& iHeight
>1 ){
1873 char *zBlob
= 0; /* Blob read from %_segments table */
1874 int nBlob
; /* Size of zBlob in bytes */
1876 if( piLeaf
&& piLeaf2
&& (*piLeaf
!=*piLeaf2
) ){
1877 rc
= sqlite3Fts3ReadBlock(p
, *piLeaf
, &zBlob
, &nBlob
, 0);
1878 if( rc
==SQLITE_OK
){
1879 rc
= fts3SelectLeaf(p
, zTerm
, nTerm
, zBlob
, nBlob
, piLeaf
, 0);
1881 sqlite3_free(zBlob
);
1886 if( rc
==SQLITE_OK
){
1887 rc
= sqlite3Fts3ReadBlock(p
, piLeaf
?*piLeaf
:*piLeaf2
, &zBlob
, &nBlob
, 0);
1889 if( rc
==SQLITE_OK
){
1890 rc
= fts3SelectLeaf(p
, zTerm
, nTerm
, zBlob
, nBlob
, piLeaf
, piLeaf2
);
1892 sqlite3_free(zBlob
);
1899 ** This function is used to create delta-encoded serialized lists of FTS3
1900 ** varints. Each call to this function appends a single varint to a list.
1902 static void fts3PutDeltaVarint(
1903 char **pp
, /* IN/OUT: Output pointer */
1904 sqlite3_int64
*piPrev
, /* IN/OUT: Previous value written to list */
1905 sqlite3_int64 iVal
/* Write this value to the list */
1907 assert( iVal
-*piPrev
> 0 || (*piPrev
==0 && iVal
==0) );
1908 *pp
+= sqlite3Fts3PutVarint(*pp
, iVal
-*piPrev
);
1913 ** When this function is called, *ppPoslist is assumed to point to the
1914 ** start of a position-list. After it returns, *ppPoslist points to the
1915 ** first byte after the position-list.
1917 ** A position list is list of positions (delta encoded) and columns for
1918 ** a single document record of a doclist. So, in other words, this
1919 ** routine advances *ppPoslist so that it points to the next docid in
1920 ** the doclist, or to the first byte past the end of the doclist.
1922 ** If pp is not NULL, then the contents of the position list are copied
1923 ** to *pp. *pp is set to point to the first byte past the last byte copied
1924 ** before this function returns.
1926 static void fts3PoslistCopy(char **pp
, char **ppPoslist
){
1927 char *pEnd
= *ppPoslist
;
1930 /* The end of a position list is marked by a zero encoded as an FTS3
1931 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
1932 ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
1933 ** of some other, multi-byte, value.
1935 ** The following while-loop moves pEnd to point to the first byte that is not
1936 ** immediately preceded by a byte with the 0x80 bit set. Then increments
1937 ** pEnd once more so that it points to the byte immediately following the
1938 ** last byte in the position-list.
1942 testcase( c
!=0 && (*pEnd
)==0 );
1944 pEnd
++; /* Advance past the POS_END terminator byte */
1947 int n
= (int)(pEnd
- *ppPoslist
);
1949 memcpy(p
, *ppPoslist
, n
);
1957 ** When this function is called, *ppPoslist is assumed to point to the
1958 ** start of a column-list. After it returns, *ppPoslist points to the
1959 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
1961 ** A column-list is list of delta-encoded positions for a single column
1962 ** within a single document within a doclist.
1964 ** The column-list is terminated either by a POS_COLUMN varint (1) or
1965 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
1966 ** the POS_COLUMN or POS_END that terminates the column-list.
1968 ** If pp is not NULL, then the contents of the column-list are copied
1969 ** to *pp. *pp is set to point to the first byte past the last byte copied
1970 ** before this function returns. The POS_COLUMN or POS_END terminator
1971 ** is not copied into *pp.
1973 static void fts3ColumnlistCopy(char **pp
, char **ppPoslist
){
1974 char *pEnd
= *ppPoslist
;
1977 /* A column-list is terminated by either a 0x01 or 0x00 byte that is
1978 ** not part of a multi-byte varint.
1980 while( 0xFE & (*pEnd
| c
) ){
1982 testcase( c
!=0 && ((*pEnd
)&0xfe)==0 );
1985 int n
= (int)(pEnd
- *ppPoslist
);
1987 memcpy(p
, *ppPoslist
, n
);
1995 ** Value used to signify the end of an position-list. This is safe because
1996 ** it is not possible to have a document with 2^31 terms.
1998 #define POSITION_LIST_END 0x7fffffff
2001 ** This function is used to help parse position-lists. When this function is
2002 ** called, *pp may point to the start of the next varint in the position-list
2003 ** being parsed, or it may point to 1 byte past the end of the position-list
2004 ** (in which case **pp will be a terminator bytes POS_END (0) or
2007 ** If *pp points past the end of the current position-list, set *pi to
2008 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
2009 ** increment the current value of *pi by the value read, and set *pp to
2010 ** point to the next value before returning.
2012 ** Before calling this routine *pi must be initialized to the value of
2013 ** the previous position, or zero if we are reading the first position
2014 ** in the position-list. Because positions are delta-encoded, the value
2015 ** of the previous position is needed in order to compute the value of
2016 ** the next position.
2018 static void fts3ReadNextPos(
2019 char **pp
, /* IN/OUT: Pointer into position-list buffer */
2020 sqlite3_int64
*pi
/* IN/OUT: Value read from position-list */
2023 fts3GetDeltaVarint(pp
, pi
);
2026 *pi
= POSITION_LIST_END
;
2031 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
2032 ** the value of iCol encoded as a varint to *pp. This will start a new
2035 ** Set *pp to point to the byte just after the last byte written before
2036 ** returning (do not modify it if iCol==0). Return the total number of bytes
2037 ** written (0 if iCol==0).
2039 static int fts3PutColNumber(char **pp
, int iCol
){
2040 int n
= 0; /* Number of bytes written */
2042 char *p
= *pp
; /* Output pointer */
2043 n
= 1 + sqlite3Fts3PutVarint(&p
[1], iCol
);
2051 ** Compute the union of two position lists. The output written
2052 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
2053 ** order and with any duplicates removed. All pointers are
2054 ** updated appropriately. The caller is responsible for insuring
2055 ** that there is enough space in *pp to hold the complete output.
2057 static void fts3PoslistMerge(
2058 char **pp
, /* Output buffer */
2059 char **pp1
, /* Left input list */
2060 char **pp2
/* Right input list */
2066 while( *p1
|| *p2
){
2067 int iCol1
; /* The current column index in pp1 */
2068 int iCol2
; /* The current column index in pp2 */
2070 if( *p1
==POS_COLUMN
) fts3GetVarint32(&p1
[1], &iCol1
);
2071 else if( *p1
==POS_END
) iCol1
= POSITION_LIST_END
;
2074 if( *p2
==POS_COLUMN
) fts3GetVarint32(&p2
[1], &iCol2
);
2075 else if( *p2
==POS_END
) iCol2
= POSITION_LIST_END
;
2079 sqlite3_int64 i1
= 0; /* Last position from pp1 */
2080 sqlite3_int64 i2
= 0; /* Last position from pp2 */
2081 sqlite3_int64 iPrev
= 0;
2082 int n
= fts3PutColNumber(&p
, iCol1
);
2086 /* At this point, both p1 and p2 point to the start of column-lists
2087 ** for the same column (the column with index iCol1 and iCol2).
2088 ** A column-list is a list of non-negative delta-encoded varints, each
2089 ** incremented by 2 before being stored. Each list is terminated by a
2090 ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
2091 ** and writes the results to buffer p. p is left pointing to the byte
2092 ** after the list written. No terminator (POS_END or POS_COLUMN) is
2093 ** written to the output.
2095 fts3GetDeltaVarint(&p1
, &i1
);
2096 fts3GetDeltaVarint(&p2
, &i2
);
2098 fts3PutDeltaVarint(&p
, &iPrev
, (i1
<i2
) ? i1
: i2
);
2101 fts3ReadNextPos(&p1
, &i1
);
2102 fts3ReadNextPos(&p2
, &i2
);
2104 fts3ReadNextPos(&p1
, &i1
);
2106 fts3ReadNextPos(&p2
, &i2
);
2108 }while( i1
!=POSITION_LIST_END
|| i2
!=POSITION_LIST_END
);
2109 }else if( iCol1
<iCol2
){
2110 p1
+= fts3PutColNumber(&p
, iCol1
);
2111 fts3ColumnlistCopy(&p
, &p1
);
2113 p2
+= fts3PutColNumber(&p
, iCol2
);
2114 fts3ColumnlistCopy(&p
, &p2
);
2125 ** This function is used to merge two position lists into one. When it is
2126 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
2127 ** the part of a doclist that follows each document id. For example, if a row
2130 ** 'a b c'|'x y z'|'a b b a'
2132 ** Then the position list for this row for token 'b' would consist of:
2134 ** 0x02 0x01 0x02 0x03 0x03 0x00
2136 ** When this function returns, both *pp1 and *pp2 are left pointing to the
2137 ** byte following the 0x00 terminator of their respective position lists.
2139 ** If isSaveLeft is 0, an entry is added to the output position list for
2140 ** each position in *pp2 for which there exists one or more positions in
2141 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
2142 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
2145 ** e.g. nToken==1 searches for adjacent positions.
2147 static int fts3PoslistPhraseMerge(
2148 char **pp
, /* IN/OUT: Preallocated output buffer */
2149 int nToken
, /* Maximum difference in token positions */
2150 int isSaveLeft
, /* Save the left position */
2151 int isExact
, /* If *pp1 is exactly nTokens before *pp2 */
2152 char **pp1
, /* IN/OUT: Left input list */
2153 char **pp2
/* IN/OUT: Right input list */
2161 /* Never set both isSaveLeft and isExact for the same invocation. */
2162 assert( isSaveLeft
==0 || isExact
==0 );
2164 assert( p
!=0 && *p1
!=0 && *p2
!=0 );
2165 if( *p1
==POS_COLUMN
){
2167 p1
+= fts3GetVarint32(p1
, &iCol1
);
2169 if( *p2
==POS_COLUMN
){
2171 p2
+= fts3GetVarint32(p2
, &iCol2
);
2177 sqlite3_int64 iPrev
= 0;
2178 sqlite3_int64 iPos1
= 0;
2179 sqlite3_int64 iPos2
= 0;
2183 p
+= sqlite3Fts3PutVarint(p
, iCol1
);
2186 assert( *p1
!=POS_END
&& *p1
!=POS_COLUMN
);
2187 assert( *p2
!=POS_END
&& *p2
!=POS_COLUMN
);
2188 fts3GetDeltaVarint(&p1
, &iPos1
); iPos1
-= 2;
2189 fts3GetDeltaVarint(&p2
, &iPos2
); iPos2
-= 2;
2192 if( iPos2
==iPos1
+nToken
2193 || (isExact
==0 && iPos2
>iPos1
&& iPos2
<=iPos1
+nToken
)
2195 sqlite3_int64 iSave
;
2196 iSave
= isSaveLeft
? iPos1
: iPos2
;
2197 fts3PutDeltaVarint(&p
, &iPrev
, iSave
+2); iPrev
-= 2;
2201 if( (!isSaveLeft
&& iPos2
<=(iPos1
+nToken
)) || iPos2
<=iPos1
){
2202 if( (*p2
&0xFE)==0 ) break;
2203 fts3GetDeltaVarint(&p2
, &iPos2
); iPos2
-= 2;
2205 if( (*p1
&0xFE)==0 ) break;
2206 fts3GetDeltaVarint(&p1
, &iPos1
); iPos1
-= 2;
2215 fts3ColumnlistCopy(0, &p1
);
2216 fts3ColumnlistCopy(0, &p2
);
2217 assert( (*p1
&0xFE)==0 && (*p2
&0xFE)==0 );
2218 if( 0==*p1
|| 0==*p2
) break;
2221 p1
+= fts3GetVarint32(p1
, &iCol1
);
2223 p2
+= fts3GetVarint32(p2
, &iCol2
);
2226 /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
2227 ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
2228 ** end of the position list, or the 0x01 that precedes the next
2229 ** column-number in the position list.
2231 else if( iCol1
<iCol2
){
2232 fts3ColumnlistCopy(0, &p1
);
2235 p1
+= fts3GetVarint32(p1
, &iCol1
);
2237 fts3ColumnlistCopy(0, &p2
);
2240 p2
+= fts3GetVarint32(p2
, &iCol2
);
2244 fts3PoslistCopy(0, &p2
);
2245 fts3PoslistCopy(0, &p1
);
2257 ** Merge two position-lists as required by the NEAR operator. The argument
2258 ** position lists correspond to the left and right phrases of an expression
2261 ** "phrase 1" NEAR "phrase number 2"
2263 ** Position list *pp1 corresponds to the left-hand side of the NEAR
2264 ** expression and *pp2 to the right. As usual, the indexes in the position
2265 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
2266 ** in the example above).
2268 ** The output position list - written to *pp - is a copy of *pp2 with those
2269 ** entries that are not sufficiently NEAR entries in *pp1 removed.
2271 static int fts3PoslistNearMerge(
2272 char **pp
, /* Output buffer */
2273 char *aTmp
, /* Temporary buffer space */
2274 int nRight
, /* Maximum difference in token positions */
2275 int nLeft
, /* Maximum difference in token positions */
2276 char **pp1
, /* IN/OUT: Left input list */
2277 char **pp2
/* IN/OUT: Right input list */
2287 fts3PoslistPhraseMerge(&pTmp1
, nRight
, 0, 0, pp1
, pp2
);
2288 aTmp2
= pTmp2
= pTmp1
;
2291 fts3PoslistPhraseMerge(&pTmp2
, nLeft
, 1, 0, pp2
, pp1
);
2292 if( pTmp1
!=aTmp
&& pTmp2
!=aTmp2
){
2293 fts3PoslistMerge(pp
, &aTmp
, &aTmp2
);
2294 }else if( pTmp1
!=aTmp
){
2295 fts3PoslistCopy(pp
, &aTmp
);
2296 }else if( pTmp2
!=aTmp2
){
2297 fts3PoslistCopy(pp
, &aTmp2
);
2306 ** An instance of this function is used to merge together the (potentially
2307 ** large number of) doclists for each term that matches a prefix query.
2308 ** See function fts3TermSelectMerge() for details.
2310 typedef struct TermSelect TermSelect
;
2312 char *aaOutput
[16]; /* Malloc'd output buffers */
2313 int anOutput
[16]; /* Size each output buffer in bytes */
2317 ** This function is used to read a single varint from a buffer. Parameter
2318 ** pEnd points 1 byte past the end of the buffer. When this function is
2319 ** called, if *pp points to pEnd or greater, then the end of the buffer
2320 ** has been reached. In this case *pp is set to 0 and the function returns.
2322 ** If *pp does not point to or past pEnd, then a single varint is read
2323 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
2325 ** If bDescIdx is false, the value read is added to *pVal before returning.
2326 ** If it is true, the value read is subtracted from *pVal before this
2327 ** function returns.
2329 static void fts3GetDeltaVarint3(
2330 char **pp
, /* IN/OUT: Point to read varint from */
2331 char *pEnd
, /* End of buffer */
2332 int bDescIdx
, /* True if docids are descending */
2333 sqlite3_int64
*pVal
/* IN/OUT: Integer value */
2339 *pp
+= sqlite3Fts3GetVarint(*pp
, &iVal
);
2349 ** This function is used to write a single varint to a buffer. The varint
2350 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
2351 ** end of the value written.
2353 ** If *pbFirst is zero when this function is called, the value written to
2354 ** the buffer is that of parameter iVal.
2356 ** If *pbFirst is non-zero when this function is called, then the value
2357 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
2358 ** (if bDescIdx is non-zero).
2360 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
2361 ** to the value of parameter iVal.
2363 static void fts3PutDeltaVarint3(
2364 char **pp
, /* IN/OUT: Output pointer */
2365 int bDescIdx
, /* True for descending docids */
2366 sqlite3_int64
*piPrev
, /* IN/OUT: Previous value written to list */
2367 int *pbFirst
, /* IN/OUT: True after first int written */
2368 sqlite3_int64 iVal
/* Write this value to the list */
2370 sqlite3_int64 iWrite
;
2371 if( bDescIdx
==0 || *pbFirst
==0 ){
2372 iWrite
= iVal
- *piPrev
;
2374 iWrite
= *piPrev
- iVal
;
2376 assert( *pbFirst
|| *piPrev
==0 );
2377 assert( *pbFirst
==0 || iWrite
>0 );
2378 *pp
+= sqlite3Fts3PutVarint(*pp
, iWrite
);
2385 ** This macro is used by various functions that merge doclists. The two
2386 ** arguments are 64-bit docid values. If the value of the stack variable
2387 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
2388 ** Otherwise, (i2-i1).
2390 ** Using this makes it easier to write code that can merge doclists that are
2391 ** sorted in either ascending or descending order.
2393 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
2396 ** This function does an "OR" merge of two doclists (output contains all
2397 ** positions contained in either argument doclist). If the docids in the
2398 ** input doclists are sorted in ascending order, parameter bDescDoclist
2399 ** should be false. If they are sorted in ascending order, it should be
2400 ** passed a non-zero value.
2402 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
2403 ** containing the output doclist and SQLITE_OK is returned. In this case
2404 ** *pnOut is set to the number of bytes in the output doclist.
2406 ** If an error occurs, an SQLite error code is returned. The output values
2407 ** are undefined in this case.
2409 static int fts3DoclistOrMerge(
2410 int bDescDoclist
, /* True if arguments are desc */
2411 char *a1
, int n1
, /* First doclist */
2412 char *a2
, int n2
, /* Second doclist */
2413 char **paOut
, int *pnOut
/* OUT: Malloc'd doclist */
2415 sqlite3_int64 i1
= 0;
2416 sqlite3_int64 i2
= 0;
2417 sqlite3_int64 iPrev
= 0;
2418 char *pEnd1
= &a1
[n1
];
2419 char *pEnd2
= &a2
[n2
];
2429 /* Allocate space for the output. Both the input and output doclists
2430 ** are delta encoded. If they are in ascending order (bDescDoclist==0),
2431 ** then the first docid in each list is simply encoded as a varint. For
2432 ** each subsequent docid, the varint stored is the difference between the
2433 ** current and previous docid (a positive number - since the list is in
2434 ** ascending order).
2436 ** The first docid written to the output is therefore encoded using the
2437 ** same number of bytes as it is in whichever of the input lists it is
2438 ** read from. And each subsequent docid read from the same input list
2439 ** consumes either the same or less bytes as it did in the input (since
2440 ** the difference between it and the previous value in the output must
2441 ** be a positive value less than or equal to the delta value read from
2442 ** the input list). The same argument applies to all but the first docid
2443 ** read from the 'other' list. And to the contents of all position lists
2444 ** that will be copied and merged from the input to the output.
2446 ** However, if the first docid copied to the output is a negative number,
2447 ** then the encoding of the first docid from the 'other' input list may
2448 ** be larger in the output than it was in the input (since the delta value
2449 ** may be a larger positive integer than the actual docid).
2451 ** The space required to store the output is therefore the sum of the
2452 ** sizes of the two inputs, plus enough space for exactly one of the input
2455 ** A symetric argument may be made if the doclists are in descending
2458 aOut
= sqlite3_malloc(n1
+n2
+FTS3_VARINT_MAX
-1);
2459 if( !aOut
) return SQLITE_NOMEM
;
2462 fts3GetDeltaVarint3(&p1
, pEnd1
, 0, &i1
);
2463 fts3GetDeltaVarint3(&p2
, pEnd2
, 0, &i2
);
2465 sqlite3_int64 iDiff
= DOCID_CMP(i1
, i2
);
2467 if( p2
&& p1
&& iDiff
==0 ){
2468 fts3PutDeltaVarint3(&p
, bDescDoclist
, &iPrev
, &bFirstOut
, i1
);
2469 fts3PoslistMerge(&p
, &p1
, &p2
);
2470 fts3GetDeltaVarint3(&p1
, pEnd1
, bDescDoclist
, &i1
);
2471 fts3GetDeltaVarint3(&p2
, pEnd2
, bDescDoclist
, &i2
);
2472 }else if( !p2
|| (p1
&& iDiff
<0) ){
2473 fts3PutDeltaVarint3(&p
, bDescDoclist
, &iPrev
, &bFirstOut
, i1
);
2474 fts3PoslistCopy(&p
, &p1
);
2475 fts3GetDeltaVarint3(&p1
, pEnd1
, bDescDoclist
, &i1
);
2477 fts3PutDeltaVarint3(&p
, bDescDoclist
, &iPrev
, &bFirstOut
, i2
);
2478 fts3PoslistCopy(&p
, &p2
);
2479 fts3GetDeltaVarint3(&p2
, pEnd2
, bDescDoclist
, &i2
);
2484 *pnOut
= (int)(p
-aOut
);
2485 assert( *pnOut
<=n1
+n2
+FTS3_VARINT_MAX
-1 );
2490 ** This function does a "phrase" merge of two doclists. In a phrase merge,
2491 ** the output contains a copy of each position from the right-hand input
2492 ** doclist for which there is a position in the left-hand input doclist
2493 ** exactly nDist tokens before it.
2495 ** If the docids in the input doclists are sorted in ascending order,
2496 ** parameter bDescDoclist should be false. If they are sorted in ascending
2497 ** order, it should be passed a non-zero value.
2499 ** The right-hand input doclist is overwritten by this function.
2501 static void fts3DoclistPhraseMerge(
2502 int bDescDoclist
, /* True if arguments are desc */
2503 int nDist
, /* Distance from left to right (1=adjacent) */
2504 char *aLeft
, int nLeft
, /* Left doclist */
2505 char *aRight
, int *pnRight
/* IN/OUT: Right/output doclist */
2507 sqlite3_int64 i1
= 0;
2508 sqlite3_int64 i2
= 0;
2509 sqlite3_int64 iPrev
= 0;
2510 char *pEnd1
= &aLeft
[nLeft
];
2511 char *pEnd2
= &aRight
[*pnRight
];
2516 char *aOut
= aRight
;
2521 fts3GetDeltaVarint3(&p1
, pEnd1
, 0, &i1
);
2522 fts3GetDeltaVarint3(&p2
, pEnd2
, 0, &i2
);
2525 sqlite3_int64 iDiff
= DOCID_CMP(i1
, i2
);
2528 sqlite3_int64 iPrevSave
= iPrev
;
2529 int bFirstOutSave
= bFirstOut
;
2531 fts3PutDeltaVarint3(&p
, bDescDoclist
, &iPrev
, &bFirstOut
, i1
);
2532 if( 0==fts3PoslistPhraseMerge(&p
, nDist
, 0, 1, &p1
, &p2
) ){
2535 bFirstOut
= bFirstOutSave
;
2537 fts3GetDeltaVarint3(&p1
, pEnd1
, bDescDoclist
, &i1
);
2538 fts3GetDeltaVarint3(&p2
, pEnd2
, bDescDoclist
, &i2
);
2539 }else if( iDiff
<0 ){
2540 fts3PoslistCopy(0, &p1
);
2541 fts3GetDeltaVarint3(&p1
, pEnd1
, bDescDoclist
, &i1
);
2543 fts3PoslistCopy(0, &p2
);
2544 fts3GetDeltaVarint3(&p2
, pEnd2
, bDescDoclist
, &i2
);
2548 *pnRight
= (int)(p
- aOut
);
2552 ** Argument pList points to a position list nList bytes in size. This
2553 ** function checks to see if the position list contains any entries for
2554 ** a token in position 0 (of any column). If so, it writes argument iDelta
2555 ** to the output buffer pOut, followed by a position list consisting only
2556 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
2557 ** The value returned is the number of bytes written to pOut (if any).
2559 int sqlite3Fts3FirstFilter(
2560 sqlite3_int64 iDelta
, /* Varint that may be written to pOut */
2561 char *pList
, /* Position list (no 0x00 term) */
2562 int nList
, /* Size of pList in bytes */
2563 char *pOut
/* Write output here */
2566 int bWritten
= 0; /* True once iDelta has been written */
2568 char *pEnd
= &pList
[nList
];
2572 nOut
+= sqlite3Fts3PutVarint(&pOut
[nOut
], iDelta
);
2573 pOut
[nOut
++] = 0x02;
2576 fts3ColumnlistCopy(0, &p
);
2579 while( p
<pEnd
&& *p
==0x01 ){
2582 p
+= sqlite3Fts3GetVarint(p
, &iCol
);
2585 nOut
+= sqlite3Fts3PutVarint(&pOut
[nOut
], iDelta
);
2588 pOut
[nOut
++] = 0x01;
2589 nOut
+= sqlite3Fts3PutVarint(&pOut
[nOut
], iCol
);
2590 pOut
[nOut
++] = 0x02;
2592 fts3ColumnlistCopy(0, &p
);
2595 pOut
[nOut
++] = 0x00;
2603 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
2604 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
2605 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
2607 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
2608 ** the responsibility of the caller to free any doclists left in the
2609 ** TermSelect.aaOutput[] array.
2611 static int fts3TermSelectFinishMerge(Fts3Table
*p
, TermSelect
*pTS
){
2616 /* Loop through the doclists in the aaOutput[] array. Merge them all
2617 ** into a single doclist.
2619 for(i
=0; i
<SizeofArray(pTS
->aaOutput
); i
++){
2620 if( pTS
->aaOutput
[i
] ){
2622 aOut
= pTS
->aaOutput
[i
];
2623 nOut
= pTS
->anOutput
[i
];
2624 pTS
->aaOutput
[i
] = 0;
2629 int rc
= fts3DoclistOrMerge(p
->bDescIdx
,
2630 pTS
->aaOutput
[i
], pTS
->anOutput
[i
], aOut
, nOut
, &aNew
, &nNew
2632 if( rc
!=SQLITE_OK
){
2637 sqlite3_free(pTS
->aaOutput
[i
]);
2639 pTS
->aaOutput
[i
] = 0;
2646 pTS
->aaOutput
[0] = aOut
;
2647 pTS
->anOutput
[0] = nOut
;
2652 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
2653 ** as the first argument. The merge is an "OR" merge (see function
2654 ** fts3DoclistOrMerge() for details).
2656 ** This function is called with the doclist for each term that matches
2657 ** a queried prefix. It merges all these doclists into one, the doclist
2658 ** for the specified prefix. Since there can be a very large number of
2659 ** doclists to merge, the merging is done pair-wise using the TermSelect
2662 ** This function returns SQLITE_OK if the merge is successful, or an
2663 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
2665 static int fts3TermSelectMerge(
2666 Fts3Table
*p
, /* FTS table handle */
2667 TermSelect
*pTS
, /* TermSelect object to merge into */
2668 char *aDoclist
, /* Pointer to doclist */
2669 int nDoclist
/* Size of aDoclist in bytes */
2671 if( pTS
->aaOutput
[0]==0 ){
2672 /* If this is the first term selected, copy the doclist to the output
2673 ** buffer using memcpy(). */
2674 pTS
->aaOutput
[0] = sqlite3_malloc(nDoclist
);
2675 pTS
->anOutput
[0] = nDoclist
;
2676 if( pTS
->aaOutput
[0] ){
2677 memcpy(pTS
->aaOutput
[0], aDoclist
, nDoclist
);
2679 return SQLITE_NOMEM
;
2682 char *aMerge
= aDoclist
;
2683 int nMerge
= nDoclist
;
2686 for(iOut
=0; iOut
<SizeofArray(pTS
->aaOutput
); iOut
++){
2687 if( pTS
->aaOutput
[iOut
]==0 ){
2689 pTS
->aaOutput
[iOut
] = aMerge
;
2690 pTS
->anOutput
[iOut
] = nMerge
;
2696 int rc
= fts3DoclistOrMerge(p
->bDescIdx
, aMerge
, nMerge
,
2697 pTS
->aaOutput
[iOut
], pTS
->anOutput
[iOut
], &aNew
, &nNew
2699 if( rc
!=SQLITE_OK
){
2700 if( aMerge
!=aDoclist
) sqlite3_free(aMerge
);
2704 if( aMerge
!=aDoclist
) sqlite3_free(aMerge
);
2705 sqlite3_free(pTS
->aaOutput
[iOut
]);
2706 pTS
->aaOutput
[iOut
] = 0;
2710 if( (iOut
+1)==SizeofArray(pTS
->aaOutput
) ){
2711 pTS
->aaOutput
[iOut
] = aMerge
;
2712 pTS
->anOutput
[iOut
] = nMerge
;
2721 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
2723 static int fts3SegReaderCursorAppend(
2724 Fts3MultiSegReader
*pCsr
,
2727 if( (pCsr
->nSegment
%16)==0 ){
2728 Fts3SegReader
**apNew
;
2729 int nByte
= (pCsr
->nSegment
+ 16)*sizeof(Fts3SegReader
*);
2730 apNew
= (Fts3SegReader
**)sqlite3_realloc(pCsr
->apSegment
, nByte
);
2732 sqlite3Fts3SegReaderFree(pNew
);
2733 return SQLITE_NOMEM
;
2735 pCsr
->apSegment
= apNew
;
2737 pCsr
->apSegment
[pCsr
->nSegment
++] = pNew
;
2742 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
2745 ** This function returns SQLITE_OK if successful, or an SQLite error code
2748 static int fts3SegReaderCursor(
2749 Fts3Table
*p
, /* FTS3 table handle */
2750 int iLangid
, /* Language id */
2751 int iIndex
, /* Index to search (from 0 to p->nIndex-1) */
2752 int iLevel
, /* Level of segments to scan */
2753 const char *zTerm
, /* Term to query for */
2754 int nTerm
, /* Size of zTerm in bytes */
2755 int isPrefix
, /* True for a prefix search */
2756 int isScan
, /* True to scan from zTerm to EOF */
2757 Fts3MultiSegReader
*pCsr
/* Cursor object to populate */
2759 int rc
= SQLITE_OK
; /* Error code */
2760 sqlite3_stmt
*pStmt
= 0; /* Statement to iterate through segments */
2761 int rc2
; /* Result of sqlite3_reset() */
2763 /* If iLevel is less than 0 and this is not a scan, include a seg-reader
2764 ** for the pending-terms. If this is a scan, then this call must be being
2765 ** made by an fts4aux module, not an FTS table. In this case calling
2766 ** Fts3SegReaderPending might segfault, as the data structures used by
2767 ** fts4aux are not completely populated. So it's easiest to filter these
2768 ** calls out here. */
2769 if( iLevel
<0 && p
->aIndex
){
2770 Fts3SegReader
*pSeg
= 0;
2771 rc
= sqlite3Fts3SegReaderPending(p
, iIndex
, zTerm
, nTerm
, isPrefix
, &pSeg
);
2772 if( rc
==SQLITE_OK
&& pSeg
){
2773 rc
= fts3SegReaderCursorAppend(pCsr
, pSeg
);
2777 if( iLevel
!=FTS3_SEGCURSOR_PENDING
){
2778 if( rc
==SQLITE_OK
){
2779 rc
= sqlite3Fts3AllSegdirs(p
, iLangid
, iIndex
, iLevel
, &pStmt
);
2782 while( rc
==SQLITE_OK
&& SQLITE_ROW
==(rc
= sqlite3_step(pStmt
)) ){
2783 Fts3SegReader
*pSeg
= 0;
2785 /* Read the values returned by the SELECT into local variables. */
2786 sqlite3_int64 iStartBlock
= sqlite3_column_int64(pStmt
, 1);
2787 sqlite3_int64 iLeavesEndBlock
= sqlite3_column_int64(pStmt
, 2);
2788 sqlite3_int64 iEndBlock
= sqlite3_column_int64(pStmt
, 3);
2789 int nRoot
= sqlite3_column_bytes(pStmt
, 4);
2790 char const *zRoot
= sqlite3_column_blob(pStmt
, 4);
2792 /* If zTerm is not NULL, and this segment is not stored entirely on its
2793 ** root node, the range of leaves scanned can be reduced. Do this. */
2794 if( iStartBlock
&& zTerm
){
2795 sqlite3_int64
*pi
= (isPrefix
? &iLeavesEndBlock
: 0);
2796 rc
= fts3SelectLeaf(p
, zTerm
, nTerm
, zRoot
, nRoot
, &iStartBlock
, pi
);
2797 if( rc
!=SQLITE_OK
) goto finished
;
2798 if( isPrefix
==0 && isScan
==0 ) iLeavesEndBlock
= iStartBlock
;
2801 rc
= sqlite3Fts3SegReaderNew(pCsr
->nSegment
+1,
2802 (isPrefix
==0 && isScan
==0),
2803 iStartBlock
, iLeavesEndBlock
,
2804 iEndBlock
, zRoot
, nRoot
, &pSeg
2806 if( rc
!=SQLITE_OK
) goto finished
;
2807 rc
= fts3SegReaderCursorAppend(pCsr
, pSeg
);
2812 rc2
= sqlite3_reset(pStmt
);
2813 if( rc
==SQLITE_DONE
) rc
= rc2
;
2819 ** Set up a cursor object for iterating through a full-text index or a
2820 ** single level therein.
2822 int sqlite3Fts3SegReaderCursor(
2823 Fts3Table
*p
, /* FTS3 table handle */
2824 int iLangid
, /* Language-id to search */
2825 int iIndex
, /* Index to search (from 0 to p->nIndex-1) */
2826 int iLevel
, /* Level of segments to scan */
2827 const char *zTerm
, /* Term to query for */
2828 int nTerm
, /* Size of zTerm in bytes */
2829 int isPrefix
, /* True for a prefix search */
2830 int isScan
, /* True to scan from zTerm to EOF */
2831 Fts3MultiSegReader
*pCsr
/* Cursor object to populate */
2833 assert( iIndex
>=0 && iIndex
<p
->nIndex
);
2834 assert( iLevel
==FTS3_SEGCURSOR_ALL
2835 || iLevel
==FTS3_SEGCURSOR_PENDING
2838 assert( iLevel
<FTS3_SEGDIR_MAXLEVEL
);
2839 assert( FTS3_SEGCURSOR_ALL
<0 && FTS3_SEGCURSOR_PENDING
<0 );
2840 assert( isPrefix
==0 || isScan
==0 );
2842 memset(pCsr
, 0, sizeof(Fts3MultiSegReader
));
2843 return fts3SegReaderCursor(
2844 p
, iLangid
, iIndex
, iLevel
, zTerm
, nTerm
, isPrefix
, isScan
, pCsr
2849 ** In addition to its current configuration, have the Fts3MultiSegReader
2850 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
2852 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
2854 static int fts3SegReaderCursorAddZero(
2855 Fts3Table
*p
, /* FTS virtual table handle */
2857 const char *zTerm
, /* Term to scan doclist of */
2858 int nTerm
, /* Number of bytes in zTerm */
2859 Fts3MultiSegReader
*pCsr
/* Fts3MultiSegReader to modify */
2861 return fts3SegReaderCursor(p
,
2862 iLangid
, 0, FTS3_SEGCURSOR_ALL
, zTerm
, nTerm
, 0, 0,pCsr
2867 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
2868 ** if isPrefix is true, to scan the doclist for all terms for which
2869 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
2870 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
2871 ** an SQLite error code.
2873 ** It is the responsibility of the caller to free this object by eventually
2874 ** passing it to fts3SegReaderCursorFree()
2876 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
2877 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
2879 static int fts3TermSegReaderCursor(
2880 Fts3Cursor
*pCsr
, /* Virtual table cursor handle */
2881 const char *zTerm
, /* Term to query for */
2882 int nTerm
, /* Size of zTerm in bytes */
2883 int isPrefix
, /* True for a prefix search */
2884 Fts3MultiSegReader
**ppSegcsr
/* OUT: Allocated seg-reader cursor */
2886 Fts3MultiSegReader
*pSegcsr
; /* Object to allocate and return */
2887 int rc
= SQLITE_NOMEM
; /* Return code */
2889 pSegcsr
= sqlite3_malloc(sizeof(Fts3MultiSegReader
));
2892 int bFound
= 0; /* True once an index has been found */
2893 Fts3Table
*p
= (Fts3Table
*)pCsr
->base
.pVtab
;
2896 for(i
=1; bFound
==0 && i
<p
->nIndex
; i
++){
2897 if( p
->aIndex
[i
].nPrefix
==nTerm
){
2899 rc
= sqlite3Fts3SegReaderCursor(p
, pCsr
->iLangid
,
2900 i
, FTS3_SEGCURSOR_ALL
, zTerm
, nTerm
, 0, 0, pSegcsr
2902 pSegcsr
->bLookup
= 1;
2906 for(i
=1; bFound
==0 && i
<p
->nIndex
; i
++){
2907 if( p
->aIndex
[i
].nPrefix
==nTerm
+1 ){
2909 rc
= sqlite3Fts3SegReaderCursor(p
, pCsr
->iLangid
,
2910 i
, FTS3_SEGCURSOR_ALL
, zTerm
, nTerm
, 1, 0, pSegcsr
2912 if( rc
==SQLITE_OK
){
2913 rc
= fts3SegReaderCursorAddZero(
2914 p
, pCsr
->iLangid
, zTerm
, nTerm
, pSegcsr
2922 rc
= sqlite3Fts3SegReaderCursor(p
, pCsr
->iLangid
,
2923 0, FTS3_SEGCURSOR_ALL
, zTerm
, nTerm
, isPrefix
, 0, pSegcsr
2925 pSegcsr
->bLookup
= !isPrefix
;
2929 *ppSegcsr
= pSegcsr
;
2934 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
2936 static void fts3SegReaderCursorFree(Fts3MultiSegReader
*pSegcsr
){
2937 sqlite3Fts3SegReaderFinish(pSegcsr
);
2938 sqlite3_free(pSegcsr
);
2942 ** This function retrieves the doclist for the specified term (or term
2943 ** prefix) from the database.
2945 static int fts3TermSelect(
2946 Fts3Table
*p
, /* Virtual table handle */
2947 Fts3PhraseToken
*pTok
, /* Token to query for */
2948 int iColumn
, /* Column to query (or -ve for all columns) */
2949 int *pnOut
, /* OUT: Size of buffer at *ppOut */
2950 char **ppOut
/* OUT: Malloced result buffer */
2952 int rc
; /* Return code */
2953 Fts3MultiSegReader
*pSegcsr
; /* Seg-reader cursor for this term */
2954 TermSelect tsc
; /* Object for pair-wise doclist merging */
2955 Fts3SegFilter filter
; /* Segment term filter configuration */
2957 pSegcsr
= pTok
->pSegcsr
;
2958 memset(&tsc
, 0, sizeof(TermSelect
));
2960 filter
.flags
= FTS3_SEGMENT_IGNORE_EMPTY
| FTS3_SEGMENT_REQUIRE_POS
2961 | (pTok
->isPrefix
? FTS3_SEGMENT_PREFIX
: 0)
2962 | (pTok
->bFirst
? FTS3_SEGMENT_FIRST
: 0)
2963 | (iColumn
<p
->nColumn
? FTS3_SEGMENT_COLUMN_FILTER
: 0);
2964 filter
.iCol
= iColumn
;
2965 filter
.zTerm
= pTok
->z
;
2966 filter
.nTerm
= pTok
->n
;
2968 rc
= sqlite3Fts3SegReaderStart(p
, pSegcsr
, &filter
);
2969 while( SQLITE_OK
==rc
2970 && SQLITE_ROW
==(rc
= sqlite3Fts3SegReaderStep(p
, pSegcsr
))
2972 rc
= fts3TermSelectMerge(p
, &tsc
, pSegcsr
->aDoclist
, pSegcsr
->nDoclist
);
2975 if( rc
==SQLITE_OK
){
2976 rc
= fts3TermSelectFinishMerge(p
, &tsc
);
2978 if( rc
==SQLITE_OK
){
2979 *ppOut
= tsc
.aaOutput
[0];
2980 *pnOut
= tsc
.anOutput
[0];
2983 for(i
=0; i
<SizeofArray(tsc
.aaOutput
); i
++){
2984 sqlite3_free(tsc
.aaOutput
[i
]);
2988 fts3SegReaderCursorFree(pSegcsr
);
2994 ** This function counts the total number of docids in the doclist stored
2995 ** in buffer aList[], size nList bytes.
2997 ** If the isPoslist argument is true, then it is assumed that the doclist
2998 ** contains a position-list following each docid. Otherwise, it is assumed
2999 ** that the doclist is simply a list of docids stored as delta encoded
3002 static int fts3DoclistCountDocids(char *aList
, int nList
){
3003 int nDoc
= 0; /* Return value */
3005 char *aEnd
= &aList
[nList
]; /* Pointer to one byte after EOF */
3006 char *p
= aList
; /* Cursor */
3009 while( (*p
++)&0x80 ); /* Skip docid varint */
3010 fts3PoslistCopy(0, &p
); /* Skip over position list */
3018 ** Advance the cursor to the next row in the %_content table that
3019 ** matches the search criteria. For a MATCH search, this will be
3020 ** the next row that matches. For a full-table scan, this will be
3021 ** simply the next row in the %_content table. For a docid lookup,
3022 ** this routine simply sets the EOF flag.
3024 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
3025 ** even if we reach end-of-file. The fts3EofMethod() will be called
3026 ** subsequently to determine whether or not an EOF was hit.
3028 static int fts3NextMethod(sqlite3_vtab_cursor
*pCursor
){
3030 Fts3Cursor
*pCsr
= (Fts3Cursor
*)pCursor
;
3031 if( pCsr
->eSearch
==FTS3_DOCID_SEARCH
|| pCsr
->eSearch
==FTS3_FULLSCAN_SEARCH
){
3032 if( SQLITE_ROW
!=sqlite3_step(pCsr
->pStmt
) ){
3034 rc
= sqlite3_reset(pCsr
->pStmt
);
3036 pCsr
->iPrevId
= sqlite3_column_int64(pCsr
->pStmt
, 0);
3040 rc
= fts3EvalNext((Fts3Cursor
*)pCursor
);
3042 assert( ((Fts3Table
*)pCsr
->base
.pVtab
)->pSegments
==0 );
3047 ** The following are copied from sqliteInt.h.
3049 ** Constants for the largest and smallest possible 64-bit signed integers.
3050 ** These macros are designed to work correctly on both 32-bit and 64-bit
3053 #ifndef SQLITE_AMALGAMATION
3054 # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
3055 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
3059 ** If the numeric type of argument pVal is "integer", then return it
3060 ** converted to a 64-bit signed integer. Otherwise, return a copy of
3061 ** the second parameter, iDefault.
3063 static sqlite3_int64
fts3DocidRange(sqlite3_value
*pVal
, i64 iDefault
){
3065 int eType
= sqlite3_value_numeric_type(pVal
);
3066 if( eType
==SQLITE_INTEGER
){
3067 return sqlite3_value_int64(pVal
);
3074 ** This is the xFilter interface for the virtual table. See
3075 ** the virtual table xFilter method documentation for additional
3078 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
3079 ** the %_content table.
3081 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
3082 ** in the %_content table.
3084 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
3085 ** column on the left-hand side of the MATCH operator is column
3086 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
3087 ** side of the MATCH operator.
3089 static int fts3FilterMethod(
3090 sqlite3_vtab_cursor
*pCursor
, /* The cursor used for this query */
3091 int idxNum
, /* Strategy index */
3092 const char *idxStr
, /* Unused */
3093 int nVal
, /* Number of elements in apVal */
3094 sqlite3_value
**apVal
/* Arguments for the indexing scheme */
3097 char *zSql
; /* SQL statement used to access %_content */
3099 Fts3Table
*p
= (Fts3Table
*)pCursor
->pVtab
;
3100 Fts3Cursor
*pCsr
= (Fts3Cursor
*)pCursor
;
3102 sqlite3_value
*pCons
= 0; /* The MATCH or rowid constraint, if any */
3103 sqlite3_value
*pLangid
= 0; /* The "langid = ?" constraint, if any */
3104 sqlite3_value
*pDocidGe
= 0; /* The "docid >= ?" constraint, if any */
3105 sqlite3_value
*pDocidLe
= 0; /* The "docid <= ?" constraint, if any */
3108 UNUSED_PARAMETER(idxStr
);
3109 UNUSED_PARAMETER(nVal
);
3111 eSearch
= (idxNum
& 0x0000FFFF);
3112 assert( eSearch
>=0 && eSearch
<=(FTS3_FULLTEXT_SEARCH
+p
->nColumn
) );
3113 assert( p
->pSegments
==0 );
3115 /* Collect arguments into local variables */
3117 if( eSearch
!=FTS3_FULLSCAN_SEARCH
) pCons
= apVal
[iIdx
++];
3118 if( idxNum
& FTS3_HAVE_LANGID
) pLangid
= apVal
[iIdx
++];
3119 if( idxNum
& FTS3_HAVE_DOCID_GE
) pDocidGe
= apVal
[iIdx
++];
3120 if( idxNum
& FTS3_HAVE_DOCID_LE
) pDocidLe
= apVal
[iIdx
++];
3121 assert( iIdx
==nVal
);
3123 /* In case the cursor has been used before, clear it now. */
3124 sqlite3_finalize(pCsr
->pStmt
);
3125 sqlite3_free(pCsr
->aDoclist
);
3126 sqlite3_free(pCsr
->aMatchinfo
);
3127 sqlite3Fts3ExprFree(pCsr
->pExpr
);
3128 memset(&pCursor
[1], 0, sizeof(Fts3Cursor
)-sizeof(sqlite3_vtab_cursor
));
3130 /* Set the lower and upper bounds on docids to return */
3131 pCsr
->iMinDocid
= fts3DocidRange(pDocidGe
, SMALLEST_INT64
);
3132 pCsr
->iMaxDocid
= fts3DocidRange(pDocidLe
, LARGEST_INT64
);
3135 pCsr
->bDesc
= (idxStr
[0]=='D');
3137 pCsr
->bDesc
= p
->bDescIdx
;
3139 pCsr
->eSearch
= (i16
)eSearch
;
3141 if( eSearch
!=FTS3_DOCID_SEARCH
&& eSearch
!=FTS3_FULLSCAN_SEARCH
){
3142 int iCol
= eSearch
-FTS3_FULLTEXT_SEARCH
;
3143 const char *zQuery
= (const char *)sqlite3_value_text(pCons
);
3145 if( zQuery
==0 && sqlite3_value_type(pCons
)!=SQLITE_NULL
){
3146 return SQLITE_NOMEM
;
3150 if( pLangid
) pCsr
->iLangid
= sqlite3_value_int(pLangid
);
3152 assert( p
->base
.zErrMsg
==0 );
3153 rc
= sqlite3Fts3ExprParse(p
->pTokenizer
, pCsr
->iLangid
,
3154 p
->azColumn
, p
->bFts4
, p
->nColumn
, iCol
, zQuery
, -1, &pCsr
->pExpr
,
3157 if( rc
!=SQLITE_OK
){
3161 rc
= fts3EvalStart(pCsr
);
3162 sqlite3Fts3SegmentsClose(p
);
3163 if( rc
!=SQLITE_OK
) return rc
;
3164 pCsr
->pNextId
= pCsr
->aDoclist
;
3168 /* Compile a SELECT statement for this cursor. For a full-table-scan, the
3169 ** statement loops through all rows of the %_content table. For a
3170 ** full-text query or docid lookup, the statement retrieves a single
3173 if( eSearch
==FTS3_FULLSCAN_SEARCH
){
3174 zSql
= sqlite3_mprintf(
3175 "SELECT %s ORDER BY rowid %s",
3176 p
->zReadExprlist
, (pCsr
->bDesc
? "DESC" : "ASC")
3179 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pCsr
->pStmt
, 0);
3184 }else if( eSearch
==FTS3_DOCID_SEARCH
){
3185 rc
= fts3CursorSeekStmt(pCsr
, &pCsr
->pStmt
);
3186 if( rc
==SQLITE_OK
){
3187 rc
= sqlite3_bind_value(pCsr
->pStmt
, 1, pCons
);
3190 if( rc
!=SQLITE_OK
) return rc
;
3192 return fts3NextMethod(pCursor
);
3196 ** This is the xEof method of the virtual table. SQLite calls this
3197 ** routine to find out if it has reached the end of a result set.
3199 static int fts3EofMethod(sqlite3_vtab_cursor
*pCursor
){
3200 return ((Fts3Cursor
*)pCursor
)->isEof
;
3204 ** This is the xRowid method. The SQLite core calls this routine to
3205 ** retrieve the rowid for the current row of the result set. fts3
3206 ** exposes %_content.docid as the rowid for the virtual table. The
3207 ** rowid should be written to *pRowid.
3209 static int fts3RowidMethod(sqlite3_vtab_cursor
*pCursor
, sqlite_int64
*pRowid
){
3210 Fts3Cursor
*pCsr
= (Fts3Cursor
*) pCursor
;
3211 *pRowid
= pCsr
->iPrevId
;
3216 ** This is the xColumn method, called by SQLite to request a value from
3217 ** the row that the supplied cursor currently points to.
3221 ** (iCol < p->nColumn) -> The value of the iCol'th user column.
3222 ** (iCol == p->nColumn) -> Magic column with the same name as the table.
3223 ** (iCol == p->nColumn+1) -> Docid column
3224 ** (iCol == p->nColumn+2) -> Langid column
3226 static int fts3ColumnMethod(
3227 sqlite3_vtab_cursor
*pCursor
, /* Cursor to retrieve value from */
3228 sqlite3_context
*pCtx
, /* Context for sqlite3_result_xxx() calls */
3229 int iCol
/* Index of column to read value from */
3231 int rc
= SQLITE_OK
; /* Return Code */
3232 Fts3Cursor
*pCsr
= (Fts3Cursor
*) pCursor
;
3233 Fts3Table
*p
= (Fts3Table
*)pCursor
->pVtab
;
3235 /* The column value supplied by SQLite must be in range. */
3236 assert( iCol
>=0 && iCol
<=p
->nColumn
+2 );
3238 if( iCol
==p
->nColumn
+1 ){
3239 /* This call is a request for the "docid" column. Since "docid" is an
3240 ** alias for "rowid", use the xRowid() method to obtain the value.
3242 sqlite3_result_int64(pCtx
, pCsr
->iPrevId
);
3243 }else if( iCol
==p
->nColumn
){
3244 /* The extra column whose name is the same as the table.
3245 ** Return a blob which is a pointer to the cursor. */
3246 sqlite3_result_blob(pCtx
, &pCsr
, sizeof(pCsr
), SQLITE_TRANSIENT
);
3247 }else if( iCol
==p
->nColumn
+2 && pCsr
->pExpr
){
3248 sqlite3_result_int64(pCtx
, pCsr
->iLangid
);
3250 /* The requested column is either a user column (one that contains
3251 ** indexed data), or the language-id column. */
3252 rc
= fts3CursorSeek(0, pCsr
);
3254 if( rc
==SQLITE_OK
){
3255 if( iCol
==p
->nColumn
+2 ){
3257 if( p
->zLanguageid
){
3258 iLangid
= sqlite3_column_int(pCsr
->pStmt
, p
->nColumn
+1);
3260 sqlite3_result_int(pCtx
, iLangid
);
3261 }else if( sqlite3_data_count(pCsr
->pStmt
)>(iCol
+1) ){
3262 sqlite3_result_value(pCtx
, sqlite3_column_value(pCsr
->pStmt
, iCol
+1));
3267 assert( ((Fts3Table
*)pCsr
->base
.pVtab
)->pSegments
==0 );
3272 ** This function is the implementation of the xUpdate callback used by
3273 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
3274 ** inserted, updated or deleted.
3276 static int fts3UpdateMethod(
3277 sqlite3_vtab
*pVtab
, /* Virtual table handle */
3278 int nArg
, /* Size of argument array */
3279 sqlite3_value
**apVal
, /* Array of arguments */
3280 sqlite_int64
*pRowid
/* OUT: The affected (or effected) rowid */
3282 return sqlite3Fts3UpdateMethod(pVtab
, nArg
, apVal
, pRowid
);
3286 ** Implementation of xSync() method. Flush the contents of the pending-terms
3287 ** hash-table to the database.
3289 static int fts3SyncMethod(sqlite3_vtab
*pVtab
){
3291 /* Following an incremental-merge operation, assuming that the input
3292 ** segments are not completely consumed (the usual case), they are updated
3293 ** in place to remove the entries that have already been merged. This
3294 ** involves updating the leaf block that contains the smallest unmerged
3295 ** entry and each block (if any) between the leaf and the root node. So
3296 ** if the height of the input segment b-trees is N, and input segments
3297 ** are merged eight at a time, updating the input segments at the end
3298 ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
3299 ** small - often between 0 and 2. So the overhead of the incremental
3300 ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
3301 ** dwarfing the actual productive work accomplished, the incremental merge
3302 ** is only attempted if it will write at least 64 leaf blocks. Hence
3305 ** Of course, updating the input segments also involves deleting a bunch
3306 ** of blocks from the segments table. But this is not considered overhead
3307 ** as it would also be required by a crisis-merge that used the same input
3310 const u32 nMinMerge
= 64; /* Minimum amount of incr-merge work to do */
3312 Fts3Table
*p
= (Fts3Table
*)pVtab
;
3313 int rc
= sqlite3Fts3PendingTermsFlush(p
);
3316 && p
->nLeafAdd
>(nMinMerge
/16)
3317 && p
->nAutoincrmerge
&& p
->nAutoincrmerge
!=0xff
3319 int mxLevel
= 0; /* Maximum relative level value in db */
3320 int A
; /* Incr-merge parameter A */
3322 rc
= sqlite3Fts3MaxLevel(p
, &mxLevel
);
3323 assert( rc
==SQLITE_OK
|| mxLevel
==0 );
3324 A
= p
->nLeafAdd
* mxLevel
;
3326 if( A
>(int)nMinMerge
) rc
= sqlite3Fts3Incrmerge(p
, A
, p
->nAutoincrmerge
);
3328 sqlite3Fts3SegmentsClose(p
);
3333 ** If it is currently unknown whether or not the FTS table has an %_stat
3334 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
3335 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
3336 ** if an error occurs.
3338 static int fts3SetHasStat(Fts3Table
*p
){
3340 if( p
->bHasStat
==2 ){
3341 const char *zFmt
="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
3342 char *zSql
= sqlite3_mprintf(zFmt
, p
->zDb
, p
->zName
);
3344 sqlite3_stmt
*pStmt
= 0;
3345 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
3346 if( rc
==SQLITE_OK
){
3347 int bHasStat
= (sqlite3_step(pStmt
)==SQLITE_ROW
);
3348 rc
= sqlite3_finalize(pStmt
);
3349 if( rc
==SQLITE_OK
) p
->bHasStat
= bHasStat
;
3360 ** Implementation of xBegin() method.
3362 static int fts3BeginMethod(sqlite3_vtab
*pVtab
){
3363 Fts3Table
*p
= (Fts3Table
*)pVtab
;
3364 UNUSED_PARAMETER(pVtab
);
3365 assert( p
->pSegments
==0 );
3366 assert( p
->nPendingData
==0 );
3367 assert( p
->inTransaction
!=1 );
3368 TESTONLY( p
->inTransaction
= 1 );
3369 TESTONLY( p
->mxSavepoint
= -1; );
3371 return fts3SetHasStat(p
);
3375 ** Implementation of xCommit() method. This is a no-op. The contents of
3376 ** the pending-terms hash-table have already been flushed into the database
3377 ** by fts3SyncMethod().
3379 static int fts3CommitMethod(sqlite3_vtab
*pVtab
){
3380 TESTONLY( Fts3Table
*p
= (Fts3Table
*)pVtab
);
3381 UNUSED_PARAMETER(pVtab
);
3382 assert( p
->nPendingData
==0 );
3383 assert( p
->inTransaction
!=0 );
3384 assert( p
->pSegments
==0 );
3385 TESTONLY( p
->inTransaction
= 0 );
3386 TESTONLY( p
->mxSavepoint
= -1; );
3391 ** Implementation of xRollback(). Discard the contents of the pending-terms
3392 ** hash-table. Any changes made to the database are reverted by SQLite.
3394 static int fts3RollbackMethod(sqlite3_vtab
*pVtab
){
3395 Fts3Table
*p
= (Fts3Table
*)pVtab
;
3396 sqlite3Fts3PendingTermsClear(p
);
3397 assert( p
->inTransaction
!=0 );
3398 TESTONLY( p
->inTransaction
= 0 );
3399 TESTONLY( p
->mxSavepoint
= -1; );
3404 ** When called, *ppPoslist must point to the byte immediately following the
3405 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
3406 ** moves *ppPoslist so that it instead points to the first byte of the
3407 ** same position list.
3409 static void fts3ReversePoslist(char *pStart
, char **ppPoslist
){
3410 char *p
= &(*ppPoslist
)[-2];
3413 while( p
>pStart
&& (c
=*p
--)==0 );
3414 while( p
>pStart
&& (*p
& 0x80) | c
){
3417 if( p
>pStart
){ p
= &p
[2]; }
3423 ** Helper function used by the implementation of the overloaded snippet(),
3424 ** offsets() and optimize() SQL functions.
3426 ** If the value passed as the third argument is a blob of size
3427 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
3428 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
3429 ** message is written to context pContext and SQLITE_ERROR returned. The
3430 ** string passed via zFunc is used as part of the error message.
3432 static int fts3FunctionArg(
3433 sqlite3_context
*pContext
, /* SQL function call context */
3434 const char *zFunc
, /* Function name */
3435 sqlite3_value
*pVal
, /* argv[0] passed to function */
3436 Fts3Cursor
**ppCsr
/* OUT: Store cursor handle here */
3439 if( sqlite3_value_type(pVal
)!=SQLITE_BLOB
3440 || sqlite3_value_bytes(pVal
)!=sizeof(Fts3Cursor
*)
3442 char *zErr
= sqlite3_mprintf("illegal first argument to %s", zFunc
);
3443 sqlite3_result_error(pContext
, zErr
, -1);
3445 return SQLITE_ERROR
;
3447 memcpy(&pRet
, sqlite3_value_blob(pVal
), sizeof(Fts3Cursor
*));
3453 ** Implementation of the snippet() function for FTS3
3455 static void fts3SnippetFunc(
3456 sqlite3_context
*pContext
, /* SQLite function call context */
3457 int nVal
, /* Size of apVal[] array */
3458 sqlite3_value
**apVal
/* Array of arguments */
3460 Fts3Cursor
*pCsr
; /* Cursor handle passed through apVal[0] */
3461 const char *zStart
= "<b>";
3462 const char *zEnd
= "</b>";
3463 const char *zEllipsis
= "<b>...</b>";
3465 int nToken
= 15; /* Default number of tokens in snippet */
3467 /* There must be at least one argument passed to this function (otherwise
3468 ** the non-overloaded version would have been called instead of this one).
3473 sqlite3_result_error(pContext
,
3474 "wrong number of arguments to function snippet()", -1);
3477 if( fts3FunctionArg(pContext
, "snippet", apVal
[0], &pCsr
) ) return;
3480 case 6: nToken
= sqlite3_value_int(apVal
[5]);
3481 case 5: iCol
= sqlite3_value_int(apVal
[4]);
3482 case 4: zEllipsis
= (const char*)sqlite3_value_text(apVal
[3]);
3483 case 3: zEnd
= (const char*)sqlite3_value_text(apVal
[2]);
3484 case 2: zStart
= (const char*)sqlite3_value_text(apVal
[1]);
3486 if( !zEllipsis
|| !zEnd
|| !zStart
){
3487 sqlite3_result_error_nomem(pContext
);
3488 }else if( SQLITE_OK
==fts3CursorSeek(pContext
, pCsr
) ){
3489 sqlite3Fts3Snippet(pContext
, pCsr
, zStart
, zEnd
, zEllipsis
, iCol
, nToken
);
3494 ** Implementation of the offsets() function for FTS3
3496 static void fts3OffsetsFunc(
3497 sqlite3_context
*pContext
, /* SQLite function call context */
3498 int nVal
, /* Size of argument array */
3499 sqlite3_value
**apVal
/* Array of arguments */
3501 Fts3Cursor
*pCsr
; /* Cursor handle passed through apVal[0] */
3503 UNUSED_PARAMETER(nVal
);
3506 if( fts3FunctionArg(pContext
, "offsets", apVal
[0], &pCsr
) ) return;
3508 if( SQLITE_OK
==fts3CursorSeek(pContext
, pCsr
) ){
3509 sqlite3Fts3Offsets(pContext
, pCsr
);
3514 ** Implementation of the special optimize() function for FTS3. This
3515 ** function merges all segments in the database to a single segment.
3516 ** Example usage is:
3518 ** SELECT optimize(t) FROM t LIMIT 1;
3520 ** where 't' is the name of an FTS3 table.
3522 static void fts3OptimizeFunc(
3523 sqlite3_context
*pContext
, /* SQLite function call context */
3524 int nVal
, /* Size of argument array */
3525 sqlite3_value
**apVal
/* Array of arguments */
3527 int rc
; /* Return code */
3528 Fts3Table
*p
; /* Virtual table handle */
3529 Fts3Cursor
*pCursor
; /* Cursor handle passed through apVal[0] */
3531 UNUSED_PARAMETER(nVal
);
3534 if( fts3FunctionArg(pContext
, "optimize", apVal
[0], &pCursor
) ) return;
3535 p
= (Fts3Table
*)pCursor
->base
.pVtab
;
3538 rc
= sqlite3Fts3Optimize(p
);
3542 sqlite3_result_text(pContext
, "Index optimized", -1, SQLITE_STATIC
);
3545 sqlite3_result_text(pContext
, "Index already optimal", -1, SQLITE_STATIC
);
3548 sqlite3_result_error_code(pContext
, rc
);
3554 ** Implementation of the matchinfo() function for FTS3
3556 static void fts3MatchinfoFunc(
3557 sqlite3_context
*pContext
, /* SQLite function call context */
3558 int nVal
, /* Size of argument array */
3559 sqlite3_value
**apVal
/* Array of arguments */
3561 Fts3Cursor
*pCsr
; /* Cursor handle passed through apVal[0] */
3562 assert( nVal
==1 || nVal
==2 );
3563 if( SQLITE_OK
==fts3FunctionArg(pContext
, "matchinfo", apVal
[0], &pCsr
) ){
3564 const char *zArg
= 0;
3566 zArg
= (const char *)sqlite3_value_text(apVal
[1]);
3568 sqlite3Fts3Matchinfo(pContext
, pCsr
, zArg
);
3573 ** This routine implements the xFindFunction method for the FTS3
3576 static int fts3FindFunctionMethod(
3577 sqlite3_vtab
*pVtab
, /* Virtual table handle */
3578 int nArg
, /* Number of SQL function arguments */
3579 const char *zName
, /* Name of SQL function */
3580 void (**pxFunc
)(sqlite3_context
*,int,sqlite3_value
**), /* OUT: Result */
3581 void **ppArg
/* Unused */
3585 void (*xFunc
)(sqlite3_context
*,int,sqlite3_value
**);
3587 { "snippet", fts3SnippetFunc
},
3588 { "offsets", fts3OffsetsFunc
},
3589 { "optimize", fts3OptimizeFunc
},
3590 { "matchinfo", fts3MatchinfoFunc
},
3592 int i
; /* Iterator variable */
3594 UNUSED_PARAMETER(pVtab
);
3595 UNUSED_PARAMETER(nArg
);
3596 UNUSED_PARAMETER(ppArg
);
3598 for(i
=0; i
<SizeofArray(aOverload
); i
++){
3599 if( strcmp(zName
, aOverload
[i
].zName
)==0 ){
3600 *pxFunc
= aOverload
[i
].xFunc
;
3605 /* No function of the specified name was found. Return 0. */
3610 ** Implementation of FTS3 xRename method. Rename an fts3 table.
3612 static int fts3RenameMethod(
3613 sqlite3_vtab
*pVtab
, /* Virtual table handle */
3614 const char *zName
/* New name of table */
3616 Fts3Table
*p
= (Fts3Table
*)pVtab
;
3617 sqlite3
*db
= p
->db
; /* Database connection */
3618 int rc
; /* Return Code */
3620 /* At this point it must be known if the %_stat table exists or not.
3621 ** So bHasStat may not be 2. */
3622 rc
= fts3SetHasStat(p
);
3624 /* As it happens, the pending terms table is always empty here. This is
3625 ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
3626 ** always opens a savepoint transaction. And the xSavepoint() method
3627 ** flushes the pending terms table. But leave the (no-op) call to
3628 ** PendingTermsFlush() in in case that changes.
3630 assert( p
->nPendingData
==0 );
3631 if( rc
==SQLITE_OK
){
3632 rc
= sqlite3Fts3PendingTermsFlush(p
);
3635 if( p
->zContentTbl
==0 ){
3637 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
3638 p
->zDb
, p
->zName
, zName
3642 if( p
->bHasDocsize
){
3644 "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
3645 p
->zDb
, p
->zName
, zName
3650 "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
3651 p
->zDb
, p
->zName
, zName
3655 "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
3656 p
->zDb
, p
->zName
, zName
3659 "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
3660 p
->zDb
, p
->zName
, zName
3666 ** The xSavepoint() method.
3668 ** Flush the contents of the pending-terms table to disk.
3670 static int fts3SavepointMethod(sqlite3_vtab
*pVtab
, int iSavepoint
){
3672 UNUSED_PARAMETER(iSavepoint
);
3673 assert( ((Fts3Table
*)pVtab
)->inTransaction
);
3674 assert( ((Fts3Table
*)pVtab
)->mxSavepoint
< iSavepoint
);
3675 TESTONLY( ((Fts3Table
*)pVtab
)->mxSavepoint
= iSavepoint
);
3676 if( ((Fts3Table
*)pVtab
)->bIgnoreSavepoint
==0 ){
3677 rc
= fts3SyncMethod(pVtab
);
3683 ** The xRelease() method.
3687 static int fts3ReleaseMethod(sqlite3_vtab
*pVtab
, int iSavepoint
){
3688 TESTONLY( Fts3Table
*p
= (Fts3Table
*)pVtab
);
3689 UNUSED_PARAMETER(iSavepoint
);
3690 UNUSED_PARAMETER(pVtab
);
3691 assert( p
->inTransaction
);
3692 assert( p
->mxSavepoint
>= iSavepoint
);
3693 TESTONLY( p
->mxSavepoint
= iSavepoint
-1 );
3698 ** The xRollbackTo() method.
3700 ** Discard the contents of the pending terms table.
3702 static int fts3RollbackToMethod(sqlite3_vtab
*pVtab
, int iSavepoint
){
3703 Fts3Table
*p
= (Fts3Table
*)pVtab
;
3704 UNUSED_PARAMETER(iSavepoint
);
3705 assert( p
->inTransaction
);
3706 assert( p
->mxSavepoint
>= iSavepoint
);
3707 TESTONLY( p
->mxSavepoint
= iSavepoint
);
3708 sqlite3Fts3PendingTermsClear(p
);
3712 static const sqlite3_module fts3Module
= {
3714 /* xCreate */ fts3CreateMethod
,
3715 /* xConnect */ fts3ConnectMethod
,
3716 /* xBestIndex */ fts3BestIndexMethod
,
3717 /* xDisconnect */ fts3DisconnectMethod
,
3718 /* xDestroy */ fts3DestroyMethod
,
3719 /* xOpen */ fts3OpenMethod
,
3720 /* xClose */ fts3CloseMethod
,
3721 /* xFilter */ fts3FilterMethod
,
3722 /* xNext */ fts3NextMethod
,
3723 /* xEof */ fts3EofMethod
,
3724 /* xColumn */ fts3ColumnMethod
,
3725 /* xRowid */ fts3RowidMethod
,
3726 /* xUpdate */ fts3UpdateMethod
,
3727 /* xBegin */ fts3BeginMethod
,
3728 /* xSync */ fts3SyncMethod
,
3729 /* xCommit */ fts3CommitMethod
,
3730 /* xRollback */ fts3RollbackMethod
,
3731 /* xFindFunction */ fts3FindFunctionMethod
,
3732 /* xRename */ fts3RenameMethod
,
3733 /* xSavepoint */ fts3SavepointMethod
,
3734 /* xRelease */ fts3ReleaseMethod
,
3735 /* xRollbackTo */ fts3RollbackToMethod
,
3739 ** This function is registered as the module destructor (called when an
3740 ** FTS3 enabled database connection is closed). It frees the memory
3741 ** allocated for the tokenizer hash table.
3743 static void hashDestroy(void *p
){
3744 Fts3Hash
*pHash
= (Fts3Hash
*)p
;
3745 sqlite3Fts3HashClear(pHash
);
3746 sqlite3_free(pHash
);
3750 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
3751 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
3752 ** respectively. The following three forward declarations are for functions
3753 ** declared in these files used to retrieve the respective implementations.
3755 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
3756 ** to by the argument to point to the "simple" tokenizer implementation.
3759 void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module
const**ppModule
);
3760 void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module
const**ppModule
);
3761 #ifndef SQLITE_DISABLE_FTS3_UNICODE
3762 void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module
const**ppModule
);
3764 #ifdef SQLITE_ENABLE_ICU
3765 void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module
const**ppModule
);
3769 ** Initialize the fts3 extension. If this extension is built as part
3770 ** of the sqlite library, then this function is called directly by
3771 ** SQLite. If fts3 is built as a dynamically loadable extension, this
3772 ** function is called by the sqlite3_extension_init() entry point.
3774 int sqlite3Fts3Init(sqlite3
*db
){
3776 Fts3Hash
*pHash
= 0;
3777 const sqlite3_tokenizer_module
*pSimple
= 0;
3778 const sqlite3_tokenizer_module
*pPorter
= 0;
3779 #ifndef SQLITE_DISABLE_FTS3_UNICODE
3780 const sqlite3_tokenizer_module
*pUnicode
= 0;
3783 #ifdef SQLITE_ENABLE_ICU
3784 const sqlite3_tokenizer_module
*pIcu
= 0;
3785 sqlite3Fts3IcuTokenizerModule(&pIcu
);
3788 #ifndef SQLITE_DISABLE_FTS3_UNICODE
3789 sqlite3Fts3UnicodeTokenizer(&pUnicode
);
3793 rc
= sqlite3Fts3InitTerm(db
);
3794 if( rc
!=SQLITE_OK
) return rc
;
3797 rc
= sqlite3Fts3InitAux(db
);
3798 if( rc
!=SQLITE_OK
) return rc
;
3800 sqlite3Fts3SimpleTokenizerModule(&pSimple
);
3801 sqlite3Fts3PorterTokenizerModule(&pPorter
);
3803 /* Allocate and initialize the hash-table used to store tokenizers. */
3804 pHash
= sqlite3_malloc(sizeof(Fts3Hash
));
3808 sqlite3Fts3HashInit(pHash
, FTS3_HASH_STRING
, 1);
3811 /* Load the built-in tokenizers into the hash table */
3812 if( rc
==SQLITE_OK
){
3813 if( sqlite3Fts3HashInsert(pHash
, "simple", 7, (void *)pSimple
)
3814 || sqlite3Fts3HashInsert(pHash
, "porter", 7, (void *)pPorter
)
3816 #ifndef SQLITE_DISABLE_FTS3_UNICODE
3817 || sqlite3Fts3HashInsert(pHash
, "unicode61", 10, (void *)pUnicode
)
3819 #ifdef SQLITE_ENABLE_ICU
3820 || (pIcu
&& sqlite3Fts3HashInsert(pHash
, "icu", 4, (void *)pIcu
))
3828 if( rc
==SQLITE_OK
){
3829 rc
= sqlite3Fts3ExprInitTestInterface(db
);
3833 /* Create the virtual table wrapper around the hash-table and overload
3834 ** the two scalar functions. If this is successful, register the
3835 ** module with sqlite.
3838 #if CHROMIUM_FTS3_CHANGES && !SQLITE_TEST
3839 /* fts3_tokenizer() disabled for security reasons. */
3841 && SQLITE_OK
==(rc
= sqlite3Fts3InitHashTable(db
, pHash
, "fts3_tokenizer"))
3843 && SQLITE_OK
==(rc
= sqlite3_overload_function(db
, "snippet", -1))
3844 && SQLITE_OK
==(rc
= sqlite3_overload_function(db
, "offsets", 1))
3845 && SQLITE_OK
==(rc
= sqlite3_overload_function(db
, "matchinfo", 1))
3846 && SQLITE_OK
==(rc
= sqlite3_overload_function(db
, "matchinfo", 2))
3847 && SQLITE_OK
==(rc
= sqlite3_overload_function(db
, "optimize", 1))
3849 rc
= sqlite3_create_module_v2(
3850 db
, "fts3", &fts3Module
, (void *)pHash
, hashDestroy
3852 #if CHROMIUM_FTS3_CHANGES && !SQLITE_TEST
3853 /* Disable fts4 and tokenizer vtab pending review. */
3855 if( rc
==SQLITE_OK
){
3856 rc
= sqlite3_create_module_v2(
3857 db
, "fts4", &fts3Module
, (void *)pHash
, 0
3860 if( rc
==SQLITE_OK
){
3861 rc
= sqlite3Fts3InitTok(db
, (void *)pHash
);
3868 /* An error has occurred. Delete the hash table and return the error code. */
3869 assert( rc
!=SQLITE_OK
);
3871 sqlite3Fts3HashClear(pHash
);
3872 sqlite3_free(pHash
);
3878 ** Allocate an Fts3MultiSegReader for each token in the expression headed
3881 ** An Fts3SegReader object is a cursor that can seek or scan a range of
3882 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
3883 ** Fts3SegReader objects internally to provide an interface to seek or scan
3884 ** within the union of all segments of a b-tree. Hence the name.
3886 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
3887 ** segment b-tree (if the term is not a prefix or it is a prefix for which
3888 ** there exists prefix b-tree of the right length) then it may be traversed
3889 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
3890 ** doclist and then traversed.
3892 static void fts3EvalAllocateReaders(
3893 Fts3Cursor
*pCsr
, /* FTS cursor handle */
3894 Fts3Expr
*pExpr
, /* Allocate readers for this expression */
3895 int *pnToken
, /* OUT: Total number of tokens in phrase. */
3896 int *pnOr
, /* OUT: Total number of OR nodes in expr. */
3897 int *pRc
/* IN/OUT: Error code */
3899 if( pExpr
&& SQLITE_OK
==*pRc
){
3900 if( pExpr
->eType
==FTSQUERY_PHRASE
){
3902 int nToken
= pExpr
->pPhrase
->nToken
;
3904 for(i
=0; i
<nToken
; i
++){
3905 Fts3PhraseToken
*pToken
= &pExpr
->pPhrase
->aToken
[i
];
3906 int rc
= fts3TermSegReaderCursor(pCsr
,
3907 pToken
->z
, pToken
->n
, pToken
->isPrefix
, &pToken
->pSegcsr
3909 if( rc
!=SQLITE_OK
){
3914 assert( pExpr
->pPhrase
->iDoclistToken
==0 );
3915 pExpr
->pPhrase
->iDoclistToken
= -1;
3917 *pnOr
+= (pExpr
->eType
==FTSQUERY_OR
);
3918 fts3EvalAllocateReaders(pCsr
, pExpr
->pLeft
, pnToken
, pnOr
, pRc
);
3919 fts3EvalAllocateReaders(pCsr
, pExpr
->pRight
, pnToken
, pnOr
, pRc
);
3925 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
3926 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
3928 ** This function assumes that pList points to a buffer allocated using
3929 ** sqlite3_malloc(). This function takes responsibility for eventually
3930 ** freeing the buffer.
3932 static void fts3EvalPhraseMergeToken(
3933 Fts3Table
*pTab
, /* FTS Table pointer */
3934 Fts3Phrase
*p
, /* Phrase to merge pList/nList into */
3935 int iToken
, /* Token pList/nList corresponds to */
3936 char *pList
, /* Pointer to doclist */
3937 int nList
/* Number of bytes in pList */
3939 assert( iToken
!=p
->iDoclistToken
);
3942 sqlite3_free(p
->doclist
.aAll
);
3943 p
->doclist
.aAll
= 0;
3944 p
->doclist
.nAll
= 0;
3947 else if( p
->iDoclistToken
<0 ){
3948 p
->doclist
.aAll
= pList
;
3949 p
->doclist
.nAll
= nList
;
3952 else if( p
->doclist
.aAll
==0 ){
3953 sqlite3_free(pList
);
3963 if( p
->iDoclistToken
<iToken
){
3964 pLeft
= p
->doclist
.aAll
;
3965 nLeft
= p
->doclist
.nAll
;
3968 nDiff
= iToken
- p
->iDoclistToken
;
3970 pRight
= p
->doclist
.aAll
;
3971 nRight
= p
->doclist
.nAll
;
3974 nDiff
= p
->iDoclistToken
- iToken
;
3977 fts3DoclistPhraseMerge(pTab
->bDescIdx
, nDiff
, pLeft
, nLeft
, pRight
,&nRight
);
3978 sqlite3_free(pLeft
);
3979 p
->doclist
.aAll
= pRight
;
3980 p
->doclist
.nAll
= nRight
;
3983 if( iToken
>p
->iDoclistToken
) p
->iDoclistToken
= iToken
;
3987 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
3988 ** does not take deferred tokens into account.
3990 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
3992 static int fts3EvalPhraseLoad(
3993 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
3994 Fts3Phrase
*p
/* Phrase object */
3996 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
4000 for(iToken
=0; rc
==SQLITE_OK
&& iToken
<p
->nToken
; iToken
++){
4001 Fts3PhraseToken
*pToken
= &p
->aToken
[iToken
];
4002 assert( pToken
->pDeferred
==0 || pToken
->pSegcsr
==0 );
4004 if( pToken
->pSegcsr
){
4007 rc
= fts3TermSelect(pTab
, pToken
, p
->iColumn
, &nThis
, &pThis
);
4008 if( rc
==SQLITE_OK
){
4009 fts3EvalPhraseMergeToken(pTab
, p
, iToken
, pThis
, nThis
);
4012 assert( pToken
->pSegcsr
==0 );
4019 ** This function is called on each phrase after the position lists for
4020 ** any deferred tokens have been loaded into memory. It updates the phrases
4021 ** current position list to include only those positions that are really
4022 ** instances of the phrase (after considering deferred tokens). If this
4023 ** means that the phrase does not appear in the current row, doclist.pList
4024 ** and doclist.nList are both zeroed.
4026 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
4028 static int fts3EvalDeferredPhrase(Fts3Cursor
*pCsr
, Fts3Phrase
*pPhrase
){
4029 int iToken
; /* Used to iterate through phrase tokens */
4030 char *aPoslist
= 0; /* Position list for deferred tokens */
4031 int nPoslist
= 0; /* Number of bytes in aPoslist */
4032 int iPrev
= -1; /* Token number of previous deferred token */
4034 assert( pPhrase
->doclist
.bFreeList
==0 );
4036 for(iToken
=0; iToken
<pPhrase
->nToken
; iToken
++){
4037 Fts3PhraseToken
*pToken
= &pPhrase
->aToken
[iToken
];
4038 Fts3DeferredToken
*pDeferred
= pToken
->pDeferred
;
4043 int rc
= sqlite3Fts3DeferredTokenList(pDeferred
, &pList
, &nList
);
4044 if( rc
!=SQLITE_OK
) return rc
;
4047 sqlite3_free(aPoslist
);
4048 pPhrase
->doclist
.pList
= 0;
4049 pPhrase
->doclist
.nList
= 0;
4052 }else if( aPoslist
==0 ){
4058 char *p1
= aPoslist
;
4062 fts3PoslistPhraseMerge(&aOut
, iToken
-iPrev
, 0, 1, &p1
, &p2
);
4063 sqlite3_free(aPoslist
);
4065 nPoslist
= (int)(aOut
- aPoslist
);
4067 sqlite3_free(aPoslist
);
4068 pPhrase
->doclist
.pList
= 0;
4069 pPhrase
->doclist
.nList
= 0;
4078 int nMaxUndeferred
= pPhrase
->iDoclistToken
;
4079 if( nMaxUndeferred
<0 ){
4080 pPhrase
->doclist
.pList
= aPoslist
;
4081 pPhrase
->doclist
.nList
= nPoslist
;
4082 pPhrase
->doclist
.iDocid
= pCsr
->iPrevId
;
4083 pPhrase
->doclist
.bFreeList
= 1;
4090 if( nMaxUndeferred
>iPrev
){
4092 p2
= pPhrase
->doclist
.pList
;
4093 nDistance
= nMaxUndeferred
- iPrev
;
4095 p1
= pPhrase
->doclist
.pList
;
4097 nDistance
= iPrev
- nMaxUndeferred
;
4100 aOut
= (char *)sqlite3_malloc(nPoslist
+8);
4102 sqlite3_free(aPoslist
);
4103 return SQLITE_NOMEM
;
4106 pPhrase
->doclist
.pList
= aOut
;
4107 if( fts3PoslistPhraseMerge(&aOut
, nDistance
, 0, 1, &p1
, &p2
) ){
4108 pPhrase
->doclist
.bFreeList
= 1;
4109 pPhrase
->doclist
.nList
= (int)(aOut
- pPhrase
->doclist
.pList
);
4112 pPhrase
->doclist
.pList
= 0;
4113 pPhrase
->doclist
.nList
= 0;
4115 sqlite3_free(aPoslist
);
4123 ** Maximum number of tokens a phrase may have to be considered for the
4124 ** incremental doclists strategy.
4126 #define MAX_INCR_PHRASE_TOKENS 4
4129 ** This function is called for each Fts3Phrase in a full-text query
4130 ** expression to initialize the mechanism for returning rows. Once this
4131 ** function has been called successfully on an Fts3Phrase, it may be
4132 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
4134 ** If parameter bOptOk is true, then the phrase may (or may not) use the
4135 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
4136 ** memory within this call.
4138 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
4140 static int fts3EvalPhraseStart(Fts3Cursor
*pCsr
, int bOptOk
, Fts3Phrase
*p
){
4141 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
4142 int rc
= SQLITE_OK
; /* Error code */
4145 /* Determine if doclists may be loaded from disk incrementally. This is
4146 ** possible if the bOptOk argument is true, the FTS doclists will be
4147 ** scanned in forward order, and the phrase consists of
4148 ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
4149 ** tokens or prefix tokens that cannot use a prefix-index. */
4151 int bIncrOk
= (bOptOk
4152 && pCsr
->bDesc
==pTab
->bDescIdx
4153 && p
->nToken
<=MAX_INCR_PHRASE_TOKENS
&& p
->nToken
>0
4154 && p
->nToken
<=MAX_INCR_PHRASE_TOKENS
&& p
->nToken
>0
4156 && pTab
->bNoIncrDoclist
==0
4159 for(i
=0; bIncrOk
==1 && i
<p
->nToken
; i
++){
4160 Fts3PhraseToken
*pToken
= &p
->aToken
[i
];
4161 if( pToken
->bFirst
|| (pToken
->pSegcsr
!=0 && !pToken
->pSegcsr
->bLookup
) ){
4164 if( pToken
->pSegcsr
) bHaveIncr
= 1;
4167 if( bIncrOk
&& bHaveIncr
){
4168 /* Use the incremental approach. */
4169 int iCol
= (p
->iColumn
>= pTab
->nColumn
? -1 : p
->iColumn
);
4170 for(i
=0; rc
==SQLITE_OK
&& i
<p
->nToken
; i
++){
4171 Fts3PhraseToken
*pToken
= &p
->aToken
[i
];
4172 Fts3MultiSegReader
*pSegcsr
= pToken
->pSegcsr
;
4174 rc
= sqlite3Fts3MsrIncrStart(pTab
, pSegcsr
, iCol
, pToken
->z
, pToken
->n
);
4179 /* Load the full doclist for the phrase into memory. */
4180 rc
= fts3EvalPhraseLoad(pCsr
, p
);
4184 assert( rc
!=SQLITE_OK
|| p
->nToken
<1 || p
->aToken
[0].pSegcsr
==0 || p
->bIncr
);
4189 ** This function is used to iterate backwards (from the end to start)
4190 ** through doclists. It is used by this module to iterate through phrase
4191 ** doclists in reverse and by the fts3_write.c module to iterate through
4192 ** pending-terms lists when writing to databases with "order=desc".
4194 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
4195 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
4196 ** function iterates from the end of the doclist to the beginning.
4198 void sqlite3Fts3DoclistPrev(
4199 int bDescIdx
, /* True if the doclist is desc */
4200 char *aDoclist
, /* Pointer to entire doclist */
4201 int nDoclist
, /* Length of aDoclist in bytes */
4202 char **ppIter
, /* IN/OUT: Iterator pointer */
4203 sqlite3_int64
*piDocid
, /* IN/OUT: Docid pointer */
4204 int *pnList
, /* OUT: List length pointer */
4205 u8
*pbEof
/* OUT: End-of-file flag */
4209 assert( nDoclist
>0 );
4210 assert( *pbEof
==0 );
4211 assert( p
|| *piDocid
==0 );
4212 assert( !p
|| (p
>aDoclist
&& p
<&aDoclist
[nDoclist
]) );
4215 sqlite3_int64 iDocid
= 0;
4217 char *pDocid
= aDoclist
;
4218 char *pEnd
= &aDoclist
[nDoclist
];
4221 while( pDocid
<pEnd
){
4222 sqlite3_int64 iDelta
;
4223 pDocid
+= sqlite3Fts3GetVarint(pDocid
, &iDelta
);
4224 iDocid
+= (iMul
* iDelta
);
4226 fts3PoslistCopy(0, &pDocid
);
4227 while( pDocid
<pEnd
&& *pDocid
==0 ) pDocid
++;
4228 iMul
= (bDescIdx
? -1 : 1);
4231 *pnList
= (int)(pEnd
- pNext
);
4235 int iMul
= (bDescIdx
? -1 : 1);
4236 sqlite3_int64 iDelta
;
4237 fts3GetReverseVarint(&p
, aDoclist
, &iDelta
);
4238 *piDocid
-= (iMul
* iDelta
);
4244 fts3ReversePoslist(aDoclist
, &p
);
4245 *pnList
= (int)(pSave
- p
);
4252 ** Iterate forwards through a doclist.
4254 void sqlite3Fts3DoclistNext(
4255 int bDescIdx
, /* True if the doclist is desc */
4256 char *aDoclist
, /* Pointer to entire doclist */
4257 int nDoclist
, /* Length of aDoclist in bytes */
4258 char **ppIter
, /* IN/OUT: Iterator pointer */
4259 sqlite3_int64
*piDocid
, /* IN/OUT: Docid pointer */
4260 u8
*pbEof
/* OUT: End-of-file flag */
4264 assert( nDoclist
>0 );
4265 assert( *pbEof
==0 );
4266 assert( p
|| *piDocid
==0 );
4267 assert( !p
|| (p
>=aDoclist
&& p
<=&aDoclist
[nDoclist
]) );
4271 p
+= sqlite3Fts3GetVarint(p
, piDocid
);
4273 fts3PoslistCopy(0, &p
);
4274 if( p
>=&aDoclist
[nDoclist
] ){
4278 p
+= sqlite3Fts3GetVarint(p
, &iVar
);
4279 *piDocid
+= ((bDescIdx
? -1 : 1) * iVar
);
4287 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
4288 ** to true if EOF is reached.
4290 static void fts3EvalDlPhraseNext(
4295 char *pIter
; /* Used to iterate through aAll */
4296 char *pEnd
= &pDL
->aAll
[pDL
->nAll
]; /* 1 byte past end of aAll */
4298 if( pDL
->pNextDocid
){
4299 pIter
= pDL
->pNextDocid
;
4305 /* We have already reached the end of this doclist. EOF. */
4308 sqlite3_int64 iDelta
;
4309 pIter
+= sqlite3Fts3GetVarint(pIter
, &iDelta
);
4310 if( pTab
->bDescIdx
==0 || pDL
->pNextDocid
==0 ){
4311 pDL
->iDocid
+= iDelta
;
4313 pDL
->iDocid
-= iDelta
;
4316 fts3PoslistCopy(0, &pIter
);
4317 pDL
->nList
= (int)(pIter
- pDL
->pList
);
4319 /* pIter now points just past the 0x00 that terminates the position-
4320 ** list for document pDL->iDocid. However, if this position-list was
4321 ** edited in place by fts3EvalNearTrim(), then pIter may not actually
4322 ** point to the start of the next docid value. The following line deals
4323 ** with this case by advancing pIter past the zero-padding added by
4324 ** fts3EvalNearTrim(). */
4325 while( pIter
<pEnd
&& *pIter
==0 ) pIter
++;
4327 pDL
->pNextDocid
= pIter
;
4328 assert( pIter
>=&pDL
->aAll
[pDL
->nAll
] || *pIter
);
4334 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
4336 typedef struct TokenDoclist TokenDoclist
;
4337 struct TokenDoclist
{
4339 sqlite3_int64 iDocid
;
4345 ** Token pToken is an incrementally loaded token that is part of a
4346 ** multi-token phrase. Advance it to the next matching document in the
4347 ** database and populate output variable *p with the details of the new
4348 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
4350 ** If an error occurs, return an SQLite error code. Otherwise, return
4353 static int incrPhraseTokenNext(
4354 Fts3Table
*pTab
, /* Virtual table handle */
4355 Fts3Phrase
*pPhrase
, /* Phrase to advance token of */
4356 int iToken
, /* Specific token to advance */
4357 TokenDoclist
*p
, /* OUT: Docid and doclist for new entry */
4358 u8
*pbEof
/* OUT: True if iterator is at EOF */
4362 if( pPhrase
->iDoclistToken
==iToken
){
4363 assert( p
->bIgnore
==0 );
4364 assert( pPhrase
->aToken
[iToken
].pSegcsr
==0 );
4365 fts3EvalDlPhraseNext(pTab
, &pPhrase
->doclist
, pbEof
);
4366 p
->pList
= pPhrase
->doclist
.pList
;
4367 p
->nList
= pPhrase
->doclist
.nList
;
4368 p
->iDocid
= pPhrase
->doclist
.iDocid
;
4370 Fts3PhraseToken
*pToken
= &pPhrase
->aToken
[iToken
];
4371 assert( pToken
->pDeferred
==0 );
4372 assert( pToken
->pSegcsr
|| pPhrase
->iDoclistToken
>=0 );
4373 if( pToken
->pSegcsr
){
4374 assert( p
->bIgnore
==0 );
4375 rc
= sqlite3Fts3MsrIncrNext(
4376 pTab
, pToken
->pSegcsr
, &p
->iDocid
, &p
->pList
, &p
->nList
4378 if( p
->pList
==0 ) *pbEof
= 1;
4389 ** The phrase iterator passed as the second argument:
4391 ** * features at least one token that uses an incremental doclist, and
4393 ** * does not contain any deferred tokens.
4395 ** Advance it to the next matching documnent in the database and populate
4396 ** the Fts3Doclist.pList and nList fields.
4398 ** If there is no "next" entry and no error occurs, then *pbEof is set to
4399 ** 1 before returning. Otherwise, if no error occurs and the iterator is
4400 ** successfully advanced, *pbEof is set to 0.
4402 ** If an error occurs, return an SQLite error code. Otherwise, return
4405 static int fts3EvalIncrPhraseNext(
4406 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4407 Fts3Phrase
*p
, /* Phrase object to advance to next docid */
4408 u8
*pbEof
/* OUT: Set to 1 if EOF */
4411 Fts3Doclist
*pDL
= &p
->doclist
;
4412 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
4415 /* This is only called if it is guaranteed that the phrase has at least
4416 ** one incremental token. In which case the bIncr flag is set. */
4417 assert( p
->bIncr
==1 );
4419 if( p
->nToken
==1 && p
->bIncr
){
4420 rc
= sqlite3Fts3MsrIncrNext(pTab
, p
->aToken
[0].pSegcsr
,
4421 &pDL
->iDocid
, &pDL
->pList
, &pDL
->nList
4423 if( pDL
->pList
==0 ) bEof
= 1;
4425 int bDescDoclist
= pCsr
->bDesc
;
4426 struct TokenDoclist a
[MAX_INCR_PHRASE_TOKENS
];
4428 memset(a
, 0, sizeof(a
));
4429 assert( p
->nToken
<=MAX_INCR_PHRASE_TOKENS
);
4430 assert( p
->iDoclistToken
<MAX_INCR_PHRASE_TOKENS
);
4434 sqlite3_int64 iMax
= 0; /* Largest docid for all iterators */
4435 int i
; /* Used to iterate through tokens */
4437 /* Advance the iterator for each token in the phrase once. */
4438 for(i
=0; rc
==SQLITE_OK
&& i
<p
->nToken
&& bEof
==0; i
++){
4439 rc
= incrPhraseTokenNext(pTab
, p
, i
, &a
[i
], &bEof
);
4440 if( a
[i
].bIgnore
==0 && (bMaxSet
==0 || DOCID_CMP(iMax
, a
[i
].iDocid
)<0) ){
4445 assert( rc
!=SQLITE_OK
|| (p
->nToken
>=1 && a
[p
->nToken
-1].bIgnore
==0) );
4446 assert( rc
!=SQLITE_OK
|| bMaxSet
);
4448 /* Keep advancing iterators until they all point to the same document */
4449 for(i
=0; i
<p
->nToken
; i
++){
4450 while( rc
==SQLITE_OK
&& bEof
==0
4451 && a
[i
].bIgnore
==0 && DOCID_CMP(a
[i
].iDocid
, iMax
)<0
4453 rc
= incrPhraseTokenNext(pTab
, p
, i
, &a
[i
], &bEof
);
4454 if( DOCID_CMP(a
[i
].iDocid
, iMax
)>0 ){
4461 /* Check if the current entries really are a phrase match */
4464 int nByte
= a
[p
->nToken
-1].nList
;
4465 char *aDoclist
= sqlite3_malloc(nByte
+1);
4466 if( !aDoclist
) return SQLITE_NOMEM
;
4467 memcpy(aDoclist
, a
[p
->nToken
-1].pList
, nByte
+1);
4469 for(i
=0; i
<(p
->nToken
-1); i
++){
4470 if( a
[i
].bIgnore
==0 ){
4471 char *pL
= a
[i
].pList
;
4472 char *pR
= aDoclist
;
4473 char *pOut
= aDoclist
;
4474 int nDist
= p
->nToken
-1-i
;
4475 int res
= fts3PoslistPhraseMerge(&pOut
, nDist
, 0, 1, &pL
, &pR
);
4477 nList
= (int)(pOut
- aDoclist
);
4480 if( i
==(p
->nToken
-1) ){
4482 pDL
->pList
= aDoclist
;
4487 sqlite3_free(aDoclist
);
4497 ** Attempt to move the phrase iterator to point to the next matching docid.
4498 ** If an error occurs, return an SQLite error code. Otherwise, return
4501 ** If there is no "next" entry and no error occurs, then *pbEof is set to
4502 ** 1 before returning. Otherwise, if no error occurs and the iterator is
4503 ** successfully advanced, *pbEof is set to 0.
4505 static int fts3EvalPhraseNext(
4506 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4507 Fts3Phrase
*p
, /* Phrase object to advance to next docid */
4508 u8
*pbEof
/* OUT: Set to 1 if EOF */
4511 Fts3Doclist
*pDL
= &p
->doclist
;
4512 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
4515 rc
= fts3EvalIncrPhraseNext(pCsr
, p
, pbEof
);
4516 }else if( pCsr
->bDesc
!=pTab
->bDescIdx
&& pDL
->nAll
){
4517 sqlite3Fts3DoclistPrev(pTab
->bDescIdx
, pDL
->aAll
, pDL
->nAll
,
4518 &pDL
->pNextDocid
, &pDL
->iDocid
, &pDL
->nList
, pbEof
4520 pDL
->pList
= pDL
->pNextDocid
;
4522 fts3EvalDlPhraseNext(pTab
, pDL
, pbEof
);
4530 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
4531 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
4532 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
4533 ** expressions for which all descendent tokens are deferred.
4535 ** If parameter bOptOk is zero, then it is guaranteed that the
4536 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
4537 ** each phrase in the expression (subject to deferred token processing).
4538 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
4539 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
4541 ** If an error occurs within this function, *pRc is set to an SQLite error
4542 ** code before returning.
4544 static void fts3EvalStartReaders(
4545 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4546 Fts3Expr
*pExpr
, /* Expression to initialize phrases in */
4547 int *pRc
/* IN/OUT: Error code */
4549 if( pExpr
&& SQLITE_OK
==*pRc
){
4550 if( pExpr
->eType
==FTSQUERY_PHRASE
){
4552 int nToken
= pExpr
->pPhrase
->nToken
;
4553 for(i
=0; i
<nToken
; i
++){
4554 if( pExpr
->pPhrase
->aToken
[i
].pDeferred
==0 ) break;
4556 pExpr
->bDeferred
= (i
==nToken
);
4557 *pRc
= fts3EvalPhraseStart(pCsr
, 1, pExpr
->pPhrase
);
4559 fts3EvalStartReaders(pCsr
, pExpr
->pLeft
, pRc
);
4560 fts3EvalStartReaders(pCsr
, pExpr
->pRight
, pRc
);
4561 pExpr
->bDeferred
= (pExpr
->pLeft
->bDeferred
&& pExpr
->pRight
->bDeferred
);
4567 ** An array of the following structures is assembled as part of the process
4568 ** of selecting tokens to defer before the query starts executing (as part
4569 ** of the xFilter() method). There is one element in the array for each
4570 ** token in the FTS expression.
4572 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
4573 ** to phrases that are connected only by AND and NEAR operators (not OR or
4574 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
4575 ** separately. The root of a tokens AND/NEAR cluster is stored in
4576 ** Fts3TokenAndCost.pRoot.
4578 typedef struct Fts3TokenAndCost Fts3TokenAndCost
;
4579 struct Fts3TokenAndCost
{
4580 Fts3Phrase
*pPhrase
; /* The phrase the token belongs to */
4581 int iToken
; /* Position of token in phrase */
4582 Fts3PhraseToken
*pToken
; /* The token itself */
4583 Fts3Expr
*pRoot
; /* Root of NEAR/AND cluster */
4584 int nOvfl
; /* Number of overflow pages to load doclist */
4585 int iCol
; /* The column the token must match */
4589 ** This function is used to populate an allocated Fts3TokenAndCost array.
4591 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
4592 ** Otherwise, if an error occurs during execution, *pRc is set to an
4593 ** SQLite error code.
4595 static void fts3EvalTokenCosts(
4596 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4597 Fts3Expr
*pRoot
, /* Root of current AND/NEAR cluster */
4598 Fts3Expr
*pExpr
, /* Expression to consider */
4599 Fts3TokenAndCost
**ppTC
, /* Write new entries to *(*ppTC)++ */
4600 Fts3Expr
***ppOr
, /* Write new OR root to *(*ppOr)++ */
4601 int *pRc
/* IN/OUT: Error code */
4603 if( *pRc
==SQLITE_OK
){
4604 if( pExpr
->eType
==FTSQUERY_PHRASE
){
4605 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
4607 for(i
=0; *pRc
==SQLITE_OK
&& i
<pPhrase
->nToken
; i
++){
4608 Fts3TokenAndCost
*pTC
= (*ppTC
)++;
4609 pTC
->pPhrase
= pPhrase
;
4612 pTC
->pToken
= &pPhrase
->aToken
[i
];
4613 pTC
->iCol
= pPhrase
->iColumn
;
4614 *pRc
= sqlite3Fts3MsrOvfl(pCsr
, pTC
->pToken
->pSegcsr
, &pTC
->nOvfl
);
4616 }else if( pExpr
->eType
!=FTSQUERY_NOT
){
4617 assert( pExpr
->eType
==FTSQUERY_OR
4618 || pExpr
->eType
==FTSQUERY_AND
4619 || pExpr
->eType
==FTSQUERY_NEAR
4621 assert( pExpr
->pLeft
&& pExpr
->pRight
);
4622 if( pExpr
->eType
==FTSQUERY_OR
){
4623 pRoot
= pExpr
->pLeft
;
4627 fts3EvalTokenCosts(pCsr
, pRoot
, pExpr
->pLeft
, ppTC
, ppOr
, pRc
);
4628 if( pExpr
->eType
==FTSQUERY_OR
){
4629 pRoot
= pExpr
->pRight
;
4633 fts3EvalTokenCosts(pCsr
, pRoot
, pExpr
->pRight
, ppTC
, ppOr
, pRc
);
4639 ** Determine the average document (row) size in pages. If successful,
4640 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
4641 ** an SQLite error code.
4643 ** The average document size in pages is calculated by first calculating
4644 ** determining the average size in bytes, B. If B is less than the amount
4645 ** of data that will fit on a single leaf page of an intkey table in
4646 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
4647 ** the number of overflow pages consumed by a record B bytes in size.
4649 static int fts3EvalAverageDocsize(Fts3Cursor
*pCsr
, int *pnPage
){
4650 if( pCsr
->nRowAvg
==0 ){
4651 /* The average document size, which is required to calculate the cost
4652 ** of each doclist, has not yet been determined. Read the required
4653 ** data from the %_stat table to calculate it.
4655 ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
4656 ** varints, where nCol is the number of columns in the FTS3 table.
4657 ** The first varint is the number of documents currently stored in
4658 ** the table. The following nCol varints contain the total amount of
4659 ** data stored in all rows of each column of the table, from left
4663 Fts3Table
*p
= (Fts3Table
*)pCsr
->base
.pVtab
;
4664 sqlite3_stmt
*pStmt
;
4665 sqlite3_int64 nDoc
= 0;
4666 sqlite3_int64 nByte
= 0;
4670 rc
= sqlite3Fts3SelectDoctotal(p
, &pStmt
);
4671 if( rc
!=SQLITE_OK
) return rc
;
4672 a
= sqlite3_column_blob(pStmt
, 0);
4675 pEnd
= &a
[sqlite3_column_bytes(pStmt
, 0)];
4676 a
+= sqlite3Fts3GetVarint(a
, &nDoc
);
4678 a
+= sqlite3Fts3GetVarint(a
, &nByte
);
4680 if( nDoc
==0 || nByte
==0 ){
4681 sqlite3_reset(pStmt
);
4682 return FTS_CORRUPT_VTAB
;
4686 pCsr
->nRowAvg
= (int)(((nByte
/ nDoc
) + p
->nPgsz
) / p
->nPgsz
);
4687 assert( pCsr
->nRowAvg
>0 );
4688 rc
= sqlite3_reset(pStmt
);
4689 if( rc
!=SQLITE_OK
) return rc
;
4692 *pnPage
= pCsr
->nRowAvg
;
4697 ** This function is called to select the tokens (if any) that will be
4698 ** deferred. The array aTC[] has already been populated when this is
4701 ** This function is called once for each AND/NEAR cluster in the
4702 ** expression. Each invocation determines which tokens to defer within
4703 ** the cluster with root node pRoot. See comments above the definition
4704 ** of struct Fts3TokenAndCost for more details.
4706 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
4707 ** called on each token to defer. Otherwise, an SQLite error code is
4710 static int fts3EvalSelectDeferred(
4711 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4712 Fts3Expr
*pRoot
, /* Consider tokens with this root node */
4713 Fts3TokenAndCost
*aTC
, /* Array of expression tokens and costs */
4714 int nTC
/* Number of entries in aTC[] */
4716 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
4717 int nDocSize
= 0; /* Number of pages per doc loaded */
4718 int rc
= SQLITE_OK
; /* Return code */
4719 int ii
; /* Iterator variable for various purposes */
4720 int nOvfl
= 0; /* Total overflow pages used by doclists */
4721 int nToken
= 0; /* Total number of tokens in cluster */
4723 int nMinEst
= 0; /* The minimum count for any phrase so far. */
4724 int nLoad4
= 1; /* (Phrases that will be loaded)^4. */
4726 /* Tokens are never deferred for FTS tables created using the content=xxx
4727 ** option. The reason being that it is not guaranteed that the content
4728 ** table actually contains the same data as the index. To prevent this from
4729 ** causing any problems, the deferred token optimization is completely
4730 ** disabled for content=xxx tables. */
4731 if( pTab
->zContentTbl
){
4735 /* Count the tokens in this AND/NEAR cluster. If none of the doclists
4736 ** associated with the tokens spill onto overflow pages, or if there is
4737 ** only 1 token, exit early. No tokens to defer in this case. */
4738 for(ii
=0; ii
<nTC
; ii
++){
4739 if( aTC
[ii
].pRoot
==pRoot
){
4740 nOvfl
+= aTC
[ii
].nOvfl
;
4744 if( nOvfl
==0 || nToken
<2 ) return SQLITE_OK
;
4746 /* Obtain the average docsize (in pages). */
4747 rc
= fts3EvalAverageDocsize(pCsr
, &nDocSize
);
4748 assert( rc
!=SQLITE_OK
|| nDocSize
>0 );
4751 /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
4752 ** of the number of overflow pages that will be loaded by the pager layer
4753 ** to retrieve the entire doclist for the token from the full-text index.
4754 ** Load the doclists for tokens that are either:
4756 ** a. The cheapest token in the entire query (i.e. the one visited by the
4757 ** first iteration of this loop), or
4759 ** b. Part of a multi-token phrase.
4761 ** After each token doclist is loaded, merge it with the others from the
4762 ** same phrase and count the number of documents that the merged doclist
4763 ** contains. Set variable "nMinEst" to the smallest number of documents in
4764 ** any phrase doclist for which 1 or more token doclists have been loaded.
4765 ** Let nOther be the number of other phrases for which it is certain that
4766 ** one or more tokens will not be deferred.
4768 ** Then, for each token, defer it if loading the doclist would result in
4769 ** loading N or more overflow pages into memory, where N is computed as:
4771 ** (nMinEst + 4^nOther - 1) / (4^nOther)
4773 for(ii
=0; ii
<nToken
&& rc
==SQLITE_OK
; ii
++){
4774 int iTC
; /* Used to iterate through aTC[] array. */
4775 Fts3TokenAndCost
*pTC
= 0; /* Set to cheapest remaining token. */
4777 /* Set pTC to point to the cheapest remaining token. */
4778 for(iTC
=0; iTC
<nTC
; iTC
++){
4779 if( aTC
[iTC
].pToken
&& aTC
[iTC
].pRoot
==pRoot
4780 && (!pTC
|| aTC
[iTC
].nOvfl
<pTC
->nOvfl
)
4787 if( ii
&& pTC
->nOvfl
>=((nMinEst
+(nLoad4
/4)-1)/(nLoad4
/4))*nDocSize
){
4788 /* The number of overflow pages to load for this (and therefore all
4789 ** subsequent) tokens is greater than the estimated number of pages
4790 ** that will be loaded if all subsequent tokens are deferred.
4792 Fts3PhraseToken
*pToken
= pTC
->pToken
;
4793 rc
= sqlite3Fts3DeferToken(pCsr
, pToken
, pTC
->iCol
);
4794 fts3SegReaderCursorFree(pToken
->pSegcsr
);
4795 pToken
->pSegcsr
= 0;
4797 /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
4798 ** for-loop. Except, limit the value to 2^24 to prevent it from
4799 ** overflowing the 32-bit integer it is stored in. */
4800 if( ii
<12 ) nLoad4
= nLoad4
*4;
4802 if( ii
==0 || (pTC
->pPhrase
->nToken
>1 && ii
!=nToken
-1) ){
4803 /* Either this is the cheapest token in the entire query, or it is
4804 ** part of a multi-token phrase. Either way, the entire doclist will
4805 ** (eventually) be loaded into memory. It may as well be now. */
4806 Fts3PhraseToken
*pToken
= pTC
->pToken
;
4809 rc
= fts3TermSelect(pTab
, pToken
, pTC
->iCol
, &nList
, &pList
);
4810 assert( rc
==SQLITE_OK
|| pList
==0 );
4811 if( rc
==SQLITE_OK
){
4813 fts3EvalPhraseMergeToken(pTab
, pTC
->pPhrase
, pTC
->iToken
,pList
,nList
);
4814 nCount
= fts3DoclistCountDocids(
4815 pTC
->pPhrase
->doclist
.aAll
, pTC
->pPhrase
->doclist
.nAll
4817 if( ii
==0 || nCount
<nMinEst
) nMinEst
= nCount
;
4828 ** This function is called from within the xFilter method. It initializes
4829 ** the full-text query currently stored in pCsr->pExpr. To iterate through
4830 ** the results of a query, the caller does:
4832 ** fts3EvalStart(pCsr);
4834 ** fts3EvalNext(pCsr);
4835 ** if( pCsr->bEof ) break;
4836 ** ... return row pCsr->iPrevId to the caller ...
4839 static int fts3EvalStart(Fts3Cursor
*pCsr
){
4840 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
4845 /* Allocate a MultiSegReader for each token in the expression. */
4846 fts3EvalAllocateReaders(pCsr
, pCsr
->pExpr
, &nToken
, &nOr
, &rc
);
4848 /* Determine which, if any, tokens in the expression should be deferred. */
4849 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
4850 if( rc
==SQLITE_OK
&& nToken
>1 && pTab
->bFts4
){
4851 Fts3TokenAndCost
*aTC
;
4853 aTC
= (Fts3TokenAndCost
*)sqlite3_malloc(
4854 sizeof(Fts3TokenAndCost
) * nToken
4855 + sizeof(Fts3Expr
*) * nOr
* 2
4857 apOr
= (Fts3Expr
**)&aTC
[nToken
];
4863 Fts3TokenAndCost
*pTC
= aTC
;
4864 Fts3Expr
**ppOr
= apOr
;
4866 fts3EvalTokenCosts(pCsr
, 0, pCsr
->pExpr
, &pTC
, &ppOr
, &rc
);
4867 nToken
= (int)(pTC
-aTC
);
4868 nOr
= (int)(ppOr
-apOr
);
4870 if( rc
==SQLITE_OK
){
4871 rc
= fts3EvalSelectDeferred(pCsr
, 0, aTC
, nToken
);
4872 for(ii
=0; rc
==SQLITE_OK
&& ii
<nOr
; ii
++){
4873 rc
= fts3EvalSelectDeferred(pCsr
, apOr
[ii
], aTC
, nToken
);
4882 fts3EvalStartReaders(pCsr
, pCsr
->pExpr
, &rc
);
4887 ** Invalidate the current position list for phrase pPhrase.
4889 static void fts3EvalInvalidatePoslist(Fts3Phrase
*pPhrase
){
4890 if( pPhrase
->doclist
.bFreeList
){
4891 sqlite3_free(pPhrase
->doclist
.pList
);
4893 pPhrase
->doclist
.pList
= 0;
4894 pPhrase
->doclist
.nList
= 0;
4895 pPhrase
->doclist
.bFreeList
= 0;
4899 ** This function is called to edit the position list associated with
4900 ** the phrase object passed as the fifth argument according to a NEAR
4901 ** condition. For example:
4903 ** abc NEAR/5 "def ghi"
4905 ** Parameter nNear is passed the NEAR distance of the expression (5 in
4906 ** the example above). When this function is called, *paPoslist points to
4907 ** the position list, and *pnToken is the number of phrase tokens in, the
4908 ** phrase on the other side of the NEAR operator to pPhrase. For example,
4909 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
4910 ** the position list associated with phrase "abc".
4912 ** All positions in the pPhrase position list that are not sufficiently
4913 ** close to a position in the *paPoslist position list are removed. If this
4914 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
4916 ** Before returning, *paPoslist is set to point to the position lsit
4917 ** associated with pPhrase. And *pnToken is set to the number of tokens in
4920 static int fts3EvalNearTrim(
4921 int nNear
, /* NEAR distance. As in "NEAR/nNear". */
4922 char *aTmp
, /* Temporary space to use */
4923 char **paPoslist
, /* IN/OUT: Position list */
4924 int *pnToken
, /* IN/OUT: Tokens in phrase of *paPoslist */
4925 Fts3Phrase
*pPhrase
/* The phrase object to trim the doclist of */
4927 int nParam1
= nNear
+ pPhrase
->nToken
;
4928 int nParam2
= nNear
+ *pnToken
;
4934 assert( pPhrase
->doclist
.pList
);
4936 p2
= pOut
= pPhrase
->doclist
.pList
;
4937 res
= fts3PoslistNearMerge(
4938 &pOut
, aTmp
, nParam1
, nParam2
, paPoslist
, &p2
4941 nNew
= (int)(pOut
- pPhrase
->doclist
.pList
) - 1;
4942 assert( pPhrase
->doclist
.pList
[nNew
]=='\0' );
4943 assert( nNew
<=pPhrase
->doclist
.nList
&& nNew
>0 );
4944 memset(&pPhrase
->doclist
.pList
[nNew
], 0, pPhrase
->doclist
.nList
- nNew
);
4945 pPhrase
->doclist
.nList
= nNew
;
4946 *paPoslist
= pPhrase
->doclist
.pList
;
4947 *pnToken
= pPhrase
->nToken
;
4954 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
4955 ** Otherwise, it advances the expression passed as the second argument to
4956 ** point to the next matching row in the database. Expressions iterate through
4957 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
4958 ** or descending if it is non-zero.
4960 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
4961 ** successful, the following variables in pExpr are set:
4963 ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
4964 ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
4966 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
4967 ** at EOF, then the following variables are populated with the position list
4968 ** for the phrase for the visited row:
4970 ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
4971 ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
4973 ** It says above that this function advances the expression to the next
4974 ** matching row. This is usually true, but there are the following exceptions:
4976 ** 1. Deferred tokens are not taken into account. If a phrase consists
4977 ** entirely of deferred tokens, it is assumed to match every row in
4978 ** the db. In this case the position-list is not populated at all.
4980 ** Or, if a phrase contains one or more deferred tokens and one or
4981 ** more non-deferred tokens, then the expression is advanced to the
4982 ** next possible match, considering only non-deferred tokens. In other
4983 ** words, if the phrase is "A B C", and "B" is deferred, the expression
4984 ** is advanced to the next row that contains an instance of "A * C",
4985 ** where "*" may match any single token. The position list in this case
4986 ** is populated as for "A * C" before returning.
4988 ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
4989 ** advanced to point to the next row that matches "x AND y".
4991 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
4992 ** really a match, taking into account deferred tokens and NEAR operators.
4994 static void fts3EvalNextRow(
4995 Fts3Cursor
*pCsr
, /* FTS Cursor handle */
4996 Fts3Expr
*pExpr
, /* Expr. to advance to next matching row */
4997 int *pRc
/* IN/OUT: Error code */
4999 if( *pRc
==SQLITE_OK
){
5000 int bDescDoclist
= pCsr
->bDesc
; /* Used by DOCID_CMP() macro */
5001 assert( pExpr
->bEof
==0 );
5004 switch( pExpr
->eType
){
5006 case FTSQUERY_AND
: {
5007 Fts3Expr
*pLeft
= pExpr
->pLeft
;
5008 Fts3Expr
*pRight
= pExpr
->pRight
;
5009 assert( !pLeft
->bDeferred
|| !pRight
->bDeferred
);
5011 if( pLeft
->bDeferred
){
5012 /* LHS is entirely deferred. So we assume it matches every row.
5013 ** Advance the RHS iterator to find the next row visited. */
5014 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5015 pExpr
->iDocid
= pRight
->iDocid
;
5016 pExpr
->bEof
= pRight
->bEof
;
5017 }else if( pRight
->bDeferred
){
5018 /* RHS is entirely deferred. So we assume it matches every row.
5019 ** Advance the LHS iterator to find the next row visited. */
5020 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5021 pExpr
->iDocid
= pLeft
->iDocid
;
5022 pExpr
->bEof
= pLeft
->bEof
;
5024 /* Neither the RHS or LHS are deferred. */
5025 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5026 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5027 while( !pLeft
->bEof
&& !pRight
->bEof
&& *pRc
==SQLITE_OK
){
5028 sqlite3_int64 iDiff
= DOCID_CMP(pLeft
->iDocid
, pRight
->iDocid
);
5029 if( iDiff
==0 ) break;
5031 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5033 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5036 pExpr
->iDocid
= pLeft
->iDocid
;
5037 pExpr
->bEof
= (pLeft
->bEof
|| pRight
->bEof
);
5043 Fts3Expr
*pLeft
= pExpr
->pLeft
;
5044 Fts3Expr
*pRight
= pExpr
->pRight
;
5045 sqlite3_int64 iCmp
= DOCID_CMP(pLeft
->iDocid
, pRight
->iDocid
);
5047 assert( pLeft
->bStart
|| pLeft
->iDocid
==pRight
->iDocid
);
5048 assert( pRight
->bStart
|| pLeft
->iDocid
==pRight
->iDocid
);
5050 if( pRight
->bEof
|| (pLeft
->bEof
==0 && iCmp
<0) ){
5051 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5052 }else if( pLeft
->bEof
|| (pRight
->bEof
==0 && iCmp
>0) ){
5053 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5055 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5056 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5059 pExpr
->bEof
= (pLeft
->bEof
&& pRight
->bEof
);
5060 iCmp
= DOCID_CMP(pLeft
->iDocid
, pRight
->iDocid
);
5061 if( pRight
->bEof
|| (pLeft
->bEof
==0 && iCmp
<0) ){
5062 pExpr
->iDocid
= pLeft
->iDocid
;
5064 pExpr
->iDocid
= pRight
->iDocid
;
5070 case FTSQUERY_NOT
: {
5071 Fts3Expr
*pLeft
= pExpr
->pLeft
;
5072 Fts3Expr
*pRight
= pExpr
->pRight
;
5074 if( pRight
->bStart
==0 ){
5075 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5076 assert( *pRc
!=SQLITE_OK
|| pRight
->bStart
);
5079 fts3EvalNextRow(pCsr
, pLeft
, pRc
);
5080 if( pLeft
->bEof
==0 ){
5083 && DOCID_CMP(pLeft
->iDocid
, pRight
->iDocid
)>0
5085 fts3EvalNextRow(pCsr
, pRight
, pRc
);
5088 pExpr
->iDocid
= pLeft
->iDocid
;
5089 pExpr
->bEof
= pLeft
->bEof
;
5094 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
5095 fts3EvalInvalidatePoslist(pPhrase
);
5096 *pRc
= fts3EvalPhraseNext(pCsr
, pPhrase
, &pExpr
->bEof
);
5097 pExpr
->iDocid
= pPhrase
->doclist
.iDocid
;
5105 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
5106 ** cluster, then this function returns 1 immediately.
5108 ** Otherwise, it checks if the current row really does match the NEAR
5109 ** expression, using the data currently stored in the position lists
5110 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
5112 ** If the current row is a match, the position list associated with each
5113 ** phrase in the NEAR expression is edited in place to contain only those
5114 ** phrase instances sufficiently close to their peers to satisfy all NEAR
5115 ** constraints. In this case it returns 1. If the NEAR expression does not
5116 ** match the current row, 0 is returned. The position lists may or may not
5117 ** be edited if 0 is returned.
5119 static int fts3EvalNearTest(Fts3Expr
*pExpr
, int *pRc
){
5122 /* The following block runs if pExpr is the root of a NEAR query.
5123 ** For example, the query:
5125 ** "w" NEAR "x" NEAR "y" NEAR "z"
5127 ** which is represented in tree form as:
5130 ** +--NEAR--+ <-- root of NEAR query
5138 ** The right-hand child of a NEAR node is always a phrase. The
5139 ** left-hand child may be either a phrase or a NEAR node. There are
5140 ** no exceptions to this - it's the way the parser in fts3_expr.c works.
5143 && pExpr
->eType
==FTSQUERY_NEAR
5145 && (pExpr
->pParent
==0 || pExpr
->pParent
->eType
!=FTSQUERY_NEAR
)
5148 int nTmp
= 0; /* Bytes of temp space */
5149 char *aTmp
; /* Temp space for PoslistNearMerge() */
5151 /* Allocate temporary working space. */
5152 for(p
=pExpr
; p
->pLeft
; p
=p
->pLeft
){
5153 nTmp
+= p
->pRight
->pPhrase
->doclist
.nList
;
5155 nTmp
+= p
->pPhrase
->doclist
.nList
;
5159 aTmp
= sqlite3_malloc(nTmp
*2);
5161 *pRc
= SQLITE_NOMEM
;
5164 char *aPoslist
= p
->pPhrase
->doclist
.pList
;
5165 int nToken
= p
->pPhrase
->nToken
;
5167 for(p
=p
->pParent
;res
&& p
&& p
->eType
==FTSQUERY_NEAR
; p
=p
->pParent
){
5168 Fts3Phrase
*pPhrase
= p
->pRight
->pPhrase
;
5169 int nNear
= p
->nNear
;
5170 res
= fts3EvalNearTrim(nNear
, aTmp
, &aPoslist
, &nToken
, pPhrase
);
5173 aPoslist
= pExpr
->pRight
->pPhrase
->doclist
.pList
;
5174 nToken
= pExpr
->pRight
->pPhrase
->nToken
;
5175 for(p
=pExpr
->pLeft
; p
&& res
; p
=p
->pLeft
){
5177 Fts3Phrase
*pPhrase
;
5178 assert( p
->pParent
&& p
->pParent
->pLeft
==p
);
5179 nNear
= p
->pParent
->nNear
;
5181 p
->eType
==FTSQUERY_NEAR
? p
->pRight
->pPhrase
: p
->pPhrase
5183 res
= fts3EvalNearTrim(nNear
, aTmp
, &aPoslist
, &nToken
, pPhrase
);
5195 ** This function is a helper function for fts3EvalTestDeferredAndNear().
5196 ** Assuming no error occurs or has occurred, It returns non-zero if the
5197 ** expression passed as the second argument matches the row that pCsr
5198 ** currently points to, or zero if it does not.
5200 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
5201 ** If an error occurs during execution of this function, *pRc is set to
5202 ** the appropriate SQLite error code. In this case the returned value is
5205 static int fts3EvalTestExpr(
5206 Fts3Cursor
*pCsr
, /* FTS cursor handle */
5207 Fts3Expr
*pExpr
, /* Expr to test. May or may not be root. */
5208 int *pRc
/* IN/OUT: Error code */
5210 int bHit
= 1; /* Return value */
5211 if( *pRc
==SQLITE_OK
){
5212 switch( pExpr
->eType
){
5216 fts3EvalTestExpr(pCsr
, pExpr
->pLeft
, pRc
)
5217 && fts3EvalTestExpr(pCsr
, pExpr
->pRight
, pRc
)
5218 && fts3EvalNearTest(pExpr
, pRc
)
5221 /* If the NEAR expression does not match any rows, zero the doclist for
5222 ** all phrases involved in the NEAR. This is because the snippet(),
5223 ** offsets() and matchinfo() functions are not supposed to recognize
5224 ** any instances of phrases that are part of unmatched NEAR queries.
5225 ** For example if this expression:
5227 ** ... MATCH 'a OR (b NEAR c)'
5229 ** is matched against a row containing:
5233 ** then any snippet() should ony highlight the "a" term, not the "b"
5234 ** (as "b" is part of a non-matching NEAR clause).
5237 && pExpr
->eType
==FTSQUERY_NEAR
5238 && (pExpr
->pParent
==0 || pExpr
->pParent
->eType
!=FTSQUERY_NEAR
)
5241 for(p
=pExpr
; p
->pPhrase
==0; p
=p
->pLeft
){
5242 if( p
->pRight
->iDocid
==pCsr
->iPrevId
){
5243 fts3EvalInvalidatePoslist(p
->pRight
->pPhrase
);
5246 if( p
->iDocid
==pCsr
->iPrevId
){
5247 fts3EvalInvalidatePoslist(p
->pPhrase
);
5254 int bHit1
= fts3EvalTestExpr(pCsr
, pExpr
->pLeft
, pRc
);
5255 int bHit2
= fts3EvalTestExpr(pCsr
, pExpr
->pRight
, pRc
);
5256 bHit
= bHit1
|| bHit2
;
5262 fts3EvalTestExpr(pCsr
, pExpr
->pLeft
, pRc
)
5263 && !fts3EvalTestExpr(pCsr
, pExpr
->pRight
, pRc
)
5268 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
5270 && (pExpr
->iDocid
==pCsr
->iPrevId
|| pExpr
->bDeferred
)
5272 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
5273 assert( pExpr
->bDeferred
|| pPhrase
->doclist
.bFreeList
==0 );
5274 if( pExpr
->bDeferred
){
5275 fts3EvalInvalidatePoslist(pPhrase
);
5277 *pRc
= fts3EvalDeferredPhrase(pCsr
, pPhrase
);
5278 bHit
= (pPhrase
->doclist
.pList
!=0);
5279 pExpr
->iDocid
= pCsr
->iPrevId
;
5283 bHit
= (pExpr
->bEof
==0 && pExpr
->iDocid
==pCsr
->iPrevId
);
5293 ** This function is called as the second part of each xNext operation when
5294 ** iterating through the results of a full-text query. At this point the
5295 ** cursor points to a row that matches the query expression, with the
5296 ** following caveats:
5298 ** * Up until this point, "NEAR" operators in the expression have been
5299 ** treated as "AND".
5301 ** * Deferred tokens have not yet been considered.
5303 ** If *pRc is not SQLITE_OK when this function is called, it immediately
5304 ** returns 0. Otherwise, it tests whether or not after considering NEAR
5305 ** operators and deferred tokens the current row is still a match for the
5306 ** expression. It returns 1 if both of the following are true:
5308 ** 1. *pRc is SQLITE_OK when this function returns, and
5310 ** 2. After scanning the current FTS table row for the deferred tokens,
5311 ** it is determined that the row does *not* match the query.
5313 ** Or, if no error occurs and it seems the current row does match the FTS
5316 static int fts3EvalTestDeferredAndNear(Fts3Cursor
*pCsr
, int *pRc
){
5319 if( rc
==SQLITE_OK
){
5321 /* If there are one or more deferred tokens, load the current row into
5322 ** memory and scan it to determine the position list for each deferred
5323 ** token. Then, see if this row is really a match, considering deferred
5324 ** tokens and NEAR operators (neither of which were taken into account
5325 ** earlier, by fts3EvalNextRow()).
5327 if( pCsr
->pDeferred
){
5328 rc
= fts3CursorSeek(0, pCsr
);
5329 if( rc
==SQLITE_OK
){
5330 rc
= sqlite3Fts3CacheDeferredDoclists(pCsr
);
5333 bMiss
= (0==fts3EvalTestExpr(pCsr
, pCsr
->pExpr
, &rc
));
5335 /* Free the position-lists accumulated for each deferred token above. */
5336 sqlite3Fts3FreeDeferredDoclists(pCsr
);
5339 return (rc
==SQLITE_OK
&& bMiss
);
5343 ** Advance to the next document that matches the FTS expression in
5344 ** Fts3Cursor.pExpr.
5346 static int fts3EvalNext(Fts3Cursor
*pCsr
){
5347 int rc
= SQLITE_OK
; /* Return Code */
5348 Fts3Expr
*pExpr
= pCsr
->pExpr
;
5349 assert( pCsr
->isEof
==0 );
5354 if( pCsr
->isRequireSeek
==0 ){
5355 sqlite3_reset(pCsr
->pStmt
);
5357 assert( sqlite3_data_count(pCsr
->pStmt
)==0 );
5358 fts3EvalNextRow(pCsr
, pExpr
, &rc
);
5359 pCsr
->isEof
= pExpr
->bEof
;
5360 pCsr
->isRequireSeek
= 1;
5361 pCsr
->isMatchinfoNeeded
= 1;
5362 pCsr
->iPrevId
= pExpr
->iDocid
;
5363 }while( pCsr
->isEof
==0 && fts3EvalTestDeferredAndNear(pCsr
, &rc
) );
5366 /* Check if the cursor is past the end of the docid range specified
5367 ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
5368 if( rc
==SQLITE_OK
&& (
5369 (pCsr
->bDesc
==0 && pCsr
->iPrevId
>pCsr
->iMaxDocid
)
5370 || (pCsr
->bDesc
!=0 && pCsr
->iPrevId
<pCsr
->iMinDocid
)
5379 ** Restart interation for expression pExpr so that the next call to
5380 ** fts3EvalNext() visits the first row. Do not allow incremental
5381 ** loading or merging of phrase doclists for this iteration.
5383 ** If *pRc is other than SQLITE_OK when this function is called, it is
5384 ** a no-op. If an error occurs within this function, *pRc is set to an
5385 ** SQLite error code before returning.
5387 static void fts3EvalRestart(
5392 if( pExpr
&& *pRc
==SQLITE_OK
){
5393 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
5396 fts3EvalInvalidatePoslist(pPhrase
);
5397 if( pPhrase
->bIncr
){
5399 for(i
=0; i
<pPhrase
->nToken
; i
++){
5400 Fts3PhraseToken
*pToken
= &pPhrase
->aToken
[i
];
5401 assert( pToken
->pDeferred
==0 );
5402 if( pToken
->pSegcsr
){
5403 sqlite3Fts3MsrIncrRestart(pToken
->pSegcsr
);
5406 *pRc
= fts3EvalPhraseStart(pCsr
, 0, pPhrase
);
5408 pPhrase
->doclist
.pNextDocid
= 0;
5409 pPhrase
->doclist
.iDocid
= 0;
5416 fts3EvalRestart(pCsr
, pExpr
->pLeft
, pRc
);
5417 fts3EvalRestart(pCsr
, pExpr
->pRight
, pRc
);
5422 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
5423 ** expression rooted at pExpr, the cursor iterates through all rows matched
5424 ** by pExpr, calling this function for each row. This function increments
5425 ** the values in Fts3Expr.aMI[] according to the position-list currently
5426 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
5427 ** expression nodes.
5429 static void fts3EvalUpdateCounts(Fts3Expr
*pExpr
){
5431 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
5432 if( pPhrase
&& pPhrase
->doclist
.pList
){
5434 char *p
= pPhrase
->doclist
.pList
;
5440 while( 0xFE & (*p
| c
) ){
5441 if( (c
&0x80)==0 ) iCnt
++;
5445 /* aMI[iCol*3 + 1] = Number of occurrences
5446 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
5448 pExpr
->aMI
[iCol
*3 + 1] += iCnt
;
5449 pExpr
->aMI
[iCol
*3 + 2] += (iCnt
>0);
5450 if( *p
==0x00 ) break;
5452 p
+= fts3GetVarint32(p
, &iCol
);
5456 fts3EvalUpdateCounts(pExpr
->pLeft
);
5457 fts3EvalUpdateCounts(pExpr
->pRight
);
5462 ** Expression pExpr must be of type FTSQUERY_PHRASE.
5464 ** If it is not already allocated and populated, this function allocates and
5465 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
5466 ** of a NEAR expression, then it also allocates and populates the same array
5467 ** for all other phrases that are part of the NEAR expression.
5469 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
5470 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
5472 static int fts3EvalGatherStats(
5473 Fts3Cursor
*pCsr
, /* Cursor object */
5474 Fts3Expr
*pExpr
/* FTSQUERY_PHRASE expression */
5476 int rc
= SQLITE_OK
; /* Return code */
5478 assert( pExpr
->eType
==FTSQUERY_PHRASE
);
5479 if( pExpr
->aMI
==0 ){
5480 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
5481 Fts3Expr
*pRoot
; /* Root of NEAR expression */
5482 Fts3Expr
*p
; /* Iterator used for several purposes */
5484 sqlite3_int64 iPrevId
= pCsr
->iPrevId
;
5485 sqlite3_int64 iDocid
;
5488 /* Find the root of the NEAR expression */
5490 while( pRoot
->pParent
&& pRoot
->pParent
->eType
==FTSQUERY_NEAR
){
5491 pRoot
= pRoot
->pParent
;
5493 iDocid
= pRoot
->iDocid
;
5495 assert( pRoot
->bStart
);
5497 /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
5498 for(p
=pRoot
; p
; p
=p
->pLeft
){
5499 Fts3Expr
*pE
= (p
->eType
==FTSQUERY_PHRASE
?p
:p
->pRight
);
5500 assert( pE
->aMI
==0 );
5501 pE
->aMI
= (u32
*)sqlite3_malloc(pTab
->nColumn
* 3 * sizeof(u32
));
5502 if( !pE
->aMI
) return SQLITE_NOMEM
;
5503 memset(pE
->aMI
, 0, pTab
->nColumn
* 3 * sizeof(u32
));
5506 fts3EvalRestart(pCsr
, pRoot
, &rc
);
5508 while( pCsr
->isEof
==0 && rc
==SQLITE_OK
){
5511 /* Ensure the %_content statement is reset. */
5512 if( pCsr
->isRequireSeek
==0 ) sqlite3_reset(pCsr
->pStmt
);
5513 assert( sqlite3_data_count(pCsr
->pStmt
)==0 );
5515 /* Advance to the next document */
5516 fts3EvalNextRow(pCsr
, pRoot
, &rc
);
5517 pCsr
->isEof
= pRoot
->bEof
;
5518 pCsr
->isRequireSeek
= 1;
5519 pCsr
->isMatchinfoNeeded
= 1;
5520 pCsr
->iPrevId
= pRoot
->iDocid
;
5521 }while( pCsr
->isEof
==0
5522 && pRoot
->eType
==FTSQUERY_NEAR
5523 && fts3EvalTestDeferredAndNear(pCsr
, &rc
)
5526 if( rc
==SQLITE_OK
&& pCsr
->isEof
==0 ){
5527 fts3EvalUpdateCounts(pRoot
);
5532 pCsr
->iPrevId
= iPrevId
;
5537 /* Caution: pRoot may iterate through docids in ascending or descending
5538 ** order. For this reason, even though it seems more defensive, the
5539 ** do loop can not be written:
5541 ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
5543 fts3EvalRestart(pCsr
, pRoot
, &rc
);
5545 fts3EvalNextRow(pCsr
, pRoot
, &rc
);
5546 assert( pRoot
->bEof
==0 );
5547 }while( pRoot
->iDocid
!=iDocid
&& rc
==SQLITE_OK
);
5548 fts3EvalTestDeferredAndNear(pCsr
, &rc
);
5555 ** This function is used by the matchinfo() module to query a phrase
5556 ** expression node for the following information:
5558 ** 1. The total number of occurrences of the phrase in each column of
5559 ** the FTS table (considering all rows), and
5561 ** 2. For each column, the number of rows in the table for which the
5562 ** column contains at least one instance of the phrase.
5564 ** If no error occurs, SQLITE_OK is returned and the values for each column
5565 ** written into the array aiOut as follows:
5567 ** aiOut[iCol*3 + 1] = Number of occurrences
5568 ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
5572 ** * If a phrase consists entirely of deferred tokens, then all output
5573 ** values are set to the number of documents in the table. In other
5574 ** words we assume that very common tokens occur exactly once in each
5575 ** column of each row of the table.
5577 ** * If a phrase contains some deferred tokens (and some non-deferred
5578 ** tokens), count the potential occurrence identified by considering
5579 ** the non-deferred tokens instead of actual phrase occurrences.
5581 ** * If the phrase is part of a NEAR expression, then only phrase instances
5582 ** that meet the NEAR constraint are included in the counts.
5584 int sqlite3Fts3EvalPhraseStats(
5585 Fts3Cursor
*pCsr
, /* FTS cursor handle */
5586 Fts3Expr
*pExpr
, /* Phrase expression */
5587 u32
*aiOut
/* Array to write results into (see above) */
5589 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
5593 if( pExpr
->bDeferred
&& pExpr
->pParent
->eType
!=FTSQUERY_NEAR
){
5594 assert( pCsr
->nDoc
>0 );
5595 for(iCol
=0; iCol
<pTab
->nColumn
; iCol
++){
5596 aiOut
[iCol
*3 + 1] = (u32
)pCsr
->nDoc
;
5597 aiOut
[iCol
*3 + 2] = (u32
)pCsr
->nDoc
;
5600 rc
= fts3EvalGatherStats(pCsr
, pExpr
);
5601 if( rc
==SQLITE_OK
){
5602 assert( pExpr
->aMI
);
5603 for(iCol
=0; iCol
<pTab
->nColumn
; iCol
++){
5604 aiOut
[iCol
*3 + 1] = pExpr
->aMI
[iCol
*3 + 1];
5605 aiOut
[iCol
*3 + 2] = pExpr
->aMI
[iCol
*3 + 2];
5614 ** The expression pExpr passed as the second argument to this function
5615 ** must be of type FTSQUERY_PHRASE.
5617 ** The returned value is either NULL or a pointer to a buffer containing
5618 ** a position-list indicating the occurrences of the phrase in column iCol
5619 ** of the current row.
5621 ** More specifically, the returned buffer contains 1 varint for each
5622 ** occurrence of the phrase in the column, stored using the normal (delta+2)
5623 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
5624 ** if the requested column contains "a b X c d X X" and the position-list
5625 ** for 'X' is requested, the buffer returned may contain:
5627 ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
5629 ** This function works regardless of whether or not the phrase is deferred,
5630 ** incremental, or neither.
5632 int sqlite3Fts3EvalPhrasePoslist(
5633 Fts3Cursor
*pCsr
, /* FTS3 cursor object */
5634 Fts3Expr
*pExpr
, /* Phrase to return doclist for */
5635 int iCol
, /* Column to return position list for */
5636 char **ppOut
/* OUT: Pointer to position list */
5638 Fts3Phrase
*pPhrase
= pExpr
->pPhrase
;
5639 Fts3Table
*pTab
= (Fts3Table
*)pCsr
->base
.pVtab
;
5642 sqlite3_int64 iDocid
;
5644 /* If this phrase is applies specifically to some column other than
5645 ** column iCol, return a NULL pointer. */
5647 assert( iCol
>=0 && iCol
<pTab
->nColumn
);
5648 if( (pPhrase
->iColumn
<pTab
->nColumn
&& pPhrase
->iColumn
!=iCol
) ){
5652 iDocid
= pExpr
->iDocid
;
5653 pIter
= pPhrase
->doclist
.pList
;
5654 if( iDocid
!=pCsr
->iPrevId
|| pExpr
->bEof
){
5655 int bDescDoclist
= pTab
->bDescIdx
; /* For DOCID_CMP macro */
5656 int iMul
; /* +1 if csr dir matches index dir, else -1 */
5660 Fts3Expr
*p
; /* Used to iterate from pExpr to root */
5661 Fts3Expr
*pNear
; /* Most senior NEAR ancestor (or pExpr) */
5663 /* Check if this phrase descends from an OR expression node. If not,
5664 ** return NULL. Otherwise, the entry that corresponds to docid
5665 ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
5666 ** tree that the node is part of has been marked as EOF, but the node
5667 ** itself is not EOF, then it may point to an earlier entry. */
5669 for(p
=pExpr
->pParent
; p
; p
=p
->pParent
){
5670 if( p
->eType
==FTSQUERY_OR
) bOr
= 1;
5671 if( p
->eType
==FTSQUERY_NEAR
) pNear
= p
;
5672 if( p
->bEof
) bTreeEof
= 1;
5674 if( bOr
==0 ) return SQLITE_OK
;
5676 /* This is the descendent of an OR node. In this case we cannot use
5677 ** an incremental phrase. Load the entire doclist for the phrase
5678 ** into memory in this case. */
5679 if( pPhrase
->bIncr
){
5681 int bEofSave
= pExpr
->bEof
;
5682 fts3EvalRestart(pCsr
, pExpr
, &rc
);
5683 while( rc
==SQLITE_OK
&& !pExpr
->bEof
){
5684 fts3EvalNextRow(pCsr
, pExpr
, &rc
);
5685 if( bEofSave
==0 && pExpr
->iDocid
==iDocid
) break;
5687 pIter
= pPhrase
->doclist
.pList
;
5688 assert( rc
!=SQLITE_OK
|| pPhrase
->bIncr
==0 );
5689 if( rc
!=SQLITE_OK
) return rc
;
5692 iMul
= ((pCsr
->bDesc
==bDescDoclist
) ? 1 : -1);
5695 && (DOCID_CMP(pNear
->iDocid
, pCsr
->iPrevId
) * iMul
)<0
5698 fts3EvalNextRow(pCsr
, pExpr
, &rc
);
5699 if( rc
!=SQLITE_OK
) return rc
;
5700 iDocid
= pExpr
->iDocid
;
5701 pIter
= pPhrase
->doclist
.pList
;
5704 bEof
= (pPhrase
->doclist
.nAll
==0);
5705 assert( bDescDoclist
==0 || bDescDoclist
==1 );
5706 assert( pCsr
->bDesc
==0 || pCsr
->bDesc
==1 );
5709 if( pCsr
->bDesc
==bDescDoclist
){
5712 /* This expression is already at EOF. So position it to point to the
5713 ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
5714 ** iDocid is already set for this entry, so all that is required is
5715 ** to set pIter to point to the first byte of the last position-list
5718 ** It would also be correct to set pIter and iDocid to zero. In
5719 ** this case, the first call to sqltie3Fts4DoclistPrev() below
5720 ** would also move the iterator to point to the last entry in the
5721 ** doclist. However, this is expensive, as to do so it has to
5722 ** iterate through the entire doclist from start to finish (since
5723 ** it does not know the docid for the last entry). */
5724 pIter
= &pPhrase
->doclist
.aAll
[pPhrase
->doclist
.nAll
-1];
5725 fts3ReversePoslist(pPhrase
->doclist
.aAll
, &pIter
);
5727 while( (pIter
==0 || DOCID_CMP(iDocid
, pCsr
->iPrevId
)>0 ) && bEof
==0 ){
5728 sqlite3Fts3DoclistPrev(
5729 bDescDoclist
, pPhrase
->doclist
.aAll
, pPhrase
->doclist
.nAll
,
5730 &pIter
, &iDocid
, &dummy
, &bEof
5738 while( (pIter
==0 || DOCID_CMP(iDocid
, pCsr
->iPrevId
)<0 ) && bEof
==0 ){
5739 sqlite3Fts3DoclistNext(
5740 bDescDoclist
, pPhrase
->doclist
.aAll
, pPhrase
->doclist
.nAll
,
5741 &pIter
, &iDocid
, &bEof
5747 if( bEof
|| iDocid
!=pCsr
->iPrevId
) pIter
= 0;
5749 if( pIter
==0 ) return SQLITE_OK
;
5753 pIter
+= fts3GetVarint32(pIter
, &iThis
);
5757 while( iThis
<iCol
){
5758 fts3ColumnlistCopy(0, &pIter
);
5759 if( *pIter
==0x00 ) return 0;
5761 pIter
+= fts3GetVarint32(pIter
, &iThis
);
5764 *ppOut
= ((iCol
==iThis
)?pIter
:0);
5769 ** Free all components of the Fts3Phrase structure that were allocated by
5770 ** the eval module. Specifically, this means to free:
5772 ** * the contents of pPhrase->doclist, and
5773 ** * any Fts3MultiSegReader objects held by phrase tokens.
5775 void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase
*pPhrase
){
5778 sqlite3_free(pPhrase
->doclist
.aAll
);
5779 fts3EvalInvalidatePoslist(pPhrase
);
5780 memset(&pPhrase
->doclist
, 0, sizeof(Fts3Doclist
));
5781 for(i
=0; i
<pPhrase
->nToken
; i
++){
5782 fts3SegReaderCursorFree(pPhrase
->aToken
[i
].pSegcsr
);
5783 pPhrase
->aToken
[i
].pSegcsr
= 0;
5790 ** Return SQLITE_CORRUPT_VTAB.
5793 int sqlite3Fts3Corrupt(){
5794 return SQLITE_CORRUPT_VTAB
;
5800 ** Initialize API pointer table, if required.
5803 __declspec(dllexport
)
5805 int sqlite3_fts3_init(
5808 const sqlite3_api_routines
*pApi
5810 SQLITE_EXTENSION_INIT2(pApi
)
5811 return sqlite3Fts3Init(db
);