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