xref: /sqlite-3.40.0/ext/fts3/fts3_write.c (revision e455e3ac)
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, 2 DESC 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     u64 iDelta = (u64)iDocid - (u64)(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 = FTS_CORRUPT_VTAB;
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         u64 iDelta;
1535         pReader->pOffsetList = p + sqlite3Fts3GetVarintU(p, &iDelta);
1536         if( pTab->bDescIdx ){
1537           pReader->iDocid = (i64)((u64)pReader->iDocid - iDelta);
1538         }else{
1539           pReader->iDocid = (i64)((u64)pReader->iDocid + iDelta);
1540         }
1541       }
1542     }
1543   }
1544 
1545   return rc;
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     if( pWriter->iFree==LARGEST_INT64 ) return FTS_CORRUPT_VTAB;
2285     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
2286     if( rc!=SQLITE_OK ) return rc;
2287     p->nLeafAdd++;
2288 
2289     /* Add the current term to the interior node tree. The term added to
2290     ** the interior tree must:
2291     **
2292     **   a) be greater than the largest term on the leaf node just written
2293     **      to the database (still available in pWriter->zTerm), and
2294     **
2295     **   b) be less than or equal to the term about to be added to the new
2296     **      leaf node (zTerm/nTerm).
2297     **
2298     ** In other words, it must be the prefix of zTerm 1 byte longer than
2299     ** the common prefix (if any) of zTerm and pWriter->zTerm.
2300     */
2301     assert( nPrefix<nTerm );
2302     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
2303     if( rc!=SQLITE_OK ) return rc;
2304 
2305     nData = 0;
2306     pWriter->nTerm = 0;
2307 
2308     nPrefix = 0;
2309     nSuffix = nTerm;
2310     nReq = 1 +                              /* varint containing prefix size */
2311       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
2312       nTerm +                               /* Term suffix */
2313       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
2314       nDoclist;                             /* Doclist data */
2315   }
2316 
2317   /* Increase the total number of bytes written to account for the new entry. */
2318   pWriter->nLeafData += nReq;
2319 
2320   /* If the buffer currently allocated is too small for this entry, realloc
2321   ** the buffer to make it large enough.
2322   */
2323   if( nReq>pWriter->nSize ){
2324     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
2325     if( !aNew ) return SQLITE_NOMEM;
2326     pWriter->aData = aNew;
2327     pWriter->nSize = nReq;
2328   }
2329   assert( nData+nReq<=pWriter->nSize );
2330 
2331   /* Append the prefix-compressed term and doclist to the buffer. */
2332   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
2333   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
2334   assert( nSuffix>0 );
2335   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
2336   nData += nSuffix;
2337   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
2338   assert( nDoclist>0 );
2339   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
2340   pWriter->nData = nData + nDoclist;
2341 
2342   /* Save the current term so that it can be used to prefix-compress the next.
2343   ** If the isCopyTerm parameter is true, then the buffer pointed to by
2344   ** zTerm is transient, so take a copy of the term data. Otherwise, just
2345   ** store a copy of the pointer.
2346   */
2347   if( isCopyTerm ){
2348     if( nTerm>pWriter->nMalloc ){
2349       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
2350       if( !zNew ){
2351         return SQLITE_NOMEM;
2352       }
2353       pWriter->nMalloc = nTerm*2;
2354       pWriter->zMalloc = zNew;
2355       pWriter->zTerm = zNew;
2356     }
2357     assert( pWriter->zTerm==pWriter->zMalloc );
2358     assert( nTerm>0 );
2359     memcpy(pWriter->zTerm, zTerm, nTerm);
2360   }else{
2361     pWriter->zTerm = (char *)zTerm;
2362   }
2363   pWriter->nTerm = nTerm;
2364 
2365   return SQLITE_OK;
2366 }
2367 
2368 /*
2369 ** Flush all data associated with the SegmentWriter object pWriter to the
2370 ** database. This function must be called after all terms have been added
2371 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
2372 ** returned. Otherwise, an SQLite error code.
2373 */
2374 static int fts3SegWriterFlush(
2375   Fts3Table *p,                   /* Virtual table handle */
2376   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
2377   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
2378   int iIdx                        /* Value for 'idx' column of %_segdir */
2379 ){
2380   int rc;                         /* Return code */
2381   if( pWriter->pTree ){
2382     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
2383     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
2384     char *zRoot = NULL;           /* Pointer to buffer containing root node */
2385     int nRoot = 0;                /* Size of buffer zRoot */
2386 
2387     iLastLeaf = pWriter->iFree;
2388     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
2389     if( rc==SQLITE_OK ){
2390       rc = fts3NodeWrite(p, pWriter->pTree, 1,
2391           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
2392     }
2393     if( rc==SQLITE_OK ){
2394       rc = fts3WriteSegdir(p, iLevel, iIdx,
2395           pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
2396     }
2397   }else{
2398     /* The entire tree fits on the root node. Write it to the segdir table. */
2399     rc = fts3WriteSegdir(p, iLevel, iIdx,
2400         0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
2401   }
2402   p->nLeafAdd++;
2403   return rc;
2404 }
2405 
2406 /*
2407 ** Release all memory held by the SegmentWriter object passed as the
2408 ** first argument.
2409 */
2410 static void fts3SegWriterFree(SegmentWriter *pWriter){
2411   if( pWriter ){
2412     sqlite3_free(pWriter->aData);
2413     sqlite3_free(pWriter->zMalloc);
2414     fts3NodeFree(pWriter->pTree);
2415     sqlite3_free(pWriter);
2416   }
2417 }
2418 
2419 /*
2420 ** The first value in the apVal[] array is assumed to contain an integer.
2421 ** This function tests if there exist any documents with docid values that
2422 ** are different from that integer. i.e. if deleting the document with docid
2423 ** pRowid would mean the FTS3 table were empty.
2424 **
2425 ** If successful, *pisEmpty is set to true if the table is empty except for
2426 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
2427 ** error occurs, an SQLite error code is returned.
2428 */
2429 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
2430   sqlite3_stmt *pStmt;
2431   int rc;
2432   if( p->zContentTbl ){
2433     /* If using the content=xxx option, assume the table is never empty */
2434     *pisEmpty = 0;
2435     rc = SQLITE_OK;
2436   }else{
2437     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
2438     if( rc==SQLITE_OK ){
2439       if( SQLITE_ROW==sqlite3_step(pStmt) ){
2440         *pisEmpty = sqlite3_column_int(pStmt, 0);
2441       }
2442       rc = sqlite3_reset(pStmt);
2443     }
2444   }
2445   return rc;
2446 }
2447 
2448 /*
2449 ** Set *pnMax to the largest segment level in the database for the index
2450 ** iIndex.
2451 **
2452 ** Segment levels are stored in the 'level' column of the %_segdir table.
2453 **
2454 ** Return SQLITE_OK if successful, or an SQLite error code if not.
2455 */
2456 static int fts3SegmentMaxLevel(
2457   Fts3Table *p,
2458   int iLangid,
2459   int iIndex,
2460   sqlite3_int64 *pnMax
2461 ){
2462   sqlite3_stmt *pStmt;
2463   int rc;
2464   assert( iIndex>=0 && iIndex<p->nIndex );
2465 
2466   /* Set pStmt to the compiled version of:
2467   **
2468   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
2469   **
2470   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
2471   */
2472   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
2473   if( rc!=SQLITE_OK ) return rc;
2474   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
2475   sqlite3_bind_int64(pStmt, 2,
2476       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
2477   );
2478   if( SQLITE_ROW==sqlite3_step(pStmt) ){
2479     *pnMax = sqlite3_column_int64(pStmt, 0);
2480   }
2481   return sqlite3_reset(pStmt);
2482 }
2483 
2484 /*
2485 ** iAbsLevel is an absolute level that may be assumed to exist within
2486 ** the database. This function checks if it is the largest level number
2487 ** within its index. Assuming no error occurs, *pbMax is set to 1 if
2488 ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
2489 ** is returned. If an error occurs, an error code is returned and the
2490 ** final value of *pbMax is undefined.
2491 */
2492 static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
2493 
2494   /* Set pStmt to the compiled version of:
2495   **
2496   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
2497   **
2498   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
2499   */
2500   sqlite3_stmt *pStmt;
2501   int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
2502   if( rc!=SQLITE_OK ) return rc;
2503   sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
2504   sqlite3_bind_int64(pStmt, 2,
2505       ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
2506   );
2507 
2508   *pbMax = 0;
2509   if( SQLITE_ROW==sqlite3_step(pStmt) ){
2510     *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
2511   }
2512   return sqlite3_reset(pStmt);
2513 }
2514 
2515 /*
2516 ** Delete all entries in the %_segments table associated with the segment
2517 ** opened with seg-reader pSeg. This function does not affect the contents
2518 ** of the %_segdir table.
2519 */
2520 static int fts3DeleteSegment(
2521   Fts3Table *p,                   /* FTS table handle */
2522   Fts3SegReader *pSeg             /* Segment to delete */
2523 ){
2524   int rc = SQLITE_OK;             /* Return code */
2525   if( pSeg->iStartBlock ){
2526     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
2527     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
2528     if( rc==SQLITE_OK ){
2529       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
2530       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
2531       sqlite3_step(pDelete);
2532       rc = sqlite3_reset(pDelete);
2533     }
2534   }
2535   return rc;
2536 }
2537 
2538 /*
2539 ** This function is used after merging multiple segments into a single large
2540 ** segment to delete the old, now redundant, segment b-trees. Specifically,
2541 ** it:
2542 **
2543 **   1) Deletes all %_segments entries for the segments associated with
2544 **      each of the SegReader objects in the array passed as the third
2545 **      argument, and
2546 **
2547 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
2548 **      entries regardless of level if (iLevel<0).
2549 **
2550 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
2551 */
2552 static int fts3DeleteSegdir(
2553   Fts3Table *p,                   /* Virtual table handle */
2554   int iLangid,                    /* Language id */
2555   int iIndex,                     /* Index for p->aIndex */
2556   int iLevel,                     /* Level of %_segdir entries to delete */
2557   Fts3SegReader **apSegment,      /* Array of SegReader objects */
2558   int nReader                     /* Size of array apSegment */
2559 ){
2560   int rc = SQLITE_OK;             /* Return Code */
2561   int i;                          /* Iterator variable */
2562   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
2563 
2564   for(i=0; rc==SQLITE_OK && i<nReader; i++){
2565     rc = fts3DeleteSegment(p, apSegment[i]);
2566   }
2567   if( rc!=SQLITE_OK ){
2568     return rc;
2569   }
2570 
2571   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
2572   if( iLevel==FTS3_SEGCURSOR_ALL ){
2573     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
2574     if( rc==SQLITE_OK ){
2575       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
2576       sqlite3_bind_int64(pDelete, 2,
2577           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
2578       );
2579     }
2580   }else{
2581     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
2582     if( rc==SQLITE_OK ){
2583       sqlite3_bind_int64(
2584           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
2585       );
2586     }
2587   }
2588 
2589   if( rc==SQLITE_OK ){
2590     sqlite3_step(pDelete);
2591     rc = sqlite3_reset(pDelete);
2592   }
2593 
2594   return rc;
2595 }
2596 
2597 /*
2598 ** When this function is called, buffer *ppList (size *pnList bytes) contains
2599 ** a position list that may (or may not) feature multiple columns. This
2600 ** function adjusts the pointer *ppList and the length *pnList so that they
2601 ** identify the subset of the position list that corresponds to column iCol.
2602 **
2603 ** If there are no entries in the input position list for column iCol, then
2604 ** *pnList is set to zero before returning.
2605 **
2606 ** If parameter bZero is non-zero, then any part of the input list following
2607 ** the end of the output list is zeroed before returning.
2608 */
2609 static void fts3ColumnFilter(
2610   int iCol,                       /* Column to filter on */
2611   int bZero,                      /* Zero out anything following *ppList */
2612   char **ppList,                  /* IN/OUT: Pointer to position list */
2613   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
2614 ){
2615   char *pList = *ppList;
2616   int nList = *pnList;
2617   char *pEnd = &pList[nList];
2618   int iCurrent = 0;
2619   char *p = pList;
2620 
2621   assert( iCol>=0 );
2622   while( 1 ){
2623     char c = 0;
2624     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
2625 
2626     if( iCol==iCurrent ){
2627       nList = (int)(p - pList);
2628       break;
2629     }
2630 
2631     nList -= (int)(p - pList);
2632     pList = p;
2633     if( nList<=0 ){
2634       break;
2635     }
2636     p = &pList[1];
2637     p += fts3GetVarint32(p, &iCurrent);
2638   }
2639 
2640   if( bZero && (pEnd - &pList[nList])>0){
2641     memset(&pList[nList], 0, pEnd - &pList[nList]);
2642   }
2643   *ppList = pList;
2644   *pnList = nList;
2645 }
2646 
2647 /*
2648 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
2649 ** existing data). Grow the buffer if required.
2650 **
2651 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
2652 ** trying to resize the buffer, return SQLITE_NOMEM.
2653 */
2654 static int fts3MsrBufferData(
2655   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
2656   char *pList,
2657   int nList
2658 ){
2659   if( nList>pMsr->nBuffer ){
2660     char *pNew;
2661     pMsr->nBuffer = nList*2;
2662     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
2663     if( !pNew ) return SQLITE_NOMEM;
2664     pMsr->aBuffer = pNew;
2665   }
2666 
2667   assert( nList>0 );
2668   memcpy(pMsr->aBuffer, pList, nList);
2669   return SQLITE_OK;
2670 }
2671 
2672 int sqlite3Fts3MsrIncrNext(
2673   Fts3Table *p,                   /* Virtual table handle */
2674   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
2675   sqlite3_int64 *piDocid,         /* OUT: Docid value */
2676   char **paPoslist,               /* OUT: Pointer to position list */
2677   int *pnPoslist                  /* OUT: Size of position list in bytes */
2678 ){
2679   int nMerge = pMsr->nAdvance;
2680   Fts3SegReader **apSegment = pMsr->apSegment;
2681   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
2682     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
2683   );
2684 
2685   if( nMerge==0 ){
2686     *paPoslist = 0;
2687     return SQLITE_OK;
2688   }
2689 
2690   while( 1 ){
2691     Fts3SegReader *pSeg;
2692     pSeg = pMsr->apSegment[0];
2693 
2694     if( pSeg->pOffsetList==0 ){
2695       *paPoslist = 0;
2696       break;
2697     }else{
2698       int rc;
2699       char *pList;
2700       int nList;
2701       int j;
2702       sqlite3_int64 iDocid = apSegment[0]->iDocid;
2703 
2704       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
2705       j = 1;
2706       while( rc==SQLITE_OK
2707         && j<nMerge
2708         && apSegment[j]->pOffsetList
2709         && apSegment[j]->iDocid==iDocid
2710       ){
2711         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
2712         j++;
2713       }
2714       if( rc!=SQLITE_OK ) return rc;
2715       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
2716 
2717       if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
2718         rc = fts3MsrBufferData(pMsr, pList, nList+1);
2719         if( rc!=SQLITE_OK ) return rc;
2720         assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
2721         pList = pMsr->aBuffer;
2722       }
2723 
2724       if( pMsr->iColFilter>=0 ){
2725         fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
2726       }
2727 
2728       if( nList>0 ){
2729         *paPoslist = pList;
2730         *piDocid = iDocid;
2731         *pnPoslist = nList;
2732         break;
2733       }
2734     }
2735   }
2736 
2737   return SQLITE_OK;
2738 }
2739 
2740 static int fts3SegReaderStart(
2741   Fts3Table *p,                   /* Virtual table handle */
2742   Fts3MultiSegReader *pCsr,       /* Cursor object */
2743   const char *zTerm,              /* Term searched for (or NULL) */
2744   int nTerm                       /* Length of zTerm in bytes */
2745 ){
2746   int i;
2747   int nSeg = pCsr->nSegment;
2748 
2749   /* If the Fts3SegFilter defines a specific term (or term prefix) to search
2750   ** for, then advance each segment iterator until it points to a term of
2751   ** equal or greater value than the specified term. This prevents many
2752   ** unnecessary merge/sort operations for the case where single segment
2753   ** b-tree leaf nodes contain more than one term.
2754   */
2755   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
2756     int res = 0;
2757     Fts3SegReader *pSeg = pCsr->apSegment[i];
2758     do {
2759       int rc = fts3SegReaderNext(p, pSeg, 0);
2760       if( rc!=SQLITE_OK ) return rc;
2761     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
2762 
2763     if( pSeg->bLookup && res!=0 ){
2764       fts3SegReaderSetEof(pSeg);
2765     }
2766   }
2767   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
2768 
2769   return SQLITE_OK;
2770 }
2771 
2772 int sqlite3Fts3SegReaderStart(
2773   Fts3Table *p,                   /* Virtual table handle */
2774   Fts3MultiSegReader *pCsr,       /* Cursor object */
2775   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
2776 ){
2777   pCsr->pFilter = pFilter;
2778   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
2779 }
2780 
2781 int sqlite3Fts3MsrIncrStart(
2782   Fts3Table *p,                   /* Virtual table handle */
2783   Fts3MultiSegReader *pCsr,       /* Cursor object */
2784   int iCol,                       /* Column to match on. */
2785   const char *zTerm,              /* Term to iterate through a doclist for */
2786   int nTerm                       /* Number of bytes in zTerm */
2787 ){
2788   int i;
2789   int rc;
2790   int nSegment = pCsr->nSegment;
2791   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
2792     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
2793   );
2794 
2795   assert( pCsr->pFilter==0 );
2796   assert( zTerm && nTerm>0 );
2797 
2798   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
2799   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
2800   if( rc!=SQLITE_OK ) return rc;
2801 
2802   /* Determine how many of the segments actually point to zTerm/nTerm. */
2803   for(i=0; i<nSegment; i++){
2804     Fts3SegReader *pSeg = pCsr->apSegment[i];
2805     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
2806       break;
2807     }
2808   }
2809   pCsr->nAdvance = i;
2810 
2811   /* Advance each of the segments to point to the first docid. */
2812   for(i=0; i<pCsr->nAdvance; i++){
2813     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
2814     if( rc!=SQLITE_OK ) return rc;
2815   }
2816   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
2817 
2818   assert( iCol<0 || iCol<p->nColumn );
2819   pCsr->iColFilter = iCol;
2820 
2821   return SQLITE_OK;
2822 }
2823 
2824 /*
2825 ** This function is called on a MultiSegReader that has been started using
2826 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
2827 ** have been made. Calling this function puts the MultiSegReader in such
2828 ** a state that if the next two calls are:
2829 **
2830 **   sqlite3Fts3SegReaderStart()
2831 **   sqlite3Fts3SegReaderStep()
2832 **
2833 ** then the entire doclist for the term is available in
2834 ** MultiSegReader.aDoclist/nDoclist.
2835 */
2836 int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
2837   int i;                          /* Used to iterate through segment-readers */
2838 
2839   assert( pCsr->zTerm==0 );
2840   assert( pCsr->nTerm==0 );
2841   assert( pCsr->aDoclist==0 );
2842   assert( pCsr->nDoclist==0 );
2843 
2844   pCsr->nAdvance = 0;
2845   pCsr->bRestart = 1;
2846   for(i=0; i<pCsr->nSegment; i++){
2847     pCsr->apSegment[i]->pOffsetList = 0;
2848     pCsr->apSegment[i]->nOffsetList = 0;
2849     pCsr->apSegment[i]->iDocid = 0;
2850   }
2851 
2852   return SQLITE_OK;
2853 }
2854 
2855 
2856 int sqlite3Fts3SegReaderStep(
2857   Fts3Table *p,                   /* Virtual table handle */
2858   Fts3MultiSegReader *pCsr        /* Cursor object */
2859 ){
2860   int rc = SQLITE_OK;
2861 
2862   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
2863   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
2864   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
2865   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
2866   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
2867   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
2868 
2869   Fts3SegReader **apSegment = pCsr->apSegment;
2870   int nSegment = pCsr->nSegment;
2871   Fts3SegFilter *pFilter = pCsr->pFilter;
2872   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
2873     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
2874   );
2875 
2876   if( pCsr->nSegment==0 ) return SQLITE_OK;
2877 
2878   do {
2879     int nMerge;
2880     int i;
2881 
2882     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
2883     ** forward. Then sort the list in order of current term again.
2884     */
2885     for(i=0; i<pCsr->nAdvance; i++){
2886       Fts3SegReader *pSeg = apSegment[i];
2887       if( pSeg->bLookup ){
2888         fts3SegReaderSetEof(pSeg);
2889       }else{
2890         rc = fts3SegReaderNext(p, pSeg, 0);
2891       }
2892       if( rc!=SQLITE_OK ) return rc;
2893     }
2894     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
2895     pCsr->nAdvance = 0;
2896 
2897     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
2898     assert( rc==SQLITE_OK );
2899     if( apSegment[0]->aNode==0 ) break;
2900 
2901     pCsr->nTerm = apSegment[0]->nTerm;
2902     pCsr->zTerm = apSegment[0]->zTerm;
2903 
2904     /* If this is a prefix-search, and if the term that apSegment[0] points
2905     ** to does not share a suffix with pFilter->zTerm/nTerm, then all
2906     ** required callbacks have been made. In this case exit early.
2907     **
2908     ** Similarly, if this is a search for an exact match, and the first term
2909     ** of segment apSegment[0] is not a match, exit early.
2910     */
2911     if( pFilter->zTerm && !isScan ){
2912       if( pCsr->nTerm<pFilter->nTerm
2913        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
2914        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
2915       ){
2916         break;
2917       }
2918     }
2919 
2920     nMerge = 1;
2921     while( nMerge<nSegment
2922         && apSegment[nMerge]->aNode
2923         && apSegment[nMerge]->nTerm==pCsr->nTerm
2924         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
2925     ){
2926       nMerge++;
2927     }
2928 
2929     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
2930     if( nMerge==1
2931      && !isIgnoreEmpty
2932      && !isFirst
2933      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
2934     ){
2935       pCsr->nDoclist = apSegment[0]->nDoclist;
2936       if( fts3SegReaderIsPending(apSegment[0]) ){
2937         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
2938         pCsr->aDoclist = pCsr->aBuffer;
2939       }else{
2940         pCsr->aDoclist = apSegment[0]->aDoclist;
2941       }
2942       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
2943     }else{
2944       int nDoclist = 0;           /* Size of doclist */
2945       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
2946 
2947       /* The current term of the first nMerge entries in the array
2948       ** of Fts3SegReader objects is the same. The doclists must be merged
2949       ** and a single term returned with the merged doclist.
2950       */
2951       for(i=0; i<nMerge; i++){
2952         fts3SegReaderFirstDocid(p, apSegment[i]);
2953       }
2954       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
2955       while( apSegment[0]->pOffsetList ){
2956         int j;                    /* Number of segments that share a docid */
2957         char *pList = 0;
2958         int nList = 0;
2959         int nByte;
2960         sqlite3_int64 iDocid = apSegment[0]->iDocid;
2961         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
2962         j = 1;
2963         while( j<nMerge
2964             && apSegment[j]->pOffsetList
2965             && apSegment[j]->iDocid==iDocid
2966         ){
2967           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
2968           j++;
2969         }
2970 
2971         if( isColFilter ){
2972           fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
2973         }
2974 
2975         if( !isIgnoreEmpty || nList>0 ){
2976 
2977           /* Calculate the 'docid' delta value to write into the merged
2978           ** doclist. */
2979           sqlite3_int64 iDelta;
2980           if( p->bDescIdx && nDoclist>0 ){
2981             if( iPrev<=iDocid ) return FTS_CORRUPT_VTAB;
2982             iDelta = (i64)((u64)iPrev - (u64)iDocid);
2983           }else{
2984             if( nDoclist>0 && iPrev>=iDocid ) return FTS_CORRUPT_VTAB;
2985             iDelta = (i64)((u64)iDocid - (u64)iPrev);
2986           }
2987 
2988           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
2989           if( nDoclist+nByte>pCsr->nBuffer ){
2990             char *aNew;
2991             pCsr->nBuffer = (nDoclist+nByte)*2;
2992             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
2993             if( !aNew ){
2994               return SQLITE_NOMEM;
2995             }
2996             pCsr->aBuffer = aNew;
2997           }
2998 
2999           if( isFirst ){
3000             char *a = &pCsr->aBuffer[nDoclist];
3001             int nWrite;
3002 
3003             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
3004             if( nWrite ){
3005               iPrev = iDocid;
3006               nDoclist += nWrite;
3007             }
3008           }else{
3009             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
3010             iPrev = iDocid;
3011             if( isRequirePos ){
3012               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
3013               nDoclist += nList;
3014               pCsr->aBuffer[nDoclist++] = '\0';
3015             }
3016           }
3017         }
3018 
3019         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
3020       }
3021       if( nDoclist>0 ){
3022         pCsr->aDoclist = pCsr->aBuffer;
3023         pCsr->nDoclist = nDoclist;
3024         rc = SQLITE_ROW;
3025       }
3026     }
3027     pCsr->nAdvance = nMerge;
3028   }while( rc==SQLITE_OK );
3029 
3030   return rc;
3031 }
3032 
3033 
3034 void sqlite3Fts3SegReaderFinish(
3035   Fts3MultiSegReader *pCsr       /* Cursor object */
3036 ){
3037   if( pCsr ){
3038     int i;
3039     for(i=0; i<pCsr->nSegment; i++){
3040       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
3041     }
3042     sqlite3_free(pCsr->apSegment);
3043     sqlite3_free(pCsr->aBuffer);
3044 
3045     pCsr->nSegment = 0;
3046     pCsr->apSegment = 0;
3047     pCsr->aBuffer = 0;
3048   }
3049 }
3050 
3051 /*
3052 ** Decode the "end_block" field, selected by column iCol of the SELECT
3053 ** statement passed as the first argument.
3054 **
3055 ** The "end_block" field may contain either an integer, or a text field
3056 ** containing the text representation of two non-negative integers separated
3057 ** by one or more space (0x20) characters. In the first case, set *piEndBlock
3058 ** to the integer value and *pnByte to zero before returning. In the second,
3059 ** set *piEndBlock to the first value and *pnByte to the second.
3060 */
3061 static void fts3ReadEndBlockField(
3062   sqlite3_stmt *pStmt,
3063   int iCol,
3064   i64 *piEndBlock,
3065   i64 *pnByte
3066 ){
3067   const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
3068   if( zText ){
3069     int i;
3070     int iMul = 1;
3071     i64 iVal = 0;
3072     for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
3073       iVal = iVal*10 + (zText[i] - '0');
3074     }
3075     *piEndBlock = iVal;
3076     while( zText[i]==' ' ) i++;
3077     iVal = 0;
3078     if( zText[i]=='-' ){
3079       i++;
3080       iMul = -1;
3081     }
3082     for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
3083       iVal = iVal*10 + (zText[i] - '0');
3084     }
3085     *pnByte = (iVal * (i64)iMul);
3086   }
3087 }
3088 
3089 
3090 /*
3091 ** A segment of size nByte bytes has just been written to absolute level
3092 ** iAbsLevel. Promote any segments that should be promoted as a result.
3093 */
3094 static int fts3PromoteSegments(
3095   Fts3Table *p,                   /* FTS table handle */
3096   sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
3097   sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
3098 ){
3099   int rc = SQLITE_OK;
3100   sqlite3_stmt *pRange;
3101 
3102   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
3103 
3104   if( rc==SQLITE_OK ){
3105     int bOk = 0;
3106     i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
3107     i64 nLimit = (nByte*3)/2;
3108 
3109     /* Loop through all entries in the %_segdir table corresponding to
3110     ** segments in this index on levels greater than iAbsLevel. If there is
3111     ** at least one such segment, and it is possible to determine that all
3112     ** such segments are smaller than nLimit bytes in size, they will be
3113     ** promoted to level iAbsLevel.  */
3114     sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
3115     sqlite3_bind_int64(pRange, 2, iLast);
3116     while( SQLITE_ROW==sqlite3_step(pRange) ){
3117       i64 nSize = 0, dummy;
3118       fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
3119       if( nSize<=0 || nSize>nLimit ){
3120         /* If nSize==0, then the %_segdir.end_block field does not not
3121         ** contain a size value. This happens if it was written by an
3122         ** old version of FTS. In this case it is not possible to determine
3123         ** the size of the segment, and so segment promotion does not
3124         ** take place.  */
3125         bOk = 0;
3126         break;
3127       }
3128       bOk = 1;
3129     }
3130     rc = sqlite3_reset(pRange);
3131 
3132     if( bOk ){
3133       int iIdx = 0;
3134       sqlite3_stmt *pUpdate1 = 0;
3135       sqlite3_stmt *pUpdate2 = 0;
3136 
3137       if( rc==SQLITE_OK ){
3138         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
3139       }
3140       if( rc==SQLITE_OK ){
3141         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
3142       }
3143 
3144       if( rc==SQLITE_OK ){
3145 
3146         /* Loop through all %_segdir entries for segments in this index with
3147         ** levels equal to or greater than iAbsLevel. As each entry is visited,
3148         ** updated it to set (level = -1) and (idx = N), where N is 0 for the
3149         ** oldest segment in the range, 1 for the next oldest, and so on.
3150         **
3151         ** In other words, move all segments being promoted to level -1,
3152         ** setting the "idx" fields as appropriate to keep them in the same
3153         ** order. The contents of level -1 (which is never used, except
3154         ** transiently here), will be moved back to level iAbsLevel below.  */
3155         sqlite3_bind_int64(pRange, 1, iAbsLevel);
3156         while( SQLITE_ROW==sqlite3_step(pRange) ){
3157           sqlite3_bind_int(pUpdate1, 1, iIdx++);
3158           sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
3159           sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
3160           sqlite3_step(pUpdate1);
3161           rc = sqlite3_reset(pUpdate1);
3162           if( rc!=SQLITE_OK ){
3163             sqlite3_reset(pRange);
3164             break;
3165           }
3166         }
3167       }
3168       if( rc==SQLITE_OK ){
3169         rc = sqlite3_reset(pRange);
3170       }
3171 
3172       /* Move level -1 to level iAbsLevel */
3173       if( rc==SQLITE_OK ){
3174         sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
3175         sqlite3_step(pUpdate2);
3176         rc = sqlite3_reset(pUpdate2);
3177       }
3178     }
3179   }
3180 
3181 
3182   return rc;
3183 }
3184 
3185 /*
3186 ** Merge all level iLevel segments in the database into a single
3187 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
3188 ** single segment with a level equal to the numerically largest level
3189 ** currently present in the database.
3190 **
3191 ** If this function is called with iLevel<0, but there is only one
3192 ** segment in the database, SQLITE_DONE is returned immediately.
3193 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
3194 ** an SQLite error code is returned.
3195 */
3196 static int fts3SegmentMerge(
3197   Fts3Table *p,
3198   int iLangid,                    /* Language id to merge */
3199   int iIndex,                     /* Index in p->aIndex[] to merge */
3200   int iLevel                      /* Level to merge */
3201 ){
3202   int rc;                         /* Return code */
3203   int iIdx = 0;                   /* Index of new segment */
3204   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
3205   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
3206   Fts3SegFilter filter;           /* Segment term filter condition */
3207   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
3208   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
3209   i64 iMaxLevel = 0;              /* Max level number for this index/langid */
3210 
3211   assert( iLevel==FTS3_SEGCURSOR_ALL
3212        || iLevel==FTS3_SEGCURSOR_PENDING
3213        || iLevel>=0
3214   );
3215   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
3216   assert( iIndex>=0 && iIndex<p->nIndex );
3217 
3218   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
3219   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
3220 
3221   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
3222     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
3223     if( rc!=SQLITE_OK ) goto finished;
3224   }
3225 
3226   if( iLevel==FTS3_SEGCURSOR_ALL ){
3227     /* This call is to merge all segments in the database to a single
3228     ** segment. The level of the new segment is equal to the numerically
3229     ** greatest segment level currently present in the database for this
3230     ** index. The idx of the new segment is always 0.  */
3231     if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
3232       rc = SQLITE_DONE;
3233       goto finished;
3234     }
3235     iNewLevel = iMaxLevel;
3236     bIgnoreEmpty = 1;
3237 
3238   }else{
3239     /* This call is to merge all segments at level iLevel. find the next
3240     ** available segment index at level iLevel+1. The call to
3241     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
3242     ** a single iLevel+2 segment if necessary.  */
3243     assert( FTS3_SEGCURSOR_PENDING==-1 );
3244     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
3245     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
3246     bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
3247   }
3248   if( rc!=SQLITE_OK ) goto finished;
3249 
3250   assert( csr.nSegment>0 );
3251   assert_fts3_nc( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
3252   assert_fts3_nc(
3253     iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL)
3254   );
3255 
3256   memset(&filter, 0, sizeof(Fts3SegFilter));
3257   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
3258   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
3259 
3260   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
3261   while( SQLITE_OK==rc ){
3262     rc = sqlite3Fts3SegReaderStep(p, &csr);
3263     if( rc!=SQLITE_ROW ) break;
3264     rc = fts3SegWriterAdd(p, &pWriter, 1,
3265         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
3266   }
3267   if( rc!=SQLITE_OK ) goto finished;
3268   assert_fts3_nc( pWriter || bIgnoreEmpty );
3269 
3270   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
3271     rc = fts3DeleteSegdir(
3272         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
3273     );
3274     if( rc!=SQLITE_OK ) goto finished;
3275   }
3276   if( pWriter ){
3277     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
3278     if( rc==SQLITE_OK ){
3279       if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
3280         rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
3281       }
3282     }
3283   }
3284 
3285  finished:
3286   fts3SegWriterFree(pWriter);
3287   sqlite3Fts3SegReaderFinish(&csr);
3288   return rc;
3289 }
3290 
3291 
3292 /*
3293 ** Flush the contents of pendingTerms to level 0 segments.
3294 */
3295 int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
3296   int rc = SQLITE_OK;
3297   int i;
3298 
3299   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
3300     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
3301     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
3302   }
3303   sqlite3Fts3PendingTermsClear(p);
3304 
3305   /* Determine the auto-incr-merge setting if unknown.  If enabled,
3306   ** estimate the number of leaf blocks of content to be written
3307   */
3308   if( rc==SQLITE_OK && p->bHasStat
3309    && p->nAutoincrmerge==0xff && p->nLeafAdd>0
3310   ){
3311     sqlite3_stmt *pStmt = 0;
3312     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
3313     if( rc==SQLITE_OK ){
3314       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
3315       rc = sqlite3_step(pStmt);
3316       if( rc==SQLITE_ROW ){
3317         p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
3318         if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
3319       }else if( rc==SQLITE_DONE ){
3320         p->nAutoincrmerge = 0;
3321       }
3322       rc = sqlite3_reset(pStmt);
3323     }
3324   }
3325   return rc;
3326 }
3327 
3328 /*
3329 ** Encode N integers as varints into a blob.
3330 */
3331 static void fts3EncodeIntArray(
3332   int N,             /* The number of integers to encode */
3333   u32 *a,            /* The integer values */
3334   char *zBuf,        /* Write the BLOB here */
3335   int *pNBuf         /* Write number of bytes if zBuf[] used here */
3336 ){
3337   int i, j;
3338   for(i=j=0; i<N; i++){
3339     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
3340   }
3341   *pNBuf = j;
3342 }
3343 
3344 /*
3345 ** Decode a blob of varints into N integers
3346 */
3347 static void fts3DecodeIntArray(
3348   int N,             /* The number of integers to decode */
3349   u32 *a,            /* Write the integer values */
3350   const char *zBuf,  /* The BLOB containing the varints */
3351   int nBuf           /* size of the BLOB */
3352 ){
3353   int i = 0;
3354   if( nBuf && (zBuf[nBuf-1]&0x80)==0 ){
3355     int j;
3356     for(i=j=0; i<N && j<nBuf; i++){
3357       sqlite3_int64 x;
3358       j += sqlite3Fts3GetVarint(&zBuf[j], &x);
3359       a[i] = (u32)(x & 0xffffffff);
3360     }
3361   }
3362   while( i<N ) a[i++] = 0;
3363 }
3364 
3365 /*
3366 ** Insert the sizes (in tokens) for each column of the document
3367 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
3368 ** a blob of varints.
3369 */
3370 static void fts3InsertDocsize(
3371   int *pRC,                       /* Result code */
3372   Fts3Table *p,                   /* Table into which to insert */
3373   u32 *aSz                        /* Sizes of each column, in tokens */
3374 ){
3375   char *pBlob;             /* The BLOB encoding of the document size */
3376   int nBlob;               /* Number of bytes in the BLOB */
3377   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
3378   int rc;                  /* Result code from subfunctions */
3379 
3380   if( *pRC ) return;
3381   pBlob = sqlite3_malloc64( 10*(sqlite3_int64)p->nColumn );
3382   if( pBlob==0 ){
3383     *pRC = SQLITE_NOMEM;
3384     return;
3385   }
3386   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
3387   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
3388   if( rc ){
3389     sqlite3_free(pBlob);
3390     *pRC = rc;
3391     return;
3392   }
3393   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
3394   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
3395   sqlite3_step(pStmt);
3396   *pRC = sqlite3_reset(pStmt);
3397 }
3398 
3399 /*
3400 ** Record 0 of the %_stat table contains a blob consisting of N varints,
3401 ** where N is the number of user defined columns in the fts3 table plus
3402 ** two. If nCol is the number of user defined columns, then values of the
3403 ** varints are set as follows:
3404 **
3405 **   Varint 0:       Total number of rows in the table.
3406 **
3407 **   Varint 1..nCol: For each column, the total number of tokens stored in
3408 **                   the column for all rows of the table.
3409 **
3410 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
3411 **                   columns of all rows of the table.
3412 **
3413 */
3414 static void fts3UpdateDocTotals(
3415   int *pRC,                       /* The result code */
3416   Fts3Table *p,                   /* Table being updated */
3417   u32 *aSzIns,                    /* Size increases */
3418   u32 *aSzDel,                    /* Size decreases */
3419   int nChng                       /* Change in the number of documents */
3420 ){
3421   char *pBlob;             /* Storage for BLOB written into %_stat */
3422   int nBlob;               /* Size of BLOB written into %_stat */
3423   u32 *a;                  /* Array of integers that becomes the BLOB */
3424   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
3425   int i;                   /* Loop counter */
3426   int rc;                  /* Result code from subfunctions */
3427 
3428   const int nStat = p->nColumn+2;
3429 
3430   if( *pRC ) return;
3431   a = sqlite3_malloc64( (sizeof(u32)+10)*(sqlite3_int64)nStat );
3432   if( a==0 ){
3433     *pRC = SQLITE_NOMEM;
3434     return;
3435   }
3436   pBlob = (char*)&a[nStat];
3437   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
3438   if( rc ){
3439     sqlite3_free(a);
3440     *pRC = rc;
3441     return;
3442   }
3443   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
3444   if( sqlite3_step(pStmt)==SQLITE_ROW ){
3445     fts3DecodeIntArray(nStat, a,
3446          sqlite3_column_blob(pStmt, 0),
3447          sqlite3_column_bytes(pStmt, 0));
3448   }else{
3449     memset(a, 0, sizeof(u32)*(nStat) );
3450   }
3451   rc = sqlite3_reset(pStmt);
3452   if( rc!=SQLITE_OK ){
3453     sqlite3_free(a);
3454     *pRC = rc;
3455     return;
3456   }
3457   if( nChng<0 && a[0]<(u32)(-nChng) ){
3458     a[0] = 0;
3459   }else{
3460     a[0] += nChng;
3461   }
3462   for(i=0; i<p->nColumn+1; i++){
3463     u32 x = a[i+1];
3464     if( x+aSzIns[i] < aSzDel[i] ){
3465       x = 0;
3466     }else{
3467       x = x + aSzIns[i] - aSzDel[i];
3468     }
3469     a[i+1] = x;
3470   }
3471   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
3472   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
3473   if( rc ){
3474     sqlite3_free(a);
3475     *pRC = rc;
3476     return;
3477   }
3478   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
3479   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
3480   sqlite3_step(pStmt);
3481   *pRC = sqlite3_reset(pStmt);
3482   sqlite3_bind_null(pStmt, 2);
3483   sqlite3_free(a);
3484 }
3485 
3486 /*
3487 ** Merge the entire database so that there is one segment for each
3488 ** iIndex/iLangid combination.
3489 */
3490 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
3491   int bSeenDone = 0;
3492   int rc;
3493   sqlite3_stmt *pAllLangid = 0;
3494 
3495   rc = sqlite3Fts3PendingTermsFlush(p);
3496   if( rc==SQLITE_OK ){
3497     rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
3498   }
3499   if( rc==SQLITE_OK ){
3500     int rc2;
3501     sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
3502     sqlite3_bind_int(pAllLangid, 2, p->nIndex);
3503     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
3504       int i;
3505       int iLangid = sqlite3_column_int(pAllLangid, 0);
3506       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
3507         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
3508         if( rc==SQLITE_DONE ){
3509           bSeenDone = 1;
3510           rc = SQLITE_OK;
3511         }
3512       }
3513     }
3514     rc2 = sqlite3_reset(pAllLangid);
3515     if( rc==SQLITE_OK ) rc = rc2;
3516   }
3517 
3518   sqlite3Fts3SegmentsClose(p);
3519 
3520   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
3521 }
3522 
3523 /*
3524 ** This function is called when the user executes the following statement:
3525 **
3526 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
3527 **
3528 ** The entire FTS index is discarded and rebuilt. If the table is one
3529 ** created using the content=xxx option, then the new index is based on
3530 ** the current contents of the xxx table. Otherwise, it is rebuilt based
3531 ** on the contents of the %_content table.
3532 */
3533 static int fts3DoRebuild(Fts3Table *p){
3534   int rc;                         /* Return Code */
3535 
3536   rc = fts3DeleteAll(p, 0);
3537   if( rc==SQLITE_OK ){
3538     u32 *aSz = 0;
3539     u32 *aSzIns = 0;
3540     u32 *aSzDel = 0;
3541     sqlite3_stmt *pStmt = 0;
3542     int nEntry = 0;
3543 
3544     /* Compose and prepare an SQL statement to loop through the content table */
3545     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
3546     if( !zSql ){
3547       rc = SQLITE_NOMEM;
3548     }else{
3549       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3550       sqlite3_free(zSql);
3551     }
3552 
3553     if( rc==SQLITE_OK ){
3554       sqlite3_int64 nByte = sizeof(u32) * ((sqlite3_int64)p->nColumn+1)*3;
3555       aSz = (u32 *)sqlite3_malloc64(nByte);
3556       if( aSz==0 ){
3557         rc = SQLITE_NOMEM;
3558       }else{
3559         memset(aSz, 0, nByte);
3560         aSzIns = &aSz[p->nColumn+1];
3561         aSzDel = &aSzIns[p->nColumn+1];
3562       }
3563     }
3564 
3565     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
3566       int iCol;
3567       int iLangid = langidFromSelect(p, pStmt);
3568       rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
3569       memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
3570       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
3571         if( p->abNotindexed[iCol]==0 ){
3572           const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
3573           rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
3574           aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
3575         }
3576       }
3577       if( p->bHasDocsize ){
3578         fts3InsertDocsize(&rc, p, aSz);
3579       }
3580       if( rc!=SQLITE_OK ){
3581         sqlite3_finalize(pStmt);
3582         pStmt = 0;
3583       }else{
3584         nEntry++;
3585         for(iCol=0; iCol<=p->nColumn; iCol++){
3586           aSzIns[iCol] += aSz[iCol];
3587         }
3588       }
3589     }
3590     if( p->bFts4 ){
3591       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
3592     }
3593     sqlite3_free(aSz);
3594 
3595     if( pStmt ){
3596       int rc2 = sqlite3_finalize(pStmt);
3597       if( rc==SQLITE_OK ){
3598         rc = rc2;
3599       }
3600     }
3601   }
3602 
3603   return rc;
3604 }
3605 
3606 
3607 /*
3608 ** This function opens a cursor used to read the input data for an
3609 ** incremental merge operation. Specifically, it opens a cursor to scan
3610 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
3611 ** level iAbsLevel.
3612 */
3613 static int fts3IncrmergeCsr(
3614   Fts3Table *p,                   /* FTS3 table handle */
3615   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
3616   int nSeg,                       /* Number of segments to merge */
3617   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
3618 ){
3619   int rc;                         /* Return Code */
3620   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
3621   sqlite3_int64 nByte;            /* Bytes allocated at pCsr->apSegment[] */
3622 
3623   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
3624   memset(pCsr, 0, sizeof(*pCsr));
3625   nByte = sizeof(Fts3SegReader *) * nSeg;
3626   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc64(nByte);
3627 
3628   if( pCsr->apSegment==0 ){
3629     rc = SQLITE_NOMEM;
3630   }else{
3631     memset(pCsr->apSegment, 0, nByte);
3632     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
3633   }
3634   if( rc==SQLITE_OK ){
3635     int i;
3636     int rc2;
3637     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
3638     assert( pCsr->nSegment==0 );
3639     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
3640       rc = sqlite3Fts3SegReaderNew(i, 0,
3641           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
3642           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
3643           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
3644           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
3645           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
3646           &pCsr->apSegment[i]
3647       );
3648       pCsr->nSegment++;
3649     }
3650     rc2 = sqlite3_reset(pStmt);
3651     if( rc==SQLITE_OK ) rc = rc2;
3652   }
3653 
3654   return rc;
3655 }
3656 
3657 typedef struct IncrmergeWriter IncrmergeWriter;
3658 typedef struct NodeWriter NodeWriter;
3659 typedef struct Blob Blob;
3660 typedef struct NodeReader NodeReader;
3661 
3662 /*
3663 ** An instance of the following structure is used as a dynamic buffer
3664 ** to build up nodes or other blobs of data in.
3665 **
3666 ** The function blobGrowBuffer() is used to extend the allocation.
3667 */
3668 struct Blob {
3669   char *a;                        /* Pointer to allocation */
3670   int n;                          /* Number of valid bytes of data in a[] */
3671   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
3672 };
3673 
3674 /*
3675 ** This structure is used to build up buffers containing segment b-tree
3676 ** nodes (blocks).
3677 */
3678 struct NodeWriter {
3679   sqlite3_int64 iBlock;           /* Current block id */
3680   Blob key;                       /* Last key written to the current block */
3681   Blob block;                     /* Current block image */
3682 };
3683 
3684 /*
3685 ** An object of this type contains the state required to create or append
3686 ** to an appendable b-tree segment.
3687 */
3688 struct IncrmergeWriter {
3689   int nLeafEst;                   /* Space allocated for leaf blocks */
3690   int nWork;                      /* Number of leaf pages flushed */
3691   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
3692   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
3693   sqlite3_int64 iStart;           /* Block number of first allocated block */
3694   sqlite3_int64 iEnd;             /* Block number of last allocated block */
3695   sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
3696   u8 bNoLeafData;                 /* If true, store 0 for segment size */
3697   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
3698 };
3699 
3700 /*
3701 ** An object of the following type is used to read data from a single
3702 ** FTS segment node. See the following functions:
3703 **
3704 **     nodeReaderInit()
3705 **     nodeReaderNext()
3706 **     nodeReaderRelease()
3707 */
3708 struct NodeReader {
3709   const char *aNode;
3710   int nNode;
3711   int iOff;                       /* Current offset within aNode[] */
3712 
3713   /* Output variables. Containing the current node entry. */
3714   sqlite3_int64 iChild;           /* Pointer to child node */
3715   Blob term;                      /* Current term */
3716   const char *aDoclist;           /* Pointer to doclist */
3717   int nDoclist;                   /* Size of doclist in bytes */
3718 };
3719 
3720 /*
3721 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
3722 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
3723 ** bytes in size, extend (realloc) it to be so.
3724 **
3725 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
3726 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
3727 ** to reflect the new size of the pBlob->a[] buffer.
3728 */
3729 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
3730   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
3731     int nAlloc = nMin;
3732     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
3733     if( a ){
3734       pBlob->nAlloc = nAlloc;
3735       pBlob->a = a;
3736     }else{
3737       *pRc = SQLITE_NOMEM;
3738     }
3739   }
3740 }
3741 
3742 /*
3743 ** Attempt to advance the node-reader object passed as the first argument to
3744 ** the next entry on the node.
3745 **
3746 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
3747 ** Otherwise return SQLITE_OK. If there is no next entry on the node
3748 ** (e.g. because the current entry is the last) set NodeReader->aNode to
3749 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
3750 ** variables for the new entry.
3751 */
3752 static int nodeReaderNext(NodeReader *p){
3753   int bFirst = (p->term.n==0);    /* True for first term on the node */
3754   int nPrefix = 0;                /* Bytes to copy from previous term */
3755   int nSuffix = 0;                /* Bytes to append to the prefix */
3756   int rc = SQLITE_OK;             /* Return code */
3757 
3758   assert( p->aNode );
3759   if( p->iChild && bFirst==0 ) p->iChild++;
3760   if( p->iOff>=p->nNode ){
3761     /* EOF */
3762     p->aNode = 0;
3763   }else{
3764     if( bFirst==0 ){
3765       p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
3766     }
3767     p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
3768 
3769     if( nPrefix>p->term.n || nSuffix>p->nNode-p->iOff || nSuffix==0 ){
3770       return FTS_CORRUPT_VTAB;
3771     }
3772     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
3773     if( rc==SQLITE_OK ){
3774       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
3775       p->term.n = nPrefix+nSuffix;
3776       p->iOff += nSuffix;
3777       if( p->iChild==0 ){
3778         p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
3779         if( (p->nNode-p->iOff)<p->nDoclist ){
3780           return FTS_CORRUPT_VTAB;
3781         }
3782         p->aDoclist = &p->aNode[p->iOff];
3783         p->iOff += p->nDoclist;
3784       }
3785     }
3786   }
3787 
3788   assert_fts3_nc( p->iOff<=p->nNode );
3789   return rc;
3790 }
3791 
3792 /*
3793 ** Release all dynamic resources held by node-reader object *p.
3794 */
3795 static void nodeReaderRelease(NodeReader *p){
3796   sqlite3_free(p->term.a);
3797 }
3798 
3799 /*
3800 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
3801 **
3802 ** If successful, SQLITE_OK is returned and the NodeReader object set to
3803 ** point to the first entry on the node (if any). Otherwise, an SQLite
3804 ** error code is returned.
3805 */
3806 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
3807   memset(p, 0, sizeof(NodeReader));
3808   p->aNode = aNode;
3809   p->nNode = nNode;
3810 
3811   /* Figure out if this is a leaf or an internal node. */
3812   if( aNode && aNode[0] ){
3813     /* An internal node. */
3814     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
3815   }else{
3816     p->iOff = 1;
3817   }
3818 
3819   return aNode ? nodeReaderNext(p) : SQLITE_OK;
3820 }
3821 
3822 /*
3823 ** This function is called while writing an FTS segment each time a leaf o
3824 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
3825 ** to be greater than the largest key on the node just written, but smaller
3826 ** than or equal to the first key that will be written to the next leaf
3827 ** node.
3828 **
3829 ** The block id of the leaf node just written to disk may be found in
3830 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
3831 */
3832 static int fts3IncrmergePush(
3833   Fts3Table *p,                   /* Fts3 table handle */
3834   IncrmergeWriter *pWriter,       /* Writer object */
3835   const char *zTerm,              /* Term to write to internal node */
3836   int nTerm                       /* Bytes at zTerm */
3837 ){
3838   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
3839   int iLayer;
3840 
3841   assert( nTerm>0 );
3842   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
3843     sqlite3_int64 iNextPtr = 0;
3844     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
3845     int rc = SQLITE_OK;
3846     int nPrefix;
3847     int nSuffix;
3848     int nSpace;
3849 
3850     /* Figure out how much space the key will consume if it is written to
3851     ** the current node of layer iLayer. Due to the prefix compression,
3852     ** the space required changes depending on which node the key is to
3853     ** be added to.  */
3854     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
3855     nSuffix = nTerm - nPrefix;
3856     if(nSuffix<=0 ) return FTS_CORRUPT_VTAB;
3857     nSpace  = sqlite3Fts3VarintLen(nPrefix);
3858     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
3859 
3860     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
3861       /* If the current node of layer iLayer contains zero keys, or if adding
3862       ** the key to it will not cause it to grow to larger than nNodeSize
3863       ** bytes in size, write the key here.  */
3864 
3865       Blob *pBlk = &pNode->block;
3866       if( pBlk->n==0 ){
3867         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
3868         if( rc==SQLITE_OK ){
3869           pBlk->a[0] = (char)iLayer;
3870           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
3871         }
3872       }
3873       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
3874       blobGrowBuffer(&pNode->key, nTerm, &rc);
3875 
3876       if( rc==SQLITE_OK ){
3877         if( pNode->key.n ){
3878           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
3879         }
3880         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
3881         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
3882         pBlk->n += nSuffix;
3883 
3884         memcpy(pNode->key.a, zTerm, nTerm);
3885         pNode->key.n = nTerm;
3886       }
3887     }else{
3888       /* Otherwise, flush the current node of layer iLayer to disk.
3889       ** Then allocate a new, empty sibling node. The key will be written
3890       ** into the parent of this node. */
3891       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
3892 
3893       assert( pNode->block.nAlloc>=p->nNodeSize );
3894       pNode->block.a[0] = (char)iLayer;
3895       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
3896 
3897       iNextPtr = pNode->iBlock;
3898       pNode->iBlock++;
3899       pNode->key.n = 0;
3900     }
3901 
3902     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
3903     iPtr = iNextPtr;
3904   }
3905 
3906   assert( 0 );
3907   return 0;
3908 }
3909 
3910 /*
3911 ** Append a term and (optionally) doclist to the FTS segment node currently
3912 ** stored in blob *pNode. The node need not contain any terms, but the
3913 ** header must be written before this function is called.
3914 **
3915 ** A node header is a single 0x00 byte for a leaf node, or a height varint
3916 ** followed by the left-hand-child varint for an internal node.
3917 **
3918 ** The term to be appended is passed via arguments zTerm/nTerm. For a
3919 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
3920 ** node, both aDoclist and nDoclist must be passed 0.
3921 **
3922 ** If the size of the value in blob pPrev is zero, then this is the first
3923 ** term written to the node. Otherwise, pPrev contains a copy of the
3924 ** previous term. Before this function returns, it is updated to contain a
3925 ** copy of zTerm/nTerm.
3926 **
3927 ** It is assumed that the buffer associated with pNode is already large
3928 ** enough to accommodate the new entry. The buffer associated with pPrev
3929 ** is extended by this function if requrired.
3930 **
3931 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
3932 ** returned. Otherwise, SQLITE_OK.
3933 */
3934 static int fts3AppendToNode(
3935   Blob *pNode,                    /* Current node image to append to */
3936   Blob *pPrev,                    /* Buffer containing previous term written */
3937   const char *zTerm,              /* New term to write */
3938   int nTerm,                      /* Size of zTerm in bytes */
3939   const char *aDoclist,           /* Doclist (or NULL) to write */
3940   int nDoclist                    /* Size of aDoclist in bytes */
3941 ){
3942   int rc = SQLITE_OK;             /* Return code */
3943   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
3944   int nPrefix;                    /* Size of term prefix in bytes */
3945   int nSuffix;                    /* Size of term suffix in bytes */
3946 
3947   /* Node must have already been started. There must be a doclist for a
3948   ** leaf node, and there must not be a doclist for an internal node.  */
3949   assert( pNode->n>0 );
3950   assert_fts3_nc( (pNode->a[0]=='\0')==(aDoclist!=0) );
3951 
3952   blobGrowBuffer(pPrev, nTerm, &rc);
3953   if( rc!=SQLITE_OK ) return rc;
3954 
3955   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
3956   nSuffix = nTerm - nPrefix;
3957   if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
3958   memcpy(pPrev->a, zTerm, nTerm);
3959   pPrev->n = nTerm;
3960 
3961   if( bFirst==0 ){
3962     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
3963   }
3964   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
3965   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
3966   pNode->n += nSuffix;
3967 
3968   if( aDoclist ){
3969     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
3970     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
3971     pNode->n += nDoclist;
3972   }
3973 
3974   assert( pNode->n<=pNode->nAlloc );
3975 
3976   return SQLITE_OK;
3977 }
3978 
3979 /*
3980 ** Append the current term and doclist pointed to by cursor pCsr to the
3981 ** appendable b-tree segment opened for writing by pWriter.
3982 **
3983 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
3984 */
3985 static int fts3IncrmergeAppend(
3986   Fts3Table *p,                   /* Fts3 table handle */
3987   IncrmergeWriter *pWriter,       /* Writer object */
3988   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
3989 ){
3990   const char *zTerm = pCsr->zTerm;
3991   int nTerm = pCsr->nTerm;
3992   const char *aDoclist = pCsr->aDoclist;
3993   int nDoclist = pCsr->nDoclist;
3994   int rc = SQLITE_OK;           /* Return code */
3995   int nSpace;                   /* Total space in bytes required on leaf */
3996   int nPrefix;                  /* Size of prefix shared with previous term */
3997   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
3998   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
3999 
4000   pLeaf = &pWriter->aNodeWriter[0];
4001   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
4002   nSuffix = nTerm - nPrefix;
4003 
4004   nSpace  = sqlite3Fts3VarintLen(nPrefix);
4005   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
4006   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
4007 
4008   /* If the current block is not empty, and if adding this term/doclist
4009   ** to the current block would make it larger than Fts3Table.nNodeSize
4010   ** bytes, write this block out to the database. */
4011   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
4012     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
4013     pWriter->nWork++;
4014 
4015     /* Add the current term to the parent node. The term added to the
4016     ** parent must:
4017     **
4018     **   a) be greater than the largest term on the leaf node just written
4019     **      to the database (still available in pLeaf->key), and
4020     **
4021     **   b) be less than or equal to the term about to be added to the new
4022     **      leaf node (zTerm/nTerm).
4023     **
4024     ** In other words, it must be the prefix of zTerm 1 byte longer than
4025     ** the common prefix (if any) of zTerm and pWriter->zTerm.
4026     */
4027     if( rc==SQLITE_OK ){
4028       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
4029     }
4030 
4031     /* Advance to the next output block */
4032     pLeaf->iBlock++;
4033     pLeaf->key.n = 0;
4034     pLeaf->block.n = 0;
4035 
4036     nSuffix = nTerm;
4037     nSpace  = 1;
4038     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
4039     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
4040   }
4041 
4042   pWriter->nLeafData += nSpace;
4043   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
4044   if( rc==SQLITE_OK ){
4045     if( pLeaf->block.n==0 ){
4046       pLeaf->block.n = 1;
4047       pLeaf->block.a[0] = '\0';
4048     }
4049     rc = fts3AppendToNode(
4050         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
4051     );
4052   }
4053 
4054   return rc;
4055 }
4056 
4057 /*
4058 ** This function is called to release all dynamic resources held by the
4059 ** merge-writer object pWriter, and if no error has occurred, to flush
4060 ** all outstanding node buffers held by pWriter to disk.
4061 **
4062 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
4063 ** is made to write any data to disk. Instead, this function serves only
4064 ** to release outstanding resources.
4065 **
4066 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
4067 ** flushing buffers to disk, *pRc is set to an SQLite error code before
4068 ** returning.
4069 */
4070 static void fts3IncrmergeRelease(
4071   Fts3Table *p,                   /* FTS3 table handle */
4072   IncrmergeWriter *pWriter,       /* Merge-writer object */
4073   int *pRc                        /* IN/OUT: Error code */
4074 ){
4075   int i;                          /* Used to iterate through non-root layers */
4076   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
4077   NodeWriter *pRoot;              /* NodeWriter for root node */
4078   int rc = *pRc;                  /* Error code */
4079 
4080   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
4081   ** root node. If the segment fits entirely on a single leaf node, iRoot
4082   ** will be set to 0. If the root node is the parent of the leaves, iRoot
4083   ** will be 1. And so on.  */
4084   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
4085     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
4086     if( pNode->block.n>0 ) break;
4087     assert( *pRc || pNode->block.nAlloc==0 );
4088     assert( *pRc || pNode->key.nAlloc==0 );
4089     sqlite3_free(pNode->block.a);
4090     sqlite3_free(pNode->key.a);
4091   }
4092 
4093   /* Empty output segment. This is a no-op. */
4094   if( iRoot<0 ) return;
4095 
4096   /* The entire output segment fits on a single node. Normally, this means
4097   ** the node would be stored as a blob in the "root" column of the %_segdir
4098   ** table. However, this is not permitted in this case. The problem is that
4099   ** space has already been reserved in the %_segments table, and so the
4100   ** start_block and end_block fields of the %_segdir table must be populated.
4101   ** And, by design or by accident, released versions of FTS cannot handle
4102   ** segments that fit entirely on the root node with start_block!=0.
4103   **
4104   ** Instead, create a synthetic root node that contains nothing but a
4105   ** pointer to the single content node. So that the segment consists of a
4106   ** single leaf and a single interior (root) node.
4107   **
4108   ** Todo: Better might be to defer allocating space in the %_segments
4109   ** table until we are sure it is needed.
4110   */
4111   if( iRoot==0 ){
4112     Blob *pBlock = &pWriter->aNodeWriter[1].block;
4113     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
4114     if( rc==SQLITE_OK ){
4115       pBlock->a[0] = 0x01;
4116       pBlock->n = 1 + sqlite3Fts3PutVarint(
4117           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
4118       );
4119     }
4120     iRoot = 1;
4121   }
4122   pRoot = &pWriter->aNodeWriter[iRoot];
4123 
4124   /* Flush all currently outstanding nodes to disk. */
4125   for(i=0; i<iRoot; i++){
4126     NodeWriter *pNode = &pWriter->aNodeWriter[i];
4127     if( pNode->block.n>0 && rc==SQLITE_OK ){
4128       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
4129     }
4130     sqlite3_free(pNode->block.a);
4131     sqlite3_free(pNode->key.a);
4132   }
4133 
4134   /* Write the %_segdir record. */
4135   if( rc==SQLITE_OK ){
4136     rc = fts3WriteSegdir(p,
4137         pWriter->iAbsLevel+1,               /* level */
4138         pWriter->iIdx,                      /* idx */
4139         pWriter->iStart,                    /* start_block */
4140         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
4141         pWriter->iEnd,                      /* end_block */
4142         (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
4143         pRoot->block.a, pRoot->block.n      /* root */
4144     );
4145   }
4146   sqlite3_free(pRoot->block.a);
4147   sqlite3_free(pRoot->key.a);
4148 
4149   *pRc = rc;
4150 }
4151 
4152 /*
4153 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
4154 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
4155 ** the other, it is considered to be smaller than the other.
4156 **
4157 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
4158 ** if it is greater.
4159 */
4160 static int fts3TermCmp(
4161   const char *zLhs, int nLhs,     /* LHS of comparison */
4162   const char *zRhs, int nRhs      /* RHS of comparison */
4163 ){
4164   int nCmp = MIN(nLhs, nRhs);
4165   int res;
4166 
4167   res = (nCmp ? memcmp(zLhs, zRhs, nCmp) : 0);
4168   if( res==0 ) res = nLhs - nRhs;
4169 
4170   return res;
4171 }
4172 
4173 
4174 /*
4175 ** Query to see if the entry in the %_segments table with blockid iEnd is
4176 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
4177 ** returning. Otherwise, set *pbRes to 0.
4178 **
4179 ** Or, if an error occurs while querying the database, return an SQLite
4180 ** error code. The final value of *pbRes is undefined in this case.
4181 **
4182 ** This is used to test if a segment is an "appendable" segment. If it
4183 ** is, then a NULL entry has been inserted into the %_segments table
4184 ** with blockid %_segdir.end_block.
4185 */
4186 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
4187   int bRes = 0;                   /* Result to set *pbRes to */
4188   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
4189   int rc;                         /* Return code */
4190 
4191   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
4192   if( rc==SQLITE_OK ){
4193     sqlite3_bind_int64(pCheck, 1, iEnd);
4194     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
4195     rc = sqlite3_reset(pCheck);
4196   }
4197 
4198   *pbRes = bRes;
4199   return rc;
4200 }
4201 
4202 /*
4203 ** This function is called when initializing an incremental-merge operation.
4204 ** It checks if the existing segment with index value iIdx at absolute level
4205 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
4206 ** merge-writer object *pWriter is initialized to write to it.
4207 **
4208 ** An existing segment can be appended to by an incremental merge if:
4209 **
4210 **   * It was initially created as an appendable segment (with all required
4211 **     space pre-allocated), and
4212 **
4213 **   * The first key read from the input (arguments zKey and nKey) is
4214 **     greater than the largest key currently stored in the potential
4215 **     output segment.
4216 */
4217 static int fts3IncrmergeLoad(
4218   Fts3Table *p,                   /* Fts3 table handle */
4219   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
4220   int iIdx,                       /* Index of candidate output segment */
4221   const char *zKey,               /* First key to write */
4222   int nKey,                       /* Number of bytes in nKey */
4223   IncrmergeWriter *pWriter        /* Populate this object */
4224 ){
4225   int rc;                         /* Return code */
4226   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
4227 
4228   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
4229   if( rc==SQLITE_OK ){
4230     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
4231     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
4232     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
4233     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
4234     int nRoot = 0;                /* Size of aRoot[] in bytes */
4235     int rc2;                      /* Return code from sqlite3_reset() */
4236     int bAppendable = 0;          /* Set to true if segment is appendable */
4237 
4238     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
4239     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
4240     sqlite3_bind_int(pSelect, 2, iIdx);
4241     if( sqlite3_step(pSelect)==SQLITE_ROW ){
4242       iStart = sqlite3_column_int64(pSelect, 1);
4243       iLeafEnd = sqlite3_column_int64(pSelect, 2);
4244       fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
4245       if( pWriter->nLeafData<0 ){
4246         pWriter->nLeafData = pWriter->nLeafData * -1;
4247       }
4248       pWriter->bNoLeafData = (pWriter->nLeafData==0);
4249       nRoot = sqlite3_column_bytes(pSelect, 4);
4250       aRoot = sqlite3_column_blob(pSelect, 4);
4251       if( aRoot==0 ){
4252         sqlite3_reset(pSelect);
4253         return nRoot ? SQLITE_NOMEM : FTS_CORRUPT_VTAB;
4254       }
4255     }else{
4256       return sqlite3_reset(pSelect);
4257     }
4258 
4259     /* Check for the zero-length marker in the %_segments table */
4260     rc = fts3IsAppendable(p, iEnd, &bAppendable);
4261 
4262     /* Check that zKey/nKey is larger than the largest key the candidate */
4263     if( rc==SQLITE_OK && bAppendable ){
4264       char *aLeaf = 0;
4265       int nLeaf = 0;
4266 
4267       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
4268       if( rc==SQLITE_OK ){
4269         NodeReader reader;
4270         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
4271             rc==SQLITE_OK && reader.aNode;
4272             rc = nodeReaderNext(&reader)
4273         ){
4274           assert( reader.aNode );
4275         }
4276         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
4277           bAppendable = 0;
4278         }
4279         nodeReaderRelease(&reader);
4280       }
4281       sqlite3_free(aLeaf);
4282     }
4283 
4284     if( rc==SQLITE_OK && bAppendable ){
4285       /* It is possible to append to this segment. Set up the IncrmergeWriter
4286       ** object to do so.  */
4287       int i;
4288       int nHeight = (int)aRoot[0];
4289       NodeWriter *pNode;
4290       if( nHeight<1 || nHeight>FTS_MAX_APPENDABLE_HEIGHT ){
4291         sqlite3_reset(pSelect);
4292         return FTS_CORRUPT_VTAB;
4293       }
4294 
4295       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
4296       pWriter->iStart = iStart;
4297       pWriter->iEnd = iEnd;
4298       pWriter->iAbsLevel = iAbsLevel;
4299       pWriter->iIdx = iIdx;
4300 
4301       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
4302         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
4303       }
4304 
4305       pNode = &pWriter->aNodeWriter[nHeight];
4306       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
4307       blobGrowBuffer(&pNode->block,
4308           MAX(nRoot, p->nNodeSize)+FTS3_NODE_PADDING, &rc
4309       );
4310       if( rc==SQLITE_OK ){
4311         memcpy(pNode->block.a, aRoot, nRoot);
4312         pNode->block.n = nRoot;
4313         memset(&pNode->block.a[nRoot], 0, FTS3_NODE_PADDING);
4314       }
4315 
4316       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
4317         NodeReader reader;
4318         pNode = &pWriter->aNodeWriter[i];
4319 
4320         if( pNode->block.a){
4321           rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
4322           while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
4323           blobGrowBuffer(&pNode->key, reader.term.n, &rc);
4324           if( rc==SQLITE_OK ){
4325             memcpy(pNode->key.a, reader.term.a, reader.term.n);
4326             pNode->key.n = reader.term.n;
4327             if( i>0 ){
4328               char *aBlock = 0;
4329               int nBlock = 0;
4330               pNode = &pWriter->aNodeWriter[i-1];
4331               pNode->iBlock = reader.iChild;
4332               rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
4333               blobGrowBuffer(&pNode->block,
4334                   MAX(nBlock, p->nNodeSize)+FTS3_NODE_PADDING, &rc
4335               );
4336               if( rc==SQLITE_OK ){
4337                 memcpy(pNode->block.a, aBlock, nBlock);
4338                 pNode->block.n = nBlock;
4339                 memset(&pNode->block.a[nBlock], 0, FTS3_NODE_PADDING);
4340               }
4341               sqlite3_free(aBlock);
4342             }
4343           }
4344         }
4345         nodeReaderRelease(&reader);
4346       }
4347     }
4348 
4349     rc2 = sqlite3_reset(pSelect);
4350     if( rc==SQLITE_OK ) rc = rc2;
4351   }
4352 
4353   return rc;
4354 }
4355 
4356 /*
4357 ** Determine the largest segment index value that exists within absolute
4358 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
4359 ** one before returning SQLITE_OK. Or, if there are no segments at all
4360 ** within level iAbsLevel, set *piIdx to zero.
4361 **
4362 ** If an error occurs, return an SQLite error code. The final value of
4363 ** *piIdx is undefined in this case.
4364 */
4365 static int fts3IncrmergeOutputIdx(
4366   Fts3Table *p,                   /* FTS Table handle */
4367   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
4368   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
4369 ){
4370   int rc;
4371   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
4372 
4373   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
4374   if( rc==SQLITE_OK ){
4375     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
4376     sqlite3_step(pOutputIdx);
4377     *piIdx = sqlite3_column_int(pOutputIdx, 0);
4378     rc = sqlite3_reset(pOutputIdx);
4379   }
4380 
4381   return rc;
4382 }
4383 
4384 /*
4385 ** Allocate an appendable output segment on absolute level iAbsLevel+1
4386 ** with idx value iIdx.
4387 **
4388 ** In the %_segdir table, a segment is defined by the values in three
4389 ** columns:
4390 **
4391 **     start_block
4392 **     leaves_end_block
4393 **     end_block
4394 **
4395 ** When an appendable segment is allocated, it is estimated that the
4396 ** maximum number of leaf blocks that may be required is the sum of the
4397 ** number of leaf blocks consumed by the input segments, plus the number
4398 ** of input segments, multiplied by two. This value is stored in stack
4399 ** variable nLeafEst.
4400 **
4401 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
4402 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
4403 ** array of leaf nodes starts at the first block allocated. The array
4404 ** of interior nodes that are parents of the leaf nodes start at block
4405 ** (start_block + (1 + end_block - start_block) / 16). And so on.
4406 **
4407 ** In the actual code below, the value "16" is replaced with the
4408 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
4409 */
4410 static int fts3IncrmergeWriter(
4411   Fts3Table *p,                   /* Fts3 table handle */
4412   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
4413   int iIdx,                       /* Index of new output segment */
4414   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
4415   IncrmergeWriter *pWriter        /* Populate this object */
4416 ){
4417   int rc;                         /* Return Code */
4418   int i;                          /* Iterator variable */
4419   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
4420   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
4421   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
4422 
4423   /* Calculate nLeafEst. */
4424   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
4425   if( rc==SQLITE_OK ){
4426     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
4427     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
4428     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
4429       nLeafEst = sqlite3_column_int(pLeafEst, 0);
4430     }
4431     rc = sqlite3_reset(pLeafEst);
4432   }
4433   if( rc!=SQLITE_OK ) return rc;
4434 
4435   /* Calculate the first block to use in the output segment */
4436   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
4437   if( rc==SQLITE_OK ){
4438     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
4439       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
4440       pWriter->iEnd = pWriter->iStart - 1;
4441       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
4442     }
4443     rc = sqlite3_reset(pFirstBlock);
4444   }
4445   if( rc!=SQLITE_OK ) return rc;
4446 
4447   /* Insert the marker in the %_segments table to make sure nobody tries
4448   ** to steal the space just allocated. This is also used to identify
4449   ** appendable segments.  */
4450   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
4451   if( rc!=SQLITE_OK ) return rc;
4452 
4453   pWriter->iAbsLevel = iAbsLevel;
4454   pWriter->nLeafEst = nLeafEst;
4455   pWriter->iIdx = iIdx;
4456 
4457   /* Set up the array of NodeWriter objects */
4458   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
4459     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
4460   }
4461   return SQLITE_OK;
4462 }
4463 
4464 /*
4465 ** Remove an entry from the %_segdir table. This involves running the
4466 ** following two statements:
4467 **
4468 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
4469 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
4470 **
4471 ** The DELETE statement removes the specific %_segdir level. The UPDATE
4472 ** statement ensures that the remaining segments have contiguously allocated
4473 ** idx values.
4474 */
4475 static int fts3RemoveSegdirEntry(
4476   Fts3Table *p,                   /* FTS3 table handle */
4477   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
4478   int iIdx                        /* Index of %_segdir entry to delete */
4479 ){
4480   int rc;                         /* Return code */
4481   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
4482 
4483   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
4484   if( rc==SQLITE_OK ){
4485     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
4486     sqlite3_bind_int(pDelete, 2, iIdx);
4487     sqlite3_step(pDelete);
4488     rc = sqlite3_reset(pDelete);
4489   }
4490 
4491   return rc;
4492 }
4493 
4494 /*
4495 ** One or more segments have just been removed from absolute level iAbsLevel.
4496 ** Update the 'idx' values of the remaining segments in the level so that
4497 ** the idx values are a contiguous sequence starting from 0.
4498 */
4499 static int fts3RepackSegdirLevel(
4500   Fts3Table *p,                   /* FTS3 table handle */
4501   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
4502 ){
4503   int rc;                         /* Return code */
4504   int *aIdx = 0;                  /* Array of remaining idx values */
4505   int nIdx = 0;                   /* Valid entries in aIdx[] */
4506   int nAlloc = 0;                 /* Allocated size of aIdx[] */
4507   int i;                          /* Iterator variable */
4508   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
4509   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
4510 
4511   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
4512   if( rc==SQLITE_OK ){
4513     int rc2;
4514     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
4515     while( SQLITE_ROW==sqlite3_step(pSelect) ){
4516       if( nIdx>=nAlloc ){
4517         int *aNew;
4518         nAlloc += 16;
4519         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
4520         if( !aNew ){
4521           rc = SQLITE_NOMEM;
4522           break;
4523         }
4524         aIdx = aNew;
4525       }
4526       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
4527     }
4528     rc2 = sqlite3_reset(pSelect);
4529     if( rc==SQLITE_OK ) rc = rc2;
4530   }
4531 
4532   if( rc==SQLITE_OK ){
4533     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
4534   }
4535   if( rc==SQLITE_OK ){
4536     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
4537   }
4538 
4539   assert( p->bIgnoreSavepoint==0 );
4540   p->bIgnoreSavepoint = 1;
4541   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
4542     if( aIdx[i]!=i ){
4543       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
4544       sqlite3_bind_int(pUpdate, 1, i);
4545       sqlite3_step(pUpdate);
4546       rc = sqlite3_reset(pUpdate);
4547     }
4548   }
4549   p->bIgnoreSavepoint = 0;
4550 
4551   sqlite3_free(aIdx);
4552   return rc;
4553 }
4554 
4555 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
4556   pNode->a[0] = (char)iHeight;
4557   if( iChild ){
4558     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
4559     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
4560   }else{
4561     assert( pNode->nAlloc>=1 );
4562     pNode->n = 1;
4563   }
4564 }
4565 
4566 /*
4567 ** The first two arguments are a pointer to and the size of a segment b-tree
4568 ** node. The node may be a leaf or an internal node.
4569 **
4570 ** This function creates a new node image in blob object *pNew by copying
4571 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
4572 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
4573 */
4574 static int fts3TruncateNode(
4575   const char *aNode,              /* Current node image */
4576   int nNode,                      /* Size of aNode in bytes */
4577   Blob *pNew,                     /* OUT: Write new node image here */
4578   const char *zTerm,              /* Omit all terms smaller than this */
4579   int nTerm,                      /* Size of zTerm in bytes */
4580   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
4581 ){
4582   NodeReader reader;              /* Reader object */
4583   Blob prev = {0, 0, 0};          /* Previous term written to new node */
4584   int rc = SQLITE_OK;             /* Return code */
4585   int bLeaf;                       /* True for a leaf node */
4586 
4587   if( nNode<1 ) return FTS_CORRUPT_VTAB;
4588   bLeaf = aNode[0]=='\0';
4589 
4590   /* Allocate required output space */
4591   blobGrowBuffer(pNew, nNode, &rc);
4592   if( rc!=SQLITE_OK ) return rc;
4593   pNew->n = 0;
4594 
4595   /* Populate new node buffer */
4596   for(rc = nodeReaderInit(&reader, aNode, nNode);
4597       rc==SQLITE_OK && reader.aNode;
4598       rc = nodeReaderNext(&reader)
4599   ){
4600     if( pNew->n==0 ){
4601       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
4602       if( res<0 || (bLeaf==0 && res==0) ) continue;
4603       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
4604       *piBlock = reader.iChild;
4605     }
4606     rc = fts3AppendToNode(
4607         pNew, &prev, reader.term.a, reader.term.n,
4608         reader.aDoclist, reader.nDoclist
4609     );
4610     if( rc!=SQLITE_OK ) break;
4611   }
4612   if( pNew->n==0 ){
4613     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
4614     *piBlock = reader.iChild;
4615   }
4616   assert( pNew->n<=pNew->nAlloc );
4617 
4618   nodeReaderRelease(&reader);
4619   sqlite3_free(prev.a);
4620   return rc;
4621 }
4622 
4623 /*
4624 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
4625 ** level iAbsLevel. This may involve deleting entries from the %_segments
4626 ** table, and modifying existing entries in both the %_segments and %_segdir
4627 ** tables.
4628 **
4629 ** SQLITE_OK is returned if the segment is updated successfully. Or an
4630 ** SQLite error code otherwise.
4631 */
4632 static int fts3TruncateSegment(
4633   Fts3Table *p,                   /* FTS3 table handle */
4634   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
4635   int iIdx,                       /* Index within level of segment to modify */
4636   const char *zTerm,              /* Remove terms smaller than this */
4637   int nTerm                      /* Number of bytes in buffer zTerm */
4638 ){
4639   int rc = SQLITE_OK;             /* Return code */
4640   Blob root = {0,0,0};            /* New root page image */
4641   Blob block = {0,0,0};           /* Buffer used for any other block */
4642   sqlite3_int64 iBlock = 0;       /* Block id */
4643   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
4644   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
4645   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
4646 
4647   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
4648   if( rc==SQLITE_OK ){
4649     int rc2;                      /* sqlite3_reset() return code */
4650     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
4651     sqlite3_bind_int(pFetch, 2, iIdx);
4652     if( SQLITE_ROW==sqlite3_step(pFetch) ){
4653       const char *aRoot = sqlite3_column_blob(pFetch, 4);
4654       int nRoot = sqlite3_column_bytes(pFetch, 4);
4655       iOldStart = sqlite3_column_int64(pFetch, 1);
4656       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
4657     }
4658     rc2 = sqlite3_reset(pFetch);
4659     if( rc==SQLITE_OK ) rc = rc2;
4660   }
4661 
4662   while( rc==SQLITE_OK && iBlock ){
4663     char *aBlock = 0;
4664     int nBlock = 0;
4665     iNewStart = iBlock;
4666 
4667     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
4668     if( rc==SQLITE_OK ){
4669       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
4670     }
4671     if( rc==SQLITE_OK ){
4672       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
4673     }
4674     sqlite3_free(aBlock);
4675   }
4676 
4677   /* Variable iNewStart now contains the first valid leaf node. */
4678   if( rc==SQLITE_OK && iNewStart ){
4679     sqlite3_stmt *pDel = 0;
4680     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
4681     if( rc==SQLITE_OK ){
4682       sqlite3_bind_int64(pDel, 1, iOldStart);
4683       sqlite3_bind_int64(pDel, 2, iNewStart-1);
4684       sqlite3_step(pDel);
4685       rc = sqlite3_reset(pDel);
4686     }
4687   }
4688 
4689   if( rc==SQLITE_OK ){
4690     sqlite3_stmt *pChomp = 0;
4691     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
4692     if( rc==SQLITE_OK ){
4693       sqlite3_bind_int64(pChomp, 1, iNewStart);
4694       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
4695       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
4696       sqlite3_bind_int(pChomp, 4, iIdx);
4697       sqlite3_step(pChomp);
4698       rc = sqlite3_reset(pChomp);
4699       sqlite3_bind_null(pChomp, 2);
4700     }
4701   }
4702 
4703   sqlite3_free(root.a);
4704   sqlite3_free(block.a);
4705   return rc;
4706 }
4707 
4708 /*
4709 ** This function is called after an incrmental-merge operation has run to
4710 ** merge (or partially merge) two or more segments from absolute level
4711 ** iAbsLevel.
4712 **
4713 ** Each input segment is either removed from the db completely (if all of
4714 ** its data was copied to the output segment by the incrmerge operation)
4715 ** or modified in place so that it no longer contains those entries that
4716 ** have been duplicated in the output segment.
4717 */
4718 static int fts3IncrmergeChomp(
4719   Fts3Table *p,                   /* FTS table handle */
4720   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
4721   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
4722   int *pnRem                      /* Number of segments not deleted */
4723 ){
4724   int i;
4725   int nRem = 0;
4726   int rc = SQLITE_OK;
4727 
4728   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
4729     Fts3SegReader *pSeg = 0;
4730     int j;
4731 
4732     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
4733     ** somewhere in the pCsr->apSegment[] array.  */
4734     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
4735       pSeg = pCsr->apSegment[j];
4736       if( pSeg->iIdx==i ) break;
4737     }
4738     assert( j<pCsr->nSegment && pSeg->iIdx==i );
4739 
4740     if( pSeg->aNode==0 ){
4741       /* Seg-reader is at EOF. Remove the entire input segment. */
4742       rc = fts3DeleteSegment(p, pSeg);
4743       if( rc==SQLITE_OK ){
4744         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
4745       }
4746       *pnRem = 0;
4747     }else{
4748       /* The incremental merge did not copy all the data from this
4749       ** segment to the upper level. The segment is modified in place
4750       ** so that it contains no keys smaller than zTerm/nTerm. */
4751       const char *zTerm = pSeg->zTerm;
4752       int nTerm = pSeg->nTerm;
4753       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
4754       nRem++;
4755     }
4756   }
4757 
4758   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
4759     rc = fts3RepackSegdirLevel(p, iAbsLevel);
4760   }
4761 
4762   *pnRem = nRem;
4763   return rc;
4764 }
4765 
4766 /*
4767 ** Store an incr-merge hint in the database.
4768 */
4769 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
4770   sqlite3_stmt *pReplace = 0;
4771   int rc;                         /* Return code */
4772 
4773   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
4774   if( rc==SQLITE_OK ){
4775     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
4776     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
4777     sqlite3_step(pReplace);
4778     rc = sqlite3_reset(pReplace);
4779     sqlite3_bind_null(pReplace, 2);
4780   }
4781 
4782   return rc;
4783 }
4784 
4785 /*
4786 ** Load an incr-merge hint from the database. The incr-merge hint, if one
4787 ** exists, is stored in the rowid==1 row of the %_stat table.
4788 **
4789 ** If successful, populate blob *pHint with the value read from the %_stat
4790 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
4791 ** SQLite error code.
4792 */
4793 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
4794   sqlite3_stmt *pSelect = 0;
4795   int rc;
4796 
4797   pHint->n = 0;
4798   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
4799   if( rc==SQLITE_OK ){
4800     int rc2;
4801     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
4802     if( SQLITE_ROW==sqlite3_step(pSelect) ){
4803       const char *aHint = sqlite3_column_blob(pSelect, 0);
4804       int nHint = sqlite3_column_bytes(pSelect, 0);
4805       if( aHint ){
4806         blobGrowBuffer(pHint, nHint, &rc);
4807         if( rc==SQLITE_OK ){
4808           memcpy(pHint->a, aHint, nHint);
4809           pHint->n = nHint;
4810         }
4811       }
4812     }
4813     rc2 = sqlite3_reset(pSelect);
4814     if( rc==SQLITE_OK ) rc = rc2;
4815   }
4816 
4817   return rc;
4818 }
4819 
4820 /*
4821 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
4822 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
4823 ** consists of two varints, the absolute level number of the input segments
4824 ** and the number of input segments.
4825 **
4826 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
4827 ** set *pRc to an SQLite error code before returning.
4828 */
4829 static void fts3IncrmergeHintPush(
4830   Blob *pHint,                    /* Hint blob to append to */
4831   i64 iAbsLevel,                  /* First varint to store in hint */
4832   int nInput,                     /* Second varint to store in hint */
4833   int *pRc                        /* IN/OUT: Error code */
4834 ){
4835   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
4836   if( *pRc==SQLITE_OK ){
4837     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
4838     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
4839   }
4840 }
4841 
4842 /*
4843 ** Read the last entry (most recently pushed) from the hint blob *pHint
4844 ** and then remove the entry. Write the two values read to *piAbsLevel and
4845 ** *pnInput before returning.
4846 **
4847 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
4848 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
4849 */
4850 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
4851   const int nHint = pHint->n;
4852   int i;
4853 
4854   i = pHint->n-1;
4855   if( (pHint->a[i] & 0x80) ) return FTS_CORRUPT_VTAB;
4856   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
4857   if( i==0 ) return FTS_CORRUPT_VTAB;
4858   i--;
4859   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
4860 
4861   pHint->n = i;
4862   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
4863   i += fts3GetVarint32(&pHint->a[i], pnInput);
4864   assert( i<=nHint );
4865   if( i!=nHint ) return FTS_CORRUPT_VTAB;
4866 
4867   return SQLITE_OK;
4868 }
4869 
4870 
4871 /*
4872 ** Attempt an incremental merge that writes nMerge leaf blocks.
4873 **
4874 ** Incremental merges happen nMin segments at a time. The segments
4875 ** to be merged are the nMin oldest segments (the ones with the smallest
4876 ** values for the _segdir.idx field) in the highest level that contains
4877 ** at least nMin segments. Multiple merges might occur in an attempt to
4878 ** write the quota of nMerge leaf blocks.
4879 */
4880 int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
4881   int rc;                         /* Return code */
4882   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
4883   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
4884   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
4885   IncrmergeWriter *pWriter;       /* Writer object */
4886   int nSeg = 0;                   /* Number of input segments */
4887   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
4888   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
4889   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
4890 
4891   /* Allocate space for the cursor, filter and writer objects */
4892   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
4893   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
4894   if( !pWriter ) return SQLITE_NOMEM;
4895   pFilter = (Fts3SegFilter *)&pWriter[1];
4896   pCsr = (Fts3MultiSegReader *)&pFilter[1];
4897 
4898   rc = fts3IncrmergeHintLoad(p, &hint);
4899   while( rc==SQLITE_OK && nRem>0 ){
4900     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
4901     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
4902     int bUseHint = 0;             /* True if attempting to append */
4903     int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
4904 
4905     /* Search the %_segdir table for the absolute level with the smallest
4906     ** relative level number that contains at least nMin segments, if any.
4907     ** If one is found, set iAbsLevel to the absolute level number and
4908     ** nSeg to nMin. If no level with at least nMin segments can be found,
4909     ** set nSeg to -1.
4910     */
4911     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
4912     sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
4913     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
4914       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
4915       nSeg = sqlite3_column_int(pFindLevel, 1);
4916       assert( nSeg>=2 );
4917     }else{
4918       nSeg = -1;
4919     }
4920     rc = sqlite3_reset(pFindLevel);
4921 
4922     /* If the hint read from the %_stat table is not empty, check if the
4923     ** last entry in it specifies a relative level smaller than or equal
4924     ** to the level identified by the block above (if any). If so, this
4925     ** iteration of the loop will work on merging at the hinted level.
4926     */
4927     if( rc==SQLITE_OK && hint.n ){
4928       int nHint = hint.n;
4929       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
4930       int nHintSeg = 0;                     /* Hint number of segments */
4931 
4932       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
4933       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
4934         /* Based on the scan in the block above, it is known that there
4935         ** are no levels with a relative level smaller than that of
4936         ** iAbsLevel with more than nSeg segments, or if nSeg is -1,
4937         ** no levels with more than nMin segments. Use this to limit the
4938         ** value of nHintSeg to avoid a large memory allocation in case the
4939         ** merge-hint is corrupt*/
4940         iAbsLevel = iHintAbsLevel;
4941         nSeg = MIN(MAX(nMin,nSeg), nHintSeg);
4942         bUseHint = 1;
4943         bDirtyHint = 1;
4944       }else{
4945         /* This undoes the effect of the HintPop() above - so that no entry
4946         ** is removed from the hint blob.  */
4947         hint.n = nHint;
4948       }
4949     }
4950 
4951     /* If nSeg is less that zero, then there is no level with at least
4952     ** nMin segments and no hint in the %_stat table. No work to do.
4953     ** Exit early in this case.  */
4954     if( nSeg<=0 ) break;
4955 
4956     /* Open a cursor to iterate through the contents of the oldest nSeg
4957     ** indexes of absolute level iAbsLevel. If this cursor is opened using
4958     ** the 'hint' parameters, it is possible that there are less than nSeg
4959     ** segments available in level iAbsLevel. In this case, no work is
4960     ** done on iAbsLevel - fall through to the next iteration of the loop
4961     ** to start work on some other level.  */
4962     memset(pWriter, 0, nAlloc);
4963     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
4964 
4965     if( rc==SQLITE_OK ){
4966       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
4967       assert( bUseHint==1 || bUseHint==0 );
4968       if( iIdx==0 || (bUseHint && iIdx==1) ){
4969         int bIgnore = 0;
4970         rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
4971         if( bIgnore ){
4972           pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
4973         }
4974       }
4975     }
4976 
4977     if( rc==SQLITE_OK ){
4978       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
4979     }
4980     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
4981      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
4982     ){
4983       int bEmpty = 0;
4984       rc = sqlite3Fts3SegReaderStep(p, pCsr);
4985       if( rc==SQLITE_OK ){
4986         bEmpty = 1;
4987       }else if( rc!=SQLITE_ROW ){
4988         sqlite3Fts3SegReaderFinish(pCsr);
4989         break;
4990       }
4991       if( bUseHint && iIdx>0 ){
4992         const char *zKey = pCsr->zTerm;
4993         int nKey = pCsr->nTerm;
4994         rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
4995       }else{
4996         rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
4997       }
4998 
4999       if( rc==SQLITE_OK && pWriter->nLeafEst ){
5000         fts3LogMerge(nSeg, iAbsLevel);
5001         if( bEmpty==0 ){
5002           do {
5003             rc = fts3IncrmergeAppend(p, pWriter, pCsr);
5004             if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
5005             if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
5006           }while( rc==SQLITE_ROW );
5007         }
5008 
5009         /* Update or delete the input segments */
5010         if( rc==SQLITE_OK ){
5011           nRem -= (1 + pWriter->nWork);
5012           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
5013           if( nSeg!=0 ){
5014             bDirtyHint = 1;
5015             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
5016           }
5017         }
5018       }
5019 
5020       if( nSeg!=0 ){
5021         pWriter->nLeafData = pWriter->nLeafData * -1;
5022       }
5023       fts3IncrmergeRelease(p, pWriter, &rc);
5024       if( nSeg==0 && pWriter->bNoLeafData==0 ){
5025         fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
5026       }
5027     }
5028 
5029     sqlite3Fts3SegReaderFinish(pCsr);
5030   }
5031 
5032   /* Write the hint values into the %_stat table for the next incr-merger */
5033   if( bDirtyHint && rc==SQLITE_OK ){
5034     rc = fts3IncrmergeHintStore(p, &hint);
5035   }
5036 
5037   sqlite3_free(pWriter);
5038   sqlite3_free(hint.a);
5039   return rc;
5040 }
5041 
5042 /*
5043 ** Convert the text beginning at *pz into an integer and return
5044 ** its value.  Advance *pz to point to the first character past
5045 ** the integer.
5046 **
5047 ** This function used for parameters to merge= and incrmerge=
5048 ** commands.
5049 */
5050 static int fts3Getint(const char **pz){
5051   const char *z = *pz;
5052   int i = 0;
5053   while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
5054   *pz = z;
5055   return i;
5056 }
5057 
5058 /*
5059 ** Process statements of the form:
5060 **
5061 **    INSERT INTO table(table) VALUES('merge=A,B');
5062 **
5063 ** A and B are integers that decode to be the number of leaf pages
5064 ** written for the merge, and the minimum number of segments on a level
5065 ** before it will be selected for a merge, respectively.
5066 */
5067 static int fts3DoIncrmerge(
5068   Fts3Table *p,                   /* FTS3 table handle */
5069   const char *zParam              /* Nul-terminated string containing "A,B" */
5070 ){
5071   int rc;
5072   int nMin = (MergeCount(p) / 2);
5073   int nMerge = 0;
5074   const char *z = zParam;
5075 
5076   /* Read the first integer value */
5077   nMerge = fts3Getint(&z);
5078 
5079   /* If the first integer value is followed by a ',',  read the second
5080   ** integer value. */
5081   if( z[0]==',' && z[1]!='\0' ){
5082     z++;
5083     nMin = fts3Getint(&z);
5084   }
5085 
5086   if( z[0]!='\0' || nMin<2 ){
5087     rc = SQLITE_ERROR;
5088   }else{
5089     rc = SQLITE_OK;
5090     if( !p->bHasStat ){
5091       assert( p->bFts4==0 );
5092       sqlite3Fts3CreateStatTable(&rc, p);
5093     }
5094     if( rc==SQLITE_OK ){
5095       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
5096     }
5097     sqlite3Fts3SegmentsClose(p);
5098   }
5099   return rc;
5100 }
5101 
5102 /*
5103 ** Process statements of the form:
5104 **
5105 **    INSERT INTO table(table) VALUES('automerge=X');
5106 **
5107 ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
5108 ** turn it on.  The setting is persistent.
5109 */
5110 static int fts3DoAutoincrmerge(
5111   Fts3Table *p,                   /* FTS3 table handle */
5112   const char *zParam              /* Nul-terminated string containing boolean */
5113 ){
5114   int rc = SQLITE_OK;
5115   sqlite3_stmt *pStmt = 0;
5116   p->nAutoincrmerge = fts3Getint(&zParam);
5117   if( p->nAutoincrmerge==1 || p->nAutoincrmerge>MergeCount(p) ){
5118     p->nAutoincrmerge = 8;
5119   }
5120   if( !p->bHasStat ){
5121     assert( p->bFts4==0 );
5122     sqlite3Fts3CreateStatTable(&rc, p);
5123     if( rc ) return rc;
5124   }
5125   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
5126   if( rc ) return rc;
5127   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
5128   sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
5129   sqlite3_step(pStmt);
5130   rc = sqlite3_reset(pStmt);
5131   return rc;
5132 }
5133 
5134 /*
5135 ** Return a 64-bit checksum for the FTS index entry specified by the
5136 ** arguments to this function.
5137 */
5138 static u64 fts3ChecksumEntry(
5139   const char *zTerm,              /* Pointer to buffer containing term */
5140   int nTerm,                      /* Size of zTerm in bytes */
5141   int iLangid,                    /* Language id for current row */
5142   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
5143   i64 iDocid,                     /* Docid for current row. */
5144   int iCol,                       /* Column number */
5145   int iPos                        /* Position */
5146 ){
5147   int i;
5148   u64 ret = (u64)iDocid;
5149 
5150   ret += (ret<<3) + iLangid;
5151   ret += (ret<<3) + iIndex;
5152   ret += (ret<<3) + iCol;
5153   ret += (ret<<3) + iPos;
5154   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
5155 
5156   return ret;
5157 }
5158 
5159 /*
5160 ** Return a checksum of all entries in the FTS index that correspond to
5161 ** language id iLangid. The checksum is calculated by XORing the checksums
5162 ** of each individual entry (see fts3ChecksumEntry()) together.
5163 **
5164 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
5165 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
5166 ** return value is undefined in this case.
5167 */
5168 static u64 fts3ChecksumIndex(
5169   Fts3Table *p,                   /* FTS3 table handle */
5170   int iLangid,                    /* Language id to return cksum for */
5171   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
5172   int *pRc                        /* OUT: Return code */
5173 ){
5174   Fts3SegFilter filter;
5175   Fts3MultiSegReader csr;
5176   int rc;
5177   u64 cksum = 0;
5178 
5179   assert( *pRc==SQLITE_OK );
5180 
5181   memset(&filter, 0, sizeof(filter));
5182   memset(&csr, 0, sizeof(csr));
5183   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
5184   filter.flags |= FTS3_SEGMENT_SCAN;
5185 
5186   rc = sqlite3Fts3SegReaderCursor(
5187       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
5188   );
5189   if( rc==SQLITE_OK ){
5190     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
5191   }
5192 
5193   if( rc==SQLITE_OK ){
5194     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
5195       char *pCsr = csr.aDoclist;
5196       char *pEnd = &pCsr[csr.nDoclist];
5197 
5198       i64 iDocid = 0;
5199       i64 iCol = 0;
5200       u64 iPos = 0;
5201 
5202       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
5203       while( pCsr<pEnd ){
5204         u64 iVal = 0;
5205         pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal);
5206         if( pCsr<pEnd ){
5207           if( iVal==0 || iVal==1 ){
5208             iCol = 0;
5209             iPos = 0;
5210             if( iVal ){
5211               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
5212             }else{
5213               pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal);
5214               if( p->bDescIdx ){
5215                 iDocid = (i64)((u64)iDocid - iVal);
5216               }else{
5217                 iDocid = (i64)((u64)iDocid + iVal);
5218               }
5219             }
5220           }else{
5221             iPos += (iVal - 2);
5222             cksum = cksum ^ fts3ChecksumEntry(
5223                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
5224                 (int)iCol, (int)iPos
5225             );
5226           }
5227         }
5228       }
5229     }
5230   }
5231   sqlite3Fts3SegReaderFinish(&csr);
5232 
5233   *pRc = rc;
5234   return cksum;
5235 }
5236 
5237 /*
5238 ** Check if the contents of the FTS index match the current contents of the
5239 ** content table. If no error occurs and the contents do match, set *pbOk
5240 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
5241 ** to false before returning.
5242 **
5243 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
5244 ** code. The final value of *pbOk is undefined in this case.
5245 */
5246 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
5247   int rc = SQLITE_OK;             /* Return code */
5248   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
5249   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
5250   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
5251 
5252   /* This block calculates the checksum according to the FTS index. */
5253   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
5254   if( rc==SQLITE_OK ){
5255     int rc2;
5256     sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
5257     sqlite3_bind_int(pAllLangid, 2, p->nIndex);
5258     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
5259       int iLangid = sqlite3_column_int(pAllLangid, 0);
5260       int i;
5261       for(i=0; i<p->nIndex; i++){
5262         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
5263       }
5264     }
5265     rc2 = sqlite3_reset(pAllLangid);
5266     if( rc==SQLITE_OK ) rc = rc2;
5267   }
5268 
5269   /* This block calculates the checksum according to the %_content table */
5270   if( rc==SQLITE_OK ){
5271     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
5272     sqlite3_stmt *pStmt = 0;
5273     char *zSql;
5274 
5275     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
5276     if( !zSql ){
5277       rc = SQLITE_NOMEM;
5278     }else{
5279       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5280       sqlite3_free(zSql);
5281     }
5282 
5283     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
5284       i64 iDocid = sqlite3_column_int64(pStmt, 0);
5285       int iLang = langidFromSelect(p, pStmt);
5286       int iCol;
5287 
5288       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
5289         if( p->abNotindexed[iCol]==0 ){
5290           const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
5291           sqlite3_tokenizer_cursor *pT = 0;
5292 
5293           rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, -1, &pT);
5294           while( rc==SQLITE_OK ){
5295             char const *zToken;       /* Buffer containing token */
5296             int nToken = 0;           /* Number of bytes in token */
5297             int iDum1 = 0, iDum2 = 0; /* Dummy variables */
5298             int iPos = 0;             /* Position of token in zText */
5299 
5300             rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
5301             if( rc==SQLITE_OK ){
5302               int i;
5303               cksum2 = cksum2 ^ fts3ChecksumEntry(
5304                   zToken, nToken, iLang, 0, iDocid, iCol, iPos
5305               );
5306               for(i=1; i<p->nIndex; i++){
5307                 if( p->aIndex[i].nPrefix<=nToken ){
5308                   cksum2 = cksum2 ^ fts3ChecksumEntry(
5309                       zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
5310                   );
5311                 }
5312               }
5313             }
5314           }
5315           if( pT ) pModule->xClose(pT);
5316           if( rc==SQLITE_DONE ) rc = SQLITE_OK;
5317         }
5318       }
5319     }
5320 
5321     sqlite3_finalize(pStmt);
5322   }
5323 
5324   *pbOk = (cksum1==cksum2);
5325   return rc;
5326 }
5327 
5328 /*
5329 ** Run the integrity-check. If no error occurs and the current contents of
5330 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
5331 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
5332 **
5333 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
5334 ** error code.
5335 **
5336 ** The integrity-check works as follows. For each token and indexed token
5337 ** prefix in the document set, a 64-bit checksum is calculated (by code
5338 ** in fts3ChecksumEntry()) based on the following:
5339 **
5340 **     + The index number (0 for the main index, 1 for the first prefix
5341 **       index etc.),
5342 **     + The token (or token prefix) text itself,
5343 **     + The language-id of the row it appears in,
5344 **     + The docid of the row it appears in,
5345 **     + The column it appears in, and
5346 **     + The tokens position within that column.
5347 **
5348 ** The checksums for all entries in the index are XORed together to create
5349 ** a single checksum for the entire index.
5350 **
5351 ** The integrity-check code calculates the same checksum in two ways:
5352 **
5353 **     1. By scanning the contents of the FTS index, and
5354 **     2. By scanning and tokenizing the content table.
5355 **
5356 ** If the two checksums are identical, the integrity-check is deemed to have
5357 ** passed.
5358 */
5359 static int fts3DoIntegrityCheck(
5360   Fts3Table *p                    /* FTS3 table handle */
5361 ){
5362   int rc;
5363   int bOk = 0;
5364   rc = fts3IntegrityCheck(p, &bOk);
5365   if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
5366   return rc;
5367 }
5368 
5369 /*
5370 ** Handle a 'special' INSERT of the form:
5371 **
5372 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
5373 **
5374 ** Argument pVal contains the result of <expr>. Currently the only
5375 ** meaningful value to insert is the text 'optimize'.
5376 */
5377 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
5378   int rc = SQLITE_ERROR;           /* Return Code */
5379   const char *zVal = (const char *)sqlite3_value_text(pVal);
5380   int nVal = sqlite3_value_bytes(pVal);
5381 
5382   if( !zVal ){
5383     return SQLITE_NOMEM;
5384   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
5385     rc = fts3DoOptimize(p, 0);
5386   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
5387     rc = fts3DoRebuild(p);
5388   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
5389     rc = fts3DoIntegrityCheck(p);
5390   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
5391     rc = fts3DoIncrmerge(p, &zVal[6]);
5392   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
5393     rc = fts3DoAutoincrmerge(p, &zVal[10]);
5394 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
5395   }else{
5396     int v;
5397     if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
5398       v = atoi(&zVal[9]);
5399       if( v>=24 && v<=p->nPgsz-35 ) p->nNodeSize = v;
5400       rc = SQLITE_OK;
5401     }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
5402       v = atoi(&zVal[11]);
5403       if( v>=64 && v<=FTS3_MAX_PENDING_DATA ) p->nMaxPendingData = v;
5404       rc = SQLITE_OK;
5405     }else if( nVal>21 && 0==sqlite3_strnicmp(zVal,"test-no-incr-doclist=",21) ){
5406       p->bNoIncrDoclist = atoi(&zVal[21]);
5407       rc = SQLITE_OK;
5408     }else if( nVal>11 && 0==sqlite3_strnicmp(zVal,"mergecount=",11) ){
5409       v = atoi(&zVal[11]);
5410       if( v>=4 && v<=FTS3_MERGE_COUNT && (v&1)==0 ) p->nMergeCount = v;
5411       rc = SQLITE_OK;
5412     }
5413 #endif
5414   }
5415   return rc;
5416 }
5417 
5418 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
5419 /*
5420 ** Delete all cached deferred doclists. Deferred doclists are cached
5421 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
5422 */
5423 void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
5424   Fts3DeferredToken *pDef;
5425   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
5426     fts3PendingListDelete(pDef->pList);
5427     pDef->pList = 0;
5428   }
5429 }
5430 
5431 /*
5432 ** Free all entries in the pCsr->pDeffered list. Entries are added to
5433 ** this list using sqlite3Fts3DeferToken().
5434 */
5435 void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
5436   Fts3DeferredToken *pDef;
5437   Fts3DeferredToken *pNext;
5438   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
5439     pNext = pDef->pNext;
5440     fts3PendingListDelete(pDef->pList);
5441     sqlite3_free(pDef);
5442   }
5443   pCsr->pDeferred = 0;
5444 }
5445 
5446 /*
5447 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
5448 ** based on the row that pCsr currently points to.
5449 **
5450 ** A deferred-doclist is like any other doclist with position information
5451 ** included, except that it only contains entries for a single row of the
5452 ** table, not for all rows.
5453 */
5454 int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
5455   int rc = SQLITE_OK;             /* Return code */
5456   if( pCsr->pDeferred ){
5457     int i;                        /* Used to iterate through table columns */
5458     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
5459     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
5460 
5461     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
5462     sqlite3_tokenizer *pT = p->pTokenizer;
5463     sqlite3_tokenizer_module const *pModule = pT->pModule;
5464 
5465     assert( pCsr->isRequireSeek==0 );
5466     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
5467 
5468     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
5469       if( p->abNotindexed[i]==0 ){
5470         const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
5471         sqlite3_tokenizer_cursor *pTC = 0;
5472 
5473         rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
5474         while( rc==SQLITE_OK ){
5475           char const *zToken;       /* Buffer containing token */
5476           int nToken = 0;           /* Number of bytes in token */
5477           int iDum1 = 0, iDum2 = 0; /* Dummy variables */
5478           int iPos = 0;             /* Position of token in zText */
5479 
5480           rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
5481           for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
5482             Fts3PhraseToken *pPT = pDef->pToken;
5483             if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
5484                 && (pPT->bFirst==0 || iPos==0)
5485                 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
5486                 && (0==memcmp(zToken, pPT->z, pPT->n))
5487               ){
5488               fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
5489             }
5490           }
5491         }
5492         if( pTC ) pModule->xClose(pTC);
5493         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
5494       }
5495     }
5496 
5497     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
5498       if( pDef->pList ){
5499         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
5500       }
5501     }
5502   }
5503 
5504   return rc;
5505 }
5506 
5507 int sqlite3Fts3DeferredTokenList(
5508   Fts3DeferredToken *p,
5509   char **ppData,
5510   int *pnData
5511 ){
5512   char *pRet;
5513   int nSkip;
5514   sqlite3_int64 dummy;
5515 
5516   *ppData = 0;
5517   *pnData = 0;
5518 
5519   if( p->pList==0 ){
5520     return SQLITE_OK;
5521   }
5522 
5523   pRet = (char *)sqlite3_malloc(p->pList->nData);
5524   if( !pRet ) return SQLITE_NOMEM;
5525 
5526   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
5527   *pnData = p->pList->nData - nSkip;
5528   *ppData = pRet;
5529 
5530   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
5531   return SQLITE_OK;
5532 }
5533 
5534 /*
5535 ** Add an entry for token pToken to the pCsr->pDeferred list.
5536 */
5537 int sqlite3Fts3DeferToken(
5538   Fts3Cursor *pCsr,               /* Fts3 table cursor */
5539   Fts3PhraseToken *pToken,        /* Token to defer */
5540   int iCol                        /* Column that token must appear in (or -1) */
5541 ){
5542   Fts3DeferredToken *pDeferred;
5543   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
5544   if( !pDeferred ){
5545     return SQLITE_NOMEM;
5546   }
5547   memset(pDeferred, 0, sizeof(*pDeferred));
5548   pDeferred->pToken = pToken;
5549   pDeferred->pNext = pCsr->pDeferred;
5550   pDeferred->iCol = iCol;
5551   pCsr->pDeferred = pDeferred;
5552 
5553   assert( pToken->pDeferred==0 );
5554   pToken->pDeferred = pDeferred;
5555 
5556   return SQLITE_OK;
5557 }
5558 #endif
5559 
5560 /*
5561 ** SQLite value pRowid contains the rowid of a row that may or may not be
5562 ** present in the FTS3 table. If it is, delete it and adjust the contents
5563 ** of subsiduary data structures accordingly.
5564 */
5565 static int fts3DeleteByRowid(
5566   Fts3Table *p,
5567   sqlite3_value *pRowid,
5568   int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
5569   u32 *aSzDel
5570 ){
5571   int rc = SQLITE_OK;             /* Return code */
5572   int bFound = 0;                 /* True if *pRowid really is in the table */
5573 
5574   fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
5575   if( bFound && rc==SQLITE_OK ){
5576     int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
5577     rc = fts3IsEmpty(p, pRowid, &isEmpty);
5578     if( rc==SQLITE_OK ){
5579       if( isEmpty ){
5580         /* Deleting this row means the whole table is empty. In this case
5581         ** delete the contents of all three tables and throw away any
5582         ** data in the pendingTerms hash table.  */
5583         rc = fts3DeleteAll(p, 1);
5584         *pnChng = 0;
5585         memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
5586       }else{
5587         *pnChng = *pnChng - 1;
5588         if( p->zContentTbl==0 ){
5589           fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
5590         }
5591         if( p->bHasDocsize ){
5592           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
5593         }
5594       }
5595     }
5596   }
5597 
5598   return rc;
5599 }
5600 
5601 /*
5602 ** This function does the work for the xUpdate method of FTS3 virtual
5603 ** tables. The schema of the virtual table being:
5604 **
5605 **     CREATE TABLE <table name>(
5606 **       <user columns>,
5607 **       <table name> HIDDEN,
5608 **       docid HIDDEN,
5609 **       <langid> HIDDEN
5610 **     );
5611 **
5612 **
5613 */
5614 int sqlite3Fts3UpdateMethod(
5615   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
5616   int nArg,                       /* Size of argument array */
5617   sqlite3_value **apVal,          /* Array of arguments */
5618   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
5619 ){
5620   Fts3Table *p = (Fts3Table *)pVtab;
5621   int rc = SQLITE_OK;             /* Return Code */
5622   u32 *aSzIns = 0;                /* Sizes of inserted documents */
5623   u32 *aSzDel = 0;                /* Sizes of deleted documents */
5624   int nChng = 0;                  /* Net change in number of documents */
5625   int bInsertDone = 0;
5626 
5627   /* At this point it must be known if the %_stat table exists or not.
5628   ** So bHasStat may not be 2.  */
5629   assert( p->bHasStat==0 || p->bHasStat==1 );
5630 
5631   assert( p->pSegments==0 );
5632   assert(
5633       nArg==1                     /* DELETE operations */
5634    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
5635   );
5636 
5637   /* Check for a "special" INSERT operation. One of the form:
5638   **
5639   **   INSERT INTO xyz(xyz) VALUES('command');
5640   */
5641   if( nArg>1
5642    && sqlite3_value_type(apVal[0])==SQLITE_NULL
5643    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
5644   ){
5645     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
5646     goto update_out;
5647   }
5648 
5649   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
5650     rc = SQLITE_CONSTRAINT;
5651     goto update_out;
5652   }
5653 
5654   /* Allocate space to hold the change in document sizes */
5655   aSzDel = sqlite3_malloc64(sizeof(aSzDel[0])*((sqlite3_int64)p->nColumn+1)*2);
5656   if( aSzDel==0 ){
5657     rc = SQLITE_NOMEM;
5658     goto update_out;
5659   }
5660   aSzIns = &aSzDel[p->nColumn+1];
5661   memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
5662 
5663   rc = fts3Writelock(p);
5664   if( rc!=SQLITE_OK ) goto update_out;
5665 
5666   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
5667   ** value, then this operation requires constraint handling.
5668   **
5669   ** If the on-conflict mode is REPLACE, this means that the existing row
5670   ** should be deleted from the database before inserting the new row. Or,
5671   ** if the on-conflict mode is other than REPLACE, then this method must
5672   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
5673   ** modify the database file.
5674   */
5675   if( nArg>1 && p->zContentTbl==0 ){
5676     /* Find the value object that holds the new rowid value. */
5677     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
5678     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
5679       pNewRowid = apVal[1];
5680     }
5681 
5682     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
5683         sqlite3_value_type(apVal[0])==SQLITE_NULL
5684      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
5685     )){
5686       /* The new rowid is not NULL (in this case the rowid will be
5687       ** automatically assigned and there is no chance of a conflict), and
5688       ** the statement is either an INSERT or an UPDATE that modifies the
5689       ** rowid column. So if the conflict mode is REPLACE, then delete any
5690       ** existing row with rowid=pNewRowid.
5691       **
5692       ** Or, if the conflict mode is not REPLACE, insert the new record into
5693       ** the %_content table. If we hit the duplicate rowid constraint (or any
5694       ** other error) while doing so, return immediately.
5695       **
5696       ** This branch may also run if pNewRowid contains a value that cannot
5697       ** be losslessly converted to an integer. In this case, the eventual
5698       ** call to fts3InsertData() (either just below or further on in this
5699       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
5700       ** invoked, it will delete zero rows (since no row will have
5701       ** docid=$pNewRowid if $pNewRowid is not an integer value).
5702       */
5703       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
5704         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
5705       }else{
5706         rc = fts3InsertData(p, apVal, pRowid);
5707         bInsertDone = 1;
5708       }
5709     }
5710   }
5711   if( rc!=SQLITE_OK ){
5712     goto update_out;
5713   }
5714 
5715   /* If this is a DELETE or UPDATE operation, remove the old record. */
5716   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
5717     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
5718     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
5719   }
5720 
5721   /* If this is an INSERT or UPDATE operation, insert the new record. */
5722   if( nArg>1 && rc==SQLITE_OK ){
5723     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
5724     if( bInsertDone==0 ){
5725       rc = fts3InsertData(p, apVal, pRowid);
5726       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
5727         rc = FTS_CORRUPT_VTAB;
5728       }
5729     }
5730     if( rc==SQLITE_OK ){
5731       rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
5732     }
5733     if( rc==SQLITE_OK ){
5734       assert( p->iPrevDocid==*pRowid );
5735       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
5736     }
5737     if( p->bHasDocsize ){
5738       fts3InsertDocsize(&rc, p, aSzIns);
5739     }
5740     nChng++;
5741   }
5742 
5743   if( p->bFts4 ){
5744     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
5745   }
5746 
5747  update_out:
5748   sqlite3_free(aSzDel);
5749   sqlite3Fts3SegmentsClose(p);
5750   return rc;
5751 }
5752 
5753 /*
5754 ** Flush any data in the pending-terms hash table to disk. If successful,
5755 ** merge all segments in the database (including the new segment, if
5756 ** there was any data to flush) into a single segment.
5757 */
5758 int sqlite3Fts3Optimize(Fts3Table *p){
5759   int rc;
5760   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
5761   if( rc==SQLITE_OK ){
5762     rc = fts3DoOptimize(p, 1);
5763     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
5764       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
5765       if( rc2!=SQLITE_OK ) rc = rc2;
5766     }else{
5767       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
5768       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
5769     }
5770   }
5771   sqlite3Fts3SegmentsClose(p);
5772   return rc;
5773 }
5774 
5775 #endif
5776