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