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