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