xref: /sqlite-3.40.0/ext/fts3/fts3_write.c (revision 962f9669)
1 /*
2 ** 2009 Oct 23
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 ******************************************************************************
12 **
13 ** This file is part of the SQLite FTS3 extension module. Specifically,
14 ** this file contains code to insert, update and delete rows from FTS3
15 ** tables. It also contains code to merge FTS3 b-tree segments. Some
16 ** of the sub-routines used to merge segments are also used by the query
17 ** code in fts3.c.
18 */
19 
20 #include "fts3Int.h"
21 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
22 
23 #include <string.h>
24 #include <assert.h>
25 #include <stdlib.h>
26 
27 
28 #define FTS_MAX_APPENDABLE_HEIGHT 16
29 
30 /*
31 ** When full-text index nodes are loaded from disk, the buffer that they
32 ** are loaded into has the following number of bytes of padding at the end
33 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
34 ** of 920 bytes is allocated for it.
35 **
36 ** This means that if we have a pointer into a buffer containing node data,
37 ** it is always safe to read up to two varints from it without risking an
38 ** overread, even if the node data is corrupted.
39 */
40 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
41 
42 /*
43 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
44 ** memory incrementally instead of all at once. This can be a big performance
45 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
46 ** method before retrieving all query results (as may happen, for example,
47 ** if a query has a LIMIT clause).
48 **
49 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
50 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
51 ** The code is written so that the hard lower-limit for each of these values
52 ** is 1. Clearly such small values would be inefficient, but can be useful
53 ** for testing purposes.
54 **
55 ** If this module is built with SQLITE_TEST defined, these constants may
56 ** be overridden at runtime for testing purposes. File fts3_test.c contains
57 ** a Tcl interface to read and write the values.
58 */
59 #ifdef SQLITE_TEST
60 int test_fts3_node_chunksize = (4*1024);
61 int test_fts3_node_chunk_threshold = (4*1024)*4;
62 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
63 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
64 #else
65 # define FTS3_NODE_CHUNKSIZE (4*1024)
66 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
67 #endif
68 
69 /*
70 ** The two values that may be meaningfully bound to the :1 parameter in
71 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
72 */
73 #define FTS_STAT_DOCTOTAL      0
74 #define FTS_STAT_INCRMERGEHINT 1
75 #define FTS_STAT_AUTOINCRMERGE 2
76 
77 /*
78 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
79 ** and incremental merge operation that takes place. This is used for
80 ** debugging FTS only, it should not usually be turned on in production
81 ** systems.
82 */
83 #ifdef FTS3_LOG_MERGES
84 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
85   sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
86 }
87 #else
88 #define fts3LogMerge(x, y)
89 #endif
90 
91 
92 typedef struct PendingList PendingList;
93 typedef struct SegmentNode SegmentNode;
94 typedef struct SegmentWriter SegmentWriter;
95 
96 /*
97 ** An instance of the following data structure is used to build doclists
98 ** incrementally. See function fts3PendingListAppend() for details.
99 */
100 struct PendingList {
101   int nData;
102   char *aData;
103   int nSpace;
104   sqlite3_int64 iLastDocid;
105   sqlite3_int64 iLastCol;
106   sqlite3_int64 iLastPos;
107 };
108 
109 
110 /*
111 ** Each cursor has a (possibly empty) linked list of the following objects.
112 */
113 struct Fts3DeferredToken {
114   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
115   int iCol;                       /* Column token must occur in */
116   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
117   PendingList *pList;             /* Doclist is assembled here */
118 };
119 
120 /*
121 ** An instance of this structure is used to iterate through the terms on
122 ** a contiguous set of segment b-tree leaf nodes. Although the details of
123 ** this structure are only manipulated by code in this file, opaque handles
124 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
125 ** terms when querying the full-text index. See functions:
126 **
127 **   sqlite3Fts3SegReaderNew()
128 **   sqlite3Fts3SegReaderFree()
129 **   sqlite3Fts3SegReaderIterate()
130 **
131 ** Methods used to manipulate Fts3SegReader structures:
132 **
133 **   fts3SegReaderNext()
134 **   fts3SegReaderFirstDocid()
135 **   fts3SegReaderNextDocid()
136 */
137 struct Fts3SegReader {
138   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
139   u8 bLookup;                     /* True for a lookup only */
140   u8 rootOnly;                    /* True for a root-only reader */
141 
142   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
143   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
144   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
145   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
146 
147   char *aNode;                    /* Pointer to node data (or NULL) */
148   int nNode;                      /* Size of buffer at aNode (or 0) */
149   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
150   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
151 
152   Fts3HashElem **ppNextElem;
153 
154   /* Variables set by fts3SegReaderNext(). These may be read directly
155   ** by the caller. They are valid from the time SegmentReaderNew() returns
156   ** until SegmentReaderNext() returns something other than SQLITE_OK
157   ** (i.e. SQLITE_DONE).
158   */
159   int nTerm;                      /* Number of bytes in current term */
160   char *zTerm;                    /* Pointer to current term */
161   int nTermAlloc;                 /* Allocated size of zTerm buffer */
162   char *aDoclist;                 /* Pointer to doclist of current entry */
163   int nDoclist;                   /* Size of doclist in current entry */
164 
165   /* The following variables are used by fts3SegReaderNextDocid() to iterate
166   ** through the current doclist (aDoclist/nDoclist).
167   */
168   char *pOffsetList;
169   int nOffsetList;                /* For descending pending seg-readers only */
170   sqlite3_int64 iDocid;
171 };
172 
173 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
174 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
175 
176 /*
177 ** An instance of this structure is used to create a segment b-tree in the
178 ** database. The internal details of this type are only accessed by the
179 ** following functions:
180 **
181 **   fts3SegWriterAdd()
182 **   fts3SegWriterFlush()
183 **   fts3SegWriterFree()
184 */
185 struct SegmentWriter {
186   SegmentNode *pTree;             /* Pointer to interior tree structure */
187   sqlite3_int64 iFirst;           /* First slot in %_segments written */
188   sqlite3_int64 iFree;            /* Next free slot in %_segments */
189   char *zTerm;                    /* Pointer to previous term buffer */
190   int nTerm;                      /* Number of bytes in zTerm */
191   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
192   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
193   int nSize;                      /* Size of allocation at aData */
194   int nData;                      /* Bytes of data in aData */
195   char *aData;                    /* Pointer to block from malloc() */
196 };
197 
198 /*
199 ** Type SegmentNode is used by the following three functions to create
200 ** the interior part of the segment b+-tree structures (everything except
201 ** the leaf nodes). These functions and type are only ever used by code
202 ** within the fts3SegWriterXXX() family of functions described above.
203 **
204 **   fts3NodeAddTerm()
205 **   fts3NodeWrite()
206 **   fts3NodeFree()
207 **
208 ** When a b+tree is written to the database (either as a result of a merge
209 ** or the pending-terms table being flushed), leaves are written into the
210 ** database file as soon as they are completely populated. The interior of
211 ** the tree is assembled in memory and written out only once all leaves have
212 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
213 ** very large, meaning that the interior of the tree consumes relatively
214 ** little memory.
215 */
216 struct SegmentNode {
217   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
218   SegmentNode *pRight;            /* Pointer to right-sibling */
219   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
220   int nEntry;                     /* Number of terms written to node so far */
221   char *zTerm;                    /* Pointer to previous term buffer */
222   int nTerm;                      /* Number of bytes in zTerm */
223   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
224   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
225   int nData;                      /* Bytes of valid data so far */
226   char *aData;                    /* Node data */
227 };
228 
229 /*
230 ** Valid values for the second argument to fts3SqlStmt().
231 */
232 #define SQL_DELETE_CONTENT             0
233 #define SQL_IS_EMPTY                   1
234 #define SQL_DELETE_ALL_CONTENT         2
235 #define SQL_DELETE_ALL_SEGMENTS        3
236 #define SQL_DELETE_ALL_SEGDIR          4
237 #define SQL_DELETE_ALL_DOCSIZE         5
238 #define SQL_DELETE_ALL_STAT            6
239 #define SQL_SELECT_CONTENT_BY_ROWID    7
240 #define SQL_NEXT_SEGMENT_INDEX         8
241 #define SQL_INSERT_SEGMENTS            9
242 #define SQL_NEXT_SEGMENTS_ID          10
243 #define SQL_INSERT_SEGDIR             11
244 #define SQL_SELECT_LEVEL              12
245 #define SQL_SELECT_LEVEL_RANGE        13
246 #define SQL_SELECT_LEVEL_COUNT        14
247 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
248 #define SQL_DELETE_SEGDIR_LEVEL       16
249 #define SQL_DELETE_SEGMENTS_RANGE     17
250 #define SQL_CONTENT_INSERT            18
251 #define SQL_DELETE_DOCSIZE            19
252 #define SQL_REPLACE_DOCSIZE           20
253 #define SQL_SELECT_DOCSIZE            21
254 #define SQL_SELECT_STAT               22
255 #define SQL_REPLACE_STAT              23
256 
257 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
258 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
259 #define SQL_DELETE_SEGDIR_RANGE       26
260 #define SQL_SELECT_ALL_LANGID         27
261 #define SQL_FIND_MERGE_LEVEL          28
262 #define SQL_MAX_LEAF_NODE_ESTIMATE    29
263 #define SQL_DELETE_SEGDIR_ENTRY       30
264 #define SQL_SHIFT_SEGDIR_ENTRY        31
265 #define SQL_SELECT_SEGDIR             32
266 #define SQL_CHOMP_SEGDIR              33
267 #define SQL_SEGMENT_IS_APPENDABLE     34
268 #define SQL_SELECT_INDEXES            35
269 #define SQL_SELECT_MXLEVEL            36
270 
271 /*
272 ** This function is used to obtain an SQLite prepared statement handle
273 ** for the statement identified by the second argument. If successful,
274 ** *pp is set to the requested statement handle and SQLITE_OK returned.
275 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
276 **
277 ** If argument apVal is not NULL, then it must point to an array with
278 ** at least as many entries as the requested statement has bound
279 ** parameters. The values are bound to the statements parameters before
280 ** returning.
281 */
282 static int fts3SqlStmt(
283   Fts3Table *p,                   /* Virtual table handle */
284   int eStmt,                      /* One of the SQL_XXX constants above */
285   sqlite3_stmt **pp,              /* OUT: Statement handle */
286   sqlite3_value **apVal           /* Values to bind to statement */
287 ){
288   const char *azSql[] = {
289 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
290 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
291 /* 2  */  "DELETE FROM %Q.'%q_content'",
292 /* 3  */  "DELETE FROM %Q.'%q_segments'",
293 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
294 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
295 /* 6  */  "DELETE FROM %Q.'%q_stat'",
296 /* 7  */  "SELECT %s WHERE rowid=?",
297 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
298 /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
299 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
300 /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
301 
302           /* Return segments in order from oldest to newest.*/
303 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
304             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
305 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
306             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
307             "ORDER BY level DESC, idx ASC",
308 
309 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
310 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
311 
312 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
313 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
314 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
315 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
316 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
317 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
318 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
319 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
320 /* 24 */  "",
321 /* 25 */  "",
322 
323 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
324 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
325 
326 /* This statement is used to determine which level to read the input from
327 ** when performing an incremental merge. It returns the absolute level number
328 ** of the oldest level in the db that contains at least ? segments. Or,
329 ** if no level in the FTS index contains more than ? segments, the statement
330 ** returns zero rows.  */
331 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
332          "  ORDER BY (level %% 1024) ASC LIMIT 1",
333 
334 /* Estimate the upper limit on the number of leaf nodes in a new segment
335 ** created by merging the oldest :2 segments from absolute level :1. See
336 ** function sqlite3Fts3Incrmerge() for details.  */
337 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
338          "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
339 
340 /* SQL_DELETE_SEGDIR_ENTRY
341 **   Delete the %_segdir entry on absolute level :1 with index :2.  */
342 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
343 
344 /* SQL_SHIFT_SEGDIR_ENTRY
345 **   Modify the idx value for the segment with idx=:3 on absolute level :2
346 **   to :1.  */
347 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
348 
349 /* SQL_SELECT_SEGDIR
350 **   Read a single entry from the %_segdir table. The entry from absolute
351 **   level :1 with index value :2.  */
352 /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
353             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
354 
355 /* SQL_CHOMP_SEGDIR
356 **   Update the start_block (:1) and root (:2) fields of the %_segdir
357 **   entry located on absolute level :3 with index :4.  */
358 /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
359             "WHERE level = ? AND idx = ?",
360 
361 /* SQL_SEGMENT_IS_APPENDABLE
362 **   Return a single row if the segment with end_block=? is appendable. Or
363 **   no rows otherwise.  */
364 /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
365 
366 /* SQL_SELECT_INDEXES
367 **   Return the list of valid segment indexes for absolute level ?  */
368 /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
369 
370 /* SQL_SELECT_MXLEVEL
371 **   Return the largest relative level in the FTS index or indexes.  */
372 /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
373   };
374   int rc = SQLITE_OK;
375   sqlite3_stmt *pStmt;
376 
377   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
378   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
379 
380   pStmt = p->aStmt[eStmt];
381   if( !pStmt ){
382     char *zSql;
383     if( eStmt==SQL_CONTENT_INSERT ){
384       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
385     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
386       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
387     }else{
388       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
389     }
390     if( !zSql ){
391       rc = SQLITE_NOMEM;
392     }else{
393       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
394       sqlite3_free(zSql);
395       assert( rc==SQLITE_OK || pStmt==0 );
396       p->aStmt[eStmt] = pStmt;
397     }
398   }
399   if( apVal ){
400     int i;
401     int nParam = sqlite3_bind_parameter_count(pStmt);
402     for(i=0; rc==SQLITE_OK && i<nParam; i++){
403       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
404     }
405   }
406   *pp = pStmt;
407   return rc;
408 }
409 
410 
411 static int fts3SelectDocsize(
412   Fts3Table *pTab,                /* FTS3 table handle */
413   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
414   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
415 ){
416   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
417   int rc;                         /* Return code */
418 
419   rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
420   if( rc==SQLITE_OK ){
421     sqlite3_bind_int64(pStmt, 1, iDocid);
422     rc = sqlite3_step(pStmt);
423     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
424       rc = sqlite3_reset(pStmt);
425       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
426       pStmt = 0;
427     }else{
428       rc = SQLITE_OK;
429     }
430   }
431 
432   *ppStmt = pStmt;
433   return rc;
434 }
435 
436 int sqlite3Fts3SelectDoctotal(
437   Fts3Table *pTab,                /* Fts3 table handle */
438   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
439 ){
440   sqlite3_stmt *pStmt = 0;
441   int rc;
442   rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
443   if( rc==SQLITE_OK ){
444     sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
445     if( sqlite3_step(pStmt)!=SQLITE_ROW
446      || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
447     ){
448       rc = sqlite3_reset(pStmt);
449       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
450       pStmt = 0;
451     }
452   }
453   *ppStmt = pStmt;
454   return rc;
455 }
456 
457 int sqlite3Fts3SelectDocsize(
458   Fts3Table *pTab,                /* Fts3 table handle */
459   sqlite3_int64 iDocid,           /* Docid to read size data for */
460   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
461 ){
462   return fts3SelectDocsize(pTab, iDocid, ppStmt);
463 }
464 
465 /*
466 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
467 ** array apVal[] to the SQL statement identified by eStmt, the statement
468 ** is executed.
469 **
470 ** Returns SQLITE_OK if the statement is successfully executed, or an
471 ** SQLite error code otherwise.
472 */
473 static void fts3SqlExec(
474   int *pRC,                /* Result code */
475   Fts3Table *p,            /* The FTS3 table */
476   int eStmt,               /* Index of statement to evaluate */
477   sqlite3_value **apVal    /* Parameters to bind */
478 ){
479   sqlite3_stmt *pStmt;
480   int rc;
481   if( *pRC ) return;
482   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
483   if( rc==SQLITE_OK ){
484     sqlite3_step(pStmt);
485     rc = sqlite3_reset(pStmt);
486   }
487   *pRC = rc;
488 }
489 
490 
491 /*
492 ** This function ensures that the caller has obtained an exclusive
493 ** shared-cache table-lock on the %_segdir table. This is required before
494 ** writing data to the fts3 table. If this lock is not acquired first, then
495 ** the caller may end up attempting to take this lock as part of committing
496 ** a transaction, causing SQLite to return SQLITE_LOCKED or
497 ** LOCKED_SHAREDCACHEto a COMMIT command.
498 **
499 ** It is best to avoid this because if FTS3 returns any error when
500 ** committing a transaction, the whole transaction will be rolled back.
501 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
502 ** It can still happen if the user locks the underlying tables directly
503 ** instead of accessing them via FTS.
504 */
505 static int fts3Writelock(Fts3Table *p){
506   int rc = SQLITE_OK;
507 
508   if( p->nPendingData==0 ){
509     sqlite3_stmt *pStmt;
510     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
511     if( rc==SQLITE_OK ){
512       sqlite3_bind_null(pStmt, 1);
513       sqlite3_step(pStmt);
514       rc = sqlite3_reset(pStmt);
515     }
516   }
517 
518   return rc;
519 }
520 
521 /*
522 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
523 ** Within each language id, a separate index is maintained to store the
524 ** document terms, and each configured prefix size (configured the FTS
525 ** "prefix=" option). And each index consists of multiple levels ("relative
526 ** levels").
527 **
528 ** All three of these values (the language id, the specific index and the
529 ** level within the index) are encoded in 64-bit integer values stored
530 ** in the %_segdir table on disk. This function is used to convert three
531 ** separate component values into the single 64-bit integer value that
532 ** can be used to query the %_segdir table.
533 **
534 ** Specifically, each language-id/index combination is allocated 1024
535 ** 64-bit integer level values ("absolute levels"). The main terms index
536 ** for language-id 0 is allocate values 0-1023. The first prefix index
537 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
538 ** Language 1 indexes are allocated immediately following language 0.
539 **
540 ** So, for a system with nPrefix prefix indexes configured, the block of
541 ** absolute levels that corresponds to language-id iLangid and index
542 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
543 */
544 static sqlite3_int64 getAbsoluteLevel(
545   Fts3Table *p,                   /* FTS3 table handle */
546   int iLangid,                    /* Language id */
547   int iIndex,                     /* Index in p->aIndex[] */
548   int iLevel                      /* Level of segments */
549 ){
550   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
551   assert( iLangid>=0 );
552   assert( p->nIndex>0 );
553   assert( iIndex>=0 && iIndex<p->nIndex );
554 
555   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
556   return iBase + iLevel;
557 }
558 
559 /*
560 ** Set *ppStmt to a statement handle that may be used to iterate through
561 ** all rows in the %_segdir table, from oldest to newest. If successful,
562 ** return SQLITE_OK. If an error occurs while preparing the statement,
563 ** return an SQLite error code.
564 **
565 ** There is only ever one instance of this SQL statement compiled for
566 ** each FTS3 table.
567 **
568 ** The statement returns the following columns from the %_segdir table:
569 **
570 **   0: idx
571 **   1: start_block
572 **   2: leaves_end_block
573 **   3: end_block
574 **   4: root
575 */
576 int sqlite3Fts3AllSegdirs(
577   Fts3Table *p,                   /* FTS3 table */
578   int iLangid,                    /* Language being queried */
579   int iIndex,                     /* Index for p->aIndex[] */
580   int iLevel,                     /* Level to select (relative level) */
581   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
582 ){
583   int rc;
584   sqlite3_stmt *pStmt = 0;
585 
586   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
587   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
588   assert( iIndex>=0 && iIndex<p->nIndex );
589 
590   if( iLevel<0 ){
591     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
592     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
593     if( rc==SQLITE_OK ){
594       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
595       sqlite3_bind_int64(pStmt, 2,
596           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
597       );
598     }
599   }else{
600     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
601     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
602     if( rc==SQLITE_OK ){
603       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
604     }
605   }
606   *ppStmt = pStmt;
607   return rc;
608 }
609 
610 
611 /*
612 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
613 ** if successful, or an SQLite error code otherwise.
614 **
615 ** This function also serves to allocate the PendingList structure itself.
616 ** For example, to create a new PendingList structure containing two
617 ** varints:
618 **
619 **   PendingList *p = 0;
620 **   fts3PendingListAppendVarint(&p, 1);
621 **   fts3PendingListAppendVarint(&p, 2);
622 */
623 static int fts3PendingListAppendVarint(
624   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
625   sqlite3_int64 i                 /* Value to append to data */
626 ){
627   PendingList *p = *pp;
628 
629   /* Allocate or grow the PendingList as required. */
630   if( !p ){
631     p = sqlite3_malloc(sizeof(*p) + 100);
632     if( !p ){
633       return SQLITE_NOMEM;
634     }
635     p->nSpace = 100;
636     p->aData = (char *)&p[1];
637     p->nData = 0;
638   }
639   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
640     int nNew = p->nSpace * 2;
641     p = sqlite3_realloc(p, sizeof(*p) + nNew);
642     if( !p ){
643       sqlite3_free(*pp);
644       *pp = 0;
645       return SQLITE_NOMEM;
646     }
647     p->nSpace = nNew;
648     p->aData = (char *)&p[1];
649   }
650 
651   /* Append the new serialized varint to the end of the list. */
652   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
653   p->aData[p->nData] = '\0';
654   *pp = p;
655   return SQLITE_OK;
656 }
657 
658 /*
659 ** Add a docid/column/position entry to a PendingList structure. Non-zero
660 ** is returned if the structure is sqlite3_realloced as part of adding
661 ** the entry. Otherwise, zero.
662 **
663 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
664 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
665 ** it is set to SQLITE_OK.
666 */
667 static int fts3PendingListAppend(
668   PendingList **pp,               /* IN/OUT: PendingList structure */
669   sqlite3_int64 iDocid,           /* Docid for entry to add */
670   sqlite3_int64 iCol,             /* Column for entry to add */
671   sqlite3_int64 iPos,             /* Position of term for entry to add */
672   int *pRc                        /* OUT: Return code */
673 ){
674   PendingList *p = *pp;
675   int rc = SQLITE_OK;
676 
677   assert( !p || p->iLastDocid<=iDocid );
678 
679   if( !p || p->iLastDocid!=iDocid ){
680     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
681     if( p ){
682       assert( p->nData<p->nSpace );
683       assert( p->aData[p->nData]==0 );
684       p->nData++;
685     }
686     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
687       goto pendinglistappend_out;
688     }
689     p->iLastCol = -1;
690     p->iLastPos = 0;
691     p->iLastDocid = iDocid;
692   }
693   if( iCol>0 && p->iLastCol!=iCol ){
694     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
695      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
696     ){
697       goto pendinglistappend_out;
698     }
699     p->iLastCol = iCol;
700     p->iLastPos = 0;
701   }
702   if( iCol>=0 ){
703     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
704     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
705     if( rc==SQLITE_OK ){
706       p->iLastPos = iPos;
707     }
708   }
709 
710  pendinglistappend_out:
711   *pRc = rc;
712   if( p!=*pp ){
713     *pp = p;
714     return 1;
715   }
716   return 0;
717 }
718 
719 /*
720 ** Free a PendingList object allocated by fts3PendingListAppend().
721 */
722 static void fts3PendingListDelete(PendingList *pList){
723   sqlite3_free(pList);
724 }
725 
726 /*
727 ** Add an entry to one of the pending-terms hash tables.
728 */
729 static int fts3PendingTermsAddOne(
730   Fts3Table *p,
731   int iCol,
732   int iPos,
733   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
734   const char *zToken,
735   int nToken
736 ){
737   PendingList *pList;
738   int rc = SQLITE_OK;
739 
740   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
741   if( pList ){
742     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
743   }
744   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
745     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
746       /* Malloc failed while inserting the new entry. This can only
747       ** happen if there was no previous entry for this token.
748       */
749       assert( 0==fts3HashFind(pHash, zToken, nToken) );
750       sqlite3_free(pList);
751       rc = SQLITE_NOMEM;
752     }
753   }
754   if( rc==SQLITE_OK ){
755     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
756   }
757   return rc;
758 }
759 
760 /*
761 ** Tokenize the nul-terminated string zText and add all tokens to the
762 ** pending-terms hash-table. The docid used is that currently stored in
763 ** p->iPrevDocid, and the column is specified by argument iCol.
764 **
765 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
766 */
767 static int fts3PendingTermsAdd(
768   Fts3Table *p,                   /* Table into which text will be inserted */
769   int iLangid,                    /* Language id to use */
770   const char *zText,              /* Text of document to be inserted */
771   int iCol,                       /* Column into which text is being inserted */
772   u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
773 ){
774   int rc;
775   int iStart = 0;
776   int iEnd = 0;
777   int iPos = 0;
778   int nWord = 0;
779 
780   char const *zToken;
781   int nToken = 0;
782 
783   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
784   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
785   sqlite3_tokenizer_cursor *pCsr;
786   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
787       const char**,int*,int*,int*,int*);
788 
789   assert( pTokenizer && pModule );
790 
791   /* If the user has inserted a NULL value, this function may be called with
792   ** zText==0. In this case, add zero token entries to the hash table and
793   ** return early. */
794   if( zText==0 ){
795     *pnWord = 0;
796     return SQLITE_OK;
797   }
798 
799   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
800   if( rc!=SQLITE_OK ){
801     return rc;
802   }
803 
804   xNext = pModule->xNext;
805   while( SQLITE_OK==rc
806       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
807   ){
808     int i;
809     if( iPos>=nWord ) nWord = iPos+1;
810 
811     /* Positions cannot be negative; we use -1 as a terminator internally.
812     ** Tokens must have a non-zero length.
813     */
814     if( iPos<0 || !zToken || nToken<=0 ){
815       rc = SQLITE_ERROR;
816       break;
817     }
818 
819     /* Add the term to the terms index */
820     rc = fts3PendingTermsAddOne(
821         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
822     );
823 
824     /* Add the term to each of the prefix indexes that it is not too
825     ** short for. */
826     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
827       struct Fts3Index *pIndex = &p->aIndex[i];
828       if( nToken<pIndex->nPrefix ) continue;
829       rc = fts3PendingTermsAddOne(
830           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
831       );
832     }
833   }
834 
835   pModule->xClose(pCsr);
836   *pnWord += nWord;
837   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
838 }
839 
840 /*
841 ** Calling this function indicates that subsequent calls to
842 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
843 ** contents of the document with docid iDocid.
844 */
845 static int fts3PendingTermsDocid(
846   Fts3Table *p,                   /* Full-text table handle */
847   int iLangid,                    /* Language id of row being written */
848   sqlite_int64 iDocid             /* Docid of row being written */
849 ){
850   assert( iLangid>=0 );
851 
852   /* TODO(shess) Explore whether partially flushing the buffer on
853   ** forced-flush would provide better performance.  I suspect that if
854   ** we ordered the doclists by size and flushed the largest until the
855   ** buffer was half empty, that would let the less frequent terms
856   ** generate longer doclists.
857   */
858   if( iDocid<=p->iPrevDocid
859    || p->iPrevLangid!=iLangid
860    || p->nPendingData>p->nMaxPendingData
861   ){
862     int rc = sqlite3Fts3PendingTermsFlush(p);
863     if( rc!=SQLITE_OK ) return rc;
864   }
865   p->iPrevDocid = iDocid;
866   p->iPrevLangid = iLangid;
867   return SQLITE_OK;
868 }
869 
870 /*
871 ** Discard the contents of the pending-terms hash tables.
872 */
873 void sqlite3Fts3PendingTermsClear(Fts3Table *p){
874   int i;
875   for(i=0; i<p->nIndex; i++){
876     Fts3HashElem *pElem;
877     Fts3Hash *pHash = &p->aIndex[i].hPending;
878     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
879       PendingList *pList = (PendingList *)fts3HashData(pElem);
880       fts3PendingListDelete(pList);
881     }
882     fts3HashClear(pHash);
883   }
884   p->nPendingData = 0;
885 }
886 
887 /*
888 ** This function is called by the xUpdate() method as part of an INSERT
889 ** operation. It adds entries for each term in the new record to the
890 ** pendingTerms hash table.
891 **
892 ** Argument apVal is the same as the similarly named argument passed to
893 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
894 */
895 static int fts3InsertTerms(
896   Fts3Table *p,
897   int iLangid,
898   sqlite3_value **apVal,
899   u32 *aSz
900 ){
901   int i;                          /* Iterator variable */
902   for(i=2; i<p->nColumn+2; i++){
903     int iCol = i-2;
904     if( p->abNotindexed[iCol]==0 ){
905       const char *zText = (const char *)sqlite3_value_text(apVal[i]);
906       int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
907       if( rc!=SQLITE_OK ){
908         return rc;
909       }
910       aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
911     }
912   }
913   return SQLITE_OK;
914 }
915 
916 /*
917 ** This function is called by the xUpdate() method for an INSERT operation.
918 ** The apVal parameter is passed a copy of the apVal argument passed by
919 ** SQLite to the xUpdate() method. i.e:
920 **
921 **   apVal[0]                Not used for INSERT.
922 **   apVal[1]                rowid
923 **   apVal[2]                Left-most user-defined column
924 **   ...
925 **   apVal[p->nColumn+1]     Right-most user-defined column
926 **   apVal[p->nColumn+2]     Hidden column with same name as table
927 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
928 **   apVal[p->nColumn+4]     Hidden languageid column
929 */
930 static int fts3InsertData(
931   Fts3Table *p,                   /* Full-text table */
932   sqlite3_value **apVal,          /* Array of values to insert */
933   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
934 ){
935   int rc;                         /* Return code */
936   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
937 
938   if( p->zContentTbl ){
939     sqlite3_value *pRowid = apVal[p->nColumn+3];
940     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
941       pRowid = apVal[1];
942     }
943     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
944       return SQLITE_CONSTRAINT;
945     }
946     *piDocid = sqlite3_value_int64(pRowid);
947     return SQLITE_OK;
948   }
949 
950   /* Locate the statement handle used to insert data into the %_content
951   ** table. The SQL for this statement is:
952   **
953   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
954   **
955   ** The statement features N '?' variables, where N is the number of user
956   ** defined columns in the FTS3 table, plus one for the docid field.
957   */
958   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
959   if( rc==SQLITE_OK && p->zLanguageid ){
960     rc = sqlite3_bind_int(
961         pContentInsert, p->nColumn+2,
962         sqlite3_value_int(apVal[p->nColumn+4])
963     );
964   }
965   if( rc!=SQLITE_OK ) return rc;
966 
967   /* There is a quirk here. The users INSERT statement may have specified
968   ** a value for the "rowid" field, for the "docid" field, or for both.
969   ** Which is a problem, since "rowid" and "docid" are aliases for the
970   ** same value. For example:
971   **
972   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
973   **
974   ** In FTS3, this is an error. It is an error to specify non-NULL values
975   ** for both docid and some other rowid alias.
976   */
977   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
978     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
979      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
980     ){
981       /* A rowid/docid conflict. */
982       return SQLITE_ERROR;
983     }
984     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
985     if( rc!=SQLITE_OK ) return rc;
986   }
987 
988   /* Execute the statement to insert the record. Set *piDocid to the
989   ** new docid value.
990   */
991   sqlite3_step(pContentInsert);
992   rc = sqlite3_reset(pContentInsert);
993 
994   *piDocid = sqlite3_last_insert_rowid(p->db);
995   return rc;
996 }
997 
998 
999 
1000 /*
1001 ** Remove all data from the FTS3 table. Clear the hash table containing
1002 ** pending terms.
1003 */
1004 static int fts3DeleteAll(Fts3Table *p, int bContent){
1005   int rc = SQLITE_OK;             /* Return code */
1006 
1007   /* Discard the contents of the pending-terms hash table. */
1008   sqlite3Fts3PendingTermsClear(p);
1009 
1010   /* Delete everything from the shadow tables. Except, leave %_content as
1011   ** is if bContent is false.  */
1012   assert( p->zContentTbl==0 || bContent==0 );
1013   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
1014   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
1015   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
1016   if( p->bHasDocsize ){
1017     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
1018   }
1019   if( p->bHasStat ){
1020     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
1021   }
1022   return rc;
1023 }
1024 
1025 /*
1026 **
1027 */
1028 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
1029   int iLangid = 0;
1030   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
1031   return iLangid;
1032 }
1033 
1034 /*
1035 ** The first element in the apVal[] array is assumed to contain the docid
1036 ** (an integer) of a row about to be deleted. Remove all terms from the
1037 ** full-text index.
1038 */
1039 static void fts3DeleteTerms(
1040   int *pRC,               /* Result code */
1041   Fts3Table *p,           /* The FTS table to delete from */
1042   sqlite3_value *pRowid,  /* The docid to be deleted */
1043   u32 *aSz,               /* Sizes of deleted document written here */
1044   int *pbFound            /* OUT: Set to true if row really does exist */
1045 ){
1046   int rc;
1047   sqlite3_stmt *pSelect;
1048 
1049   assert( *pbFound==0 );
1050   if( *pRC ) return;
1051   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
1052   if( rc==SQLITE_OK ){
1053     if( SQLITE_ROW==sqlite3_step(pSelect) ){
1054       int i;
1055       int iLangid = langidFromSelect(p, pSelect);
1056       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
1057       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
1058         int iCol = i-1;
1059         if( p->abNotindexed[iCol]==0 ){
1060           const char *zText = (const char *)sqlite3_column_text(pSelect, i);
1061           rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
1062           aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
1063         }
1064       }
1065       if( rc!=SQLITE_OK ){
1066         sqlite3_reset(pSelect);
1067         *pRC = rc;
1068         return;
1069       }
1070       *pbFound = 1;
1071     }
1072     rc = sqlite3_reset(pSelect);
1073   }else{
1074     sqlite3_reset(pSelect);
1075   }
1076   *pRC = rc;
1077 }
1078 
1079 /*
1080 ** Forward declaration to account for the circular dependency between
1081 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
1082 */
1083 static int fts3SegmentMerge(Fts3Table *, int, int, int);
1084 
1085 /*
1086 ** This function allocates a new level iLevel index in the segdir table.
1087 ** Usually, indexes are allocated within a level sequentially starting
1088 ** with 0, so the allocated index is one greater than the value returned
1089 ** by:
1090 **
1091 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
1092 **
1093 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
1094 ** level, they are merged into a single level (iLevel+1) segment and the
1095 ** allocated index is 0.
1096 **
1097 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
1098 ** returned. Otherwise, an SQLite error code is returned.
1099 */
1100 static int fts3AllocateSegdirIdx(
1101   Fts3Table *p,
1102   int iLangid,                    /* Language id */
1103   int iIndex,                     /* Index for p->aIndex */
1104   int iLevel,
1105   int *piIdx
1106 ){
1107   int rc;                         /* Return Code */
1108   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
1109   int iNext = 0;                  /* Result of query pNextIdx */
1110 
1111   assert( iLangid>=0 );
1112   assert( p->nIndex>=1 );
1113 
1114   /* Set variable iNext to the next available segdir index at level iLevel. */
1115   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
1116   if( rc==SQLITE_OK ){
1117     sqlite3_bind_int64(
1118         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
1119     );
1120     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
1121       iNext = sqlite3_column_int(pNextIdx, 0);
1122     }
1123     rc = sqlite3_reset(pNextIdx);
1124   }
1125 
1126   if( rc==SQLITE_OK ){
1127     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
1128     ** full, merge all segments in level iLevel into a single iLevel+1
1129     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
1130     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
1131     */
1132     if( iNext>=FTS3_MERGE_COUNT ){
1133       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
1134       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
1135       *piIdx = 0;
1136     }else{
1137       *piIdx = iNext;
1138     }
1139   }
1140 
1141   return rc;
1142 }
1143 
1144 /*
1145 ** The %_segments table is declared as follows:
1146 **
1147 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
1148 **
1149 ** This function reads data from a single row of the %_segments table. The
1150 ** specific row is identified by the iBlockid parameter. If paBlob is not
1151 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
1152 ** with the contents of the blob stored in the "block" column of the
1153 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
1154 ** to the size of the blob in bytes before returning.
1155 **
1156 ** If an error occurs, or the table does not contain the specified row,
1157 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
1158 ** paBlob is non-NULL, then it is the responsibility of the caller to
1159 ** eventually free the returned buffer.
1160 **
1161 ** This function may leave an open sqlite3_blob* handle in the
1162 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
1163 ** to this function. The handle may be closed by calling the
1164 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
1165 ** performance improvement, but the blob handle should always be closed
1166 ** before control is returned to the user (to prevent a lock being held
1167 ** on the database file for longer than necessary). Thus, any virtual table
1168 ** method (xFilter etc.) that may directly or indirectly call this function
1169 ** must call sqlite3Fts3SegmentsClose() before returning.
1170 */
1171 int sqlite3Fts3ReadBlock(
1172   Fts3Table *p,                   /* FTS3 table handle */
1173   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
1174   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
1175   int *pnBlob,                    /* OUT: Size of blob data */
1176   int *pnLoad                     /* OUT: Bytes actually loaded */
1177 ){
1178   int rc;                         /* Return code */
1179 
1180   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
1181   assert( pnBlob );
1182 
1183   if( p->pSegments ){
1184     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
1185   }else{
1186     if( 0==p->zSegmentsTbl ){
1187       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
1188       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
1189     }
1190     rc = sqlite3_blob_open(
1191        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
1192     );
1193   }
1194 
1195   if( rc==SQLITE_OK ){
1196     int nByte = sqlite3_blob_bytes(p->pSegments);
1197     *pnBlob = nByte;
1198     if( paBlob ){
1199       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
1200       if( !aByte ){
1201         rc = SQLITE_NOMEM;
1202       }else{
1203         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
1204           nByte = FTS3_NODE_CHUNKSIZE;
1205           *pnLoad = nByte;
1206         }
1207         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
1208         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
1209         if( rc!=SQLITE_OK ){
1210           sqlite3_free(aByte);
1211           aByte = 0;
1212         }
1213       }
1214       *paBlob = aByte;
1215     }
1216   }
1217 
1218   return rc;
1219 }
1220 
1221 /*
1222 ** Close the blob handle at p->pSegments, if it is open. See comments above
1223 ** the sqlite3Fts3ReadBlock() function for details.
1224 */
1225 void sqlite3Fts3SegmentsClose(Fts3Table *p){
1226   sqlite3_blob_close(p->pSegments);
1227   p->pSegments = 0;
1228 }
1229 
1230 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
1231   int nRead;                      /* Number of bytes to read */
1232   int rc;                         /* Return code */
1233 
1234   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
1235   rc = sqlite3_blob_read(
1236       pReader->pBlob,
1237       &pReader->aNode[pReader->nPopulate],
1238       nRead,
1239       pReader->nPopulate
1240   );
1241 
1242   if( rc==SQLITE_OK ){
1243     pReader->nPopulate += nRead;
1244     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
1245     if( pReader->nPopulate==pReader->nNode ){
1246       sqlite3_blob_close(pReader->pBlob);
1247       pReader->pBlob = 0;
1248       pReader->nPopulate = 0;
1249     }
1250   }
1251   return rc;
1252 }
1253 
1254 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
1255   int rc = SQLITE_OK;
1256   assert( !pReader->pBlob
1257        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
1258   );
1259   while( pReader->pBlob && rc==SQLITE_OK
1260      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
1261   ){
1262     rc = fts3SegReaderIncrRead(pReader);
1263   }
1264   return rc;
1265 }
1266 
1267 /*
1268 ** Set an Fts3SegReader cursor to point at EOF.
1269 */
1270 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
1271   if( !fts3SegReaderIsRootOnly(pSeg) ){
1272     sqlite3_free(pSeg->aNode);
1273     sqlite3_blob_close(pSeg->pBlob);
1274     pSeg->pBlob = 0;
1275   }
1276   pSeg->aNode = 0;
1277 }
1278 
1279 /*
1280 ** Move the iterator passed as the first argument to the next term in the
1281 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
1282 ** SQLITE_DONE. Otherwise, an SQLite error code.
1283 */
1284 static int fts3SegReaderNext(
1285   Fts3Table *p,
1286   Fts3SegReader *pReader,
1287   int bIncr
1288 ){
1289   int rc;                         /* Return code of various sub-routines */
1290   char *pNext;                    /* Cursor variable */
1291   int nPrefix;                    /* Number of bytes in term prefix */
1292   int nSuffix;                    /* Number of bytes in term suffix */
1293 
1294   if( !pReader->aDoclist ){
1295     pNext = pReader->aNode;
1296   }else{
1297     pNext = &pReader->aDoclist[pReader->nDoclist];
1298   }
1299 
1300   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
1301 
1302     if( fts3SegReaderIsPending(pReader) ){
1303       Fts3HashElem *pElem = *(pReader->ppNextElem);
1304       if( pElem==0 ){
1305         pReader->aNode = 0;
1306       }else{
1307         PendingList *pList = (PendingList *)fts3HashData(pElem);
1308         pReader->zTerm = (char *)fts3HashKey(pElem);
1309         pReader->nTerm = fts3HashKeysize(pElem);
1310         pReader->nNode = pReader->nDoclist = pList->nData + 1;
1311         pReader->aNode = pReader->aDoclist = pList->aData;
1312         pReader->ppNextElem++;
1313         assert( pReader->aNode );
1314       }
1315       return SQLITE_OK;
1316     }
1317 
1318     fts3SegReaderSetEof(pReader);
1319 
1320     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
1321     ** blocks have already been traversed.  */
1322     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
1323     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
1324       return SQLITE_OK;
1325     }
1326 
1327     rc = sqlite3Fts3ReadBlock(
1328         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
1329         (bIncr ? &pReader->nPopulate : 0)
1330     );
1331     if( rc!=SQLITE_OK ) return rc;
1332     assert( pReader->pBlob==0 );
1333     if( bIncr && pReader->nPopulate<pReader->nNode ){
1334       pReader->pBlob = p->pSegments;
1335       p->pSegments = 0;
1336     }
1337     pNext = pReader->aNode;
1338   }
1339 
1340   assert( !fts3SegReaderIsPending(pReader) );
1341 
1342   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
1343   if( rc!=SQLITE_OK ) return rc;
1344 
1345   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
1346   ** safe (no risk of overread) even if the node data is corrupted. */
1347   pNext += fts3GetVarint32(pNext, &nPrefix);
1348   pNext += fts3GetVarint32(pNext, &nSuffix);
1349   if( nPrefix<0 || nSuffix<=0
1350    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
1351   ){
1352     return FTS_CORRUPT_VTAB;
1353   }
1354 
1355   if( nPrefix+nSuffix>pReader->nTermAlloc ){
1356     int nNew = (nPrefix+nSuffix)*2;
1357     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
1358     if( !zNew ){
1359       return SQLITE_NOMEM;
1360     }
1361     pReader->zTerm = zNew;
1362     pReader->nTermAlloc = nNew;
1363   }
1364 
1365   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
1366   if( rc!=SQLITE_OK ) return rc;
1367 
1368   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
1369   pReader->nTerm = nPrefix+nSuffix;
1370   pNext += nSuffix;
1371   pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
1372   pReader->aDoclist = pNext;
1373   pReader->pOffsetList = 0;
1374 
1375   /* Check that the doclist does not appear to extend past the end of the
1376   ** b-tree node. And that the final byte of the doclist is 0x00. If either
1377   ** of these statements is untrue, then the data structure is corrupt.
1378   */
1379   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
1380    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
1381   ){
1382     return FTS_CORRUPT_VTAB;
1383   }
1384   return SQLITE_OK;
1385 }
1386 
1387 /*
1388 ** Set the SegReader to point to the first docid in the doclist associated
1389 ** with the current term.
1390 */
1391 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
1392   int rc = SQLITE_OK;
1393   assert( pReader->aDoclist );
1394   assert( !pReader->pOffsetList );
1395   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
1396     u8 bEof = 0;
1397     pReader->iDocid = 0;
1398     pReader->nOffsetList = 0;
1399     sqlite3Fts3DoclistPrev(0,
1400         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
1401         &pReader->iDocid, &pReader->nOffsetList, &bEof
1402     );
1403   }else{
1404     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
1405     if( rc==SQLITE_OK ){
1406       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
1407       pReader->pOffsetList = &pReader->aDoclist[n];
1408     }
1409   }
1410   return rc;
1411 }
1412 
1413 /*
1414 ** Advance the SegReader to point to the next docid in the doclist
1415 ** associated with the current term.
1416 **
1417 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
1418 ** *ppOffsetList is set to point to the first column-offset list
1419 ** in the doclist entry (i.e. immediately past the docid varint).
1420 ** *pnOffsetList is set to the length of the set of column-offset
1421 ** lists, not including the nul-terminator byte. For example:
1422 */
1423 static int fts3SegReaderNextDocid(
1424   Fts3Table *pTab,
1425   Fts3SegReader *pReader,         /* Reader to advance to next docid */
1426   char **ppOffsetList,            /* OUT: Pointer to current position-list */
1427   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
1428 ){
1429   int rc = SQLITE_OK;
1430   char *p = pReader->pOffsetList;
1431   char c = 0;
1432 
1433   assert( p );
1434 
1435   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
1436     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
1437     ** Pending-terms doclists are always built up in ascending order, so
1438     ** we have to iterate through them backwards here. */
1439     u8 bEof = 0;
1440     if( ppOffsetList ){
1441       *ppOffsetList = pReader->pOffsetList;
1442       *pnOffsetList = pReader->nOffsetList - 1;
1443     }
1444     sqlite3Fts3DoclistPrev(0,
1445         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
1446         &pReader->nOffsetList, &bEof
1447     );
1448     if( bEof ){
1449       pReader->pOffsetList = 0;
1450     }else{
1451       pReader->pOffsetList = p;
1452     }
1453   }else{
1454     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
1455 
1456     /* Pointer p currently points at the first byte of an offset list. The
1457     ** following block advances it to point one byte past the end of
1458     ** the same offset list. */
1459     while( 1 ){
1460 
1461       /* The following line of code (and the "p++" below the while() loop) is
1462       ** normally all that is required to move pointer p to the desired
1463       ** position. The exception is if this node is being loaded from disk
1464       ** incrementally and pointer "p" now points to the first byte past
1465       ** the populated part of pReader->aNode[].
1466       */
1467       while( *p | c ) c = *p++ & 0x80;
1468       assert( *p==0 );
1469 
1470       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
1471       rc = fts3SegReaderIncrRead(pReader);
1472       if( rc!=SQLITE_OK ) return rc;
1473     }
1474     p++;
1475 
1476     /* If required, populate the output variables with a pointer to and the
1477     ** size of the previous offset-list.
1478     */
1479     if( ppOffsetList ){
1480       *ppOffsetList = pReader->pOffsetList;
1481       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
1482     }
1483 
1484     /* List may have been edited in place by fts3EvalNearTrim() */
1485     while( p<pEnd && *p==0 ) p++;
1486 
1487     /* If there are no more entries in the doclist, set pOffsetList to
1488     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
1489     ** Fts3SegReader.pOffsetList to point to the next offset list before
1490     ** returning.
1491     */
1492     if( p>=pEnd ){
1493       pReader->pOffsetList = 0;
1494     }else{
1495       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
1496       if( rc==SQLITE_OK ){
1497         sqlite3_int64 iDelta;
1498         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
1499         if( pTab->bDescIdx ){
1500           pReader->iDocid -= iDelta;
1501         }else{
1502           pReader->iDocid += iDelta;
1503         }
1504       }
1505     }
1506   }
1507 
1508   return SQLITE_OK;
1509 }
1510 
1511 
1512 int sqlite3Fts3MsrOvfl(
1513   Fts3Cursor *pCsr,
1514   Fts3MultiSegReader *pMsr,
1515   int *pnOvfl
1516 ){
1517   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
1518   int nOvfl = 0;
1519   int ii;
1520   int rc = SQLITE_OK;
1521   int pgsz = p->nPgsz;
1522 
1523   assert( p->bFts4 );
1524   assert( pgsz>0 );
1525 
1526   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
1527     Fts3SegReader *pReader = pMsr->apSegment[ii];
1528     if( !fts3SegReaderIsPending(pReader)
1529      && !fts3SegReaderIsRootOnly(pReader)
1530     ){
1531       sqlite3_int64 jj;
1532       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
1533         int nBlob;
1534         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
1535         if( rc!=SQLITE_OK ) break;
1536         if( (nBlob+35)>pgsz ){
1537           nOvfl += (nBlob + 34)/pgsz;
1538         }
1539       }
1540     }
1541   }
1542   *pnOvfl = nOvfl;
1543   return rc;
1544 }
1545 
1546 /*
1547 ** Free all allocations associated with the iterator passed as the
1548 ** second argument.
1549 */
1550 void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
1551   if( pReader && !fts3SegReaderIsPending(pReader) ){
1552     sqlite3_free(pReader->zTerm);
1553     if( !fts3SegReaderIsRootOnly(pReader) ){
1554       sqlite3_free(pReader->aNode);
1555       sqlite3_blob_close(pReader->pBlob);
1556     }
1557   }
1558   sqlite3_free(pReader);
1559 }
1560 
1561 /*
1562 ** Allocate a new SegReader object.
1563 */
1564 int sqlite3Fts3SegReaderNew(
1565   int iAge,                       /* Segment "age". */
1566   int bLookup,                    /* True for a lookup only */
1567   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
1568   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
1569   sqlite3_int64 iEndBlock,        /* Final block of segment */
1570   const char *zRoot,              /* Buffer containing root node */
1571   int nRoot,                      /* Size of buffer containing root node */
1572   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
1573 ){
1574   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
1575   int nExtra = 0;                 /* Bytes to allocate segment root node */
1576 
1577   assert( iStartLeaf<=iEndLeaf );
1578   if( iStartLeaf==0 ){
1579     nExtra = nRoot + FTS3_NODE_PADDING;
1580   }
1581 
1582   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
1583   if( !pReader ){
1584     return SQLITE_NOMEM;
1585   }
1586   memset(pReader, 0, sizeof(Fts3SegReader));
1587   pReader->iIdx = iAge;
1588   pReader->bLookup = bLookup!=0;
1589   pReader->iStartBlock = iStartLeaf;
1590   pReader->iLeafEndBlock = iEndLeaf;
1591   pReader->iEndBlock = iEndBlock;
1592 
1593   if( nExtra ){
1594     /* The entire segment is stored in the root node. */
1595     pReader->aNode = (char *)&pReader[1];
1596     pReader->rootOnly = 1;
1597     pReader->nNode = nRoot;
1598     memcpy(pReader->aNode, zRoot, nRoot);
1599     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
1600   }else{
1601     pReader->iCurrentBlock = iStartLeaf-1;
1602   }
1603   *ppReader = pReader;
1604   return SQLITE_OK;
1605 }
1606 
1607 /*
1608 ** This is a comparison function used as a qsort() callback when sorting
1609 ** an array of pending terms by term. This occurs as part of flushing
1610 ** the contents of the pending-terms hash table to the database.
1611 */
1612 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
1613   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
1614   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
1615   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
1616   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
1617 
1618   int n = (n1<n2 ? n1 : n2);
1619   int c = memcmp(z1, z2, n);
1620   if( c==0 ){
1621     c = n1 - n2;
1622   }
1623   return c;
1624 }
1625 
1626 /*
1627 ** This function is used to allocate an Fts3SegReader that iterates through
1628 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
1629 **
1630 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
1631 ** through each term in the pending-terms table. Or, if isPrefixIter is
1632 ** non-zero, it iterates through each term and its prefixes. For example, if
1633 ** the pending terms hash table contains the terms "sqlite", "mysql" and
1634 ** "firebird", then the iterator visits the following 'terms' (in the order
1635 ** shown):
1636 **
1637 **   f fi fir fire fireb firebi firebir firebird
1638 **   m my mys mysq mysql
1639 **   s sq sql sqli sqlit sqlite
1640 **
1641 ** Whereas if isPrefixIter is zero, the terms visited are:
1642 **
1643 **   firebird mysql sqlite
1644 */
1645 int sqlite3Fts3SegReaderPending(
1646   Fts3Table *p,                   /* Virtual table handle */
1647   int iIndex,                     /* Index for p->aIndex */
1648   const char *zTerm,              /* Term to search for */
1649   int nTerm,                      /* Size of buffer zTerm */
1650   int bPrefix,                    /* True for a prefix iterator */
1651   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
1652 ){
1653   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
1654   Fts3HashElem *pE;               /* Iterator variable */
1655   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
1656   int nElem = 0;                  /* Size of array at aElem */
1657   int rc = SQLITE_OK;             /* Return Code */
1658   Fts3Hash *pHash;
1659 
1660   pHash = &p->aIndex[iIndex].hPending;
1661   if( bPrefix ){
1662     int nAlloc = 0;               /* Size of allocated array at aElem */
1663 
1664     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
1665       char *zKey = (char *)fts3HashKey(pE);
1666       int nKey = fts3HashKeysize(pE);
1667       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
1668         if( nElem==nAlloc ){
1669           Fts3HashElem **aElem2;
1670           nAlloc += 16;
1671           aElem2 = (Fts3HashElem **)sqlite3_realloc(
1672               aElem, nAlloc*sizeof(Fts3HashElem *)
1673           );
1674           if( !aElem2 ){
1675             rc = SQLITE_NOMEM;
1676             nElem = 0;
1677             break;
1678           }
1679           aElem = aElem2;
1680         }
1681 
1682         aElem[nElem++] = pE;
1683       }
1684     }
1685 
1686     /* If more than one term matches the prefix, sort the Fts3HashElem
1687     ** objects in term order using qsort(). This uses the same comparison
1688     ** callback as is used when flushing terms to disk.
1689     */
1690     if( nElem>1 ){
1691       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
1692     }
1693 
1694   }else{
1695     /* The query is a simple term lookup that matches at most one term in
1696     ** the index. All that is required is a straight hash-lookup.
1697     **
1698     ** Because the stack address of pE may be accessed via the aElem pointer
1699     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
1700     ** within this entire function, not just this "else{...}" block.
1701     */
1702     pE = fts3HashFindElem(pHash, zTerm, nTerm);
1703     if( pE ){
1704       aElem = &pE;
1705       nElem = 1;
1706     }
1707   }
1708 
1709   if( nElem>0 ){
1710     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
1711     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
1712     if( !pReader ){
1713       rc = SQLITE_NOMEM;
1714     }else{
1715       memset(pReader, 0, nByte);
1716       pReader->iIdx = 0x7FFFFFFF;
1717       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
1718       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
1719     }
1720   }
1721 
1722   if( bPrefix ){
1723     sqlite3_free(aElem);
1724   }
1725   *ppReader = pReader;
1726   return rc;
1727 }
1728 
1729 /*
1730 ** Compare the entries pointed to by two Fts3SegReader structures.
1731 ** Comparison is as follows:
1732 **
1733 **   1) EOF is greater than not EOF.
1734 **
1735 **   2) The current terms (if any) are compared using memcmp(). If one
1736 **      term is a prefix of another, the longer term is considered the
1737 **      larger.
1738 **
1739 **   3) By segment age. An older segment is considered larger.
1740 */
1741 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
1742   int rc;
1743   if( pLhs->aNode && pRhs->aNode ){
1744     int rc2 = pLhs->nTerm - pRhs->nTerm;
1745     if( rc2<0 ){
1746       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
1747     }else{
1748       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
1749     }
1750     if( rc==0 ){
1751       rc = rc2;
1752     }
1753   }else{
1754     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
1755   }
1756   if( rc==0 ){
1757     rc = pRhs->iIdx - pLhs->iIdx;
1758   }
1759   assert( rc!=0 );
1760   return rc;
1761 }
1762 
1763 /*
1764 ** A different comparison function for SegReader structures. In this
1765 ** version, it is assumed that each SegReader points to an entry in
1766 ** a doclist for identical terms. Comparison is made as follows:
1767 **
1768 **   1) EOF (end of doclist in this case) is greater than not EOF.
1769 **
1770 **   2) By current docid.
1771 **
1772 **   3) By segment age. An older segment is considered larger.
1773 */
1774 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
1775   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
1776   if( rc==0 ){
1777     if( pLhs->iDocid==pRhs->iDocid ){
1778       rc = pRhs->iIdx - pLhs->iIdx;
1779     }else{
1780       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
1781     }
1782   }
1783   assert( pLhs->aNode && pRhs->aNode );
1784   return rc;
1785 }
1786 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
1787   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
1788   if( rc==0 ){
1789     if( pLhs->iDocid==pRhs->iDocid ){
1790       rc = pRhs->iIdx - pLhs->iIdx;
1791     }else{
1792       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
1793     }
1794   }
1795   assert( pLhs->aNode && pRhs->aNode );
1796   return rc;
1797 }
1798 
1799 /*
1800 ** Compare the term that the Fts3SegReader object passed as the first argument
1801 ** points to with the term specified by arguments zTerm and nTerm.
1802 **
1803 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
1804 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
1805 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
1806 */
1807 static int fts3SegReaderTermCmp(
1808   Fts3SegReader *pSeg,            /* Segment reader object */
1809   const char *zTerm,              /* Term to compare to */
1810   int nTerm                       /* Size of term zTerm in bytes */
1811 ){
1812   int res = 0;
1813   if( pSeg->aNode ){
1814     if( pSeg->nTerm>nTerm ){
1815       res = memcmp(pSeg->zTerm, zTerm, nTerm);
1816     }else{
1817       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
1818     }
1819     if( res==0 ){
1820       res = pSeg->nTerm-nTerm;
1821     }
1822   }
1823   return res;
1824 }
1825 
1826 /*
1827 ** Argument apSegment is an array of nSegment elements. It is known that
1828 ** the final (nSegment-nSuspect) members are already in sorted order
1829 ** (according to the comparison function provided). This function shuffles
1830 ** the array around until all entries are in sorted order.
1831 */
1832 static void fts3SegReaderSort(
1833   Fts3SegReader **apSegment,                     /* Array to sort entries of */
1834   int nSegment,                                  /* Size of apSegment array */
1835   int nSuspect,                                  /* Unsorted entry count */
1836   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
1837 ){
1838   int i;                          /* Iterator variable */
1839 
1840   assert( nSuspect<=nSegment );
1841 
1842   if( nSuspect==nSegment ) nSuspect--;
1843   for(i=nSuspect-1; i>=0; i--){
1844     int j;
1845     for(j=i; j<(nSegment-1); j++){
1846       Fts3SegReader *pTmp;
1847       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
1848       pTmp = apSegment[j+1];
1849       apSegment[j+1] = apSegment[j];
1850       apSegment[j] = pTmp;
1851     }
1852   }
1853 
1854 #ifndef NDEBUG
1855   /* Check that the list really is sorted now. */
1856   for(i=0; i<(nSuspect-1); i++){
1857     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
1858   }
1859 #endif
1860 }
1861 
1862 /*
1863 ** Insert a record into the %_segments table.
1864 */
1865 static int fts3WriteSegment(
1866   Fts3Table *p,                   /* Virtual table handle */
1867   sqlite3_int64 iBlock,           /* Block id for new block */
1868   char *z,                        /* Pointer to buffer containing block data */
1869   int n                           /* Size of buffer z in bytes */
1870 ){
1871   sqlite3_stmt *pStmt;
1872   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
1873   if( rc==SQLITE_OK ){
1874     sqlite3_bind_int64(pStmt, 1, iBlock);
1875     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
1876     sqlite3_step(pStmt);
1877     rc = sqlite3_reset(pStmt);
1878   }
1879   return rc;
1880 }
1881 
1882 /*
1883 ** Find the largest relative level number in the table. If successful, set
1884 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
1885 ** set *pnMax to zero and return an SQLite error code.
1886 */
1887 int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
1888   int rc;
1889   int mxLevel = 0;
1890   sqlite3_stmt *pStmt = 0;
1891 
1892   rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
1893   if( rc==SQLITE_OK ){
1894     if( SQLITE_ROW==sqlite3_step(pStmt) ){
1895       mxLevel = sqlite3_column_int(pStmt, 0);
1896     }
1897     rc = sqlite3_reset(pStmt);
1898   }
1899   *pnMax = mxLevel;
1900   return rc;
1901 }
1902 
1903 /*
1904 ** Insert a record into the %_segdir table.
1905 */
1906 static int fts3WriteSegdir(
1907   Fts3Table *p,                   /* Virtual table handle */
1908   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
1909   int iIdx,                       /* Value for "idx" field */
1910   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
1911   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
1912   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
1913   char *zRoot,                    /* Blob value for "root" field */
1914   int nRoot                       /* Number of bytes in buffer zRoot */
1915 ){
1916   sqlite3_stmt *pStmt;
1917   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
1918   if( rc==SQLITE_OK ){
1919     sqlite3_bind_int64(pStmt, 1, iLevel);
1920     sqlite3_bind_int(pStmt, 2, iIdx);
1921     sqlite3_bind_int64(pStmt, 3, iStartBlock);
1922     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
1923     sqlite3_bind_int64(pStmt, 5, iEndBlock);
1924     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
1925     sqlite3_step(pStmt);
1926     rc = sqlite3_reset(pStmt);
1927   }
1928   return rc;
1929 }
1930 
1931 /*
1932 ** Return the size of the common prefix (if any) shared by zPrev and
1933 ** zNext, in bytes. For example,
1934 **
1935 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
1936 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
1937 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
1938 */
1939 static int fts3PrefixCompress(
1940   const char *zPrev,              /* Buffer containing previous term */
1941   int nPrev,                      /* Size of buffer zPrev in bytes */
1942   const char *zNext,              /* Buffer containing next term */
1943   int nNext                       /* Size of buffer zNext in bytes */
1944 ){
1945   int n;
1946   UNUSED_PARAMETER(nNext);
1947   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
1948   return n;
1949 }
1950 
1951 /*
1952 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
1953 ** (according to memcmp) than the previous term.
1954 */
1955 static int fts3NodeAddTerm(
1956   Fts3Table *p,                   /* Virtual table handle */
1957   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
1958   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
1959   const char *zTerm,              /* Pointer to buffer containing term */
1960   int nTerm                       /* Size of term in bytes */
1961 ){
1962   SegmentNode *pTree = *ppTree;
1963   int rc;
1964   SegmentNode *pNew;
1965 
1966   /* First try to append the term to the current node. Return early if
1967   ** this is possible.
1968   */
1969   if( pTree ){
1970     int nData = pTree->nData;     /* Current size of node in bytes */
1971     int nReq = nData;             /* Required space after adding zTerm */
1972     int nPrefix;                  /* Number of bytes of prefix compression */
1973     int nSuffix;                  /* Suffix length */
1974 
1975     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
1976     nSuffix = nTerm-nPrefix;
1977 
1978     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
1979     if( nReq<=p->nNodeSize || !pTree->zTerm ){
1980 
1981       if( nReq>p->nNodeSize ){
1982         /* An unusual case: this is the first term to be added to the node
1983         ** and the static node buffer (p->nNodeSize bytes) is not large
1984         ** enough. Use a separately malloced buffer instead This wastes
1985         ** p->nNodeSize bytes, but since this scenario only comes about when
1986         ** the database contain two terms that share a prefix of almost 2KB,
1987         ** this is not expected to be a serious problem.
1988         */
1989         assert( pTree->aData==(char *)&pTree[1] );
1990         pTree->aData = (char *)sqlite3_malloc(nReq);
1991         if( !pTree->aData ){
1992           return SQLITE_NOMEM;
1993         }
1994       }
1995 
1996       if( pTree->zTerm ){
1997         /* There is no prefix-length field for first term in a node */
1998         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
1999       }
2000 
2001       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
2002       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
2003       pTree->nData = nData + nSuffix;
2004       pTree->nEntry++;
2005 
2006       if( isCopyTerm ){
2007         if( pTree->nMalloc<nTerm ){
2008           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
2009           if( !zNew ){
2010             return SQLITE_NOMEM;
2011           }
2012           pTree->nMalloc = nTerm*2;
2013           pTree->zMalloc = zNew;
2014         }
2015         pTree->zTerm = pTree->zMalloc;
2016         memcpy(pTree->zTerm, zTerm, nTerm);
2017         pTree->nTerm = nTerm;
2018       }else{
2019         pTree->zTerm = (char *)zTerm;
2020         pTree->nTerm = nTerm;
2021       }
2022       return SQLITE_OK;
2023     }
2024   }
2025 
2026   /* If control flows to here, it was not possible to append zTerm to the
2027   ** current node. Create a new node (a right-sibling of the current node).
2028   ** If this is the first node in the tree, the term is added to it.
2029   **
2030   ** Otherwise, the term is not added to the new node, it is left empty for
2031   ** now. Instead, the term is inserted into the parent of pTree. If pTree
2032   ** has no parent, one is created here.
2033   */
2034   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
2035   if( !pNew ){
2036     return SQLITE_NOMEM;
2037   }
2038   memset(pNew, 0, sizeof(SegmentNode));
2039   pNew->nData = 1 + FTS3_VARINT_MAX;
2040   pNew->aData = (char *)&pNew[1];
2041 
2042   if( pTree ){
2043     SegmentNode *pParent = pTree->pParent;
2044     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
2045     if( pTree->pParent==0 ){
2046       pTree->pParent = pParent;
2047     }
2048     pTree->pRight = pNew;
2049     pNew->pLeftmost = pTree->pLeftmost;
2050     pNew->pParent = pParent;
2051     pNew->zMalloc = pTree->zMalloc;
2052     pNew->nMalloc = pTree->nMalloc;
2053     pTree->zMalloc = 0;
2054   }else{
2055     pNew->pLeftmost = pNew;
2056     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
2057   }
2058 
2059   *ppTree = pNew;
2060   return rc;
2061 }
2062 
2063 /*
2064 ** Helper function for fts3NodeWrite().
2065 */
2066 static int fts3TreeFinishNode(
2067   SegmentNode *pTree,
2068   int iHeight,
2069   sqlite3_int64 iLeftChild
2070 ){
2071   int nStart;
2072   assert( iHeight>=1 && iHeight<128 );
2073   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
2074   pTree->aData[nStart] = (char)iHeight;
2075   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
2076   return nStart;
2077 }
2078 
2079 /*
2080 ** Write the buffer for the segment node pTree and all of its peers to the
2081 ** database. Then call this function recursively to write the parent of
2082 ** pTree and its peers to the database.
2083 **
2084 ** Except, if pTree is a root node, do not write it to the database. Instead,
2085 ** set output variables *paRoot and *pnRoot to contain the root node.
2086 **
2087 ** If successful, SQLITE_OK is returned and output variable *piLast is
2088 ** set to the largest blockid written to the database (or zero if no
2089 ** blocks were written to the db). Otherwise, an SQLite error code is
2090 ** returned.
2091 */
2092 static int fts3NodeWrite(
2093   Fts3Table *p,                   /* Virtual table handle */
2094   SegmentNode *pTree,             /* SegmentNode handle */
2095   int iHeight,                    /* Height of this node in tree */
2096   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
2097   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
2098   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
2099   char **paRoot,                  /* OUT: Data for root node */
2100   int *pnRoot                     /* OUT: Size of root node in bytes */
2101 ){
2102   int rc = SQLITE_OK;
2103 
2104   if( !pTree->pParent ){
2105     /* Root node of the tree. */
2106     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
2107     *piLast = iFree-1;
2108     *pnRoot = pTree->nData - nStart;
2109     *paRoot = &pTree->aData[nStart];
2110   }else{
2111     SegmentNode *pIter;
2112     sqlite3_int64 iNextFree = iFree;
2113     sqlite3_int64 iNextLeaf = iLeaf;
2114     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
2115       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
2116       int nWrite = pIter->nData - nStart;
2117 
2118       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
2119       iNextFree++;
2120       iNextLeaf += (pIter->nEntry+1);
2121     }
2122     if( rc==SQLITE_OK ){
2123       assert( iNextLeaf==iFree );
2124       rc = fts3NodeWrite(
2125           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
2126       );
2127     }
2128   }
2129 
2130   return rc;
2131 }
2132 
2133 /*
2134 ** Free all memory allocations associated with the tree pTree.
2135 */
2136 static void fts3NodeFree(SegmentNode *pTree){
2137   if( pTree ){
2138     SegmentNode *p = pTree->pLeftmost;
2139     fts3NodeFree(p->pParent);
2140     while( p ){
2141       SegmentNode *pRight = p->pRight;
2142       if( p->aData!=(char *)&p[1] ){
2143         sqlite3_free(p->aData);
2144       }
2145       assert( pRight==0 || p->zMalloc==0 );
2146       sqlite3_free(p->zMalloc);
2147       sqlite3_free(p);
2148       p = pRight;
2149     }
2150   }
2151 }
2152 
2153 /*
2154 ** Add a term to the segment being constructed by the SegmentWriter object
2155 ** *ppWriter. When adding the first term to a segment, *ppWriter should
2156 ** be passed NULL. This function will allocate a new SegmentWriter object
2157 ** and return it via the input/output variable *ppWriter in this case.
2158 **
2159 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
2160 */
2161 static int fts3SegWriterAdd(
2162   Fts3Table *p,                   /* Virtual table handle */
2163   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
2164   int isCopyTerm,                 /* True if buffer zTerm must be copied */
2165   const char *zTerm,              /* Pointer to buffer containing term */
2166   int nTerm,                      /* Size of term in bytes */
2167   const char *aDoclist,           /* Pointer to buffer containing doclist */
2168   int nDoclist                    /* Size of doclist in bytes */
2169 ){
2170   int nPrefix;                    /* Size of term prefix in bytes */
2171   int nSuffix;                    /* Size of term suffix in bytes */
2172   int nReq;                       /* Number of bytes required on leaf page */
2173   int nData;
2174   SegmentWriter *pWriter = *ppWriter;
2175 
2176   if( !pWriter ){
2177     int rc;
2178     sqlite3_stmt *pStmt;
2179 
2180     /* Allocate the SegmentWriter structure */
2181     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
2182     if( !pWriter ) return SQLITE_NOMEM;
2183     memset(pWriter, 0, sizeof(SegmentWriter));
2184     *ppWriter = pWriter;
2185 
2186     /* Allocate a buffer in which to accumulate data */
2187     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
2188     if( !pWriter->aData ) return SQLITE_NOMEM;
2189     pWriter->nSize = p->nNodeSize;
2190 
2191     /* Find the next free blockid in the %_segments table */
2192     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
2193     if( rc!=SQLITE_OK ) return rc;
2194     if( SQLITE_ROW==sqlite3_step(pStmt) ){
2195       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
2196       pWriter->iFirst = pWriter->iFree;
2197     }
2198     rc = sqlite3_reset(pStmt);
2199     if( rc!=SQLITE_OK ) return rc;
2200   }
2201   nData = pWriter->nData;
2202 
2203   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
2204   nSuffix = nTerm-nPrefix;
2205 
2206   /* Figure out how many bytes are required by this new entry */
2207   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
2208     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
2209     nSuffix +                               /* Term suffix */
2210     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
2211     nDoclist;                               /* Doclist data */
2212 
2213   if( nData>0 && nData+nReq>p->nNodeSize ){
2214     int rc;
2215 
2216     /* The current leaf node is full. Write it out to the database. */
2217     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
2218     if( rc!=SQLITE_OK ) return rc;
2219     p->nLeafAdd++;
2220 
2221     /* Add the current term to the interior node tree. The term added to
2222     ** the interior tree must:
2223     **
2224     **   a) be greater than the largest term on the leaf node just written
2225     **      to the database (still available in pWriter->zTerm), and
2226     **
2227     **   b) be less than or equal to the term about to be added to the new
2228     **      leaf node (zTerm/nTerm).
2229     **
2230     ** In other words, it must be the prefix of zTerm 1 byte longer than
2231     ** the common prefix (if any) of zTerm and pWriter->zTerm.
2232     */
2233     assert( nPrefix<nTerm );
2234     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
2235     if( rc!=SQLITE_OK ) return rc;
2236 
2237     nData = 0;
2238     pWriter->nTerm = 0;
2239 
2240     nPrefix = 0;
2241     nSuffix = nTerm;
2242     nReq = 1 +                              /* varint containing prefix size */
2243       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
2244       nTerm +                               /* Term suffix */
2245       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
2246       nDoclist;                             /* Doclist data */
2247   }
2248 
2249   /* If the buffer currently allocated is too small for this entry, realloc
2250   ** the buffer to make it large enough.
2251   */
2252   if( nReq>pWriter->nSize ){
2253     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
2254     if( !aNew ) return SQLITE_NOMEM;
2255     pWriter->aData = aNew;
2256     pWriter->nSize = nReq;
2257   }
2258   assert( nData+nReq<=pWriter->nSize );
2259 
2260   /* Append the prefix-compressed term and doclist to the buffer. */
2261   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
2262   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
2263   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
2264   nData += nSuffix;
2265   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
2266   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
2267   pWriter->nData = nData + nDoclist;
2268 
2269   /* Save the current term so that it can be used to prefix-compress the next.
2270   ** If the isCopyTerm parameter is true, then the buffer pointed to by
2271   ** zTerm is transient, so take a copy of the term data. Otherwise, just
2272   ** store a copy of the pointer.
2273   */
2274   if( isCopyTerm ){
2275     if( nTerm>pWriter->nMalloc ){
2276       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
2277       if( !zNew ){
2278         return SQLITE_NOMEM;
2279       }
2280       pWriter->nMalloc = nTerm*2;
2281       pWriter->zMalloc = zNew;
2282       pWriter->zTerm = zNew;
2283     }
2284     assert( pWriter->zTerm==pWriter->zMalloc );
2285     memcpy(pWriter->zTerm, zTerm, nTerm);
2286   }else{
2287     pWriter->zTerm = (char *)zTerm;
2288   }
2289   pWriter->nTerm = nTerm;
2290 
2291   return SQLITE_OK;
2292 }
2293 
2294 /*
2295 ** Flush all data associated with the SegmentWriter object pWriter to the
2296 ** database. This function must be called after all terms have been added
2297 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
2298 ** returned. Otherwise, an SQLite error code.
2299 */
2300 static int fts3SegWriterFlush(
2301   Fts3Table *p,                   /* Virtual table handle */
2302   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
2303   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
2304   int iIdx                        /* Value for 'idx' column of %_segdir */
2305 ){
2306   int rc;                         /* Return code */
2307   if( pWriter->pTree ){
2308     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
2309     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
2310     char *zRoot = NULL;           /* Pointer to buffer containing root node */
2311     int nRoot = 0;                /* Size of buffer zRoot */
2312 
2313     iLastLeaf = pWriter->iFree;
2314     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
2315     if( rc==SQLITE_OK ){
2316       rc = fts3NodeWrite(p, pWriter->pTree, 1,
2317           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
2318     }
2319     if( rc==SQLITE_OK ){
2320       rc = fts3WriteSegdir(
2321           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
2322     }
2323   }else{
2324     /* The entire tree fits on the root node. Write it to the segdir table. */
2325     rc = fts3WriteSegdir(
2326         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
2327   }
2328   p->nLeafAdd++;
2329   return rc;
2330 }
2331 
2332 /*
2333 ** Release all memory held by the SegmentWriter object passed as the
2334 ** first argument.
2335 */
2336 static void fts3SegWriterFree(SegmentWriter *pWriter){
2337   if( pWriter ){
2338     sqlite3_free(pWriter->aData);
2339     sqlite3_free(pWriter->zMalloc);
2340     fts3NodeFree(pWriter->pTree);
2341     sqlite3_free(pWriter);
2342   }
2343 }
2344 
2345 /*
2346 ** The first value in the apVal[] array is assumed to contain an integer.
2347 ** This function tests if there exist any documents with docid values that
2348 ** are different from that integer. i.e. if deleting the document with docid
2349 ** pRowid would mean the FTS3 table were empty.
2350 **
2351 ** If successful, *pisEmpty is set to true if the table is empty except for
2352 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
2353 ** error occurs, an SQLite error code is returned.
2354 */
2355 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
2356   sqlite3_stmt *pStmt;
2357   int rc;
2358   if( p->zContentTbl ){
2359     /* If using the content=xxx option, assume the table is never empty */
2360     *pisEmpty = 0;
2361     rc = SQLITE_OK;
2362   }else{
2363     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
2364     if( rc==SQLITE_OK ){
2365       if( SQLITE_ROW==sqlite3_step(pStmt) ){
2366         *pisEmpty = sqlite3_column_int(pStmt, 0);
2367       }
2368       rc = sqlite3_reset(pStmt);
2369     }
2370   }
2371   return rc;
2372 }
2373 
2374 /*
2375 ** Set *pnMax to the largest segment level in the database for the index
2376 ** iIndex.
2377 **
2378 ** Segment levels are stored in the 'level' column of the %_segdir table.
2379 **
2380 ** Return SQLITE_OK if successful, or an SQLite error code if not.
2381 */
2382 static int fts3SegmentMaxLevel(
2383   Fts3Table *p,
2384   int iLangid,
2385   int iIndex,
2386   sqlite3_int64 *pnMax
2387 ){
2388   sqlite3_stmt *pStmt;
2389   int rc;
2390   assert( iIndex>=0 && iIndex<p->nIndex );
2391 
2392   /* Set pStmt to the compiled version of:
2393   **
2394   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
2395   **
2396   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
2397   */
2398   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
2399   if( rc!=SQLITE_OK ) return rc;
2400   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
2401   sqlite3_bind_int64(pStmt, 2,
2402       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
2403   );
2404   if( SQLITE_ROW==sqlite3_step(pStmt) ){
2405     *pnMax = sqlite3_column_int64(pStmt, 0);
2406   }
2407   return sqlite3_reset(pStmt);
2408 }
2409 
2410 /*
2411 ** Delete all entries in the %_segments table associated with the segment
2412 ** opened with seg-reader pSeg. This function does not affect the contents
2413 ** of the %_segdir table.
2414 */
2415 static int fts3DeleteSegment(
2416   Fts3Table *p,                   /* FTS table handle */
2417   Fts3SegReader *pSeg             /* Segment to delete */
2418 ){
2419   int rc = SQLITE_OK;             /* Return code */
2420   if( pSeg->iStartBlock ){
2421     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
2422     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
2423     if( rc==SQLITE_OK ){
2424       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
2425       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
2426       sqlite3_step(pDelete);
2427       rc = sqlite3_reset(pDelete);
2428     }
2429   }
2430   return rc;
2431 }
2432 
2433 /*
2434 ** This function is used after merging multiple segments into a single large
2435 ** segment to delete the old, now redundant, segment b-trees. Specifically,
2436 ** it:
2437 **
2438 **   1) Deletes all %_segments entries for the segments associated with
2439 **      each of the SegReader objects in the array passed as the third
2440 **      argument, and
2441 **
2442 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
2443 **      entries regardless of level if (iLevel<0).
2444 **
2445 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
2446 */
2447 static int fts3DeleteSegdir(
2448   Fts3Table *p,                   /* Virtual table handle */
2449   int iLangid,                    /* Language id */
2450   int iIndex,                     /* Index for p->aIndex */
2451   int iLevel,                     /* Level of %_segdir entries to delete */
2452   Fts3SegReader **apSegment,      /* Array of SegReader objects */
2453   int nReader                     /* Size of array apSegment */
2454 ){
2455   int rc = SQLITE_OK;             /* Return Code */
2456   int i;                          /* Iterator variable */
2457   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
2458 
2459   for(i=0; rc==SQLITE_OK && i<nReader; i++){
2460     rc = fts3DeleteSegment(p, apSegment[i]);
2461   }
2462   if( rc!=SQLITE_OK ){
2463     return rc;
2464   }
2465 
2466   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
2467   if( iLevel==FTS3_SEGCURSOR_ALL ){
2468     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
2469     if( rc==SQLITE_OK ){
2470       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
2471       sqlite3_bind_int64(pDelete, 2,
2472           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
2473       );
2474     }
2475   }else{
2476     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
2477     if( rc==SQLITE_OK ){
2478       sqlite3_bind_int64(
2479           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
2480       );
2481     }
2482   }
2483 
2484   if( rc==SQLITE_OK ){
2485     sqlite3_step(pDelete);
2486     rc = sqlite3_reset(pDelete);
2487   }
2488 
2489   return rc;
2490 }
2491 
2492 /*
2493 ** When this function is called, buffer *ppList (size *pnList bytes) contains
2494 ** a position list that may (or may not) feature multiple columns. This
2495 ** function adjusts the pointer *ppList and the length *pnList so that they
2496 ** identify the subset of the position list that corresponds to column iCol.
2497 **
2498 ** If there are no entries in the input position list for column iCol, then
2499 ** *pnList is set to zero before returning.
2500 **
2501 ** If parameter bZero is non-zero, then any part of the input list following
2502 ** the end of the output list is zeroed before returning.
2503 */
2504 static void fts3ColumnFilter(
2505   int iCol,                       /* Column to filter on */
2506   int bZero,                      /* Zero out anything following *ppList */
2507   char **ppList,                  /* IN/OUT: Pointer to position list */
2508   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
2509 ){
2510   char *pList = *ppList;
2511   int nList = *pnList;
2512   char *pEnd = &pList[nList];
2513   int iCurrent = 0;
2514   char *p = pList;
2515 
2516   assert( iCol>=0 );
2517   while( 1 ){
2518     char c = 0;
2519     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
2520 
2521     if( iCol==iCurrent ){
2522       nList = (int)(p - pList);
2523       break;
2524     }
2525 
2526     nList -= (int)(p - pList);
2527     pList = p;
2528     if( nList==0 ){
2529       break;
2530     }
2531     p = &pList[1];
2532     p += fts3GetVarint32(p, &iCurrent);
2533   }
2534 
2535   if( bZero && &pList[nList]!=pEnd ){
2536     memset(&pList[nList], 0, pEnd - &pList[nList]);
2537   }
2538   *ppList = pList;
2539   *pnList = nList;
2540 }
2541 
2542 /*
2543 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
2544 ** existing data). Grow the buffer if required.
2545 **
2546 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
2547 ** trying to resize the buffer, return SQLITE_NOMEM.
2548 */
2549 static int fts3MsrBufferData(
2550   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
2551   char *pList,
2552   int nList
2553 ){
2554   if( nList>pMsr->nBuffer ){
2555     char *pNew;
2556     pMsr->nBuffer = nList*2;
2557     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
2558     if( !pNew ) return SQLITE_NOMEM;
2559     pMsr->aBuffer = pNew;
2560   }
2561 
2562   memcpy(pMsr->aBuffer, pList, nList);
2563   return SQLITE_OK;
2564 }
2565 
2566 int sqlite3Fts3MsrIncrNext(
2567   Fts3Table *p,                   /* Virtual table handle */
2568   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
2569   sqlite3_int64 *piDocid,         /* OUT: Docid value */
2570   char **paPoslist,               /* OUT: Pointer to position list */
2571   int *pnPoslist                  /* OUT: Size of position list in bytes */
2572 ){
2573   int nMerge = pMsr->nAdvance;
2574   Fts3SegReader **apSegment = pMsr->apSegment;
2575   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
2576     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
2577   );
2578 
2579   if( nMerge==0 ){
2580     *paPoslist = 0;
2581     return SQLITE_OK;
2582   }
2583 
2584   while( 1 ){
2585     Fts3SegReader *pSeg;
2586     pSeg = pMsr->apSegment[0];
2587 
2588     if( pSeg->pOffsetList==0 ){
2589       *paPoslist = 0;
2590       break;
2591     }else{
2592       int rc;
2593       char *pList;
2594       int nList;
2595       int j;
2596       sqlite3_int64 iDocid = apSegment[0]->iDocid;
2597 
2598       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
2599       j = 1;
2600       while( rc==SQLITE_OK
2601         && j<nMerge
2602         && apSegment[j]->pOffsetList
2603         && apSegment[j]->iDocid==iDocid
2604       ){
2605         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
2606         j++;
2607       }
2608       if( rc!=SQLITE_OK ) return rc;
2609       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
2610 
2611       if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
2612         rc = fts3MsrBufferData(pMsr, pList, nList+1);
2613         if( rc!=SQLITE_OK ) return rc;
2614         assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
2615         pList = pMsr->aBuffer;
2616       }
2617 
2618       if( pMsr->iColFilter>=0 ){
2619         fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
2620       }
2621 
2622       if( nList>0 ){
2623         *paPoslist = pList;
2624         *piDocid = iDocid;
2625         *pnPoslist = nList;
2626         break;
2627       }
2628     }
2629   }
2630 
2631   return SQLITE_OK;
2632 }
2633 
2634 static int fts3SegReaderStart(
2635   Fts3Table *p,                   /* Virtual table handle */
2636   Fts3MultiSegReader *pCsr,       /* Cursor object */
2637   const char *zTerm,              /* Term searched for (or NULL) */
2638   int nTerm                       /* Length of zTerm in bytes */
2639 ){
2640   int i;
2641   int nSeg = pCsr->nSegment;
2642 
2643   /* If the Fts3SegFilter defines a specific term (or term prefix) to search
2644   ** for, then advance each segment iterator until it points to a term of
2645   ** equal or greater value than the specified term. This prevents many
2646   ** unnecessary merge/sort operations for the case where single segment
2647   ** b-tree leaf nodes contain more than one term.
2648   */
2649   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
2650     int res = 0;
2651     Fts3SegReader *pSeg = pCsr->apSegment[i];
2652     do {
2653       int rc = fts3SegReaderNext(p, pSeg, 0);
2654       if( rc!=SQLITE_OK ) return rc;
2655     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
2656 
2657     if( pSeg->bLookup && res!=0 ){
2658       fts3SegReaderSetEof(pSeg);
2659     }
2660   }
2661   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
2662 
2663   return SQLITE_OK;
2664 }
2665 
2666 int sqlite3Fts3SegReaderStart(
2667   Fts3Table *p,                   /* Virtual table handle */
2668   Fts3MultiSegReader *pCsr,       /* Cursor object */
2669   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
2670 ){
2671   pCsr->pFilter = pFilter;
2672   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
2673 }
2674 
2675 int sqlite3Fts3MsrIncrStart(
2676   Fts3Table *p,                   /* Virtual table handle */
2677   Fts3MultiSegReader *pCsr,       /* Cursor object */
2678   int iCol,                       /* Column to match on. */
2679   const char *zTerm,              /* Term to iterate through a doclist for */
2680   int nTerm                       /* Number of bytes in zTerm */
2681 ){
2682   int i;
2683   int rc;
2684   int nSegment = pCsr->nSegment;
2685   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
2686     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
2687   );
2688 
2689   assert( pCsr->pFilter==0 );
2690   assert( zTerm && nTerm>0 );
2691 
2692   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
2693   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
2694   if( rc!=SQLITE_OK ) return rc;
2695 
2696   /* Determine how many of the segments actually point to zTerm/nTerm. */
2697   for(i=0; i<nSegment; i++){
2698     Fts3SegReader *pSeg = pCsr->apSegment[i];
2699     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
2700       break;
2701     }
2702   }
2703   pCsr->nAdvance = i;
2704 
2705   /* Advance each of the segments to point to the first docid. */
2706   for(i=0; i<pCsr->nAdvance; i++){
2707     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
2708     if( rc!=SQLITE_OK ) return rc;
2709   }
2710   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
2711 
2712   assert( iCol<0 || iCol<p->nColumn );
2713   pCsr->iColFilter = iCol;
2714 
2715   return SQLITE_OK;
2716 }
2717 
2718 /*
2719 ** This function is called on a MultiSegReader that has been started using
2720 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
2721 ** have been made. Calling this function puts the MultiSegReader in such
2722 ** a state that if the next two calls are:
2723 **
2724 **   sqlite3Fts3SegReaderStart()
2725 **   sqlite3Fts3SegReaderStep()
2726 **
2727 ** then the entire doclist for the term is available in
2728 ** MultiSegReader.aDoclist/nDoclist.
2729 */
2730 int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
2731   int i;                          /* Used to iterate through segment-readers */
2732 
2733   assert( pCsr->zTerm==0 );
2734   assert( pCsr->nTerm==0 );
2735   assert( pCsr->aDoclist==0 );
2736   assert( pCsr->nDoclist==0 );
2737 
2738   pCsr->nAdvance = 0;
2739   pCsr->bRestart = 1;
2740   for(i=0; i<pCsr->nSegment; i++){
2741     pCsr->apSegment[i]->pOffsetList = 0;
2742     pCsr->apSegment[i]->nOffsetList = 0;
2743     pCsr->apSegment[i]->iDocid = 0;
2744   }
2745 
2746   return SQLITE_OK;
2747 }
2748 
2749 
2750 int sqlite3Fts3SegReaderStep(
2751   Fts3Table *p,                   /* Virtual table handle */
2752   Fts3MultiSegReader *pCsr        /* Cursor object */
2753 ){
2754   int rc = SQLITE_OK;
2755 
2756   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
2757   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
2758   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
2759   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
2760   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
2761   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
2762 
2763   Fts3SegReader **apSegment = pCsr->apSegment;
2764   int nSegment = pCsr->nSegment;
2765   Fts3SegFilter *pFilter = pCsr->pFilter;
2766   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
2767     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
2768   );
2769 
2770   if( pCsr->nSegment==0 ) return SQLITE_OK;
2771 
2772   do {
2773     int nMerge;
2774     int i;
2775 
2776     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
2777     ** forward. Then sort the list in order of current term again.
2778     */
2779     for(i=0; i<pCsr->nAdvance; i++){
2780       Fts3SegReader *pSeg = apSegment[i];
2781       if( pSeg->bLookup ){
2782         fts3SegReaderSetEof(pSeg);
2783       }else{
2784         rc = fts3SegReaderNext(p, pSeg, 0);
2785       }
2786       if( rc!=SQLITE_OK ) return rc;
2787     }
2788     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
2789     pCsr->nAdvance = 0;
2790 
2791     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
2792     assert( rc==SQLITE_OK );
2793     if( apSegment[0]->aNode==0 ) break;
2794 
2795     pCsr->nTerm = apSegment[0]->nTerm;
2796     pCsr->zTerm = apSegment[0]->zTerm;
2797 
2798     /* If this is a prefix-search, and if the term that apSegment[0] points
2799     ** to does not share a suffix with pFilter->zTerm/nTerm, then all
2800     ** required callbacks have been made. In this case exit early.
2801     **
2802     ** Similarly, if this is a search for an exact match, and the first term
2803     ** of segment apSegment[0] is not a match, exit early.
2804     */
2805     if( pFilter->zTerm && !isScan ){
2806       if( pCsr->nTerm<pFilter->nTerm
2807        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
2808        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
2809       ){
2810         break;
2811       }
2812     }
2813 
2814     nMerge = 1;
2815     while( nMerge<nSegment
2816         && apSegment[nMerge]->aNode
2817         && apSegment[nMerge]->nTerm==pCsr->nTerm
2818         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
2819     ){
2820       nMerge++;
2821     }
2822 
2823     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
2824     if( nMerge==1
2825      && !isIgnoreEmpty
2826      && !isFirst
2827      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
2828     ){
2829       pCsr->nDoclist = apSegment[0]->nDoclist;
2830       if( fts3SegReaderIsPending(apSegment[0]) ){
2831         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
2832         pCsr->aDoclist = pCsr->aBuffer;
2833       }else{
2834         pCsr->aDoclist = apSegment[0]->aDoclist;
2835       }
2836       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
2837     }else{
2838       int nDoclist = 0;           /* Size of doclist */
2839       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
2840 
2841       /* The current term of the first nMerge entries in the array
2842       ** of Fts3SegReader objects is the same. The doclists must be merged
2843       ** and a single term returned with the merged doclist.
2844       */
2845       for(i=0; i<nMerge; i++){
2846         fts3SegReaderFirstDocid(p, apSegment[i]);
2847       }
2848       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
2849       while( apSegment[0]->pOffsetList ){
2850         int j;                    /* Number of segments that share a docid */
2851         char *pList = 0;
2852         int nList = 0;
2853         int nByte;
2854         sqlite3_int64 iDocid = apSegment[0]->iDocid;
2855         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
2856         j = 1;
2857         while( j<nMerge
2858             && apSegment[j]->pOffsetList
2859             && apSegment[j]->iDocid==iDocid
2860         ){
2861           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
2862           j++;
2863         }
2864 
2865         if( isColFilter ){
2866           fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
2867         }
2868 
2869         if( !isIgnoreEmpty || nList>0 ){
2870 
2871           /* Calculate the 'docid' delta value to write into the merged
2872           ** doclist. */
2873           sqlite3_int64 iDelta;
2874           if( p->bDescIdx && nDoclist>0 ){
2875             iDelta = iPrev - iDocid;
2876           }else{
2877             iDelta = iDocid - iPrev;
2878           }
2879           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
2880           assert( nDoclist>0 || iDelta==iDocid );
2881 
2882           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
2883           if( nDoclist+nByte>pCsr->nBuffer ){
2884             char *aNew;
2885             pCsr->nBuffer = (nDoclist+nByte)*2;
2886             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
2887             if( !aNew ){
2888               return SQLITE_NOMEM;
2889             }
2890             pCsr->aBuffer = aNew;
2891           }
2892 
2893           if( isFirst ){
2894             char *a = &pCsr->aBuffer[nDoclist];
2895             int nWrite;
2896 
2897             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
2898             if( nWrite ){
2899               iPrev = iDocid;
2900               nDoclist += nWrite;
2901             }
2902           }else{
2903             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
2904             iPrev = iDocid;
2905             if( isRequirePos ){
2906               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
2907               nDoclist += nList;
2908               pCsr->aBuffer[nDoclist++] = '\0';
2909             }
2910           }
2911         }
2912 
2913         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
2914       }
2915       if( nDoclist>0 ){
2916         pCsr->aDoclist = pCsr->aBuffer;
2917         pCsr->nDoclist = nDoclist;
2918         rc = SQLITE_ROW;
2919       }
2920     }
2921     pCsr->nAdvance = nMerge;
2922   }while( rc==SQLITE_OK );
2923 
2924   return rc;
2925 }
2926 
2927 
2928 void sqlite3Fts3SegReaderFinish(
2929   Fts3MultiSegReader *pCsr       /* Cursor object */
2930 ){
2931   if( pCsr ){
2932     int i;
2933     for(i=0; i<pCsr->nSegment; i++){
2934       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
2935     }
2936     sqlite3_free(pCsr->apSegment);
2937     sqlite3_free(pCsr->aBuffer);
2938 
2939     pCsr->nSegment = 0;
2940     pCsr->apSegment = 0;
2941     pCsr->aBuffer = 0;
2942   }
2943 }
2944 
2945 /*
2946 ** Merge all level iLevel segments in the database into a single
2947 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
2948 ** single segment with a level equal to the numerically largest level
2949 ** currently present in the database.
2950 **
2951 ** If this function is called with iLevel<0, but there is only one
2952 ** segment in the database, SQLITE_DONE is returned immediately.
2953 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
2954 ** an SQLite error code is returned.
2955 */
2956 static int fts3SegmentMerge(
2957   Fts3Table *p,
2958   int iLangid,                    /* Language id to merge */
2959   int iIndex,                     /* Index in p->aIndex[] to merge */
2960   int iLevel                      /* Level to merge */
2961 ){
2962   int rc;                         /* Return code */
2963   int iIdx = 0;                   /* Index of new segment */
2964   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
2965   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
2966   Fts3SegFilter filter;           /* Segment term filter condition */
2967   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
2968   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
2969 
2970   assert( iLevel==FTS3_SEGCURSOR_ALL
2971        || iLevel==FTS3_SEGCURSOR_PENDING
2972        || iLevel>=0
2973   );
2974   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
2975   assert( iIndex>=0 && iIndex<p->nIndex );
2976 
2977   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
2978   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
2979 
2980   if( iLevel==FTS3_SEGCURSOR_ALL ){
2981     /* This call is to merge all segments in the database to a single
2982     ** segment. The level of the new segment is equal to the numerically
2983     ** greatest segment level currently present in the database for this
2984     ** index. The idx of the new segment is always 0.  */
2985     if( csr.nSegment==1 ){
2986       rc = SQLITE_DONE;
2987       goto finished;
2988     }
2989     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
2990     bIgnoreEmpty = 1;
2991 
2992   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
2993     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
2994     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
2995   }else{
2996     /* This call is to merge all segments at level iLevel. find the next
2997     ** available segment index at level iLevel+1. The call to
2998     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
2999     ** a single iLevel+2 segment if necessary.  */
3000     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
3001     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
3002   }
3003   if( rc!=SQLITE_OK ) goto finished;
3004   assert( csr.nSegment>0 );
3005   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
3006   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
3007 
3008   memset(&filter, 0, sizeof(Fts3SegFilter));
3009   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
3010   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
3011 
3012   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
3013   while( SQLITE_OK==rc ){
3014     rc = sqlite3Fts3SegReaderStep(p, &csr);
3015     if( rc!=SQLITE_ROW ) break;
3016     rc = fts3SegWriterAdd(p, &pWriter, 1,
3017         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
3018   }
3019   if( rc!=SQLITE_OK ) goto finished;
3020   assert( pWriter );
3021 
3022   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
3023     rc = fts3DeleteSegdir(
3024         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
3025     );
3026     if( rc!=SQLITE_OK ) goto finished;
3027   }
3028   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
3029 
3030  finished:
3031   fts3SegWriterFree(pWriter);
3032   sqlite3Fts3SegReaderFinish(&csr);
3033   return rc;
3034 }
3035 
3036 
3037 /*
3038 ** Flush the contents of pendingTerms to level 0 segments.
3039 */
3040 int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
3041   int rc = SQLITE_OK;
3042   int i;
3043 
3044   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
3045     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
3046     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
3047   }
3048   sqlite3Fts3PendingTermsClear(p);
3049 
3050   /* Determine the auto-incr-merge setting if unknown.  If enabled,
3051   ** estimate the number of leaf blocks of content to be written
3052   */
3053   if( rc==SQLITE_OK && p->bHasStat
3054    && p->bAutoincrmerge==0xff && p->nLeafAdd>0
3055   ){
3056     sqlite3_stmt *pStmt = 0;
3057     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
3058     if( rc==SQLITE_OK ){
3059       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
3060       rc = sqlite3_step(pStmt);
3061       p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
3062       rc = sqlite3_reset(pStmt);
3063     }
3064   }
3065   return rc;
3066 }
3067 
3068 /*
3069 ** Encode N integers as varints into a blob.
3070 */
3071 static void fts3EncodeIntArray(
3072   int N,             /* The number of integers to encode */
3073   u32 *a,            /* The integer values */
3074   char *zBuf,        /* Write the BLOB here */
3075   int *pNBuf         /* Write number of bytes if zBuf[] used here */
3076 ){
3077   int i, j;
3078   for(i=j=0; i<N; i++){
3079     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
3080   }
3081   *pNBuf = j;
3082 }
3083 
3084 /*
3085 ** Decode a blob of varints into N integers
3086 */
3087 static void fts3DecodeIntArray(
3088   int N,             /* The number of integers to decode */
3089   u32 *a,            /* Write the integer values */
3090   const char *zBuf,  /* The BLOB containing the varints */
3091   int nBuf           /* size of the BLOB */
3092 ){
3093   int i, j;
3094   UNUSED_PARAMETER(nBuf);
3095   for(i=j=0; i<N; i++){
3096     sqlite3_int64 x;
3097     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
3098     assert(j<=nBuf);
3099     a[i] = (u32)(x & 0xffffffff);
3100   }
3101 }
3102 
3103 /*
3104 ** Insert the sizes (in tokens) for each column of the document
3105 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
3106 ** a blob of varints.
3107 */
3108 static void fts3InsertDocsize(
3109   int *pRC,                       /* Result code */
3110   Fts3Table *p,                   /* Table into which to insert */
3111   u32 *aSz                        /* Sizes of each column, in tokens */
3112 ){
3113   char *pBlob;             /* The BLOB encoding of the document size */
3114   int nBlob;               /* Number of bytes in the BLOB */
3115   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
3116   int rc;                  /* Result code from subfunctions */
3117 
3118   if( *pRC ) return;
3119   pBlob = sqlite3_malloc( 10*p->nColumn );
3120   if( pBlob==0 ){
3121     *pRC = SQLITE_NOMEM;
3122     return;
3123   }
3124   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
3125   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
3126   if( rc ){
3127     sqlite3_free(pBlob);
3128     *pRC = rc;
3129     return;
3130   }
3131   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
3132   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
3133   sqlite3_step(pStmt);
3134   *pRC = sqlite3_reset(pStmt);
3135 }
3136 
3137 /*
3138 ** Record 0 of the %_stat table contains a blob consisting of N varints,
3139 ** where N is the number of user defined columns in the fts3 table plus
3140 ** two. If nCol is the number of user defined columns, then values of the
3141 ** varints are set as follows:
3142 **
3143 **   Varint 0:       Total number of rows in the table.
3144 **
3145 **   Varint 1..nCol: For each column, the total number of tokens stored in
3146 **                   the column for all rows of the table.
3147 **
3148 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
3149 **                   columns of all rows of the table.
3150 **
3151 */
3152 static void fts3UpdateDocTotals(
3153   int *pRC,                       /* The result code */
3154   Fts3Table *p,                   /* Table being updated */
3155   u32 *aSzIns,                    /* Size increases */
3156   u32 *aSzDel,                    /* Size decreases */
3157   int nChng                       /* Change in the number of documents */
3158 ){
3159   char *pBlob;             /* Storage for BLOB written into %_stat */
3160   int nBlob;               /* Size of BLOB written into %_stat */
3161   u32 *a;                  /* Array of integers that becomes the BLOB */
3162   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
3163   int i;                   /* Loop counter */
3164   int rc;                  /* Result code from subfunctions */
3165 
3166   const int nStat = p->nColumn+2;
3167 
3168   if( *pRC ) return;
3169   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
3170   if( a==0 ){
3171     *pRC = SQLITE_NOMEM;
3172     return;
3173   }
3174   pBlob = (char*)&a[nStat];
3175   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
3176   if( rc ){
3177     sqlite3_free(a);
3178     *pRC = rc;
3179     return;
3180   }
3181   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
3182   if( sqlite3_step(pStmt)==SQLITE_ROW ){
3183     fts3DecodeIntArray(nStat, a,
3184          sqlite3_column_blob(pStmt, 0),
3185          sqlite3_column_bytes(pStmt, 0));
3186   }else{
3187     memset(a, 0, sizeof(u32)*(nStat) );
3188   }
3189   rc = sqlite3_reset(pStmt);
3190   if( rc!=SQLITE_OK ){
3191     sqlite3_free(a);
3192     *pRC = rc;
3193     return;
3194   }
3195   if( nChng<0 && a[0]<(u32)(-nChng) ){
3196     a[0] = 0;
3197   }else{
3198     a[0] += nChng;
3199   }
3200   for(i=0; i<p->nColumn+1; i++){
3201     u32 x = a[i+1];
3202     if( x+aSzIns[i] < aSzDel[i] ){
3203       x = 0;
3204     }else{
3205       x = x + aSzIns[i] - aSzDel[i];
3206     }
3207     a[i+1] = x;
3208   }
3209   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
3210   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
3211   if( rc ){
3212     sqlite3_free(a);
3213     *pRC = rc;
3214     return;
3215   }
3216   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
3217   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
3218   sqlite3_step(pStmt);
3219   *pRC = sqlite3_reset(pStmt);
3220   sqlite3_free(a);
3221 }
3222 
3223 /*
3224 ** Merge the entire database so that there is one segment for each
3225 ** iIndex/iLangid combination.
3226 */
3227 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
3228   int bSeenDone = 0;
3229   int rc;
3230   sqlite3_stmt *pAllLangid = 0;
3231 
3232   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
3233   if( rc==SQLITE_OK ){
3234     int rc2;
3235     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
3236     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
3237       int i;
3238       int iLangid = sqlite3_column_int(pAllLangid, 0);
3239       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
3240         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
3241         if( rc==SQLITE_DONE ){
3242           bSeenDone = 1;
3243           rc = SQLITE_OK;
3244         }
3245       }
3246     }
3247     rc2 = sqlite3_reset(pAllLangid);
3248     if( rc==SQLITE_OK ) rc = rc2;
3249   }
3250 
3251   sqlite3Fts3SegmentsClose(p);
3252   sqlite3Fts3PendingTermsClear(p);
3253 
3254   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
3255 }
3256 
3257 /*
3258 ** This function is called when the user executes the following statement:
3259 **
3260 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
3261 **
3262 ** The entire FTS index is discarded and rebuilt. If the table is one
3263 ** created using the content=xxx option, then the new index is based on
3264 ** the current contents of the xxx table. Otherwise, it is rebuilt based
3265 ** on the contents of the %_content table.
3266 */
3267 static int fts3DoRebuild(Fts3Table *p){
3268   int rc;                         /* Return Code */
3269 
3270   rc = fts3DeleteAll(p, 0);
3271   if( rc==SQLITE_OK ){
3272     u32 *aSz = 0;
3273     u32 *aSzIns = 0;
3274     u32 *aSzDel = 0;
3275     sqlite3_stmt *pStmt = 0;
3276     int nEntry = 0;
3277 
3278     /* Compose and prepare an SQL statement to loop through the content table */
3279     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
3280     if( !zSql ){
3281       rc = SQLITE_NOMEM;
3282     }else{
3283       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3284       sqlite3_free(zSql);
3285     }
3286 
3287     if( rc==SQLITE_OK ){
3288       int nByte = sizeof(u32) * (p->nColumn+1)*3;
3289       aSz = (u32 *)sqlite3_malloc(nByte);
3290       if( aSz==0 ){
3291         rc = SQLITE_NOMEM;
3292       }else{
3293         memset(aSz, 0, nByte);
3294         aSzIns = &aSz[p->nColumn+1];
3295         aSzDel = &aSzIns[p->nColumn+1];
3296       }
3297     }
3298 
3299     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
3300       int iCol;
3301       int iLangid = langidFromSelect(p, pStmt);
3302       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
3303       memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
3304       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
3305         if( p->abNotindexed[iCol]==0 ){
3306           const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
3307           rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
3308           aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
3309         }
3310       }
3311       if( p->bHasDocsize ){
3312         fts3InsertDocsize(&rc, p, aSz);
3313       }
3314       if( rc!=SQLITE_OK ){
3315         sqlite3_finalize(pStmt);
3316         pStmt = 0;
3317       }else{
3318         nEntry++;
3319         for(iCol=0; iCol<=p->nColumn; iCol++){
3320           aSzIns[iCol] += aSz[iCol];
3321         }
3322       }
3323     }
3324     if( p->bFts4 ){
3325       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
3326     }
3327     sqlite3_free(aSz);
3328 
3329     if( pStmt ){
3330       int rc2 = sqlite3_finalize(pStmt);
3331       if( rc==SQLITE_OK ){
3332         rc = rc2;
3333       }
3334     }
3335   }
3336 
3337   return rc;
3338 }
3339 
3340 
3341 /*
3342 ** This function opens a cursor used to read the input data for an
3343 ** incremental merge operation. Specifically, it opens a cursor to scan
3344 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
3345 ** level iAbsLevel.
3346 */
3347 static int fts3IncrmergeCsr(
3348   Fts3Table *p,                   /* FTS3 table handle */
3349   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
3350   int nSeg,                       /* Number of segments to merge */
3351   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
3352 ){
3353   int rc;                         /* Return Code */
3354   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
3355   int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
3356 
3357   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
3358   memset(pCsr, 0, sizeof(*pCsr));
3359   nByte = sizeof(Fts3SegReader *) * nSeg;
3360   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
3361 
3362   if( pCsr->apSegment==0 ){
3363     rc = SQLITE_NOMEM;
3364   }else{
3365     memset(pCsr->apSegment, 0, nByte);
3366     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
3367   }
3368   if( rc==SQLITE_OK ){
3369     int i;
3370     int rc2;
3371     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
3372     assert( pCsr->nSegment==0 );
3373     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
3374       rc = sqlite3Fts3SegReaderNew(i, 0,
3375           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
3376           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
3377           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
3378           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
3379           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
3380           &pCsr->apSegment[i]
3381       );
3382       pCsr->nSegment++;
3383     }
3384     rc2 = sqlite3_reset(pStmt);
3385     if( rc==SQLITE_OK ) rc = rc2;
3386   }
3387 
3388   return rc;
3389 }
3390 
3391 typedef struct IncrmergeWriter IncrmergeWriter;
3392 typedef struct NodeWriter NodeWriter;
3393 typedef struct Blob Blob;
3394 typedef struct NodeReader NodeReader;
3395 
3396 /*
3397 ** An instance of the following structure is used as a dynamic buffer
3398 ** to build up nodes or other blobs of data in.
3399 **
3400 ** The function blobGrowBuffer() is used to extend the allocation.
3401 */
3402 struct Blob {
3403   char *a;                        /* Pointer to allocation */
3404   int n;                          /* Number of valid bytes of data in a[] */
3405   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
3406 };
3407 
3408 /*
3409 ** This structure is used to build up buffers containing segment b-tree
3410 ** nodes (blocks).
3411 */
3412 struct NodeWriter {
3413   sqlite3_int64 iBlock;           /* Current block id */
3414   Blob key;                       /* Last key written to the current block */
3415   Blob block;                     /* Current block image */
3416 };
3417 
3418 /*
3419 ** An object of this type contains the state required to create or append
3420 ** to an appendable b-tree segment.
3421 */
3422 struct IncrmergeWriter {
3423   int nLeafEst;                   /* Space allocated for leaf blocks */
3424   int nWork;                      /* Number of leaf pages flushed */
3425   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
3426   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
3427   sqlite3_int64 iStart;           /* Block number of first allocated block */
3428   sqlite3_int64 iEnd;             /* Block number of last allocated block */
3429   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
3430 };
3431 
3432 /*
3433 ** An object of the following type is used to read data from a single
3434 ** FTS segment node. See the following functions:
3435 **
3436 **     nodeReaderInit()
3437 **     nodeReaderNext()
3438 **     nodeReaderRelease()
3439 */
3440 struct NodeReader {
3441   const char *aNode;
3442   int nNode;
3443   int iOff;                       /* Current offset within aNode[] */
3444 
3445   /* Output variables. Containing the current node entry. */
3446   sqlite3_int64 iChild;           /* Pointer to child node */
3447   Blob term;                      /* Current term */
3448   const char *aDoclist;           /* Pointer to doclist */
3449   int nDoclist;                   /* Size of doclist in bytes */
3450 };
3451 
3452 /*
3453 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
3454 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
3455 ** bytes in size, extend (realloc) it to be so.
3456 **
3457 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
3458 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
3459 ** to reflect the new size of the pBlob->a[] buffer.
3460 */
3461 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
3462   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
3463     int nAlloc = nMin;
3464     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
3465     if( a ){
3466       pBlob->nAlloc = nAlloc;
3467       pBlob->a = a;
3468     }else{
3469       *pRc = SQLITE_NOMEM;
3470     }
3471   }
3472 }
3473 
3474 /*
3475 ** Attempt to advance the node-reader object passed as the first argument to
3476 ** the next entry on the node.
3477 **
3478 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
3479 ** Otherwise return SQLITE_OK. If there is no next entry on the node
3480 ** (e.g. because the current entry is the last) set NodeReader->aNode to
3481 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
3482 ** variables for the new entry.
3483 */
3484 static int nodeReaderNext(NodeReader *p){
3485   int bFirst = (p->term.n==0);    /* True for first term on the node */
3486   int nPrefix = 0;                /* Bytes to copy from previous term */
3487   int nSuffix = 0;                /* Bytes to append to the prefix */
3488   int rc = SQLITE_OK;             /* Return code */
3489 
3490   assert( p->aNode );
3491   if( p->iChild && bFirst==0 ) p->iChild++;
3492   if( p->iOff>=p->nNode ){
3493     /* EOF */
3494     p->aNode = 0;
3495   }else{
3496     if( bFirst==0 ){
3497       p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
3498     }
3499     p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
3500 
3501     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
3502     if( rc==SQLITE_OK ){
3503       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
3504       p->term.n = nPrefix+nSuffix;
3505       p->iOff += nSuffix;
3506       if( p->iChild==0 ){
3507         p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
3508         p->aDoclist = &p->aNode[p->iOff];
3509         p->iOff += p->nDoclist;
3510       }
3511     }
3512   }
3513 
3514   assert( p->iOff<=p->nNode );
3515 
3516   return rc;
3517 }
3518 
3519 /*
3520 ** Release all dynamic resources held by node-reader object *p.
3521 */
3522 static void nodeReaderRelease(NodeReader *p){
3523   sqlite3_free(p->term.a);
3524 }
3525 
3526 /*
3527 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
3528 **
3529 ** If successful, SQLITE_OK is returned and the NodeReader object set to
3530 ** point to the first entry on the node (if any). Otherwise, an SQLite
3531 ** error code is returned.
3532 */
3533 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
3534   memset(p, 0, sizeof(NodeReader));
3535   p->aNode = aNode;
3536   p->nNode = nNode;
3537 
3538   /* Figure out if this is a leaf or an internal node. */
3539   if( p->aNode[0] ){
3540     /* An internal node. */
3541     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
3542   }else{
3543     p->iOff = 1;
3544   }
3545 
3546   return nodeReaderNext(p);
3547 }
3548 
3549 /*
3550 ** This function is called while writing an FTS segment each time a leaf o
3551 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
3552 ** to be greater than the largest key on the node just written, but smaller
3553 ** than or equal to the first key that will be written to the next leaf
3554 ** node.
3555 **
3556 ** The block id of the leaf node just written to disk may be found in
3557 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
3558 */
3559 static int fts3IncrmergePush(
3560   Fts3Table *p,                   /* Fts3 table handle */
3561   IncrmergeWriter *pWriter,       /* Writer object */
3562   const char *zTerm,              /* Term to write to internal node */
3563   int nTerm                       /* Bytes at zTerm */
3564 ){
3565   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
3566   int iLayer;
3567 
3568   assert( nTerm>0 );
3569   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
3570     sqlite3_int64 iNextPtr = 0;
3571     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
3572     int rc = SQLITE_OK;
3573     int nPrefix;
3574     int nSuffix;
3575     int nSpace;
3576 
3577     /* Figure out how much space the key will consume if it is written to
3578     ** the current node of layer iLayer. Due to the prefix compression,
3579     ** the space required changes depending on which node the key is to
3580     ** be added to.  */
3581     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
3582     nSuffix = nTerm - nPrefix;
3583     nSpace  = sqlite3Fts3VarintLen(nPrefix);
3584     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
3585 
3586     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
3587       /* If the current node of layer iLayer contains zero keys, or if adding
3588       ** the key to it will not cause it to grow to larger than nNodeSize
3589       ** bytes in size, write the key here.  */
3590 
3591       Blob *pBlk = &pNode->block;
3592       if( pBlk->n==0 ){
3593         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
3594         if( rc==SQLITE_OK ){
3595           pBlk->a[0] = (char)iLayer;
3596           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
3597         }
3598       }
3599       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
3600       blobGrowBuffer(&pNode->key, nTerm, &rc);
3601 
3602       if( rc==SQLITE_OK ){
3603         if( pNode->key.n ){
3604           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
3605         }
3606         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
3607         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
3608         pBlk->n += nSuffix;
3609 
3610         memcpy(pNode->key.a, zTerm, nTerm);
3611         pNode->key.n = nTerm;
3612       }
3613     }else{
3614       /* Otherwise, flush the current node of layer iLayer to disk.
3615       ** Then allocate a new, empty sibling node. The key will be written
3616       ** into the parent of this node. */
3617       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
3618 
3619       assert( pNode->block.nAlloc>=p->nNodeSize );
3620       pNode->block.a[0] = (char)iLayer;
3621       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
3622 
3623       iNextPtr = pNode->iBlock;
3624       pNode->iBlock++;
3625       pNode->key.n = 0;
3626     }
3627 
3628     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
3629     iPtr = iNextPtr;
3630   }
3631 
3632   assert( 0 );
3633   return 0;
3634 }
3635 
3636 /*
3637 ** Append a term and (optionally) doclist to the FTS segment node currently
3638 ** stored in blob *pNode. The node need not contain any terms, but the
3639 ** header must be written before this function is called.
3640 **
3641 ** A node header is a single 0x00 byte for a leaf node, or a height varint
3642 ** followed by the left-hand-child varint for an internal node.
3643 **
3644 ** The term to be appended is passed via arguments zTerm/nTerm. For a
3645 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
3646 ** node, both aDoclist and nDoclist must be passed 0.
3647 **
3648 ** If the size of the value in blob pPrev is zero, then this is the first
3649 ** term written to the node. Otherwise, pPrev contains a copy of the
3650 ** previous term. Before this function returns, it is updated to contain a
3651 ** copy of zTerm/nTerm.
3652 **
3653 ** It is assumed that the buffer associated with pNode is already large
3654 ** enough to accommodate the new entry. The buffer associated with pPrev
3655 ** is extended by this function if requrired.
3656 **
3657 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
3658 ** returned. Otherwise, SQLITE_OK.
3659 */
3660 static int fts3AppendToNode(
3661   Blob *pNode,                    /* Current node image to append to */
3662   Blob *pPrev,                    /* Buffer containing previous term written */
3663   const char *zTerm,              /* New term to write */
3664   int nTerm,                      /* Size of zTerm in bytes */
3665   const char *aDoclist,           /* Doclist (or NULL) to write */
3666   int nDoclist                    /* Size of aDoclist in bytes */
3667 ){
3668   int rc = SQLITE_OK;             /* Return code */
3669   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
3670   int nPrefix;                    /* Size of term prefix in bytes */
3671   int nSuffix;                    /* Size of term suffix in bytes */
3672 
3673   /* Node must have already been started. There must be a doclist for a
3674   ** leaf node, and there must not be a doclist for an internal node.  */
3675   assert( pNode->n>0 );
3676   assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
3677 
3678   blobGrowBuffer(pPrev, nTerm, &rc);
3679   if( rc!=SQLITE_OK ) return rc;
3680 
3681   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
3682   nSuffix = nTerm - nPrefix;
3683   memcpy(pPrev->a, zTerm, nTerm);
3684   pPrev->n = nTerm;
3685 
3686   if( bFirst==0 ){
3687     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
3688   }
3689   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
3690   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
3691   pNode->n += nSuffix;
3692 
3693   if( aDoclist ){
3694     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
3695     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
3696     pNode->n += nDoclist;
3697   }
3698 
3699   assert( pNode->n<=pNode->nAlloc );
3700 
3701   return SQLITE_OK;
3702 }
3703 
3704 /*
3705 ** Append the current term and doclist pointed to by cursor pCsr to the
3706 ** appendable b-tree segment opened for writing by pWriter.
3707 **
3708 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
3709 */
3710 static int fts3IncrmergeAppend(
3711   Fts3Table *p,                   /* Fts3 table handle */
3712   IncrmergeWriter *pWriter,       /* Writer object */
3713   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
3714 ){
3715   const char *zTerm = pCsr->zTerm;
3716   int nTerm = pCsr->nTerm;
3717   const char *aDoclist = pCsr->aDoclist;
3718   int nDoclist = pCsr->nDoclist;
3719   int rc = SQLITE_OK;           /* Return code */
3720   int nSpace;                   /* Total space in bytes required on leaf */
3721   int nPrefix;                  /* Size of prefix shared with previous term */
3722   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
3723   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
3724 
3725   pLeaf = &pWriter->aNodeWriter[0];
3726   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
3727   nSuffix = nTerm - nPrefix;
3728 
3729   nSpace  = sqlite3Fts3VarintLen(nPrefix);
3730   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
3731   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
3732 
3733   /* If the current block is not empty, and if adding this term/doclist
3734   ** to the current block would make it larger than Fts3Table.nNodeSize
3735   ** bytes, write this block out to the database. */
3736   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
3737     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
3738     pWriter->nWork++;
3739 
3740     /* Add the current term to the parent node. The term added to the
3741     ** parent must:
3742     **
3743     **   a) be greater than the largest term on the leaf node just written
3744     **      to the database (still available in pLeaf->key), and
3745     **
3746     **   b) be less than or equal to the term about to be added to the new
3747     **      leaf node (zTerm/nTerm).
3748     **
3749     ** In other words, it must be the prefix of zTerm 1 byte longer than
3750     ** the common prefix (if any) of zTerm and pWriter->zTerm.
3751     */
3752     if( rc==SQLITE_OK ){
3753       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
3754     }
3755 
3756     /* Advance to the next output block */
3757     pLeaf->iBlock++;
3758     pLeaf->key.n = 0;
3759     pLeaf->block.n = 0;
3760 
3761     nSuffix = nTerm;
3762     nSpace  = 1;
3763     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
3764     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
3765   }
3766 
3767   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
3768 
3769   if( rc==SQLITE_OK ){
3770     if( pLeaf->block.n==0 ){
3771       pLeaf->block.n = 1;
3772       pLeaf->block.a[0] = '\0';
3773     }
3774     rc = fts3AppendToNode(
3775         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
3776     );
3777   }
3778 
3779   return rc;
3780 }
3781 
3782 /*
3783 ** This function is called to release all dynamic resources held by the
3784 ** merge-writer object pWriter, and if no error has occurred, to flush
3785 ** all outstanding node buffers held by pWriter to disk.
3786 **
3787 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
3788 ** is made to write any data to disk. Instead, this function serves only
3789 ** to release outstanding resources.
3790 **
3791 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
3792 ** flushing buffers to disk, *pRc is set to an SQLite error code before
3793 ** returning.
3794 */
3795 static void fts3IncrmergeRelease(
3796   Fts3Table *p,                   /* FTS3 table handle */
3797   IncrmergeWriter *pWriter,       /* Merge-writer object */
3798   int *pRc                        /* IN/OUT: Error code */
3799 ){
3800   int i;                          /* Used to iterate through non-root layers */
3801   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
3802   NodeWriter *pRoot;              /* NodeWriter for root node */
3803   int rc = *pRc;                  /* Error code */
3804 
3805   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
3806   ** root node. If the segment fits entirely on a single leaf node, iRoot
3807   ** will be set to 0. If the root node is the parent of the leaves, iRoot
3808   ** will be 1. And so on.  */
3809   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
3810     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
3811     if( pNode->block.n>0 ) break;
3812     assert( *pRc || pNode->block.nAlloc==0 );
3813     assert( *pRc || pNode->key.nAlloc==0 );
3814     sqlite3_free(pNode->block.a);
3815     sqlite3_free(pNode->key.a);
3816   }
3817 
3818   /* Empty output segment. This is a no-op. */
3819   if( iRoot<0 ) return;
3820 
3821   /* The entire output segment fits on a single node. Normally, this means
3822   ** the node would be stored as a blob in the "root" column of the %_segdir
3823   ** table. However, this is not permitted in this case. The problem is that
3824   ** space has already been reserved in the %_segments table, and so the
3825   ** start_block and end_block fields of the %_segdir table must be populated.
3826   ** And, by design or by accident, released versions of FTS cannot handle
3827   ** segments that fit entirely on the root node with start_block!=0.
3828   **
3829   ** Instead, create a synthetic root node that contains nothing but a
3830   ** pointer to the single content node. So that the segment consists of a
3831   ** single leaf and a single interior (root) node.
3832   **
3833   ** Todo: Better might be to defer allocating space in the %_segments
3834   ** table until we are sure it is needed.
3835   */
3836   if( iRoot==0 ){
3837     Blob *pBlock = &pWriter->aNodeWriter[1].block;
3838     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
3839     if( rc==SQLITE_OK ){
3840       pBlock->a[0] = 0x01;
3841       pBlock->n = 1 + sqlite3Fts3PutVarint(
3842           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
3843       );
3844     }
3845     iRoot = 1;
3846   }
3847   pRoot = &pWriter->aNodeWriter[iRoot];
3848 
3849   /* Flush all currently outstanding nodes to disk. */
3850   for(i=0; i<iRoot; i++){
3851     NodeWriter *pNode = &pWriter->aNodeWriter[i];
3852     if( pNode->block.n>0 && rc==SQLITE_OK ){
3853       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
3854     }
3855     sqlite3_free(pNode->block.a);
3856     sqlite3_free(pNode->key.a);
3857   }
3858 
3859   /* Write the %_segdir record. */
3860   if( rc==SQLITE_OK ){
3861     rc = fts3WriteSegdir(p,
3862         pWriter->iAbsLevel+1,               /* level */
3863         pWriter->iIdx,                      /* idx */
3864         pWriter->iStart,                    /* start_block */
3865         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
3866         pWriter->iEnd,                      /* end_block */
3867         pRoot->block.a, pRoot->block.n      /* root */
3868     );
3869   }
3870   sqlite3_free(pRoot->block.a);
3871   sqlite3_free(pRoot->key.a);
3872 
3873   *pRc = rc;
3874 }
3875 
3876 /*
3877 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
3878 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
3879 ** the other, it is considered to be smaller than the other.
3880 **
3881 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
3882 ** if it is greater.
3883 */
3884 static int fts3TermCmp(
3885   const char *zLhs, int nLhs,     /* LHS of comparison */
3886   const char *zRhs, int nRhs      /* RHS of comparison */
3887 ){
3888   int nCmp = MIN(nLhs, nRhs);
3889   int res;
3890 
3891   res = memcmp(zLhs, zRhs, nCmp);
3892   if( res==0 ) res = nLhs - nRhs;
3893 
3894   return res;
3895 }
3896 
3897 
3898 /*
3899 ** Query to see if the entry in the %_segments table with blockid iEnd is
3900 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
3901 ** returning. Otherwise, set *pbRes to 0.
3902 **
3903 ** Or, if an error occurs while querying the database, return an SQLite
3904 ** error code. The final value of *pbRes is undefined in this case.
3905 **
3906 ** This is used to test if a segment is an "appendable" segment. If it
3907 ** is, then a NULL entry has been inserted into the %_segments table
3908 ** with blockid %_segdir.end_block.
3909 */
3910 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
3911   int bRes = 0;                   /* Result to set *pbRes to */
3912   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
3913   int rc;                         /* Return code */
3914 
3915   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
3916   if( rc==SQLITE_OK ){
3917     sqlite3_bind_int64(pCheck, 1, iEnd);
3918     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
3919     rc = sqlite3_reset(pCheck);
3920   }
3921 
3922   *pbRes = bRes;
3923   return rc;
3924 }
3925 
3926 /*
3927 ** This function is called when initializing an incremental-merge operation.
3928 ** It checks if the existing segment with index value iIdx at absolute level
3929 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
3930 ** merge-writer object *pWriter is initialized to write to it.
3931 **
3932 ** An existing segment can be appended to by an incremental merge if:
3933 **
3934 **   * It was initially created as an appendable segment (with all required
3935 **     space pre-allocated), and
3936 **
3937 **   * The first key read from the input (arguments zKey and nKey) is
3938 **     greater than the largest key currently stored in the potential
3939 **     output segment.
3940 */
3941 static int fts3IncrmergeLoad(
3942   Fts3Table *p,                   /* Fts3 table handle */
3943   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
3944   int iIdx,                       /* Index of candidate output segment */
3945   const char *zKey,               /* First key to write */
3946   int nKey,                       /* Number of bytes in nKey */
3947   IncrmergeWriter *pWriter        /* Populate this object */
3948 ){
3949   int rc;                         /* Return code */
3950   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
3951 
3952   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
3953   if( rc==SQLITE_OK ){
3954     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
3955     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
3956     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
3957     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
3958     int nRoot = 0;                /* Size of aRoot[] in bytes */
3959     int rc2;                      /* Return code from sqlite3_reset() */
3960     int bAppendable = 0;          /* Set to true if segment is appendable */
3961 
3962     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
3963     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
3964     sqlite3_bind_int(pSelect, 2, iIdx);
3965     if( sqlite3_step(pSelect)==SQLITE_ROW ){
3966       iStart = sqlite3_column_int64(pSelect, 1);
3967       iLeafEnd = sqlite3_column_int64(pSelect, 2);
3968       iEnd = sqlite3_column_int64(pSelect, 3);
3969       nRoot = sqlite3_column_bytes(pSelect, 4);
3970       aRoot = sqlite3_column_blob(pSelect, 4);
3971     }else{
3972       return sqlite3_reset(pSelect);
3973     }
3974 
3975     /* Check for the zero-length marker in the %_segments table */
3976     rc = fts3IsAppendable(p, iEnd, &bAppendable);
3977 
3978     /* Check that zKey/nKey is larger than the largest key the candidate */
3979     if( rc==SQLITE_OK && bAppendable ){
3980       char *aLeaf = 0;
3981       int nLeaf = 0;
3982 
3983       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
3984       if( rc==SQLITE_OK ){
3985         NodeReader reader;
3986         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
3987             rc==SQLITE_OK && reader.aNode;
3988             rc = nodeReaderNext(&reader)
3989         ){
3990           assert( reader.aNode );
3991         }
3992         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
3993           bAppendable = 0;
3994         }
3995         nodeReaderRelease(&reader);
3996       }
3997       sqlite3_free(aLeaf);
3998     }
3999 
4000     if( rc==SQLITE_OK && bAppendable ){
4001       /* It is possible to append to this segment. Set up the IncrmergeWriter
4002       ** object to do so.  */
4003       int i;
4004       int nHeight = (int)aRoot[0];
4005       NodeWriter *pNode;
4006 
4007       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
4008       pWriter->iStart = iStart;
4009       pWriter->iEnd = iEnd;
4010       pWriter->iAbsLevel = iAbsLevel;
4011       pWriter->iIdx = iIdx;
4012 
4013       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
4014         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
4015       }
4016 
4017       pNode = &pWriter->aNodeWriter[nHeight];
4018       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
4019       blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
4020       if( rc==SQLITE_OK ){
4021         memcpy(pNode->block.a, aRoot, nRoot);
4022         pNode->block.n = nRoot;
4023       }
4024 
4025       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
4026         NodeReader reader;
4027         pNode = &pWriter->aNodeWriter[i];
4028 
4029         rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
4030         while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
4031         blobGrowBuffer(&pNode->key, reader.term.n, &rc);
4032         if( rc==SQLITE_OK ){
4033           memcpy(pNode->key.a, reader.term.a, reader.term.n);
4034           pNode->key.n = reader.term.n;
4035           if( i>0 ){
4036             char *aBlock = 0;
4037             int nBlock = 0;
4038             pNode = &pWriter->aNodeWriter[i-1];
4039             pNode->iBlock = reader.iChild;
4040             rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
4041             blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
4042             if( rc==SQLITE_OK ){
4043               memcpy(pNode->block.a, aBlock, nBlock);
4044               pNode->block.n = nBlock;
4045             }
4046             sqlite3_free(aBlock);
4047           }
4048         }
4049         nodeReaderRelease(&reader);
4050       }
4051     }
4052 
4053     rc2 = sqlite3_reset(pSelect);
4054     if( rc==SQLITE_OK ) rc = rc2;
4055   }
4056 
4057   return rc;
4058 }
4059 
4060 /*
4061 ** Determine the largest segment index value that exists within absolute
4062 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
4063 ** one before returning SQLITE_OK. Or, if there are no segments at all
4064 ** within level iAbsLevel, set *piIdx to zero.
4065 **
4066 ** If an error occurs, return an SQLite error code. The final value of
4067 ** *piIdx is undefined in this case.
4068 */
4069 static int fts3IncrmergeOutputIdx(
4070   Fts3Table *p,                   /* FTS Table handle */
4071   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
4072   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
4073 ){
4074   int rc;
4075   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
4076 
4077   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
4078   if( rc==SQLITE_OK ){
4079     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
4080     sqlite3_step(pOutputIdx);
4081     *piIdx = sqlite3_column_int(pOutputIdx, 0);
4082     rc = sqlite3_reset(pOutputIdx);
4083   }
4084 
4085   return rc;
4086 }
4087 
4088 /*
4089 ** Allocate an appendable output segment on absolute level iAbsLevel+1
4090 ** with idx value iIdx.
4091 **
4092 ** In the %_segdir table, a segment is defined by the values in three
4093 ** columns:
4094 **
4095 **     start_block
4096 **     leaves_end_block
4097 **     end_block
4098 **
4099 ** When an appendable segment is allocated, it is estimated that the
4100 ** maximum number of leaf blocks that may be required is the sum of the
4101 ** number of leaf blocks consumed by the input segments, plus the number
4102 ** of input segments, multiplied by two. This value is stored in stack
4103 ** variable nLeafEst.
4104 **
4105 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
4106 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
4107 ** array of leaf nodes starts at the first block allocated. The array
4108 ** of interior nodes that are parents of the leaf nodes start at block
4109 ** (start_block + (1 + end_block - start_block) / 16). And so on.
4110 **
4111 ** In the actual code below, the value "16" is replaced with the
4112 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
4113 */
4114 static int fts3IncrmergeWriter(
4115   Fts3Table *p,                   /* Fts3 table handle */
4116   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
4117   int iIdx,                       /* Index of new output segment */
4118   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
4119   IncrmergeWriter *pWriter        /* Populate this object */
4120 ){
4121   int rc;                         /* Return Code */
4122   int i;                          /* Iterator variable */
4123   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
4124   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
4125   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
4126 
4127   /* Calculate nLeafEst. */
4128   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
4129   if( rc==SQLITE_OK ){
4130     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
4131     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
4132     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
4133       nLeafEst = sqlite3_column_int(pLeafEst, 0);
4134     }
4135     rc = sqlite3_reset(pLeafEst);
4136   }
4137   if( rc!=SQLITE_OK ) return rc;
4138 
4139   /* Calculate the first block to use in the output segment */
4140   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
4141   if( rc==SQLITE_OK ){
4142     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
4143       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
4144       pWriter->iEnd = pWriter->iStart - 1;
4145       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
4146     }
4147     rc = sqlite3_reset(pFirstBlock);
4148   }
4149   if( rc!=SQLITE_OK ) return rc;
4150 
4151   /* Insert the marker in the %_segments table to make sure nobody tries
4152   ** to steal the space just allocated. This is also used to identify
4153   ** appendable segments.  */
4154   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
4155   if( rc!=SQLITE_OK ) return rc;
4156 
4157   pWriter->iAbsLevel = iAbsLevel;
4158   pWriter->nLeafEst = nLeafEst;
4159   pWriter->iIdx = iIdx;
4160 
4161   /* Set up the array of NodeWriter objects */
4162   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
4163     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
4164   }
4165   return SQLITE_OK;
4166 }
4167 
4168 /*
4169 ** Remove an entry from the %_segdir table. This involves running the
4170 ** following two statements:
4171 **
4172 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
4173 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
4174 **
4175 ** The DELETE statement removes the specific %_segdir level. The UPDATE
4176 ** statement ensures that the remaining segments have contiguously allocated
4177 ** idx values.
4178 */
4179 static int fts3RemoveSegdirEntry(
4180   Fts3Table *p,                   /* FTS3 table handle */
4181   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
4182   int iIdx                        /* Index of %_segdir entry to delete */
4183 ){
4184   int rc;                         /* Return code */
4185   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
4186 
4187   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
4188   if( rc==SQLITE_OK ){
4189     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
4190     sqlite3_bind_int(pDelete, 2, iIdx);
4191     sqlite3_step(pDelete);
4192     rc = sqlite3_reset(pDelete);
4193   }
4194 
4195   return rc;
4196 }
4197 
4198 /*
4199 ** One or more segments have just been removed from absolute level iAbsLevel.
4200 ** Update the 'idx' values of the remaining segments in the level so that
4201 ** the idx values are a contiguous sequence starting from 0.
4202 */
4203 static int fts3RepackSegdirLevel(
4204   Fts3Table *p,                   /* FTS3 table handle */
4205   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
4206 ){
4207   int rc;                         /* Return code */
4208   int *aIdx = 0;                  /* Array of remaining idx values */
4209   int nIdx = 0;                   /* Valid entries in aIdx[] */
4210   int nAlloc = 0;                 /* Allocated size of aIdx[] */
4211   int i;                          /* Iterator variable */
4212   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
4213   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
4214 
4215   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
4216   if( rc==SQLITE_OK ){
4217     int rc2;
4218     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
4219     while( SQLITE_ROW==sqlite3_step(pSelect) ){
4220       if( nIdx>=nAlloc ){
4221         int *aNew;
4222         nAlloc += 16;
4223         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
4224         if( !aNew ){
4225           rc = SQLITE_NOMEM;
4226           break;
4227         }
4228         aIdx = aNew;
4229       }
4230       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
4231     }
4232     rc2 = sqlite3_reset(pSelect);
4233     if( rc==SQLITE_OK ) rc = rc2;
4234   }
4235 
4236   if( rc==SQLITE_OK ){
4237     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
4238   }
4239   if( rc==SQLITE_OK ){
4240     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
4241   }
4242 
4243   assert( p->bIgnoreSavepoint==0 );
4244   p->bIgnoreSavepoint = 1;
4245   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
4246     if( aIdx[i]!=i ){
4247       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
4248       sqlite3_bind_int(pUpdate, 1, i);
4249       sqlite3_step(pUpdate);
4250       rc = sqlite3_reset(pUpdate);
4251     }
4252   }
4253   p->bIgnoreSavepoint = 0;
4254 
4255   sqlite3_free(aIdx);
4256   return rc;
4257 }
4258 
4259 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
4260   pNode->a[0] = (char)iHeight;
4261   if( iChild ){
4262     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
4263     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
4264   }else{
4265     assert( pNode->nAlloc>=1 );
4266     pNode->n = 1;
4267   }
4268 }
4269 
4270 /*
4271 ** The first two arguments are a pointer to and the size of a segment b-tree
4272 ** node. The node may be a leaf or an internal node.
4273 **
4274 ** This function creates a new node image in blob object *pNew by copying
4275 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
4276 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
4277 */
4278 static int fts3TruncateNode(
4279   const char *aNode,              /* Current node image */
4280   int nNode,                      /* Size of aNode in bytes */
4281   Blob *pNew,                     /* OUT: Write new node image here */
4282   const char *zTerm,              /* Omit all terms smaller than this */
4283   int nTerm,                      /* Size of zTerm in bytes */
4284   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
4285 ){
4286   NodeReader reader;              /* Reader object */
4287   Blob prev = {0, 0, 0};          /* Previous term written to new node */
4288   int rc = SQLITE_OK;             /* Return code */
4289   int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
4290 
4291   /* Allocate required output space */
4292   blobGrowBuffer(pNew, nNode, &rc);
4293   if( rc!=SQLITE_OK ) return rc;
4294   pNew->n = 0;
4295 
4296   /* Populate new node buffer */
4297   for(rc = nodeReaderInit(&reader, aNode, nNode);
4298       rc==SQLITE_OK && reader.aNode;
4299       rc = nodeReaderNext(&reader)
4300   ){
4301     if( pNew->n==0 ){
4302       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
4303       if( res<0 || (bLeaf==0 && res==0) ) continue;
4304       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
4305       *piBlock = reader.iChild;
4306     }
4307     rc = fts3AppendToNode(
4308         pNew, &prev, reader.term.a, reader.term.n,
4309         reader.aDoclist, reader.nDoclist
4310     );
4311     if( rc!=SQLITE_OK ) break;
4312   }
4313   if( pNew->n==0 ){
4314     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
4315     *piBlock = reader.iChild;
4316   }
4317   assert( pNew->n<=pNew->nAlloc );
4318 
4319   nodeReaderRelease(&reader);
4320   sqlite3_free(prev.a);
4321   return rc;
4322 }
4323 
4324 /*
4325 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
4326 ** level iAbsLevel. This may involve deleting entries from the %_segments
4327 ** table, and modifying existing entries in both the %_segments and %_segdir
4328 ** tables.
4329 **
4330 ** SQLITE_OK is returned if the segment is updated successfully. Or an
4331 ** SQLite error code otherwise.
4332 */
4333 static int fts3TruncateSegment(
4334   Fts3Table *p,                   /* FTS3 table handle */
4335   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
4336   int iIdx,                       /* Index within level of segment to modify */
4337   const char *zTerm,              /* Remove terms smaller than this */
4338   int nTerm                      /* Number of bytes in buffer zTerm */
4339 ){
4340   int rc = SQLITE_OK;             /* Return code */
4341   Blob root = {0,0,0};            /* New root page image */
4342   Blob block = {0,0,0};           /* Buffer used for any other block */
4343   sqlite3_int64 iBlock = 0;       /* Block id */
4344   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
4345   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
4346   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
4347 
4348   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
4349   if( rc==SQLITE_OK ){
4350     int rc2;                      /* sqlite3_reset() return code */
4351     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
4352     sqlite3_bind_int(pFetch, 2, iIdx);
4353     if( SQLITE_ROW==sqlite3_step(pFetch) ){
4354       const char *aRoot = sqlite3_column_blob(pFetch, 4);
4355       int nRoot = sqlite3_column_bytes(pFetch, 4);
4356       iOldStart = sqlite3_column_int64(pFetch, 1);
4357       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
4358     }
4359     rc2 = sqlite3_reset(pFetch);
4360     if( rc==SQLITE_OK ) rc = rc2;
4361   }
4362 
4363   while( rc==SQLITE_OK && iBlock ){
4364     char *aBlock = 0;
4365     int nBlock = 0;
4366     iNewStart = iBlock;
4367 
4368     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
4369     if( rc==SQLITE_OK ){
4370       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
4371     }
4372     if( rc==SQLITE_OK ){
4373       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
4374     }
4375     sqlite3_free(aBlock);
4376   }
4377 
4378   /* Variable iNewStart now contains the first valid leaf node. */
4379   if( rc==SQLITE_OK && iNewStart ){
4380     sqlite3_stmt *pDel = 0;
4381     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
4382     if( rc==SQLITE_OK ){
4383       sqlite3_bind_int64(pDel, 1, iOldStart);
4384       sqlite3_bind_int64(pDel, 2, iNewStart-1);
4385       sqlite3_step(pDel);
4386       rc = sqlite3_reset(pDel);
4387     }
4388   }
4389 
4390   if( rc==SQLITE_OK ){
4391     sqlite3_stmt *pChomp = 0;
4392     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
4393     if( rc==SQLITE_OK ){
4394       sqlite3_bind_int64(pChomp, 1, iNewStart);
4395       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
4396       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
4397       sqlite3_bind_int(pChomp, 4, iIdx);
4398       sqlite3_step(pChomp);
4399       rc = sqlite3_reset(pChomp);
4400     }
4401   }
4402 
4403   sqlite3_free(root.a);
4404   sqlite3_free(block.a);
4405   return rc;
4406 }
4407 
4408 /*
4409 ** This function is called after an incrmental-merge operation has run to
4410 ** merge (or partially merge) two or more segments from absolute level
4411 ** iAbsLevel.
4412 **
4413 ** Each input segment is either removed from the db completely (if all of
4414 ** its data was copied to the output segment by the incrmerge operation)
4415 ** or modified in place so that it no longer contains those entries that
4416 ** have been duplicated in the output segment.
4417 */
4418 static int fts3IncrmergeChomp(
4419   Fts3Table *p,                   /* FTS table handle */
4420   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
4421   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
4422   int *pnRem                      /* Number of segments not deleted */
4423 ){
4424   int i;
4425   int nRem = 0;
4426   int rc = SQLITE_OK;
4427 
4428   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
4429     Fts3SegReader *pSeg = 0;
4430     int j;
4431 
4432     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
4433     ** somewhere in the pCsr->apSegment[] array.  */
4434     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
4435       pSeg = pCsr->apSegment[j];
4436       if( pSeg->iIdx==i ) break;
4437     }
4438     assert( j<pCsr->nSegment && pSeg->iIdx==i );
4439 
4440     if( pSeg->aNode==0 ){
4441       /* Seg-reader is at EOF. Remove the entire input segment. */
4442       rc = fts3DeleteSegment(p, pSeg);
4443       if( rc==SQLITE_OK ){
4444         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
4445       }
4446       *pnRem = 0;
4447     }else{
4448       /* The incremental merge did not copy all the data from this
4449       ** segment to the upper level. The segment is modified in place
4450       ** so that it contains no keys smaller than zTerm/nTerm. */
4451       const char *zTerm = pSeg->zTerm;
4452       int nTerm = pSeg->nTerm;
4453       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
4454       nRem++;
4455     }
4456   }
4457 
4458   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
4459     rc = fts3RepackSegdirLevel(p, iAbsLevel);
4460   }
4461 
4462   *pnRem = nRem;
4463   return rc;
4464 }
4465 
4466 /*
4467 ** Store an incr-merge hint in the database.
4468 */
4469 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
4470   sqlite3_stmt *pReplace = 0;
4471   int rc;                         /* Return code */
4472 
4473   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
4474   if( rc==SQLITE_OK ){
4475     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
4476     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
4477     sqlite3_step(pReplace);
4478     rc = sqlite3_reset(pReplace);
4479   }
4480 
4481   return rc;
4482 }
4483 
4484 /*
4485 ** Load an incr-merge hint from the database. The incr-merge hint, if one
4486 ** exists, is stored in the rowid==1 row of the %_stat table.
4487 **
4488 ** If successful, populate blob *pHint with the value read from the %_stat
4489 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
4490 ** SQLite error code.
4491 */
4492 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
4493   sqlite3_stmt *pSelect = 0;
4494   int rc;
4495 
4496   pHint->n = 0;
4497   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
4498   if( rc==SQLITE_OK ){
4499     int rc2;
4500     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
4501     if( SQLITE_ROW==sqlite3_step(pSelect) ){
4502       const char *aHint = sqlite3_column_blob(pSelect, 0);
4503       int nHint = sqlite3_column_bytes(pSelect, 0);
4504       if( aHint ){
4505         blobGrowBuffer(pHint, nHint, &rc);
4506         if( rc==SQLITE_OK ){
4507           memcpy(pHint->a, aHint, nHint);
4508           pHint->n = nHint;
4509         }
4510       }
4511     }
4512     rc2 = sqlite3_reset(pSelect);
4513     if( rc==SQLITE_OK ) rc = rc2;
4514   }
4515 
4516   return rc;
4517 }
4518 
4519 /*
4520 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
4521 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
4522 ** consists of two varints, the absolute level number of the input segments
4523 ** and the number of input segments.
4524 **
4525 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
4526 ** set *pRc to an SQLite error code before returning.
4527 */
4528 static void fts3IncrmergeHintPush(
4529   Blob *pHint,                    /* Hint blob to append to */
4530   i64 iAbsLevel,                  /* First varint to store in hint */
4531   int nInput,                     /* Second varint to store in hint */
4532   int *pRc                        /* IN/OUT: Error code */
4533 ){
4534   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
4535   if( *pRc==SQLITE_OK ){
4536     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
4537     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
4538   }
4539 }
4540 
4541 /*
4542 ** Read the last entry (most recently pushed) from the hint blob *pHint
4543 ** and then remove the entry. Write the two values read to *piAbsLevel and
4544 ** *pnInput before returning.
4545 **
4546 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
4547 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
4548 */
4549 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
4550   const int nHint = pHint->n;
4551   int i;
4552 
4553   i = pHint->n-2;
4554   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
4555   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
4556 
4557   pHint->n = i;
4558   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
4559   i += fts3GetVarint32(&pHint->a[i], pnInput);
4560   if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
4561 
4562   return SQLITE_OK;
4563 }
4564 
4565 
4566 /*
4567 ** Attempt an incremental merge that writes nMerge leaf blocks.
4568 **
4569 ** Incremental merges happen nMin segments at a time. The two
4570 ** segments to be merged are the nMin oldest segments (the ones with
4571 ** the smallest indexes) in the highest level that contains at least
4572 ** nMin segments. Multiple merges might occur in an attempt to write the
4573 ** quota of nMerge leaf blocks.
4574 */
4575 int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
4576   int rc;                         /* Return code */
4577   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
4578   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
4579   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
4580   IncrmergeWriter *pWriter;       /* Writer object */
4581   int nSeg = 0;                   /* Number of input segments */
4582   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
4583   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
4584   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
4585 
4586   /* Allocate space for the cursor, filter and writer objects */
4587   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
4588   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
4589   if( !pWriter ) return SQLITE_NOMEM;
4590   pFilter = (Fts3SegFilter *)&pWriter[1];
4591   pCsr = (Fts3MultiSegReader *)&pFilter[1];
4592 
4593   rc = fts3IncrmergeHintLoad(p, &hint);
4594   while( rc==SQLITE_OK && nRem>0 ){
4595     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
4596     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
4597     int bUseHint = 0;             /* True if attempting to append */
4598 
4599     /* Search the %_segdir table for the absolute level with the smallest
4600     ** relative level number that contains at least nMin segments, if any.
4601     ** If one is found, set iAbsLevel to the absolute level number and
4602     ** nSeg to nMin. If no level with at least nMin segments can be found,
4603     ** set nSeg to -1.
4604     */
4605     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
4606     sqlite3_bind_int(pFindLevel, 1, nMin);
4607     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
4608       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
4609       nSeg = nMin;
4610     }else{
4611       nSeg = -1;
4612     }
4613     rc = sqlite3_reset(pFindLevel);
4614 
4615     /* If the hint read from the %_stat table is not empty, check if the
4616     ** last entry in it specifies a relative level smaller than or equal
4617     ** to the level identified by the block above (if any). If so, this
4618     ** iteration of the loop will work on merging at the hinted level.
4619     */
4620     if( rc==SQLITE_OK && hint.n ){
4621       int nHint = hint.n;
4622       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
4623       int nHintSeg = 0;                     /* Hint number of segments */
4624 
4625       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
4626       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
4627         iAbsLevel = iHintAbsLevel;
4628         nSeg = nHintSeg;
4629         bUseHint = 1;
4630         bDirtyHint = 1;
4631       }else{
4632         /* This undoes the effect of the HintPop() above - so that no entry
4633         ** is removed from the hint blob.  */
4634         hint.n = nHint;
4635       }
4636     }
4637 
4638     /* If nSeg is less that zero, then there is no level with at least
4639     ** nMin segments and no hint in the %_stat table. No work to do.
4640     ** Exit early in this case.  */
4641     if( nSeg<0 ) break;
4642 
4643     /* Open a cursor to iterate through the contents of the oldest nSeg
4644     ** indexes of absolute level iAbsLevel. If this cursor is opened using
4645     ** the 'hint' parameters, it is possible that there are less than nSeg
4646     ** segments available in level iAbsLevel. In this case, no work is
4647     ** done on iAbsLevel - fall through to the next iteration of the loop
4648     ** to start work on some other level.  */
4649     memset(pWriter, 0, nAlloc);
4650     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
4651     if( rc==SQLITE_OK ){
4652       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
4653     }
4654     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
4655      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
4656      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
4657     ){
4658       int iIdx = 0;               /* Largest idx in level (iAbsLevel+1) */
4659       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
4660       if( rc==SQLITE_OK ){
4661         if( bUseHint && iIdx>0 ){
4662           const char *zKey = pCsr->zTerm;
4663           int nKey = pCsr->nTerm;
4664           rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
4665         }else{
4666           rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
4667         }
4668       }
4669 
4670       if( rc==SQLITE_OK && pWriter->nLeafEst ){
4671         fts3LogMerge(nSeg, iAbsLevel);
4672         do {
4673           rc = fts3IncrmergeAppend(p, pWriter, pCsr);
4674           if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
4675           if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
4676         }while( rc==SQLITE_ROW );
4677 
4678         /* Update or delete the input segments */
4679         if( rc==SQLITE_OK ){
4680           nRem -= (1 + pWriter->nWork);
4681           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
4682           if( nSeg!=0 ){
4683             bDirtyHint = 1;
4684             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
4685           }
4686         }
4687       }
4688 
4689       fts3IncrmergeRelease(p, pWriter, &rc);
4690     }
4691 
4692     sqlite3Fts3SegReaderFinish(pCsr);
4693   }
4694 
4695   /* Write the hint values into the %_stat table for the next incr-merger */
4696   if( bDirtyHint && rc==SQLITE_OK ){
4697     rc = fts3IncrmergeHintStore(p, &hint);
4698   }
4699 
4700   sqlite3_free(pWriter);
4701   sqlite3_free(hint.a);
4702   return rc;
4703 }
4704 
4705 /*
4706 ** Convert the text beginning at *pz into an integer and return
4707 ** its value.  Advance *pz to point to the first character past
4708 ** the integer.
4709 */
4710 static int fts3Getint(const char **pz){
4711   const char *z = *pz;
4712   int i = 0;
4713   while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
4714   *pz = z;
4715   return i;
4716 }
4717 
4718 /*
4719 ** Process statements of the form:
4720 **
4721 **    INSERT INTO table(table) VALUES('merge=A,B');
4722 **
4723 ** A and B are integers that decode to be the number of leaf pages
4724 ** written for the merge, and the minimum number of segments on a level
4725 ** before it will be selected for a merge, respectively.
4726 */
4727 static int fts3DoIncrmerge(
4728   Fts3Table *p,                   /* FTS3 table handle */
4729   const char *zParam              /* Nul-terminated string containing "A,B" */
4730 ){
4731   int rc;
4732   int nMin = (FTS3_MERGE_COUNT / 2);
4733   int nMerge = 0;
4734   const char *z = zParam;
4735 
4736   /* Read the first integer value */
4737   nMerge = fts3Getint(&z);
4738 
4739   /* If the first integer value is followed by a ',',  read the second
4740   ** integer value. */
4741   if( z[0]==',' && z[1]!='\0' ){
4742     z++;
4743     nMin = fts3Getint(&z);
4744   }
4745 
4746   if( z[0]!='\0' || nMin<2 ){
4747     rc = SQLITE_ERROR;
4748   }else{
4749     rc = SQLITE_OK;
4750     if( !p->bHasStat ){
4751       assert( p->bFts4==0 );
4752       sqlite3Fts3CreateStatTable(&rc, p);
4753     }
4754     if( rc==SQLITE_OK ){
4755       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
4756     }
4757     sqlite3Fts3SegmentsClose(p);
4758   }
4759   return rc;
4760 }
4761 
4762 /*
4763 ** Process statements of the form:
4764 **
4765 **    INSERT INTO table(table) VALUES('automerge=X');
4766 **
4767 ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
4768 ** turn it on.  The setting is persistent.
4769 */
4770 static int fts3DoAutoincrmerge(
4771   Fts3Table *p,                   /* FTS3 table handle */
4772   const char *zParam              /* Nul-terminated string containing boolean */
4773 ){
4774   int rc = SQLITE_OK;
4775   sqlite3_stmt *pStmt = 0;
4776   p->bAutoincrmerge = fts3Getint(&zParam)!=0;
4777   if( !p->bHasStat ){
4778     assert( p->bFts4==0 );
4779     sqlite3Fts3CreateStatTable(&rc, p);
4780     if( rc ) return rc;
4781   }
4782   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
4783   if( rc ) return rc;
4784   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
4785   sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
4786   sqlite3_step(pStmt);
4787   rc = sqlite3_reset(pStmt);
4788   return rc;
4789 }
4790 
4791 /*
4792 ** Return a 64-bit checksum for the FTS index entry specified by the
4793 ** arguments to this function.
4794 */
4795 static u64 fts3ChecksumEntry(
4796   const char *zTerm,              /* Pointer to buffer containing term */
4797   int nTerm,                      /* Size of zTerm in bytes */
4798   int iLangid,                    /* Language id for current row */
4799   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
4800   i64 iDocid,                     /* Docid for current row. */
4801   int iCol,                       /* Column number */
4802   int iPos                        /* Position */
4803 ){
4804   int i;
4805   u64 ret = (u64)iDocid;
4806 
4807   ret += (ret<<3) + iLangid;
4808   ret += (ret<<3) + iIndex;
4809   ret += (ret<<3) + iCol;
4810   ret += (ret<<3) + iPos;
4811   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
4812 
4813   return ret;
4814 }
4815 
4816 /*
4817 ** Return a checksum of all entries in the FTS index that correspond to
4818 ** language id iLangid. The checksum is calculated by XORing the checksums
4819 ** of each individual entry (see fts3ChecksumEntry()) together.
4820 **
4821 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
4822 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
4823 ** return value is undefined in this case.
4824 */
4825 static u64 fts3ChecksumIndex(
4826   Fts3Table *p,                   /* FTS3 table handle */
4827   int iLangid,                    /* Language id to return cksum for */
4828   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
4829   int *pRc                        /* OUT: Return code */
4830 ){
4831   Fts3SegFilter filter;
4832   Fts3MultiSegReader csr;
4833   int rc;
4834   u64 cksum = 0;
4835 
4836   assert( *pRc==SQLITE_OK );
4837 
4838   memset(&filter, 0, sizeof(filter));
4839   memset(&csr, 0, sizeof(csr));
4840   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
4841   filter.flags |= FTS3_SEGMENT_SCAN;
4842 
4843   rc = sqlite3Fts3SegReaderCursor(
4844       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
4845   );
4846   if( rc==SQLITE_OK ){
4847     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
4848   }
4849 
4850   if( rc==SQLITE_OK ){
4851     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
4852       char *pCsr = csr.aDoclist;
4853       char *pEnd = &pCsr[csr.nDoclist];
4854 
4855       i64 iDocid = 0;
4856       i64 iCol = 0;
4857       i64 iPos = 0;
4858 
4859       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
4860       while( pCsr<pEnd ){
4861         i64 iVal = 0;
4862         pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
4863         if( pCsr<pEnd ){
4864           if( iVal==0 || iVal==1 ){
4865             iCol = 0;
4866             iPos = 0;
4867             if( iVal ){
4868               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
4869             }else{
4870               pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
4871               iDocid += iVal;
4872             }
4873           }else{
4874             iPos += (iVal - 2);
4875             cksum = cksum ^ fts3ChecksumEntry(
4876                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
4877                 (int)iCol, (int)iPos
4878             );
4879           }
4880         }
4881       }
4882     }
4883   }
4884   sqlite3Fts3SegReaderFinish(&csr);
4885 
4886   *pRc = rc;
4887   return cksum;
4888 }
4889 
4890 /*
4891 ** Check if the contents of the FTS index match the current contents of the
4892 ** content table. If no error occurs and the contents do match, set *pbOk
4893 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
4894 ** to false before returning.
4895 **
4896 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
4897 ** code. The final value of *pbOk is undefined in this case.
4898 */
4899 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
4900   int rc = SQLITE_OK;             /* Return code */
4901   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
4902   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
4903   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
4904 
4905   /* This block calculates the checksum according to the FTS index. */
4906   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
4907   if( rc==SQLITE_OK ){
4908     int rc2;
4909     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
4910     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
4911       int iLangid = sqlite3_column_int(pAllLangid, 0);
4912       int i;
4913       for(i=0; i<p->nIndex; i++){
4914         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
4915       }
4916     }
4917     rc2 = sqlite3_reset(pAllLangid);
4918     if( rc==SQLITE_OK ) rc = rc2;
4919   }
4920 
4921   /* This block calculates the checksum according to the %_content table */
4922   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
4923   if( rc==SQLITE_OK ){
4924     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
4925     sqlite3_stmt *pStmt = 0;
4926     char *zSql;
4927 
4928     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
4929     if( !zSql ){
4930       rc = SQLITE_NOMEM;
4931     }else{
4932       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4933       sqlite3_free(zSql);
4934     }
4935 
4936     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
4937       i64 iDocid = sqlite3_column_int64(pStmt, 0);
4938       int iLang = langidFromSelect(p, pStmt);
4939       int iCol;
4940 
4941       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
4942         const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
4943         int nText = sqlite3_column_bytes(pStmt, iCol+1);
4944         sqlite3_tokenizer_cursor *pT = 0;
4945 
4946         rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
4947         while( rc==SQLITE_OK ){
4948           char const *zToken;       /* Buffer containing token */
4949           int nToken = 0;           /* Number of bytes in token */
4950           int iDum1 = 0, iDum2 = 0; /* Dummy variables */
4951           int iPos = 0;             /* Position of token in zText */
4952 
4953           rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
4954           if( rc==SQLITE_OK ){
4955             int i;
4956             cksum2 = cksum2 ^ fts3ChecksumEntry(
4957                 zToken, nToken, iLang, 0, iDocid, iCol, iPos
4958             );
4959             for(i=1; i<p->nIndex; i++){
4960               if( p->aIndex[i].nPrefix<=nToken ){
4961                 cksum2 = cksum2 ^ fts3ChecksumEntry(
4962                   zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
4963                 );
4964               }
4965             }
4966           }
4967         }
4968         if( pT ) pModule->xClose(pT);
4969         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
4970       }
4971     }
4972 
4973     sqlite3_finalize(pStmt);
4974   }
4975 
4976   *pbOk = (cksum1==cksum2);
4977   return rc;
4978 }
4979 
4980 /*
4981 ** Run the integrity-check. If no error occurs and the current contents of
4982 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
4983 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
4984 **
4985 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
4986 ** error code.
4987 **
4988 ** The integrity-check works as follows. For each token and indexed token
4989 ** prefix in the document set, a 64-bit checksum is calculated (by code
4990 ** in fts3ChecksumEntry()) based on the following:
4991 **
4992 **     + The index number (0 for the main index, 1 for the first prefix
4993 **       index etc.),
4994 **     + The token (or token prefix) text itself,
4995 **     + The language-id of the row it appears in,
4996 **     + The docid of the row it appears in,
4997 **     + The column it appears in, and
4998 **     + The tokens position within that column.
4999 **
5000 ** The checksums for all entries in the index are XORed together to create
5001 ** a single checksum for the entire index.
5002 **
5003 ** The integrity-check code calculates the same checksum in two ways:
5004 **
5005 **     1. By scanning the contents of the FTS index, and
5006 **     2. By scanning and tokenizing the content table.
5007 **
5008 ** If the two checksums are identical, the integrity-check is deemed to have
5009 ** passed.
5010 */
5011 static int fts3DoIntegrityCheck(
5012   Fts3Table *p                    /* FTS3 table handle */
5013 ){
5014   int rc;
5015   int bOk = 0;
5016   rc = fts3IntegrityCheck(p, &bOk);
5017   if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
5018   return rc;
5019 }
5020 
5021 /*
5022 ** Handle a 'special' INSERT of the form:
5023 **
5024 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
5025 **
5026 ** Argument pVal contains the result of <expr>. Currently the only
5027 ** meaningful value to insert is the text 'optimize'.
5028 */
5029 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
5030   int rc;                         /* Return Code */
5031   const char *zVal = (const char *)sqlite3_value_text(pVal);
5032   int nVal = sqlite3_value_bytes(pVal);
5033 
5034   if( !zVal ){
5035     return SQLITE_NOMEM;
5036   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
5037     rc = fts3DoOptimize(p, 0);
5038   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
5039     rc = fts3DoRebuild(p);
5040   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
5041     rc = fts3DoIntegrityCheck(p);
5042   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
5043     rc = fts3DoIncrmerge(p, &zVal[6]);
5044   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
5045     rc = fts3DoAutoincrmerge(p, &zVal[10]);
5046 #ifdef SQLITE_TEST
5047   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
5048     p->nNodeSize = atoi(&zVal[9]);
5049     rc = SQLITE_OK;
5050   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
5051     p->nMaxPendingData = atoi(&zVal[11]);
5052     rc = SQLITE_OK;
5053   }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
5054     p->bNoIncrDoclist = atoi(&zVal[21]);
5055     rc = SQLITE_OK;
5056 #endif
5057   }else{
5058     rc = SQLITE_ERROR;
5059   }
5060 
5061   return rc;
5062 }
5063 
5064 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
5065 /*
5066 ** Delete all cached deferred doclists. Deferred doclists are cached
5067 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
5068 */
5069 void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
5070   Fts3DeferredToken *pDef;
5071   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
5072     fts3PendingListDelete(pDef->pList);
5073     pDef->pList = 0;
5074   }
5075 }
5076 
5077 /*
5078 ** Free all entries in the pCsr->pDeffered list. Entries are added to
5079 ** this list using sqlite3Fts3DeferToken().
5080 */
5081 void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
5082   Fts3DeferredToken *pDef;
5083   Fts3DeferredToken *pNext;
5084   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
5085     pNext = pDef->pNext;
5086     fts3PendingListDelete(pDef->pList);
5087     sqlite3_free(pDef);
5088   }
5089   pCsr->pDeferred = 0;
5090 }
5091 
5092 /*
5093 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
5094 ** based on the row that pCsr currently points to.
5095 **
5096 ** A deferred-doclist is like any other doclist with position information
5097 ** included, except that it only contains entries for a single row of the
5098 ** table, not for all rows.
5099 */
5100 int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
5101   int rc = SQLITE_OK;             /* Return code */
5102   if( pCsr->pDeferred ){
5103     int i;                        /* Used to iterate through table columns */
5104     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
5105     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
5106 
5107     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
5108     sqlite3_tokenizer *pT = p->pTokenizer;
5109     sqlite3_tokenizer_module const *pModule = pT->pModule;
5110 
5111     assert( pCsr->isRequireSeek==0 );
5112     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
5113 
5114     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
5115       if( p->abNotindexed[i]==0 ){
5116         const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
5117         sqlite3_tokenizer_cursor *pTC = 0;
5118 
5119         rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
5120         while( rc==SQLITE_OK ){
5121           char const *zToken;       /* Buffer containing token */
5122           int nToken = 0;           /* Number of bytes in token */
5123           int iDum1 = 0, iDum2 = 0; /* Dummy variables */
5124           int iPos = 0;             /* Position of token in zText */
5125 
5126           rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
5127           for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
5128             Fts3PhraseToken *pPT = pDef->pToken;
5129             if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
5130                 && (pPT->bFirst==0 || iPos==0)
5131                 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
5132                 && (0==memcmp(zToken, pPT->z, pPT->n))
5133               ){
5134               fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
5135             }
5136           }
5137         }
5138         if( pTC ) pModule->xClose(pTC);
5139         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
5140       }
5141     }
5142 
5143     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
5144       if( pDef->pList ){
5145         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
5146       }
5147     }
5148   }
5149 
5150   return rc;
5151 }
5152 
5153 int sqlite3Fts3DeferredTokenList(
5154   Fts3DeferredToken *p,
5155   char **ppData,
5156   int *pnData
5157 ){
5158   char *pRet;
5159   int nSkip;
5160   sqlite3_int64 dummy;
5161 
5162   *ppData = 0;
5163   *pnData = 0;
5164 
5165   if( p->pList==0 ){
5166     return SQLITE_OK;
5167   }
5168 
5169   pRet = (char *)sqlite3_malloc(p->pList->nData);
5170   if( !pRet ) return SQLITE_NOMEM;
5171 
5172   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
5173   *pnData = p->pList->nData - nSkip;
5174   *ppData = pRet;
5175 
5176   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
5177   return SQLITE_OK;
5178 }
5179 
5180 /*
5181 ** Add an entry for token pToken to the pCsr->pDeferred list.
5182 */
5183 int sqlite3Fts3DeferToken(
5184   Fts3Cursor *pCsr,               /* Fts3 table cursor */
5185   Fts3PhraseToken *pToken,        /* Token to defer */
5186   int iCol                        /* Column that token must appear in (or -1) */
5187 ){
5188   Fts3DeferredToken *pDeferred;
5189   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
5190   if( !pDeferred ){
5191     return SQLITE_NOMEM;
5192   }
5193   memset(pDeferred, 0, sizeof(*pDeferred));
5194   pDeferred->pToken = pToken;
5195   pDeferred->pNext = pCsr->pDeferred;
5196   pDeferred->iCol = iCol;
5197   pCsr->pDeferred = pDeferred;
5198 
5199   assert( pToken->pDeferred==0 );
5200   pToken->pDeferred = pDeferred;
5201 
5202   return SQLITE_OK;
5203 }
5204 #endif
5205 
5206 /*
5207 ** SQLite value pRowid contains the rowid of a row that may or may not be
5208 ** present in the FTS3 table. If it is, delete it and adjust the contents
5209 ** of subsiduary data structures accordingly.
5210 */
5211 static int fts3DeleteByRowid(
5212   Fts3Table *p,
5213   sqlite3_value *pRowid,
5214   int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
5215   u32 *aSzDel
5216 ){
5217   int rc = SQLITE_OK;             /* Return code */
5218   int bFound = 0;                 /* True if *pRowid really is in the table */
5219 
5220   fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
5221   if( bFound && rc==SQLITE_OK ){
5222     int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
5223     rc = fts3IsEmpty(p, pRowid, &isEmpty);
5224     if( rc==SQLITE_OK ){
5225       if( isEmpty ){
5226         /* Deleting this row means the whole table is empty. In this case
5227         ** delete the contents of all three tables and throw away any
5228         ** data in the pendingTerms hash table.  */
5229         rc = fts3DeleteAll(p, 1);
5230         *pnChng = 0;
5231         memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
5232       }else{
5233         *pnChng = *pnChng - 1;
5234         if( p->zContentTbl==0 ){
5235           fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
5236         }
5237         if( p->bHasDocsize ){
5238           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
5239         }
5240       }
5241     }
5242   }
5243 
5244   return rc;
5245 }
5246 
5247 /*
5248 ** This function does the work for the xUpdate method of FTS3 virtual
5249 ** tables. The schema of the virtual table being:
5250 **
5251 **     CREATE TABLE <table name>(
5252 **       <user columns>,
5253 **       <table name> HIDDEN,
5254 **       docid HIDDEN,
5255 **       <langid> HIDDEN
5256 **     );
5257 **
5258 **
5259 */
5260 int sqlite3Fts3UpdateMethod(
5261   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
5262   int nArg,                       /* Size of argument array */
5263   sqlite3_value **apVal,          /* Array of arguments */
5264   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
5265 ){
5266   Fts3Table *p = (Fts3Table *)pVtab;
5267   int rc = SQLITE_OK;             /* Return Code */
5268   int isRemove = 0;               /* True for an UPDATE or DELETE */
5269   u32 *aSzIns = 0;                /* Sizes of inserted documents */
5270   u32 *aSzDel = 0;                /* Sizes of deleted documents */
5271   int nChng = 0;                  /* Net change in number of documents */
5272   int bInsertDone = 0;
5273 
5274   assert( p->pSegments==0 );
5275   assert(
5276       nArg==1                     /* DELETE operations */
5277    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
5278   );
5279 
5280   /* Check for a "special" INSERT operation. One of the form:
5281   **
5282   **   INSERT INTO xyz(xyz) VALUES('command');
5283   */
5284   if( nArg>1
5285    && sqlite3_value_type(apVal[0])==SQLITE_NULL
5286    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
5287   ){
5288     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
5289     goto update_out;
5290   }
5291 
5292   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
5293     rc = SQLITE_CONSTRAINT;
5294     goto update_out;
5295   }
5296 
5297   /* Allocate space to hold the change in document sizes */
5298   aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
5299   if( aSzDel==0 ){
5300     rc = SQLITE_NOMEM;
5301     goto update_out;
5302   }
5303   aSzIns = &aSzDel[p->nColumn+1];
5304   memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
5305 
5306   rc = fts3Writelock(p);
5307   if( rc!=SQLITE_OK ) goto update_out;
5308 
5309   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
5310   ** value, then this operation requires constraint handling.
5311   **
5312   ** If the on-conflict mode is REPLACE, this means that the existing row
5313   ** should be deleted from the database before inserting the new row. Or,
5314   ** if the on-conflict mode is other than REPLACE, then this method must
5315   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
5316   ** modify the database file.
5317   */
5318   if( nArg>1 && p->zContentTbl==0 ){
5319     /* Find the value object that holds the new rowid value. */
5320     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
5321     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
5322       pNewRowid = apVal[1];
5323     }
5324 
5325     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
5326         sqlite3_value_type(apVal[0])==SQLITE_NULL
5327      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
5328     )){
5329       /* The new rowid is not NULL (in this case the rowid will be
5330       ** automatically assigned and there is no chance of a conflict), and
5331       ** the statement is either an INSERT or an UPDATE that modifies the
5332       ** rowid column. So if the conflict mode is REPLACE, then delete any
5333       ** existing row with rowid=pNewRowid.
5334       **
5335       ** Or, if the conflict mode is not REPLACE, insert the new record into
5336       ** the %_content table. If we hit the duplicate rowid constraint (or any
5337       ** other error) while doing so, return immediately.
5338       **
5339       ** This branch may also run if pNewRowid contains a value that cannot
5340       ** be losslessly converted to an integer. In this case, the eventual
5341       ** call to fts3InsertData() (either just below or further on in this
5342       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
5343       ** invoked, it will delete zero rows (since no row will have
5344       ** docid=$pNewRowid if $pNewRowid is not an integer value).
5345       */
5346       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
5347         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
5348       }else{
5349         rc = fts3InsertData(p, apVal, pRowid);
5350         bInsertDone = 1;
5351       }
5352     }
5353   }
5354   if( rc!=SQLITE_OK ){
5355     goto update_out;
5356   }
5357 
5358   /* If this is a DELETE or UPDATE operation, remove the old record. */
5359   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
5360     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
5361     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
5362     isRemove = 1;
5363   }
5364 
5365   /* If this is an INSERT or UPDATE operation, insert the new record. */
5366   if( nArg>1 && rc==SQLITE_OK ){
5367     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
5368     if( bInsertDone==0 ){
5369       rc = fts3InsertData(p, apVal, pRowid);
5370       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
5371         rc = FTS_CORRUPT_VTAB;
5372       }
5373     }
5374     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
5375       rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
5376     }
5377     if( rc==SQLITE_OK ){
5378       assert( p->iPrevDocid==*pRowid );
5379       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
5380     }
5381     if( p->bHasDocsize ){
5382       fts3InsertDocsize(&rc, p, aSzIns);
5383     }
5384     nChng++;
5385   }
5386 
5387   if( p->bFts4 ){
5388     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
5389   }
5390 
5391  update_out:
5392   sqlite3_free(aSzDel);
5393   sqlite3Fts3SegmentsClose(p);
5394   return rc;
5395 }
5396 
5397 /*
5398 ** Flush any data in the pending-terms hash table to disk. If successful,
5399 ** merge all segments in the database (including the new segment, if
5400 ** there was any data to flush) into a single segment.
5401 */
5402 int sqlite3Fts3Optimize(Fts3Table *p){
5403   int rc;
5404   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
5405   if( rc==SQLITE_OK ){
5406     rc = fts3DoOptimize(p, 1);
5407     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
5408       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
5409       if( rc2!=SQLITE_OK ) rc = rc2;
5410     }else{
5411       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
5412       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
5413     }
5414   }
5415   sqlite3Fts3SegmentsClose(p);
5416   return rc;
5417 }
5418 
5419 #endif
5420