defer memory hook until after xInit
[sqlcipher.git] / ext / fts3 / fts3_write.c
blob0baf82b76ec76a0a9ff512a7720a4981b2fa7e07
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.
11 ******************************************************************************
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.
20 #include "fts3Int.h"
21 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
23 #include <string.h>
24 #include <assert.h>
25 #include <stdlib.h>
28 #define FTS_MAX_APPENDABLE_HEIGHT 16
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.
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.
40 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
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).
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.
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.
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
70 ** The two values that may be meaningfully bound to the :1 parameter in
71 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
73 #define FTS_STAT_DOCTOTAL 0
74 #define FTS_STAT_INCRMERGEHINT 1
75 #define FTS_STAT_AUTOINCRMERGE 2
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.
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);
87 #else
88 #define fts3LogMerge(x, y)
89 #endif
92 typedef struct PendingList PendingList;
93 typedef struct SegmentNode SegmentNode;
94 typedef struct SegmentWriter SegmentWriter;
97 ** An instance of the following data structure is used to build doclists
98 ** incrementally. See function fts3PendingListAppend() for details.
100 struct PendingList {
101 int nData;
102 char *aData;
103 int nSpace;
104 sqlite3_int64 iLastDocid;
105 sqlite3_int64 iLastCol;
106 sqlite3_int64 iLastPos;
111 ** Each cursor has a (possibly empty) linked list of the following objects.
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 */
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:
127 ** sqlite3Fts3SegReaderNew()
128 ** sqlite3Fts3SegReaderFree()
129 ** sqlite3Fts3SegReaderIterate()
131 ** Methods used to manipulate Fts3SegReader structures:
133 ** fts3SegReaderNext()
134 ** fts3SegReaderFirstDocid()
135 ** fts3SegReaderNextDocid()
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 */
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) */
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 */
152 Fts3HashElem **ppNextElem;
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).
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 */
165 /* The following variables are used by fts3SegReaderNextDocid() to iterate
166 ** through the current doclist (aDoclist/nDoclist).
168 char *pOffsetList;
169 int nOffsetList; /* For descending pending seg-readers only */
170 sqlite3_int64 iDocid;
173 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
174 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
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:
181 ** fts3SegWriterAdd()
182 ** fts3SegWriterFlush()
183 ** fts3SegWriterFree()
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 */
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.
205 ** fts3NodeAddTerm()
206 ** fts3NodeWrite()
207 ** fts3NodeFree()
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.
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 */
231 ** Valid values for the second argument to fts3SqlStmt().
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
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
272 #define SQL_SELECT_LEVEL_RANGE2 37
273 #define SQL_UPDATE_LEVEL_IDX 38
274 #define SQL_UPDATE_LEVEL 39
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.
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.
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 */
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(?,?,?,?,?,?)",
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",
314 /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
315 /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
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 */ "",
328 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
329 /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
331 /* This statement is used to determine which level to read the input from
332 ** when performing an incremental merge. It returns the absolute level number
333 ** of the oldest level in the db that contains at least ? segments. Or,
334 ** if no level in the FTS index contains more than ? segments, the statement
335 ** returns zero rows. */
336 /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
337 " GROUP BY level HAVING cnt>=?"
338 " ORDER BY (level %% 1024) ASC LIMIT 1",
340 /* Estimate the upper limit on the number of leaf nodes in a new segment
341 ** created by merging the oldest :2 segments from absolute level :1. See
342 ** function sqlite3Fts3Incrmerge() for details. */
343 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
344 " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
346 /* SQL_DELETE_SEGDIR_ENTRY
347 ** Delete the %_segdir entry on absolute level :1 with index :2. */
348 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
350 /* SQL_SHIFT_SEGDIR_ENTRY
351 ** Modify the idx value for the segment with idx=:3 on absolute level :2
352 ** to :1. */
353 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
355 /* SQL_SELECT_SEGDIR
356 ** Read a single entry from the %_segdir table. The entry from absolute
357 ** level :1 with index value :2. */
358 /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
359 "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
361 /* SQL_CHOMP_SEGDIR
362 ** Update the start_block (:1) and root (:2) fields of the %_segdir
363 ** entry located on absolute level :3 with index :4. */
364 /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
365 "WHERE level = ? AND idx = ?",
367 /* SQL_SEGMENT_IS_APPENDABLE
368 ** Return a single row if the segment with end_block=? is appendable. Or
369 ** no rows otherwise. */
370 /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
372 /* SQL_SELECT_INDEXES
373 ** Return the list of valid segment indexes for absolute level ? */
374 /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
376 /* SQL_SELECT_MXLEVEL
377 ** Return the largest relative level in the FTS index or indexes. */
378 /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
380 /* Return segments in order from oldest to newest.*/
381 /* 37 */ "SELECT level, idx, end_block "
382 "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
383 "ORDER BY level DESC, idx ASC",
385 /* Update statements used while promoting segments */
386 /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
387 "WHERE level=? AND idx=?",
388 /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
391 int rc = SQLITE_OK;
392 sqlite3_stmt *pStmt;
394 assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
395 assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
397 pStmt = p->aStmt[eStmt];
398 if( !pStmt ){
399 char *zSql;
400 if( eStmt==SQL_CONTENT_INSERT ){
401 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
402 }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
403 zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
404 }else{
405 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
407 if( !zSql ){
408 rc = SQLITE_NOMEM;
409 }else{
410 rc = sqlite3_prepare_v3(p->db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
411 &pStmt, NULL);
412 sqlite3_free(zSql);
413 assert( rc==SQLITE_OK || pStmt==0 );
414 p->aStmt[eStmt] = pStmt;
417 if( apVal ){
418 int i;
419 int nParam = sqlite3_bind_parameter_count(pStmt);
420 for(i=0; rc==SQLITE_OK && i<nParam; i++){
421 rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
424 *pp = pStmt;
425 return rc;
429 static int fts3SelectDocsize(
430 Fts3Table *pTab, /* FTS3 table handle */
431 sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
432 sqlite3_stmt **ppStmt /* OUT: Statement handle */
434 sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
435 int rc; /* Return code */
437 rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
438 if( rc==SQLITE_OK ){
439 sqlite3_bind_int64(pStmt, 1, iDocid);
440 rc = sqlite3_step(pStmt);
441 if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
442 rc = sqlite3_reset(pStmt);
443 if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
444 pStmt = 0;
445 }else{
446 rc = SQLITE_OK;
450 *ppStmt = pStmt;
451 return rc;
454 int sqlite3Fts3SelectDoctotal(
455 Fts3Table *pTab, /* Fts3 table handle */
456 sqlite3_stmt **ppStmt /* OUT: Statement handle */
458 sqlite3_stmt *pStmt = 0;
459 int rc;
460 rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
461 if( rc==SQLITE_OK ){
462 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
463 if( sqlite3_step(pStmt)!=SQLITE_ROW
464 || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
466 rc = sqlite3_reset(pStmt);
467 if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
468 pStmt = 0;
471 *ppStmt = pStmt;
472 return rc;
475 int sqlite3Fts3SelectDocsize(
476 Fts3Table *pTab, /* Fts3 table handle */
477 sqlite3_int64 iDocid, /* Docid to read size data for */
478 sqlite3_stmt **ppStmt /* OUT: Statement handle */
480 return fts3SelectDocsize(pTab, iDocid, ppStmt);
484 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
485 ** array apVal[] to the SQL statement identified by eStmt, the statement
486 ** is executed.
488 ** Returns SQLITE_OK if the statement is successfully executed, or an
489 ** SQLite error code otherwise.
491 static void fts3SqlExec(
492 int *pRC, /* Result code */
493 Fts3Table *p, /* The FTS3 table */
494 int eStmt, /* Index of statement to evaluate */
495 sqlite3_value **apVal /* Parameters to bind */
497 sqlite3_stmt *pStmt;
498 int rc;
499 if( *pRC ) return;
500 rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
501 if( rc==SQLITE_OK ){
502 sqlite3_step(pStmt);
503 rc = sqlite3_reset(pStmt);
505 *pRC = rc;
510 ** This function ensures that the caller has obtained an exclusive
511 ** shared-cache table-lock on the %_segdir table. This is required before
512 ** writing data to the fts3 table. If this lock is not acquired first, then
513 ** the caller may end up attempting to take this lock as part of committing
514 ** a transaction, causing SQLite to return SQLITE_LOCKED or
515 ** LOCKED_SHAREDCACHEto a COMMIT command.
517 ** It is best to avoid this because if FTS3 returns any error when
518 ** committing a transaction, the whole transaction will be rolled back.
519 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
520 ** It can still happen if the user locks the underlying tables directly
521 ** instead of accessing them via FTS.
523 static int fts3Writelock(Fts3Table *p){
524 int rc = SQLITE_OK;
526 if( p->nPendingData==0 ){
527 sqlite3_stmt *pStmt;
528 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
529 if( rc==SQLITE_OK ){
530 sqlite3_bind_null(pStmt, 1);
531 sqlite3_step(pStmt);
532 rc = sqlite3_reset(pStmt);
536 return rc;
540 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
541 ** Within each language id, a separate index is maintained to store the
542 ** document terms, and each configured prefix size (configured the FTS
543 ** "prefix=" option). And each index consists of multiple levels ("relative
544 ** levels").
546 ** All three of these values (the language id, the specific index and the
547 ** level within the index) are encoded in 64-bit integer values stored
548 ** in the %_segdir table on disk. This function is used to convert three
549 ** separate component values into the single 64-bit integer value that
550 ** can be used to query the %_segdir table.
552 ** Specifically, each language-id/index combination is allocated 1024
553 ** 64-bit integer level values ("absolute levels"). The main terms index
554 ** for language-id 0 is allocate values 0-1023. The first prefix index
555 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
556 ** Language 1 indexes are allocated immediately following language 0.
558 ** So, for a system with nPrefix prefix indexes configured, the block of
559 ** absolute levels that corresponds to language-id iLangid and index
560 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
562 static sqlite3_int64 getAbsoluteLevel(
563 Fts3Table *p, /* FTS3 table handle */
564 int iLangid, /* Language id */
565 int iIndex, /* Index in p->aIndex[] */
566 int iLevel /* Level of segments */
568 sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
569 assert( iLangid>=0 );
570 assert( p->nIndex>0 );
571 assert( iIndex>=0 && iIndex<p->nIndex );
573 iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
574 return iBase + iLevel;
578 ** Set *ppStmt to a statement handle that may be used to iterate through
579 ** all rows in the %_segdir table, from oldest to newest. If successful,
580 ** return SQLITE_OK. If an error occurs while preparing the statement,
581 ** return an SQLite error code.
583 ** There is only ever one instance of this SQL statement compiled for
584 ** each FTS3 table.
586 ** The statement returns the following columns from the %_segdir table:
588 ** 0: idx
589 ** 1: start_block
590 ** 2: leaves_end_block
591 ** 3: end_block
592 ** 4: root
594 int sqlite3Fts3AllSegdirs(
595 Fts3Table *p, /* FTS3 table */
596 int iLangid, /* Language being queried */
597 int iIndex, /* Index for p->aIndex[] */
598 int iLevel, /* Level to select (relative level) */
599 sqlite3_stmt **ppStmt /* OUT: Compiled statement */
601 int rc;
602 sqlite3_stmt *pStmt = 0;
604 assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
605 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
606 assert( iIndex>=0 && iIndex<p->nIndex );
608 if( iLevel<0 ){
609 /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
610 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
611 if( rc==SQLITE_OK ){
612 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
613 sqlite3_bind_int64(pStmt, 2,
614 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
617 }else{
618 /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
619 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
620 if( rc==SQLITE_OK ){
621 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
624 *ppStmt = pStmt;
625 return rc;
630 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
631 ** if successful, or an SQLite error code otherwise.
633 ** This function also serves to allocate the PendingList structure itself.
634 ** For example, to create a new PendingList structure containing two
635 ** varints:
637 ** PendingList *p = 0;
638 ** fts3PendingListAppendVarint(&p, 1);
639 ** fts3PendingListAppendVarint(&p, 2);
641 static int fts3PendingListAppendVarint(
642 PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
643 sqlite3_int64 i /* Value to append to data */
645 PendingList *p = *pp;
647 /* Allocate or grow the PendingList as required. */
648 if( !p ){
649 p = sqlite3_malloc(sizeof(*p) + 100);
650 if( !p ){
651 return SQLITE_NOMEM;
653 p->nSpace = 100;
654 p->aData = (char *)&p[1];
655 p->nData = 0;
657 else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
658 int nNew = p->nSpace * 2;
659 p = sqlite3_realloc(p, sizeof(*p) + nNew);
660 if( !p ){
661 sqlite3_free(*pp);
662 *pp = 0;
663 return SQLITE_NOMEM;
665 p->nSpace = nNew;
666 p->aData = (char *)&p[1];
669 /* Append the new serialized varint to the end of the list. */
670 p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
671 p->aData[p->nData] = '\0';
672 *pp = p;
673 return SQLITE_OK;
677 ** Add a docid/column/position entry to a PendingList structure. Non-zero
678 ** is returned if the structure is sqlite3_realloced as part of adding
679 ** the entry. Otherwise, zero.
681 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
682 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
683 ** it is set to SQLITE_OK.
685 static int fts3PendingListAppend(
686 PendingList **pp, /* IN/OUT: PendingList structure */
687 sqlite3_int64 iDocid, /* Docid for entry to add */
688 sqlite3_int64 iCol, /* Column for entry to add */
689 sqlite3_int64 iPos, /* Position of term for entry to add */
690 int *pRc /* OUT: Return code */
692 PendingList *p = *pp;
693 int rc = SQLITE_OK;
695 assert( !p || p->iLastDocid<=iDocid );
697 if( !p || p->iLastDocid!=iDocid ){
698 sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
699 if( p ){
700 assert( p->nData<p->nSpace );
701 assert( p->aData[p->nData]==0 );
702 p->nData++;
704 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
705 goto pendinglistappend_out;
707 p->iLastCol = -1;
708 p->iLastPos = 0;
709 p->iLastDocid = iDocid;
711 if( iCol>0 && p->iLastCol!=iCol ){
712 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
713 || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
715 goto pendinglistappend_out;
717 p->iLastCol = iCol;
718 p->iLastPos = 0;
720 if( iCol>=0 ){
721 assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
722 rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
723 if( rc==SQLITE_OK ){
724 p->iLastPos = iPos;
728 pendinglistappend_out:
729 *pRc = rc;
730 if( p!=*pp ){
731 *pp = p;
732 return 1;
734 return 0;
738 ** Free a PendingList object allocated by fts3PendingListAppend().
740 static void fts3PendingListDelete(PendingList *pList){
741 sqlite3_free(pList);
745 ** Add an entry to one of the pending-terms hash tables.
747 static int fts3PendingTermsAddOne(
748 Fts3Table *p,
749 int iCol,
750 int iPos,
751 Fts3Hash *pHash, /* Pending terms hash table to add entry to */
752 const char *zToken,
753 int nToken
755 PendingList *pList;
756 int rc = SQLITE_OK;
758 pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
759 if( pList ){
760 p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
762 if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
763 if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
764 /* Malloc failed while inserting the new entry. This can only
765 ** happen if there was no previous entry for this token.
767 assert( 0==fts3HashFind(pHash, zToken, nToken) );
768 sqlite3_free(pList);
769 rc = SQLITE_NOMEM;
772 if( rc==SQLITE_OK ){
773 p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
775 return rc;
779 ** Tokenize the nul-terminated string zText and add all tokens to the
780 ** pending-terms hash-table. The docid used is that currently stored in
781 ** p->iPrevDocid, and the column is specified by argument iCol.
783 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
785 static int fts3PendingTermsAdd(
786 Fts3Table *p, /* Table into which text will be inserted */
787 int iLangid, /* Language id to use */
788 const char *zText, /* Text of document to be inserted */
789 int iCol, /* Column into which text is being inserted */
790 u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
792 int rc;
793 int iStart = 0;
794 int iEnd = 0;
795 int iPos = 0;
796 int nWord = 0;
798 char const *zToken;
799 int nToken = 0;
801 sqlite3_tokenizer *pTokenizer = p->pTokenizer;
802 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
803 sqlite3_tokenizer_cursor *pCsr;
804 int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
805 const char**,int*,int*,int*,int*);
807 assert( pTokenizer && pModule );
809 /* If the user has inserted a NULL value, this function may be called with
810 ** zText==0. In this case, add zero token entries to the hash table and
811 ** return early. */
812 if( zText==0 ){
813 *pnWord = 0;
814 return SQLITE_OK;
817 rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
818 if( rc!=SQLITE_OK ){
819 return rc;
822 xNext = pModule->xNext;
823 while( SQLITE_OK==rc
824 && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
826 int i;
827 if( iPos>=nWord ) nWord = iPos+1;
829 /* Positions cannot be negative; we use -1 as a terminator internally.
830 ** Tokens must have a non-zero length.
832 if( iPos<0 || !zToken || nToken<=0 ){
833 rc = SQLITE_ERROR;
834 break;
837 /* Add the term to the terms index */
838 rc = fts3PendingTermsAddOne(
839 p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
842 /* Add the term to each of the prefix indexes that it is not too
843 ** short for. */
844 for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
845 struct Fts3Index *pIndex = &p->aIndex[i];
846 if( nToken<pIndex->nPrefix ) continue;
847 rc = fts3PendingTermsAddOne(
848 p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
853 pModule->xClose(pCsr);
854 *pnWord += nWord;
855 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
859 ** Calling this function indicates that subsequent calls to
860 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
861 ** contents of the document with docid iDocid.
863 static int fts3PendingTermsDocid(
864 Fts3Table *p, /* Full-text table handle */
865 int bDelete, /* True if this op is a delete */
866 int iLangid, /* Language id of row being written */
867 sqlite_int64 iDocid /* Docid of row being written */
869 assert( iLangid>=0 );
870 assert( bDelete==1 || bDelete==0 );
872 /* TODO(shess) Explore whether partially flushing the buffer on
873 ** forced-flush would provide better performance. I suspect that if
874 ** we ordered the doclists by size and flushed the largest until the
875 ** buffer was half empty, that would let the less frequent terms
876 ** generate longer doclists.
878 if( iDocid<p->iPrevDocid
879 || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
880 || p->iPrevLangid!=iLangid
881 || p->nPendingData>p->nMaxPendingData
883 int rc = sqlite3Fts3PendingTermsFlush(p);
884 if( rc!=SQLITE_OK ) return rc;
886 p->iPrevDocid = iDocid;
887 p->iPrevLangid = iLangid;
888 p->bPrevDelete = bDelete;
889 return SQLITE_OK;
893 ** Discard the contents of the pending-terms hash tables.
895 void sqlite3Fts3PendingTermsClear(Fts3Table *p){
896 int i;
897 for(i=0; i<p->nIndex; i++){
898 Fts3HashElem *pElem;
899 Fts3Hash *pHash = &p->aIndex[i].hPending;
900 for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
901 PendingList *pList = (PendingList *)fts3HashData(pElem);
902 fts3PendingListDelete(pList);
904 fts3HashClear(pHash);
906 p->nPendingData = 0;
910 ** This function is called by the xUpdate() method as part of an INSERT
911 ** operation. It adds entries for each term in the new record to the
912 ** pendingTerms hash table.
914 ** Argument apVal is the same as the similarly named argument passed to
915 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
917 static int fts3InsertTerms(
918 Fts3Table *p,
919 int iLangid,
920 sqlite3_value **apVal,
921 u32 *aSz
923 int i; /* Iterator variable */
924 for(i=2; i<p->nColumn+2; i++){
925 int iCol = i-2;
926 if( p->abNotindexed[iCol]==0 ){
927 const char *zText = (const char *)sqlite3_value_text(apVal[i]);
928 int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
929 if( rc!=SQLITE_OK ){
930 return rc;
932 aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
935 return SQLITE_OK;
939 ** This function is called by the xUpdate() method for an INSERT operation.
940 ** The apVal parameter is passed a copy of the apVal argument passed by
941 ** SQLite to the xUpdate() method. i.e:
943 ** apVal[0] Not used for INSERT.
944 ** apVal[1] rowid
945 ** apVal[2] Left-most user-defined column
946 ** ...
947 ** apVal[p->nColumn+1] Right-most user-defined column
948 ** apVal[p->nColumn+2] Hidden column with same name as table
949 ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
950 ** apVal[p->nColumn+4] Hidden languageid column
952 static int fts3InsertData(
953 Fts3Table *p, /* Full-text table */
954 sqlite3_value **apVal, /* Array of values to insert */
955 sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
957 int rc; /* Return code */
958 sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
960 if( p->zContentTbl ){
961 sqlite3_value *pRowid = apVal[p->nColumn+3];
962 if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
963 pRowid = apVal[1];
965 if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
966 return SQLITE_CONSTRAINT;
968 *piDocid = sqlite3_value_int64(pRowid);
969 return SQLITE_OK;
972 /* Locate the statement handle used to insert data into the %_content
973 ** table. The SQL for this statement is:
975 ** INSERT INTO %_content VALUES(?, ?, ?, ...)
977 ** The statement features N '?' variables, where N is the number of user
978 ** defined columns in the FTS3 table, plus one for the docid field.
980 rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
981 if( rc==SQLITE_OK && p->zLanguageid ){
982 rc = sqlite3_bind_int(
983 pContentInsert, p->nColumn+2,
984 sqlite3_value_int(apVal[p->nColumn+4])
987 if( rc!=SQLITE_OK ) return rc;
989 /* There is a quirk here. The users INSERT statement may have specified
990 ** a value for the "rowid" field, for the "docid" field, or for both.
991 ** Which is a problem, since "rowid" and "docid" are aliases for the
992 ** same value. For example:
994 ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
996 ** In FTS3, this is an error. It is an error to specify non-NULL values
997 ** for both docid and some other rowid alias.
999 if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
1000 if( SQLITE_NULL==sqlite3_value_type(apVal[0])
1001 && SQLITE_NULL!=sqlite3_value_type(apVal[1])
1003 /* A rowid/docid conflict. */
1004 return SQLITE_ERROR;
1006 rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
1007 if( rc!=SQLITE_OK ) return rc;
1010 /* Execute the statement to insert the record. Set *piDocid to the
1011 ** new docid value.
1013 sqlite3_step(pContentInsert);
1014 rc = sqlite3_reset(pContentInsert);
1016 *piDocid = sqlite3_last_insert_rowid(p->db);
1017 return rc;
1023 ** Remove all data from the FTS3 table. Clear the hash table containing
1024 ** pending terms.
1026 static int fts3DeleteAll(Fts3Table *p, int bContent){
1027 int rc = SQLITE_OK; /* Return code */
1029 /* Discard the contents of the pending-terms hash table. */
1030 sqlite3Fts3PendingTermsClear(p);
1032 /* Delete everything from the shadow tables. Except, leave %_content as
1033 ** is if bContent is false. */
1034 assert( p->zContentTbl==0 || bContent==0 );
1035 if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
1036 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
1037 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
1038 if( p->bHasDocsize ){
1039 fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
1041 if( p->bHasStat ){
1042 fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
1044 return rc;
1050 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
1051 int iLangid = 0;
1052 if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
1053 return iLangid;
1057 ** The first element in the apVal[] array is assumed to contain the docid
1058 ** (an integer) of a row about to be deleted. Remove all terms from the
1059 ** full-text index.
1061 static void fts3DeleteTerms(
1062 int *pRC, /* Result code */
1063 Fts3Table *p, /* The FTS table to delete from */
1064 sqlite3_value *pRowid, /* The docid to be deleted */
1065 u32 *aSz, /* Sizes of deleted document written here */
1066 int *pbFound /* OUT: Set to true if row really does exist */
1068 int rc;
1069 sqlite3_stmt *pSelect;
1071 assert( *pbFound==0 );
1072 if( *pRC ) return;
1073 rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
1074 if( rc==SQLITE_OK ){
1075 if( SQLITE_ROW==sqlite3_step(pSelect) ){
1076 int i;
1077 int iLangid = langidFromSelect(p, pSelect);
1078 i64 iDocid = sqlite3_column_int64(pSelect, 0);
1079 rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
1080 for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
1081 int iCol = i-1;
1082 if( p->abNotindexed[iCol]==0 ){
1083 const char *zText = (const char *)sqlite3_column_text(pSelect, i);
1084 rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
1085 aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
1088 if( rc!=SQLITE_OK ){
1089 sqlite3_reset(pSelect);
1090 *pRC = rc;
1091 return;
1093 *pbFound = 1;
1095 rc = sqlite3_reset(pSelect);
1096 }else{
1097 sqlite3_reset(pSelect);
1099 *pRC = rc;
1103 ** Forward declaration to account for the circular dependency between
1104 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
1106 static int fts3SegmentMerge(Fts3Table *, int, int, int);
1109 ** This function allocates a new level iLevel index in the segdir table.
1110 ** Usually, indexes are allocated within a level sequentially starting
1111 ** with 0, so the allocated index is one greater than the value returned
1112 ** by:
1114 ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
1116 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
1117 ** level, they are merged into a single level (iLevel+1) segment and the
1118 ** allocated index is 0.
1120 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
1121 ** returned. Otherwise, an SQLite error code is returned.
1123 static int fts3AllocateSegdirIdx(
1124 Fts3Table *p,
1125 int iLangid, /* Language id */
1126 int iIndex, /* Index for p->aIndex */
1127 int iLevel,
1128 int *piIdx
1130 int rc; /* Return Code */
1131 sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
1132 int iNext = 0; /* Result of query pNextIdx */
1134 assert( iLangid>=0 );
1135 assert( p->nIndex>=1 );
1137 /* Set variable iNext to the next available segdir index at level iLevel. */
1138 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
1139 if( rc==SQLITE_OK ){
1140 sqlite3_bind_int64(
1141 pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
1143 if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
1144 iNext = sqlite3_column_int(pNextIdx, 0);
1146 rc = sqlite3_reset(pNextIdx);
1149 if( rc==SQLITE_OK ){
1150 /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
1151 ** full, merge all segments in level iLevel into a single iLevel+1
1152 ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
1153 ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
1155 if( iNext>=FTS3_MERGE_COUNT ){
1156 fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
1157 rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
1158 *piIdx = 0;
1159 }else{
1160 *piIdx = iNext;
1164 return rc;
1168 ** The %_segments table is declared as follows:
1170 ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
1172 ** This function reads data from a single row of the %_segments table. The
1173 ** specific row is identified by the iBlockid parameter. If paBlob is not
1174 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
1175 ** with the contents of the blob stored in the "block" column of the
1176 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
1177 ** to the size of the blob in bytes before returning.
1179 ** If an error occurs, or the table does not contain the specified row,
1180 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
1181 ** paBlob is non-NULL, then it is the responsibility of the caller to
1182 ** eventually free the returned buffer.
1184 ** This function may leave an open sqlite3_blob* handle in the
1185 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
1186 ** to this function. The handle may be closed by calling the
1187 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
1188 ** performance improvement, but the blob handle should always be closed
1189 ** before control is returned to the user (to prevent a lock being held
1190 ** on the database file for longer than necessary). Thus, any virtual table
1191 ** method (xFilter etc.) that may directly or indirectly call this function
1192 ** must call sqlite3Fts3SegmentsClose() before returning.
1194 int sqlite3Fts3ReadBlock(
1195 Fts3Table *p, /* FTS3 table handle */
1196 sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
1197 char **paBlob, /* OUT: Blob data in malloc'd buffer */
1198 int *pnBlob, /* OUT: Size of blob data */
1199 int *pnLoad /* OUT: Bytes actually loaded */
1201 int rc; /* Return code */
1203 /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
1204 assert( pnBlob );
1206 if( p->pSegments ){
1207 rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
1208 }else{
1209 if( 0==p->zSegmentsTbl ){
1210 p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
1211 if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
1213 rc = sqlite3_blob_open(
1214 p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
1218 if( rc==SQLITE_OK ){
1219 int nByte = sqlite3_blob_bytes(p->pSegments);
1220 *pnBlob = nByte;
1221 if( paBlob ){
1222 char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
1223 if( !aByte ){
1224 rc = SQLITE_NOMEM;
1225 }else{
1226 if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
1227 nByte = FTS3_NODE_CHUNKSIZE;
1228 *pnLoad = nByte;
1230 rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
1231 memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
1232 if( rc!=SQLITE_OK ){
1233 sqlite3_free(aByte);
1234 aByte = 0;
1237 *paBlob = aByte;
1241 return rc;
1245 ** Close the blob handle at p->pSegments, if it is open. See comments above
1246 ** the sqlite3Fts3ReadBlock() function for details.
1248 void sqlite3Fts3SegmentsClose(Fts3Table *p){
1249 sqlite3_blob_close(p->pSegments);
1250 p->pSegments = 0;
1253 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
1254 int nRead; /* Number of bytes to read */
1255 int rc; /* Return code */
1257 nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
1258 rc = sqlite3_blob_read(
1259 pReader->pBlob,
1260 &pReader->aNode[pReader->nPopulate],
1261 nRead,
1262 pReader->nPopulate
1265 if( rc==SQLITE_OK ){
1266 pReader->nPopulate += nRead;
1267 memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
1268 if( pReader->nPopulate==pReader->nNode ){
1269 sqlite3_blob_close(pReader->pBlob);
1270 pReader->pBlob = 0;
1271 pReader->nPopulate = 0;
1274 return rc;
1277 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
1278 int rc = SQLITE_OK;
1279 assert( !pReader->pBlob
1280 || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
1282 while( pReader->pBlob && rc==SQLITE_OK
1283 && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
1285 rc = fts3SegReaderIncrRead(pReader);
1287 return rc;
1291 ** Set an Fts3SegReader cursor to point at EOF.
1293 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
1294 if( !fts3SegReaderIsRootOnly(pSeg) ){
1295 sqlite3_free(pSeg->aNode);
1296 sqlite3_blob_close(pSeg->pBlob);
1297 pSeg->pBlob = 0;
1299 pSeg->aNode = 0;
1303 ** Move the iterator passed as the first argument to the next term in the
1304 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
1305 ** SQLITE_DONE. Otherwise, an SQLite error code.
1307 static int fts3SegReaderNext(
1308 Fts3Table *p,
1309 Fts3SegReader *pReader,
1310 int bIncr
1312 int rc; /* Return code of various sub-routines */
1313 char *pNext; /* Cursor variable */
1314 int nPrefix; /* Number of bytes in term prefix */
1315 int nSuffix; /* Number of bytes in term suffix */
1317 if( !pReader->aDoclist ){
1318 pNext = pReader->aNode;
1319 }else{
1320 pNext = &pReader->aDoclist[pReader->nDoclist];
1323 if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
1325 if( fts3SegReaderIsPending(pReader) ){
1326 Fts3HashElem *pElem = *(pReader->ppNextElem);
1327 sqlite3_free(pReader->aNode);
1328 pReader->aNode = 0;
1329 if( pElem ){
1330 char *aCopy;
1331 PendingList *pList = (PendingList *)fts3HashData(pElem);
1332 int nCopy = pList->nData+1;
1333 pReader->zTerm = (char *)fts3HashKey(pElem);
1334 pReader->nTerm = fts3HashKeysize(pElem);
1335 aCopy = (char*)sqlite3_malloc(nCopy);
1336 if( !aCopy ) return SQLITE_NOMEM;
1337 memcpy(aCopy, pList->aData, nCopy);
1338 pReader->nNode = pReader->nDoclist = nCopy;
1339 pReader->aNode = pReader->aDoclist = aCopy;
1340 pReader->ppNextElem++;
1341 assert( pReader->aNode );
1343 return SQLITE_OK;
1346 fts3SegReaderSetEof(pReader);
1348 /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
1349 ** blocks have already been traversed. */
1350 assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
1351 if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
1352 return SQLITE_OK;
1355 rc = sqlite3Fts3ReadBlock(
1356 p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
1357 (bIncr ? &pReader->nPopulate : 0)
1359 if( rc!=SQLITE_OK ) return rc;
1360 assert( pReader->pBlob==0 );
1361 if( bIncr && pReader->nPopulate<pReader->nNode ){
1362 pReader->pBlob = p->pSegments;
1363 p->pSegments = 0;
1365 pNext = pReader->aNode;
1368 assert( !fts3SegReaderIsPending(pReader) );
1370 rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
1371 if( rc!=SQLITE_OK ) return rc;
1373 /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
1374 ** safe (no risk of overread) even if the node data is corrupted. */
1375 pNext += fts3GetVarint32(pNext, &nPrefix);
1376 pNext += fts3GetVarint32(pNext, &nSuffix);
1377 if( nPrefix<0 || nSuffix<=0
1378 || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
1380 return FTS_CORRUPT_VTAB;
1383 if( nPrefix+nSuffix>pReader->nTermAlloc ){
1384 int nNew = (nPrefix+nSuffix)*2;
1385 char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
1386 if( !zNew ){
1387 return SQLITE_NOMEM;
1389 pReader->zTerm = zNew;
1390 pReader->nTermAlloc = nNew;
1393 rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
1394 if( rc!=SQLITE_OK ) return rc;
1396 memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
1397 pReader->nTerm = nPrefix+nSuffix;
1398 pNext += nSuffix;
1399 pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
1400 pReader->aDoclist = pNext;
1401 pReader->pOffsetList = 0;
1403 /* Check that the doclist does not appear to extend past the end of the
1404 ** b-tree node. And that the final byte of the doclist is 0x00. If either
1405 ** of these statements is untrue, then the data structure is corrupt.
1407 if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
1408 || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
1410 return FTS_CORRUPT_VTAB;
1412 return SQLITE_OK;
1416 ** Set the SegReader to point to the first docid in the doclist associated
1417 ** with the current term.
1419 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
1420 int rc = SQLITE_OK;
1421 assert( pReader->aDoclist );
1422 assert( !pReader->pOffsetList );
1423 if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
1424 u8 bEof = 0;
1425 pReader->iDocid = 0;
1426 pReader->nOffsetList = 0;
1427 sqlite3Fts3DoclistPrev(0,
1428 pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
1429 &pReader->iDocid, &pReader->nOffsetList, &bEof
1431 }else{
1432 rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
1433 if( rc==SQLITE_OK ){
1434 int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
1435 pReader->pOffsetList = &pReader->aDoclist[n];
1438 return rc;
1442 ** Advance the SegReader to point to the next docid in the doclist
1443 ** associated with the current term.
1445 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
1446 ** *ppOffsetList is set to point to the first column-offset list
1447 ** in the doclist entry (i.e. immediately past the docid varint).
1448 ** *pnOffsetList is set to the length of the set of column-offset
1449 ** lists, not including the nul-terminator byte. For example:
1451 static int fts3SegReaderNextDocid(
1452 Fts3Table *pTab,
1453 Fts3SegReader *pReader, /* Reader to advance to next docid */
1454 char **ppOffsetList, /* OUT: Pointer to current position-list */
1455 int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
1457 int rc = SQLITE_OK;
1458 char *p = pReader->pOffsetList;
1459 char c = 0;
1461 assert( p );
1463 if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
1464 /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
1465 ** Pending-terms doclists are always built up in ascending order, so
1466 ** we have to iterate through them backwards here. */
1467 u8 bEof = 0;
1468 if( ppOffsetList ){
1469 *ppOffsetList = pReader->pOffsetList;
1470 *pnOffsetList = pReader->nOffsetList - 1;
1472 sqlite3Fts3DoclistPrev(0,
1473 pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
1474 &pReader->nOffsetList, &bEof
1476 if( bEof ){
1477 pReader->pOffsetList = 0;
1478 }else{
1479 pReader->pOffsetList = p;
1481 }else{
1482 char *pEnd = &pReader->aDoclist[pReader->nDoclist];
1484 /* Pointer p currently points at the first byte of an offset list. The
1485 ** following block advances it to point one byte past the end of
1486 ** the same offset list. */
1487 while( 1 ){
1489 /* The following line of code (and the "p++" below the while() loop) is
1490 ** normally all that is required to move pointer p to the desired
1491 ** position. The exception is if this node is being loaded from disk
1492 ** incrementally and pointer "p" now points to the first byte past
1493 ** the populated part of pReader->aNode[].
1495 while( *p | c ) c = *p++ & 0x80;
1496 assert( *p==0 );
1498 if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
1499 rc = fts3SegReaderIncrRead(pReader);
1500 if( rc!=SQLITE_OK ) return rc;
1502 p++;
1504 /* If required, populate the output variables with a pointer to and the
1505 ** size of the previous offset-list.
1507 if( ppOffsetList ){
1508 *ppOffsetList = pReader->pOffsetList;
1509 *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
1512 /* List may have been edited in place by fts3EvalNearTrim() */
1513 while( p<pEnd && *p==0 ) p++;
1515 /* If there are no more entries in the doclist, set pOffsetList to
1516 ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
1517 ** Fts3SegReader.pOffsetList to point to the next offset list before
1518 ** returning.
1520 if( p>=pEnd ){
1521 pReader->pOffsetList = 0;
1522 }else{
1523 rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
1524 if( rc==SQLITE_OK ){
1525 sqlite3_int64 iDelta;
1526 pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
1527 if( pTab->bDescIdx ){
1528 pReader->iDocid -= iDelta;
1529 }else{
1530 pReader->iDocid += iDelta;
1536 return SQLITE_OK;
1540 int sqlite3Fts3MsrOvfl(
1541 Fts3Cursor *pCsr,
1542 Fts3MultiSegReader *pMsr,
1543 int *pnOvfl
1545 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
1546 int nOvfl = 0;
1547 int ii;
1548 int rc = SQLITE_OK;
1549 int pgsz = p->nPgsz;
1551 assert( p->bFts4 );
1552 assert( pgsz>0 );
1554 for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
1555 Fts3SegReader *pReader = pMsr->apSegment[ii];
1556 if( !fts3SegReaderIsPending(pReader)
1557 && !fts3SegReaderIsRootOnly(pReader)
1559 sqlite3_int64 jj;
1560 for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
1561 int nBlob;
1562 rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
1563 if( rc!=SQLITE_OK ) break;
1564 if( (nBlob+35)>pgsz ){
1565 nOvfl += (nBlob + 34)/pgsz;
1570 *pnOvfl = nOvfl;
1571 return rc;
1575 ** Free all allocations associated with the iterator passed as the
1576 ** second argument.
1578 void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
1579 if( pReader ){
1580 if( !fts3SegReaderIsPending(pReader) ){
1581 sqlite3_free(pReader->zTerm);
1583 if( !fts3SegReaderIsRootOnly(pReader) ){
1584 sqlite3_free(pReader->aNode);
1586 sqlite3_blob_close(pReader->pBlob);
1588 sqlite3_free(pReader);
1592 ** Allocate a new SegReader object.
1594 int sqlite3Fts3SegReaderNew(
1595 int iAge, /* Segment "age". */
1596 int bLookup, /* True for a lookup only */
1597 sqlite3_int64 iStartLeaf, /* First leaf to traverse */
1598 sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
1599 sqlite3_int64 iEndBlock, /* Final block of segment */
1600 const char *zRoot, /* Buffer containing root node */
1601 int nRoot, /* Size of buffer containing root node */
1602 Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
1604 Fts3SegReader *pReader; /* Newly allocated SegReader object */
1605 int nExtra = 0; /* Bytes to allocate segment root node */
1607 assert( iStartLeaf<=iEndLeaf );
1608 if( iStartLeaf==0 ){
1609 nExtra = nRoot + FTS3_NODE_PADDING;
1612 pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
1613 if( !pReader ){
1614 return SQLITE_NOMEM;
1616 memset(pReader, 0, sizeof(Fts3SegReader));
1617 pReader->iIdx = iAge;
1618 pReader->bLookup = bLookup!=0;
1619 pReader->iStartBlock = iStartLeaf;
1620 pReader->iLeafEndBlock = iEndLeaf;
1621 pReader->iEndBlock = iEndBlock;
1623 if( nExtra ){
1624 /* The entire segment is stored in the root node. */
1625 pReader->aNode = (char *)&pReader[1];
1626 pReader->rootOnly = 1;
1627 pReader->nNode = nRoot;
1628 memcpy(pReader->aNode, zRoot, nRoot);
1629 memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
1630 }else{
1631 pReader->iCurrentBlock = iStartLeaf-1;
1633 *ppReader = pReader;
1634 return SQLITE_OK;
1638 ** This is a comparison function used as a qsort() callback when sorting
1639 ** an array of pending terms by term. This occurs as part of flushing
1640 ** the contents of the pending-terms hash table to the database.
1642 static int SQLITE_CDECL fts3CompareElemByTerm(
1643 const void *lhs,
1644 const void *rhs
1646 char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
1647 char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
1648 int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
1649 int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
1651 int n = (n1<n2 ? n1 : n2);
1652 int c = memcmp(z1, z2, n);
1653 if( c==0 ){
1654 c = n1 - n2;
1656 return c;
1660 ** This function is used to allocate an Fts3SegReader that iterates through
1661 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
1663 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
1664 ** through each term in the pending-terms table. Or, if isPrefixIter is
1665 ** non-zero, it iterates through each term and its prefixes. For example, if
1666 ** the pending terms hash table contains the terms "sqlite", "mysql" and
1667 ** "firebird", then the iterator visits the following 'terms' (in the order
1668 ** shown):
1670 ** f fi fir fire fireb firebi firebir firebird
1671 ** m my mys mysq mysql
1672 ** s sq sql sqli sqlit sqlite
1674 ** Whereas if isPrefixIter is zero, the terms visited are:
1676 ** firebird mysql sqlite
1678 int sqlite3Fts3SegReaderPending(
1679 Fts3Table *p, /* Virtual table handle */
1680 int iIndex, /* Index for p->aIndex */
1681 const char *zTerm, /* Term to search for */
1682 int nTerm, /* Size of buffer zTerm */
1683 int bPrefix, /* True for a prefix iterator */
1684 Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
1686 Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
1687 Fts3HashElem *pE; /* Iterator variable */
1688 Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
1689 int nElem = 0; /* Size of array at aElem */
1690 int rc = SQLITE_OK; /* Return Code */
1691 Fts3Hash *pHash;
1693 pHash = &p->aIndex[iIndex].hPending;
1694 if( bPrefix ){
1695 int nAlloc = 0; /* Size of allocated array at aElem */
1697 for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
1698 char *zKey = (char *)fts3HashKey(pE);
1699 int nKey = fts3HashKeysize(pE);
1700 if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
1701 if( nElem==nAlloc ){
1702 Fts3HashElem **aElem2;
1703 nAlloc += 16;
1704 aElem2 = (Fts3HashElem **)sqlite3_realloc(
1705 aElem, nAlloc*sizeof(Fts3HashElem *)
1707 if( !aElem2 ){
1708 rc = SQLITE_NOMEM;
1709 nElem = 0;
1710 break;
1712 aElem = aElem2;
1715 aElem[nElem++] = pE;
1719 /* If more than one term matches the prefix, sort the Fts3HashElem
1720 ** objects in term order using qsort(). This uses the same comparison
1721 ** callback as is used when flushing terms to disk.
1723 if( nElem>1 ){
1724 qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
1727 }else{
1728 /* The query is a simple term lookup that matches at most one term in
1729 ** the index. All that is required is a straight hash-lookup.
1731 ** Because the stack address of pE may be accessed via the aElem pointer
1732 ** below, the "Fts3HashElem *pE" must be declared so that it is valid
1733 ** within this entire function, not just this "else{...}" block.
1735 pE = fts3HashFindElem(pHash, zTerm, nTerm);
1736 if( pE ){
1737 aElem = &pE;
1738 nElem = 1;
1742 if( nElem>0 ){
1743 int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
1744 pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
1745 if( !pReader ){
1746 rc = SQLITE_NOMEM;
1747 }else{
1748 memset(pReader, 0, nByte);
1749 pReader->iIdx = 0x7FFFFFFF;
1750 pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
1751 memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
1755 if( bPrefix ){
1756 sqlite3_free(aElem);
1758 *ppReader = pReader;
1759 return rc;
1763 ** Compare the entries pointed to by two Fts3SegReader structures.
1764 ** Comparison is as follows:
1766 ** 1) EOF is greater than not EOF.
1768 ** 2) The current terms (if any) are compared using memcmp(). If one
1769 ** term is a prefix of another, the longer term is considered the
1770 ** larger.
1772 ** 3) By segment age. An older segment is considered larger.
1774 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
1775 int rc;
1776 if( pLhs->aNode && pRhs->aNode ){
1777 int rc2 = pLhs->nTerm - pRhs->nTerm;
1778 if( rc2<0 ){
1779 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
1780 }else{
1781 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
1783 if( rc==0 ){
1784 rc = rc2;
1786 }else{
1787 rc = (pLhs->aNode==0) - (pRhs->aNode==0);
1789 if( rc==0 ){
1790 rc = pRhs->iIdx - pLhs->iIdx;
1792 assert( rc!=0 );
1793 return rc;
1797 ** A different comparison function for SegReader structures. In this
1798 ** version, it is assumed that each SegReader points to an entry in
1799 ** a doclist for identical terms. Comparison is made as follows:
1801 ** 1) EOF (end of doclist in this case) is greater than not EOF.
1803 ** 2) By current docid.
1805 ** 3) By segment age. An older segment is considered larger.
1807 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
1808 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
1809 if( rc==0 ){
1810 if( pLhs->iDocid==pRhs->iDocid ){
1811 rc = pRhs->iIdx - pLhs->iIdx;
1812 }else{
1813 rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
1816 assert( pLhs->aNode && pRhs->aNode );
1817 return rc;
1819 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
1820 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
1821 if( rc==0 ){
1822 if( pLhs->iDocid==pRhs->iDocid ){
1823 rc = pRhs->iIdx - pLhs->iIdx;
1824 }else{
1825 rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
1828 assert( pLhs->aNode && pRhs->aNode );
1829 return rc;
1833 ** Compare the term that the Fts3SegReader object passed as the first argument
1834 ** points to with the term specified by arguments zTerm and nTerm.
1836 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
1837 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
1838 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
1840 static int fts3SegReaderTermCmp(
1841 Fts3SegReader *pSeg, /* Segment reader object */
1842 const char *zTerm, /* Term to compare to */
1843 int nTerm /* Size of term zTerm in bytes */
1845 int res = 0;
1846 if( pSeg->aNode ){
1847 if( pSeg->nTerm>nTerm ){
1848 res = memcmp(pSeg->zTerm, zTerm, nTerm);
1849 }else{
1850 res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
1852 if( res==0 ){
1853 res = pSeg->nTerm-nTerm;
1856 return res;
1860 ** Argument apSegment is an array of nSegment elements. It is known that
1861 ** the final (nSegment-nSuspect) members are already in sorted order
1862 ** (according to the comparison function provided). This function shuffles
1863 ** the array around until all entries are in sorted order.
1865 static void fts3SegReaderSort(
1866 Fts3SegReader **apSegment, /* Array to sort entries of */
1867 int nSegment, /* Size of apSegment array */
1868 int nSuspect, /* Unsorted entry count */
1869 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
1871 int i; /* Iterator variable */
1873 assert( nSuspect<=nSegment );
1875 if( nSuspect==nSegment ) nSuspect--;
1876 for(i=nSuspect-1; i>=0; i--){
1877 int j;
1878 for(j=i; j<(nSegment-1); j++){
1879 Fts3SegReader *pTmp;
1880 if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
1881 pTmp = apSegment[j+1];
1882 apSegment[j+1] = apSegment[j];
1883 apSegment[j] = pTmp;
1887 #ifndef NDEBUG
1888 /* Check that the list really is sorted now. */
1889 for(i=0; i<(nSuspect-1); i++){
1890 assert( xCmp(apSegment[i], apSegment[i+1])<0 );
1892 #endif
1896 ** Insert a record into the %_segments table.
1898 static int fts3WriteSegment(
1899 Fts3Table *p, /* Virtual table handle */
1900 sqlite3_int64 iBlock, /* Block id for new block */
1901 char *z, /* Pointer to buffer containing block data */
1902 int n /* Size of buffer z in bytes */
1904 sqlite3_stmt *pStmt;
1905 int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
1906 if( rc==SQLITE_OK ){
1907 sqlite3_bind_int64(pStmt, 1, iBlock);
1908 sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
1909 sqlite3_step(pStmt);
1910 rc = sqlite3_reset(pStmt);
1911 sqlite3_bind_null(pStmt, 2);
1913 return rc;
1917 ** Find the largest relative level number in the table. If successful, set
1918 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
1919 ** set *pnMax to zero and return an SQLite error code.
1921 int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
1922 int rc;
1923 int mxLevel = 0;
1924 sqlite3_stmt *pStmt = 0;
1926 rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
1927 if( rc==SQLITE_OK ){
1928 if( SQLITE_ROW==sqlite3_step(pStmt) ){
1929 mxLevel = sqlite3_column_int(pStmt, 0);
1931 rc = sqlite3_reset(pStmt);
1933 *pnMax = mxLevel;
1934 return rc;
1938 ** Insert a record into the %_segdir table.
1940 static int fts3WriteSegdir(
1941 Fts3Table *p, /* Virtual table handle */
1942 sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
1943 int iIdx, /* Value for "idx" field */
1944 sqlite3_int64 iStartBlock, /* Value for "start_block" field */
1945 sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
1946 sqlite3_int64 iEndBlock, /* Value for "end_block" field */
1947 sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
1948 char *zRoot, /* Blob value for "root" field */
1949 int nRoot /* Number of bytes in buffer zRoot */
1951 sqlite3_stmt *pStmt;
1952 int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
1953 if( rc==SQLITE_OK ){
1954 sqlite3_bind_int64(pStmt, 1, iLevel);
1955 sqlite3_bind_int(pStmt, 2, iIdx);
1956 sqlite3_bind_int64(pStmt, 3, iStartBlock);
1957 sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
1958 if( nLeafData==0 ){
1959 sqlite3_bind_int64(pStmt, 5, iEndBlock);
1960 }else{
1961 char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
1962 if( !zEnd ) return SQLITE_NOMEM;
1963 sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
1965 sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
1966 sqlite3_step(pStmt);
1967 rc = sqlite3_reset(pStmt);
1968 sqlite3_bind_null(pStmt, 6);
1970 return rc;
1974 ** Return the size of the common prefix (if any) shared by zPrev and
1975 ** zNext, in bytes. For example,
1977 ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
1978 ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
1979 ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
1981 static int fts3PrefixCompress(
1982 const char *zPrev, /* Buffer containing previous term */
1983 int nPrev, /* Size of buffer zPrev in bytes */
1984 const char *zNext, /* Buffer containing next term */
1985 int nNext /* Size of buffer zNext in bytes */
1987 int n;
1988 UNUSED_PARAMETER(nNext);
1989 for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
1990 return n;
1994 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
1995 ** (according to memcmp) than the previous term.
1997 static int fts3NodeAddTerm(
1998 Fts3Table *p, /* Virtual table handle */
1999 SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
2000 int isCopyTerm, /* True if zTerm/nTerm is transient */
2001 const char *zTerm, /* Pointer to buffer containing term */
2002 int nTerm /* Size of term in bytes */
2004 SegmentNode *pTree = *ppTree;
2005 int rc;
2006 SegmentNode *pNew;
2008 /* First try to append the term to the current node. Return early if
2009 ** this is possible.
2011 if( pTree ){
2012 int nData = pTree->nData; /* Current size of node in bytes */
2013 int nReq = nData; /* Required space after adding zTerm */
2014 int nPrefix; /* Number of bytes of prefix compression */
2015 int nSuffix; /* Suffix length */
2017 nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
2018 nSuffix = nTerm-nPrefix;
2020 nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
2021 if( nReq<=p->nNodeSize || !pTree->zTerm ){
2023 if( nReq>p->nNodeSize ){
2024 /* An unusual case: this is the first term to be added to the node
2025 ** and the static node buffer (p->nNodeSize bytes) is not large
2026 ** enough. Use a separately malloced buffer instead This wastes
2027 ** p->nNodeSize bytes, but since this scenario only comes about when
2028 ** the database contain two terms that share a prefix of almost 2KB,
2029 ** this is not expected to be a serious problem.
2031 assert( pTree->aData==(char *)&pTree[1] );
2032 pTree->aData = (char *)sqlite3_malloc(nReq);
2033 if( !pTree->aData ){
2034 return SQLITE_NOMEM;
2038 if( pTree->zTerm ){
2039 /* There is no prefix-length field for first term in a node */
2040 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
2043 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
2044 memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
2045 pTree->nData = nData + nSuffix;
2046 pTree->nEntry++;
2048 if( isCopyTerm ){
2049 if( pTree->nMalloc<nTerm ){
2050 char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
2051 if( !zNew ){
2052 return SQLITE_NOMEM;
2054 pTree->nMalloc = nTerm*2;
2055 pTree->zMalloc = zNew;
2057 pTree->zTerm = pTree->zMalloc;
2058 memcpy(pTree->zTerm, zTerm, nTerm);
2059 pTree->nTerm = nTerm;
2060 }else{
2061 pTree->zTerm = (char *)zTerm;
2062 pTree->nTerm = nTerm;
2064 return SQLITE_OK;
2068 /* If control flows to here, it was not possible to append zTerm to the
2069 ** current node. Create a new node (a right-sibling of the current node).
2070 ** If this is the first node in the tree, the term is added to it.
2072 ** Otherwise, the term is not added to the new node, it is left empty for
2073 ** now. Instead, the term is inserted into the parent of pTree. If pTree
2074 ** has no parent, one is created here.
2076 pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
2077 if( !pNew ){
2078 return SQLITE_NOMEM;
2080 memset(pNew, 0, sizeof(SegmentNode));
2081 pNew->nData = 1 + FTS3_VARINT_MAX;
2082 pNew->aData = (char *)&pNew[1];
2084 if( pTree ){
2085 SegmentNode *pParent = pTree->pParent;
2086 rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
2087 if( pTree->pParent==0 ){
2088 pTree->pParent = pParent;
2090 pTree->pRight = pNew;
2091 pNew->pLeftmost = pTree->pLeftmost;
2092 pNew->pParent = pParent;
2093 pNew->zMalloc = pTree->zMalloc;
2094 pNew->nMalloc = pTree->nMalloc;
2095 pTree->zMalloc = 0;
2096 }else{
2097 pNew->pLeftmost = pNew;
2098 rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
2101 *ppTree = pNew;
2102 return rc;
2106 ** Helper function for fts3NodeWrite().
2108 static int fts3TreeFinishNode(
2109 SegmentNode *pTree,
2110 int iHeight,
2111 sqlite3_int64 iLeftChild
2113 int nStart;
2114 assert( iHeight>=1 && iHeight<128 );
2115 nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
2116 pTree->aData[nStart] = (char)iHeight;
2117 sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
2118 return nStart;
2122 ** Write the buffer for the segment node pTree and all of its peers to the
2123 ** database. Then call this function recursively to write the parent of
2124 ** pTree and its peers to the database.
2126 ** Except, if pTree is a root node, do not write it to the database. Instead,
2127 ** set output variables *paRoot and *pnRoot to contain the root node.
2129 ** If successful, SQLITE_OK is returned and output variable *piLast is
2130 ** set to the largest blockid written to the database (or zero if no
2131 ** blocks were written to the db). Otherwise, an SQLite error code is
2132 ** returned.
2134 static int fts3NodeWrite(
2135 Fts3Table *p, /* Virtual table handle */
2136 SegmentNode *pTree, /* SegmentNode handle */
2137 int iHeight, /* Height of this node in tree */
2138 sqlite3_int64 iLeaf, /* Block id of first leaf node */
2139 sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
2140 sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
2141 char **paRoot, /* OUT: Data for root node */
2142 int *pnRoot /* OUT: Size of root node in bytes */
2144 int rc = SQLITE_OK;
2146 if( !pTree->pParent ){
2147 /* Root node of the tree. */
2148 int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
2149 *piLast = iFree-1;
2150 *pnRoot = pTree->nData - nStart;
2151 *paRoot = &pTree->aData[nStart];
2152 }else{
2153 SegmentNode *pIter;
2154 sqlite3_int64 iNextFree = iFree;
2155 sqlite3_int64 iNextLeaf = iLeaf;
2156 for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
2157 int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
2158 int nWrite = pIter->nData - nStart;
2160 rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
2161 iNextFree++;
2162 iNextLeaf += (pIter->nEntry+1);
2164 if( rc==SQLITE_OK ){
2165 assert( iNextLeaf==iFree );
2166 rc = fts3NodeWrite(
2167 p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
2172 return rc;
2176 ** Free all memory allocations associated with the tree pTree.
2178 static void fts3NodeFree(SegmentNode *pTree){
2179 if( pTree ){
2180 SegmentNode *p = pTree->pLeftmost;
2181 fts3NodeFree(p->pParent);
2182 while( p ){
2183 SegmentNode *pRight = p->pRight;
2184 if( p->aData!=(char *)&p[1] ){
2185 sqlite3_free(p->aData);
2187 assert( pRight==0 || p->zMalloc==0 );
2188 sqlite3_free(p->zMalloc);
2189 sqlite3_free(p);
2190 p = pRight;
2196 ** Add a term to the segment being constructed by the SegmentWriter object
2197 ** *ppWriter. When adding the first term to a segment, *ppWriter should
2198 ** be passed NULL. This function will allocate a new SegmentWriter object
2199 ** and return it via the input/output variable *ppWriter in this case.
2201 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
2203 static int fts3SegWriterAdd(
2204 Fts3Table *p, /* Virtual table handle */
2205 SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
2206 int isCopyTerm, /* True if buffer zTerm must be copied */
2207 const char *zTerm, /* Pointer to buffer containing term */
2208 int nTerm, /* Size of term in bytes */
2209 const char *aDoclist, /* Pointer to buffer containing doclist */
2210 int nDoclist /* Size of doclist in bytes */
2212 int nPrefix; /* Size of term prefix in bytes */
2213 int nSuffix; /* Size of term suffix in bytes */
2214 int nReq; /* Number of bytes required on leaf page */
2215 int nData;
2216 SegmentWriter *pWriter = *ppWriter;
2218 if( !pWriter ){
2219 int rc;
2220 sqlite3_stmt *pStmt;
2222 /* Allocate the SegmentWriter structure */
2223 pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
2224 if( !pWriter ) return SQLITE_NOMEM;
2225 memset(pWriter, 0, sizeof(SegmentWriter));
2226 *ppWriter = pWriter;
2228 /* Allocate a buffer in which to accumulate data */
2229 pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
2230 if( !pWriter->aData ) return SQLITE_NOMEM;
2231 pWriter->nSize = p->nNodeSize;
2233 /* Find the next free blockid in the %_segments table */
2234 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
2235 if( rc!=SQLITE_OK ) return rc;
2236 if( SQLITE_ROW==sqlite3_step(pStmt) ){
2237 pWriter->iFree = sqlite3_column_int64(pStmt, 0);
2238 pWriter->iFirst = pWriter->iFree;
2240 rc = sqlite3_reset(pStmt);
2241 if( rc!=SQLITE_OK ) return rc;
2243 nData = pWriter->nData;
2245 nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
2246 nSuffix = nTerm-nPrefix;
2248 /* Figure out how many bytes are required by this new entry */
2249 nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
2250 sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
2251 nSuffix + /* Term suffix */
2252 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
2253 nDoclist; /* Doclist data */
2255 if( nData>0 && nData+nReq>p->nNodeSize ){
2256 int rc;
2258 /* The current leaf node is full. Write it out to the database. */
2259 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
2260 if( rc!=SQLITE_OK ) return rc;
2261 p->nLeafAdd++;
2263 /* Add the current term to the interior node tree. The term added to
2264 ** the interior tree must:
2266 ** a) be greater than the largest term on the leaf node just written
2267 ** to the database (still available in pWriter->zTerm), and
2269 ** b) be less than or equal to the term about to be added to the new
2270 ** leaf node (zTerm/nTerm).
2272 ** In other words, it must be the prefix of zTerm 1 byte longer than
2273 ** the common prefix (if any) of zTerm and pWriter->zTerm.
2275 assert( nPrefix<nTerm );
2276 rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
2277 if( rc!=SQLITE_OK ) return rc;
2279 nData = 0;
2280 pWriter->nTerm = 0;
2282 nPrefix = 0;
2283 nSuffix = nTerm;
2284 nReq = 1 + /* varint containing prefix size */
2285 sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
2286 nTerm + /* Term suffix */
2287 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
2288 nDoclist; /* Doclist data */
2291 /* Increase the total number of bytes written to account for the new entry. */
2292 pWriter->nLeafData += nReq;
2294 /* If the buffer currently allocated is too small for this entry, realloc
2295 ** the buffer to make it large enough.
2297 if( nReq>pWriter->nSize ){
2298 char *aNew = sqlite3_realloc(pWriter->aData, nReq);
2299 if( !aNew ) return SQLITE_NOMEM;
2300 pWriter->aData = aNew;
2301 pWriter->nSize = nReq;
2303 assert( nData+nReq<=pWriter->nSize );
2305 /* Append the prefix-compressed term and doclist to the buffer. */
2306 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
2307 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
2308 memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
2309 nData += nSuffix;
2310 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
2311 memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
2312 pWriter->nData = nData + nDoclist;
2314 /* Save the current term so that it can be used to prefix-compress the next.
2315 ** If the isCopyTerm parameter is true, then the buffer pointed to by
2316 ** zTerm is transient, so take a copy of the term data. Otherwise, just
2317 ** store a copy of the pointer.
2319 if( isCopyTerm ){
2320 if( nTerm>pWriter->nMalloc ){
2321 char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
2322 if( !zNew ){
2323 return SQLITE_NOMEM;
2325 pWriter->nMalloc = nTerm*2;
2326 pWriter->zMalloc = zNew;
2327 pWriter->zTerm = zNew;
2329 assert( pWriter->zTerm==pWriter->zMalloc );
2330 memcpy(pWriter->zTerm, zTerm, nTerm);
2331 }else{
2332 pWriter->zTerm = (char *)zTerm;
2334 pWriter->nTerm = nTerm;
2336 return SQLITE_OK;
2340 ** Flush all data associated with the SegmentWriter object pWriter to the
2341 ** database. This function must be called after all terms have been added
2342 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
2343 ** returned. Otherwise, an SQLite error code.
2345 static int fts3SegWriterFlush(
2346 Fts3Table *p, /* Virtual table handle */
2347 SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
2348 sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
2349 int iIdx /* Value for 'idx' column of %_segdir */
2351 int rc; /* Return code */
2352 if( pWriter->pTree ){
2353 sqlite3_int64 iLast = 0; /* Largest block id written to database */
2354 sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
2355 char *zRoot = NULL; /* Pointer to buffer containing root node */
2356 int nRoot = 0; /* Size of buffer zRoot */
2358 iLastLeaf = pWriter->iFree;
2359 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
2360 if( rc==SQLITE_OK ){
2361 rc = fts3NodeWrite(p, pWriter->pTree, 1,
2362 pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
2364 if( rc==SQLITE_OK ){
2365 rc = fts3WriteSegdir(p, iLevel, iIdx,
2366 pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
2368 }else{
2369 /* The entire tree fits on the root node. Write it to the segdir table. */
2370 rc = fts3WriteSegdir(p, iLevel, iIdx,
2371 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
2373 p->nLeafAdd++;
2374 return rc;
2378 ** Release all memory held by the SegmentWriter object passed as the
2379 ** first argument.
2381 static void fts3SegWriterFree(SegmentWriter *pWriter){
2382 if( pWriter ){
2383 sqlite3_free(pWriter->aData);
2384 sqlite3_free(pWriter->zMalloc);
2385 fts3NodeFree(pWriter->pTree);
2386 sqlite3_free(pWriter);
2391 ** The first value in the apVal[] array is assumed to contain an integer.
2392 ** This function tests if there exist any documents with docid values that
2393 ** are different from that integer. i.e. if deleting the document with docid
2394 ** pRowid would mean the FTS3 table were empty.
2396 ** If successful, *pisEmpty is set to true if the table is empty except for
2397 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
2398 ** error occurs, an SQLite error code is returned.
2400 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
2401 sqlite3_stmt *pStmt;
2402 int rc;
2403 if( p->zContentTbl ){
2404 /* If using the content=xxx option, assume the table is never empty */
2405 *pisEmpty = 0;
2406 rc = SQLITE_OK;
2407 }else{
2408 rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
2409 if( rc==SQLITE_OK ){
2410 if( SQLITE_ROW==sqlite3_step(pStmt) ){
2411 *pisEmpty = sqlite3_column_int(pStmt, 0);
2413 rc = sqlite3_reset(pStmt);
2416 return rc;
2420 ** Set *pnMax to the largest segment level in the database for the index
2421 ** iIndex.
2423 ** Segment levels are stored in the 'level' column of the %_segdir table.
2425 ** Return SQLITE_OK if successful, or an SQLite error code if not.
2427 static int fts3SegmentMaxLevel(
2428 Fts3Table *p,
2429 int iLangid,
2430 int iIndex,
2431 sqlite3_int64 *pnMax
2433 sqlite3_stmt *pStmt;
2434 int rc;
2435 assert( iIndex>=0 && iIndex<p->nIndex );
2437 /* Set pStmt to the compiled version of:
2439 ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
2441 ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
2443 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
2444 if( rc!=SQLITE_OK ) return rc;
2445 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
2446 sqlite3_bind_int64(pStmt, 2,
2447 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
2449 if( SQLITE_ROW==sqlite3_step(pStmt) ){
2450 *pnMax = sqlite3_column_int64(pStmt, 0);
2452 return sqlite3_reset(pStmt);
2456 ** iAbsLevel is an absolute level that may be assumed to exist within
2457 ** the database. This function checks if it is the largest level number
2458 ** within its index. Assuming no error occurs, *pbMax is set to 1 if
2459 ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
2460 ** is returned. If an error occurs, an error code is returned and the
2461 ** final value of *pbMax is undefined.
2463 static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
2465 /* Set pStmt to the compiled version of:
2467 ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
2469 ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
2471 sqlite3_stmt *pStmt;
2472 int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
2473 if( rc!=SQLITE_OK ) return rc;
2474 sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
2475 sqlite3_bind_int64(pStmt, 2,
2476 ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
2479 *pbMax = 0;
2480 if( SQLITE_ROW==sqlite3_step(pStmt) ){
2481 *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
2483 return sqlite3_reset(pStmt);
2487 ** Delete all entries in the %_segments table associated with the segment
2488 ** opened with seg-reader pSeg. This function does not affect the contents
2489 ** of the %_segdir table.
2491 static int fts3DeleteSegment(
2492 Fts3Table *p, /* FTS table handle */
2493 Fts3SegReader *pSeg /* Segment to delete */
2495 int rc = SQLITE_OK; /* Return code */
2496 if( pSeg->iStartBlock ){
2497 sqlite3_stmt *pDelete; /* SQL statement to delete rows */
2498 rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
2499 if( rc==SQLITE_OK ){
2500 sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
2501 sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
2502 sqlite3_step(pDelete);
2503 rc = sqlite3_reset(pDelete);
2506 return rc;
2510 ** This function is used after merging multiple segments into a single large
2511 ** segment to delete the old, now redundant, segment b-trees. Specifically,
2512 ** it:
2514 ** 1) Deletes all %_segments entries for the segments associated with
2515 ** each of the SegReader objects in the array passed as the third
2516 ** argument, and
2518 ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
2519 ** entries regardless of level if (iLevel<0).
2521 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
2523 static int fts3DeleteSegdir(
2524 Fts3Table *p, /* Virtual table handle */
2525 int iLangid, /* Language id */
2526 int iIndex, /* Index for p->aIndex */
2527 int iLevel, /* Level of %_segdir entries to delete */
2528 Fts3SegReader **apSegment, /* Array of SegReader objects */
2529 int nReader /* Size of array apSegment */
2531 int rc = SQLITE_OK; /* Return Code */
2532 int i; /* Iterator variable */
2533 sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
2535 for(i=0; rc==SQLITE_OK && i<nReader; i++){
2536 rc = fts3DeleteSegment(p, apSegment[i]);
2538 if( rc!=SQLITE_OK ){
2539 return rc;
2542 assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
2543 if( iLevel==FTS3_SEGCURSOR_ALL ){
2544 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
2545 if( rc==SQLITE_OK ){
2546 sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
2547 sqlite3_bind_int64(pDelete, 2,
2548 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
2551 }else{
2552 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
2553 if( rc==SQLITE_OK ){
2554 sqlite3_bind_int64(
2555 pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
2560 if( rc==SQLITE_OK ){
2561 sqlite3_step(pDelete);
2562 rc = sqlite3_reset(pDelete);
2565 return rc;
2569 ** When this function is called, buffer *ppList (size *pnList bytes) contains
2570 ** a position list that may (or may not) feature multiple columns. This
2571 ** function adjusts the pointer *ppList and the length *pnList so that they
2572 ** identify the subset of the position list that corresponds to column iCol.
2574 ** If there are no entries in the input position list for column iCol, then
2575 ** *pnList is set to zero before returning.
2577 ** If parameter bZero is non-zero, then any part of the input list following
2578 ** the end of the output list is zeroed before returning.
2580 static void fts3ColumnFilter(
2581 int iCol, /* Column to filter on */
2582 int bZero, /* Zero out anything following *ppList */
2583 char **ppList, /* IN/OUT: Pointer to position list */
2584 int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
2586 char *pList = *ppList;
2587 int nList = *pnList;
2588 char *pEnd = &pList[nList];
2589 int iCurrent = 0;
2590 char *p = pList;
2592 assert( iCol>=0 );
2593 while( 1 ){
2594 char c = 0;
2595 while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
2597 if( iCol==iCurrent ){
2598 nList = (int)(p - pList);
2599 break;
2602 nList -= (int)(p - pList);
2603 pList = p;
2604 if( nList==0 ){
2605 break;
2607 p = &pList[1];
2608 p += fts3GetVarint32(p, &iCurrent);
2611 if( bZero && &pList[nList]!=pEnd ){
2612 memset(&pList[nList], 0, pEnd - &pList[nList]);
2614 *ppList = pList;
2615 *pnList = nList;
2619 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
2620 ** existing data). Grow the buffer if required.
2622 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
2623 ** trying to resize the buffer, return SQLITE_NOMEM.
2625 static int fts3MsrBufferData(
2626 Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
2627 char *pList,
2628 int nList
2630 if( nList>pMsr->nBuffer ){
2631 char *pNew;
2632 pMsr->nBuffer = nList*2;
2633 pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
2634 if( !pNew ) return SQLITE_NOMEM;
2635 pMsr->aBuffer = pNew;
2638 memcpy(pMsr->aBuffer, pList, nList);
2639 return SQLITE_OK;
2642 int sqlite3Fts3MsrIncrNext(
2643 Fts3Table *p, /* Virtual table handle */
2644 Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
2645 sqlite3_int64 *piDocid, /* OUT: Docid value */
2646 char **paPoslist, /* OUT: Pointer to position list */
2647 int *pnPoslist /* OUT: Size of position list in bytes */
2649 int nMerge = pMsr->nAdvance;
2650 Fts3SegReader **apSegment = pMsr->apSegment;
2651 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
2652 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
2655 if( nMerge==0 ){
2656 *paPoslist = 0;
2657 return SQLITE_OK;
2660 while( 1 ){
2661 Fts3SegReader *pSeg;
2662 pSeg = pMsr->apSegment[0];
2664 if( pSeg->pOffsetList==0 ){
2665 *paPoslist = 0;
2666 break;
2667 }else{
2668 int rc;
2669 char *pList;
2670 int nList;
2671 int j;
2672 sqlite3_int64 iDocid = apSegment[0]->iDocid;
2674 rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
2675 j = 1;
2676 while( rc==SQLITE_OK
2677 && j<nMerge
2678 && apSegment[j]->pOffsetList
2679 && apSegment[j]->iDocid==iDocid
2681 rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
2682 j++;
2684 if( rc!=SQLITE_OK ) return rc;
2685 fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
2687 if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
2688 rc = fts3MsrBufferData(pMsr, pList, nList+1);
2689 if( rc!=SQLITE_OK ) return rc;
2690 assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
2691 pList = pMsr->aBuffer;
2694 if( pMsr->iColFilter>=0 ){
2695 fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
2698 if( nList>0 ){
2699 *paPoslist = pList;
2700 *piDocid = iDocid;
2701 *pnPoslist = nList;
2702 break;
2707 return SQLITE_OK;
2710 static int fts3SegReaderStart(
2711 Fts3Table *p, /* Virtual table handle */
2712 Fts3MultiSegReader *pCsr, /* Cursor object */
2713 const char *zTerm, /* Term searched for (or NULL) */
2714 int nTerm /* Length of zTerm in bytes */
2716 int i;
2717 int nSeg = pCsr->nSegment;
2719 /* If the Fts3SegFilter defines a specific term (or term prefix) to search
2720 ** for, then advance each segment iterator until it points to a term of
2721 ** equal or greater value than the specified term. This prevents many
2722 ** unnecessary merge/sort operations for the case where single segment
2723 ** b-tree leaf nodes contain more than one term.
2725 for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
2726 int res = 0;
2727 Fts3SegReader *pSeg = pCsr->apSegment[i];
2728 do {
2729 int rc = fts3SegReaderNext(p, pSeg, 0);
2730 if( rc!=SQLITE_OK ) return rc;
2731 }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
2733 if( pSeg->bLookup && res!=0 ){
2734 fts3SegReaderSetEof(pSeg);
2737 fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
2739 return SQLITE_OK;
2742 int sqlite3Fts3SegReaderStart(
2743 Fts3Table *p, /* Virtual table handle */
2744 Fts3MultiSegReader *pCsr, /* Cursor object */
2745 Fts3SegFilter *pFilter /* Restrictions on range of iteration */
2747 pCsr->pFilter = pFilter;
2748 return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
2751 int sqlite3Fts3MsrIncrStart(
2752 Fts3Table *p, /* Virtual table handle */
2753 Fts3MultiSegReader *pCsr, /* Cursor object */
2754 int iCol, /* Column to match on. */
2755 const char *zTerm, /* Term to iterate through a doclist for */
2756 int nTerm /* Number of bytes in zTerm */
2758 int i;
2759 int rc;
2760 int nSegment = pCsr->nSegment;
2761 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
2762 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
2765 assert( pCsr->pFilter==0 );
2766 assert( zTerm && nTerm>0 );
2768 /* Advance each segment iterator until it points to the term zTerm/nTerm. */
2769 rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
2770 if( rc!=SQLITE_OK ) return rc;
2772 /* Determine how many of the segments actually point to zTerm/nTerm. */
2773 for(i=0; i<nSegment; i++){
2774 Fts3SegReader *pSeg = pCsr->apSegment[i];
2775 if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
2776 break;
2779 pCsr->nAdvance = i;
2781 /* Advance each of the segments to point to the first docid. */
2782 for(i=0; i<pCsr->nAdvance; i++){
2783 rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
2784 if( rc!=SQLITE_OK ) return rc;
2786 fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
2788 assert( iCol<0 || iCol<p->nColumn );
2789 pCsr->iColFilter = iCol;
2791 return SQLITE_OK;
2795 ** This function is called on a MultiSegReader that has been started using
2796 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
2797 ** have been made. Calling this function puts the MultiSegReader in such
2798 ** a state that if the next two calls are:
2800 ** sqlite3Fts3SegReaderStart()
2801 ** sqlite3Fts3SegReaderStep()
2803 ** then the entire doclist for the term is available in
2804 ** MultiSegReader.aDoclist/nDoclist.
2806 int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
2807 int i; /* Used to iterate through segment-readers */
2809 assert( pCsr->zTerm==0 );
2810 assert( pCsr->nTerm==0 );
2811 assert( pCsr->aDoclist==0 );
2812 assert( pCsr->nDoclist==0 );
2814 pCsr->nAdvance = 0;
2815 pCsr->bRestart = 1;
2816 for(i=0; i<pCsr->nSegment; i++){
2817 pCsr->apSegment[i]->pOffsetList = 0;
2818 pCsr->apSegment[i]->nOffsetList = 0;
2819 pCsr->apSegment[i]->iDocid = 0;
2822 return SQLITE_OK;
2826 int sqlite3Fts3SegReaderStep(
2827 Fts3Table *p, /* Virtual table handle */
2828 Fts3MultiSegReader *pCsr /* Cursor object */
2830 int rc = SQLITE_OK;
2832 int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
2833 int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
2834 int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
2835 int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
2836 int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
2837 int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
2839 Fts3SegReader **apSegment = pCsr->apSegment;
2840 int nSegment = pCsr->nSegment;
2841 Fts3SegFilter *pFilter = pCsr->pFilter;
2842 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
2843 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
2846 if( pCsr->nSegment==0 ) return SQLITE_OK;
2848 do {
2849 int nMerge;
2850 int i;
2852 /* Advance the first pCsr->nAdvance entries in the apSegment[] array
2853 ** forward. Then sort the list in order of current term again.
2855 for(i=0; i<pCsr->nAdvance; i++){
2856 Fts3SegReader *pSeg = apSegment[i];
2857 if( pSeg->bLookup ){
2858 fts3SegReaderSetEof(pSeg);
2859 }else{
2860 rc = fts3SegReaderNext(p, pSeg, 0);
2862 if( rc!=SQLITE_OK ) return rc;
2864 fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
2865 pCsr->nAdvance = 0;
2867 /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
2868 assert( rc==SQLITE_OK );
2869 if( apSegment[0]->aNode==0 ) break;
2871 pCsr->nTerm = apSegment[0]->nTerm;
2872 pCsr->zTerm = apSegment[0]->zTerm;
2874 /* If this is a prefix-search, and if the term that apSegment[0] points
2875 ** to does not share a suffix with pFilter->zTerm/nTerm, then all
2876 ** required callbacks have been made. In this case exit early.
2878 ** Similarly, if this is a search for an exact match, and the first term
2879 ** of segment apSegment[0] is not a match, exit early.
2881 if( pFilter->zTerm && !isScan ){
2882 if( pCsr->nTerm<pFilter->nTerm
2883 || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
2884 || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
2886 break;
2890 nMerge = 1;
2891 while( nMerge<nSegment
2892 && apSegment[nMerge]->aNode
2893 && apSegment[nMerge]->nTerm==pCsr->nTerm
2894 && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
2896 nMerge++;
2899 assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
2900 if( nMerge==1
2901 && !isIgnoreEmpty
2902 && !isFirst
2903 && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
2905 pCsr->nDoclist = apSegment[0]->nDoclist;
2906 if( fts3SegReaderIsPending(apSegment[0]) ){
2907 rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
2908 pCsr->aDoclist = pCsr->aBuffer;
2909 }else{
2910 pCsr->aDoclist = apSegment[0]->aDoclist;
2912 if( rc==SQLITE_OK ) rc = SQLITE_ROW;
2913 }else{
2914 int nDoclist = 0; /* Size of doclist */
2915 sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
2917 /* The current term of the first nMerge entries in the array
2918 ** of Fts3SegReader objects is the same. The doclists must be merged
2919 ** and a single term returned with the merged doclist.
2921 for(i=0; i<nMerge; i++){
2922 fts3SegReaderFirstDocid(p, apSegment[i]);
2924 fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
2925 while( apSegment[0]->pOffsetList ){
2926 int j; /* Number of segments that share a docid */
2927 char *pList = 0;
2928 int nList = 0;
2929 int nByte;
2930 sqlite3_int64 iDocid = apSegment[0]->iDocid;
2931 fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
2932 j = 1;
2933 while( j<nMerge
2934 && apSegment[j]->pOffsetList
2935 && apSegment[j]->iDocid==iDocid
2937 fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
2938 j++;
2941 if( isColFilter ){
2942 fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
2945 if( !isIgnoreEmpty || nList>0 ){
2947 /* Calculate the 'docid' delta value to write into the merged
2948 ** doclist. */
2949 sqlite3_int64 iDelta;
2950 if( p->bDescIdx && nDoclist>0 ){
2951 iDelta = iPrev - iDocid;
2952 }else{
2953 iDelta = iDocid - iPrev;
2955 assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
2956 assert( nDoclist>0 || iDelta==iDocid );
2958 nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
2959 if( nDoclist+nByte>pCsr->nBuffer ){
2960 char *aNew;
2961 pCsr->nBuffer = (nDoclist+nByte)*2;
2962 aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
2963 if( !aNew ){
2964 return SQLITE_NOMEM;
2966 pCsr->aBuffer = aNew;
2969 if( isFirst ){
2970 char *a = &pCsr->aBuffer[nDoclist];
2971 int nWrite;
2973 nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
2974 if( nWrite ){
2975 iPrev = iDocid;
2976 nDoclist += nWrite;
2978 }else{
2979 nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
2980 iPrev = iDocid;
2981 if( isRequirePos ){
2982 memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
2983 nDoclist += nList;
2984 pCsr->aBuffer[nDoclist++] = '\0';
2989 fts3SegReaderSort(apSegment, nMerge, j, xCmp);
2991 if( nDoclist>0 ){
2992 pCsr->aDoclist = pCsr->aBuffer;
2993 pCsr->nDoclist = nDoclist;
2994 rc = SQLITE_ROW;
2997 pCsr->nAdvance = nMerge;
2998 }while( rc==SQLITE_OK );
3000 return rc;
3004 void sqlite3Fts3SegReaderFinish(
3005 Fts3MultiSegReader *pCsr /* Cursor object */
3007 if( pCsr ){
3008 int i;
3009 for(i=0; i<pCsr->nSegment; i++){
3010 sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
3012 sqlite3_free(pCsr->apSegment);
3013 sqlite3_free(pCsr->aBuffer);
3015 pCsr->nSegment = 0;
3016 pCsr->apSegment = 0;
3017 pCsr->aBuffer = 0;
3022 ** Decode the "end_block" field, selected by column iCol of the SELECT
3023 ** statement passed as the first argument.
3025 ** The "end_block" field may contain either an integer, or a text field
3026 ** containing the text representation of two non-negative integers separated
3027 ** by one or more space (0x20) characters. In the first case, set *piEndBlock
3028 ** to the integer value and *pnByte to zero before returning. In the second,
3029 ** set *piEndBlock to the first value and *pnByte to the second.
3031 static void fts3ReadEndBlockField(
3032 sqlite3_stmt *pStmt,
3033 int iCol,
3034 i64 *piEndBlock,
3035 i64 *pnByte
3037 const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
3038 if( zText ){
3039 int i;
3040 int iMul = 1;
3041 i64 iVal = 0;
3042 for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
3043 iVal = iVal*10 + (zText[i] - '0');
3045 *piEndBlock = iVal;
3046 while( zText[i]==' ' ) i++;
3047 iVal = 0;
3048 if( zText[i]=='-' ){
3049 i++;
3050 iMul = -1;
3052 for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
3053 iVal = iVal*10 + (zText[i] - '0');
3055 *pnByte = (iVal * (i64)iMul);
3061 ** A segment of size nByte bytes has just been written to absolute level
3062 ** iAbsLevel. Promote any segments that should be promoted as a result.
3064 static int fts3PromoteSegments(
3065 Fts3Table *p, /* FTS table handle */
3066 sqlite3_int64 iAbsLevel, /* Absolute level just updated */
3067 sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
3069 int rc = SQLITE_OK;
3070 sqlite3_stmt *pRange;
3072 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
3074 if( rc==SQLITE_OK ){
3075 int bOk = 0;
3076 i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
3077 i64 nLimit = (nByte*3)/2;
3079 /* Loop through all entries in the %_segdir table corresponding to
3080 ** segments in this index on levels greater than iAbsLevel. If there is
3081 ** at least one such segment, and it is possible to determine that all
3082 ** such segments are smaller than nLimit bytes in size, they will be
3083 ** promoted to level iAbsLevel. */
3084 sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
3085 sqlite3_bind_int64(pRange, 2, iLast);
3086 while( SQLITE_ROW==sqlite3_step(pRange) ){
3087 i64 nSize = 0, dummy;
3088 fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
3089 if( nSize<=0 || nSize>nLimit ){
3090 /* If nSize==0, then the %_segdir.end_block field does not not
3091 ** contain a size value. This happens if it was written by an
3092 ** old version of FTS. In this case it is not possible to determine
3093 ** the size of the segment, and so segment promotion does not
3094 ** take place. */
3095 bOk = 0;
3096 break;
3098 bOk = 1;
3100 rc = sqlite3_reset(pRange);
3102 if( bOk ){
3103 int iIdx = 0;
3104 sqlite3_stmt *pUpdate1 = 0;
3105 sqlite3_stmt *pUpdate2 = 0;
3107 if( rc==SQLITE_OK ){
3108 rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
3110 if( rc==SQLITE_OK ){
3111 rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
3114 if( rc==SQLITE_OK ){
3116 /* Loop through all %_segdir entries for segments in this index with
3117 ** levels equal to or greater than iAbsLevel. As each entry is visited,
3118 ** updated it to set (level = -1) and (idx = N), where N is 0 for the
3119 ** oldest segment in the range, 1 for the next oldest, and so on.
3121 ** In other words, move all segments being promoted to level -1,
3122 ** setting the "idx" fields as appropriate to keep them in the same
3123 ** order. The contents of level -1 (which is never used, except
3124 ** transiently here), will be moved back to level iAbsLevel below. */
3125 sqlite3_bind_int64(pRange, 1, iAbsLevel);
3126 while( SQLITE_ROW==sqlite3_step(pRange) ){
3127 sqlite3_bind_int(pUpdate1, 1, iIdx++);
3128 sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
3129 sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
3130 sqlite3_step(pUpdate1);
3131 rc = sqlite3_reset(pUpdate1);
3132 if( rc!=SQLITE_OK ){
3133 sqlite3_reset(pRange);
3134 break;
3138 if( rc==SQLITE_OK ){
3139 rc = sqlite3_reset(pRange);
3142 /* Move level -1 to level iAbsLevel */
3143 if( rc==SQLITE_OK ){
3144 sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
3145 sqlite3_step(pUpdate2);
3146 rc = sqlite3_reset(pUpdate2);
3152 return rc;
3156 ** Merge all level iLevel segments in the database into a single
3157 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
3158 ** single segment with a level equal to the numerically largest level
3159 ** currently present in the database.
3161 ** If this function is called with iLevel<0, but there is only one
3162 ** segment in the database, SQLITE_DONE is returned immediately.
3163 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
3164 ** an SQLite error code is returned.
3166 static int fts3SegmentMerge(
3167 Fts3Table *p,
3168 int iLangid, /* Language id to merge */
3169 int iIndex, /* Index in p->aIndex[] to merge */
3170 int iLevel /* Level to merge */
3172 int rc; /* Return code */
3173 int iIdx = 0; /* Index of new segment */
3174 sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
3175 SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
3176 Fts3SegFilter filter; /* Segment term filter condition */
3177 Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
3178 int bIgnoreEmpty = 0; /* True to ignore empty segments */
3179 i64 iMaxLevel = 0; /* Max level number for this index/langid */
3181 assert( iLevel==FTS3_SEGCURSOR_ALL
3182 || iLevel==FTS3_SEGCURSOR_PENDING
3183 || iLevel>=0
3185 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
3186 assert( iIndex>=0 && iIndex<p->nIndex );
3188 rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
3189 if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
3191 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
3192 rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
3193 if( rc!=SQLITE_OK ) goto finished;
3196 if( iLevel==FTS3_SEGCURSOR_ALL ){
3197 /* This call is to merge all segments in the database to a single
3198 ** segment. The level of the new segment is equal to the numerically
3199 ** greatest segment level currently present in the database for this
3200 ** index. The idx of the new segment is always 0. */
3201 if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
3202 rc = SQLITE_DONE;
3203 goto finished;
3205 iNewLevel = iMaxLevel;
3206 bIgnoreEmpty = 1;
3208 }else{
3209 /* This call is to merge all segments at level iLevel. find the next
3210 ** available segment index at level iLevel+1. The call to
3211 ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
3212 ** a single iLevel+2 segment if necessary. */
3213 assert( FTS3_SEGCURSOR_PENDING==-1 );
3214 iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
3215 rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
3216 bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
3218 if( rc!=SQLITE_OK ) goto finished;
3220 assert( csr.nSegment>0 );
3221 assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
3222 assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
3224 memset(&filter, 0, sizeof(Fts3SegFilter));
3225 filter.flags = FTS3_SEGMENT_REQUIRE_POS;
3226 filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
3228 rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
3229 while( SQLITE_OK==rc ){
3230 rc = sqlite3Fts3SegReaderStep(p, &csr);
3231 if( rc!=SQLITE_ROW ) break;
3232 rc = fts3SegWriterAdd(p, &pWriter, 1,
3233 csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
3235 if( rc!=SQLITE_OK ) goto finished;
3236 assert( pWriter || bIgnoreEmpty );
3238 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
3239 rc = fts3DeleteSegdir(
3240 p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
3242 if( rc!=SQLITE_OK ) goto finished;
3244 if( pWriter ){
3245 rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
3246 if( rc==SQLITE_OK ){
3247 if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
3248 rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
3253 finished:
3254 fts3SegWriterFree(pWriter);
3255 sqlite3Fts3SegReaderFinish(&csr);
3256 return rc;
3261 ** Flush the contents of pendingTerms to level 0 segments.
3263 int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
3264 int rc = SQLITE_OK;
3265 int i;
3267 for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
3268 rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
3269 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
3271 sqlite3Fts3PendingTermsClear(p);
3273 /* Determine the auto-incr-merge setting if unknown. If enabled,
3274 ** estimate the number of leaf blocks of content to be written
3276 if( rc==SQLITE_OK && p->bHasStat
3277 && p->nAutoincrmerge==0xff && p->nLeafAdd>0
3279 sqlite3_stmt *pStmt = 0;
3280 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
3281 if( rc==SQLITE_OK ){
3282 sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
3283 rc = sqlite3_step(pStmt);
3284 if( rc==SQLITE_ROW ){
3285 p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
3286 if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
3287 }else if( rc==SQLITE_DONE ){
3288 p->nAutoincrmerge = 0;
3290 rc = sqlite3_reset(pStmt);
3293 return rc;
3297 ** Encode N integers as varints into a blob.
3299 static void fts3EncodeIntArray(
3300 int N, /* The number of integers to encode */
3301 u32 *a, /* The integer values */
3302 char *zBuf, /* Write the BLOB here */
3303 int *pNBuf /* Write number of bytes if zBuf[] used here */
3305 int i, j;
3306 for(i=j=0; i<N; i++){
3307 j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
3309 *pNBuf = j;
3313 ** Decode a blob of varints into N integers
3315 static void fts3DecodeIntArray(
3316 int N, /* The number of integers to decode */
3317 u32 *a, /* Write the integer values */
3318 const char *zBuf, /* The BLOB containing the varints */
3319 int nBuf /* size of the BLOB */
3321 int i, j;
3322 UNUSED_PARAMETER(nBuf);
3323 for(i=j=0; i<N; i++){
3324 sqlite3_int64 x;
3325 j += sqlite3Fts3GetVarint(&zBuf[j], &x);
3326 assert(j<=nBuf);
3327 a[i] = (u32)(x & 0xffffffff);
3332 ** Insert the sizes (in tokens) for each column of the document
3333 ** with docid equal to p->iPrevDocid. The sizes are encoded as
3334 ** a blob of varints.
3336 static void fts3InsertDocsize(
3337 int *pRC, /* Result code */
3338 Fts3Table *p, /* Table into which to insert */
3339 u32 *aSz /* Sizes of each column, in tokens */
3341 char *pBlob; /* The BLOB encoding of the document size */
3342 int nBlob; /* Number of bytes in the BLOB */
3343 sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
3344 int rc; /* Result code from subfunctions */
3346 if( *pRC ) return;
3347 pBlob = sqlite3_malloc( 10*p->nColumn );
3348 if( pBlob==0 ){
3349 *pRC = SQLITE_NOMEM;
3350 return;
3352 fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
3353 rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
3354 if( rc ){
3355 sqlite3_free(pBlob);
3356 *pRC = rc;
3357 return;
3359 sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
3360 sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
3361 sqlite3_step(pStmt);
3362 *pRC = sqlite3_reset(pStmt);
3366 ** Record 0 of the %_stat table contains a blob consisting of N varints,
3367 ** where N is the number of user defined columns in the fts3 table plus
3368 ** two. If nCol is the number of user defined columns, then values of the
3369 ** varints are set as follows:
3371 ** Varint 0: Total number of rows in the table.
3373 ** Varint 1..nCol: For each column, the total number of tokens stored in
3374 ** the column for all rows of the table.
3376 ** Varint 1+nCol: The total size, in bytes, of all text values in all
3377 ** columns of all rows of the table.
3380 static void fts3UpdateDocTotals(
3381 int *pRC, /* The result code */
3382 Fts3Table *p, /* Table being updated */
3383 u32 *aSzIns, /* Size increases */
3384 u32 *aSzDel, /* Size decreases */
3385 int nChng /* Change in the number of documents */
3387 char *pBlob; /* Storage for BLOB written into %_stat */
3388 int nBlob; /* Size of BLOB written into %_stat */
3389 u32 *a; /* Array of integers that becomes the BLOB */
3390 sqlite3_stmt *pStmt; /* Statement for reading and writing */
3391 int i; /* Loop counter */
3392 int rc; /* Result code from subfunctions */
3394 const int nStat = p->nColumn+2;
3396 if( *pRC ) return;
3397 a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
3398 if( a==0 ){
3399 *pRC = SQLITE_NOMEM;
3400 return;
3402 pBlob = (char*)&a[nStat];
3403 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
3404 if( rc ){
3405 sqlite3_free(a);
3406 *pRC = rc;
3407 return;
3409 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
3410 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3411 fts3DecodeIntArray(nStat, a,
3412 sqlite3_column_blob(pStmt, 0),
3413 sqlite3_column_bytes(pStmt, 0));
3414 }else{
3415 memset(a, 0, sizeof(u32)*(nStat) );
3417 rc = sqlite3_reset(pStmt);
3418 if( rc!=SQLITE_OK ){
3419 sqlite3_free(a);
3420 *pRC = rc;
3421 return;
3423 if( nChng<0 && a[0]<(u32)(-nChng) ){
3424 a[0] = 0;
3425 }else{
3426 a[0] += nChng;
3428 for(i=0; i<p->nColumn+1; i++){
3429 u32 x = a[i+1];
3430 if( x+aSzIns[i] < aSzDel[i] ){
3431 x = 0;
3432 }else{
3433 x = x + aSzIns[i] - aSzDel[i];
3435 a[i+1] = x;
3437 fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
3438 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
3439 if( rc ){
3440 sqlite3_free(a);
3441 *pRC = rc;
3442 return;
3444 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
3445 sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
3446 sqlite3_step(pStmt);
3447 *pRC = sqlite3_reset(pStmt);
3448 sqlite3_bind_null(pStmt, 2);
3449 sqlite3_free(a);
3453 ** Merge the entire database so that there is one segment for each
3454 ** iIndex/iLangid combination.
3456 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
3457 int bSeenDone = 0;
3458 int rc;
3459 sqlite3_stmt *pAllLangid = 0;
3461 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
3462 if( rc==SQLITE_OK ){
3463 int rc2;
3464 sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
3465 sqlite3_bind_int(pAllLangid, 2, p->nIndex);
3466 while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
3467 int i;
3468 int iLangid = sqlite3_column_int(pAllLangid, 0);
3469 for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
3470 rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
3471 if( rc==SQLITE_DONE ){
3472 bSeenDone = 1;
3473 rc = SQLITE_OK;
3477 rc2 = sqlite3_reset(pAllLangid);
3478 if( rc==SQLITE_OK ) rc = rc2;
3481 sqlite3Fts3SegmentsClose(p);
3482 sqlite3Fts3PendingTermsClear(p);
3484 return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
3488 ** This function is called when the user executes the following statement:
3490 ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
3492 ** The entire FTS index is discarded and rebuilt. If the table is one
3493 ** created using the content=xxx option, then the new index is based on
3494 ** the current contents of the xxx table. Otherwise, it is rebuilt based
3495 ** on the contents of the %_content table.
3497 static int fts3DoRebuild(Fts3Table *p){
3498 int rc; /* Return Code */
3500 rc = fts3DeleteAll(p, 0);
3501 if( rc==SQLITE_OK ){
3502 u32 *aSz = 0;
3503 u32 *aSzIns = 0;
3504 u32 *aSzDel = 0;
3505 sqlite3_stmt *pStmt = 0;
3506 int nEntry = 0;
3508 /* Compose and prepare an SQL statement to loop through the content table */
3509 char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
3510 if( !zSql ){
3511 rc = SQLITE_NOMEM;
3512 }else{
3513 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3514 sqlite3_free(zSql);
3517 if( rc==SQLITE_OK ){
3518 int nByte = sizeof(u32) * (p->nColumn+1)*3;
3519 aSz = (u32 *)sqlite3_malloc(nByte);
3520 if( aSz==0 ){
3521 rc = SQLITE_NOMEM;
3522 }else{
3523 memset(aSz, 0, nByte);
3524 aSzIns = &aSz[p->nColumn+1];
3525 aSzDel = &aSzIns[p->nColumn+1];
3529 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
3530 int iCol;
3531 int iLangid = langidFromSelect(p, pStmt);
3532 rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
3533 memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
3534 for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
3535 if( p->abNotindexed[iCol]==0 ){
3536 const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
3537 rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
3538 aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
3541 if( p->bHasDocsize ){
3542 fts3InsertDocsize(&rc, p, aSz);
3544 if( rc!=SQLITE_OK ){
3545 sqlite3_finalize(pStmt);
3546 pStmt = 0;
3547 }else{
3548 nEntry++;
3549 for(iCol=0; iCol<=p->nColumn; iCol++){
3550 aSzIns[iCol] += aSz[iCol];
3554 if( p->bFts4 ){
3555 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
3557 sqlite3_free(aSz);
3559 if( pStmt ){
3560 int rc2 = sqlite3_finalize(pStmt);
3561 if( rc==SQLITE_OK ){
3562 rc = rc2;
3567 return rc;
3572 ** This function opens a cursor used to read the input data for an
3573 ** incremental merge operation. Specifically, it opens a cursor to scan
3574 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
3575 ** level iAbsLevel.
3577 static int fts3IncrmergeCsr(
3578 Fts3Table *p, /* FTS3 table handle */
3579 sqlite3_int64 iAbsLevel, /* Absolute level to open */
3580 int nSeg, /* Number of segments to merge */
3581 Fts3MultiSegReader *pCsr /* Cursor object to populate */
3583 int rc; /* Return Code */
3584 sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
3585 int nByte; /* Bytes allocated at pCsr->apSegment[] */
3587 /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
3588 memset(pCsr, 0, sizeof(*pCsr));
3589 nByte = sizeof(Fts3SegReader *) * nSeg;
3590 pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
3592 if( pCsr->apSegment==0 ){
3593 rc = SQLITE_NOMEM;
3594 }else{
3595 memset(pCsr->apSegment, 0, nByte);
3596 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
3598 if( rc==SQLITE_OK ){
3599 int i;
3600 int rc2;
3601 sqlite3_bind_int64(pStmt, 1, iAbsLevel);
3602 assert( pCsr->nSegment==0 );
3603 for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
3604 rc = sqlite3Fts3SegReaderNew(i, 0,
3605 sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
3606 sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
3607 sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
3608 sqlite3_column_blob(pStmt, 4), /* segdir.root */
3609 sqlite3_column_bytes(pStmt, 4), /* segdir.root */
3610 &pCsr->apSegment[i]
3612 pCsr->nSegment++;
3614 rc2 = sqlite3_reset(pStmt);
3615 if( rc==SQLITE_OK ) rc = rc2;
3618 return rc;
3621 typedef struct IncrmergeWriter IncrmergeWriter;
3622 typedef struct NodeWriter NodeWriter;
3623 typedef struct Blob Blob;
3624 typedef struct NodeReader NodeReader;
3627 ** An instance of the following structure is used as a dynamic buffer
3628 ** to build up nodes or other blobs of data in.
3630 ** The function blobGrowBuffer() is used to extend the allocation.
3632 struct Blob {
3633 char *a; /* Pointer to allocation */
3634 int n; /* Number of valid bytes of data in a[] */
3635 int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
3639 ** This structure is used to build up buffers containing segment b-tree
3640 ** nodes (blocks).
3642 struct NodeWriter {
3643 sqlite3_int64 iBlock; /* Current block id */
3644 Blob key; /* Last key written to the current block */
3645 Blob block; /* Current block image */
3649 ** An object of this type contains the state required to create or append
3650 ** to an appendable b-tree segment.
3652 struct IncrmergeWriter {
3653 int nLeafEst; /* Space allocated for leaf blocks */
3654 int nWork; /* Number of leaf pages flushed */
3655 sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
3656 int iIdx; /* Index of *output* segment in iAbsLevel+1 */
3657 sqlite3_int64 iStart; /* Block number of first allocated block */
3658 sqlite3_int64 iEnd; /* Block number of last allocated block */
3659 sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
3660 u8 bNoLeafData; /* If true, store 0 for segment size */
3661 NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
3665 ** An object of the following type is used to read data from a single
3666 ** FTS segment node. See the following functions:
3668 ** nodeReaderInit()
3669 ** nodeReaderNext()
3670 ** nodeReaderRelease()
3672 struct NodeReader {
3673 const char *aNode;
3674 int nNode;
3675 int iOff; /* Current offset within aNode[] */
3677 /* Output variables. Containing the current node entry. */
3678 sqlite3_int64 iChild; /* Pointer to child node */
3679 Blob term; /* Current term */
3680 const char *aDoclist; /* Pointer to doclist */
3681 int nDoclist; /* Size of doclist in bytes */
3685 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
3686 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
3687 ** bytes in size, extend (realloc) it to be so.
3689 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
3690 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
3691 ** to reflect the new size of the pBlob->a[] buffer.
3693 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
3694 if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
3695 int nAlloc = nMin;
3696 char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
3697 if( a ){
3698 pBlob->nAlloc = nAlloc;
3699 pBlob->a = a;
3700 }else{
3701 *pRc = SQLITE_NOMEM;
3707 ** Attempt to advance the node-reader object passed as the first argument to
3708 ** the next entry on the node.
3710 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
3711 ** Otherwise return SQLITE_OK. If there is no next entry on the node
3712 ** (e.g. because the current entry is the last) set NodeReader->aNode to
3713 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
3714 ** variables for the new entry.
3716 static int nodeReaderNext(NodeReader *p){
3717 int bFirst = (p->term.n==0); /* True for first term on the node */
3718 int nPrefix = 0; /* Bytes to copy from previous term */
3719 int nSuffix = 0; /* Bytes to append to the prefix */
3720 int rc = SQLITE_OK; /* Return code */
3722 assert( p->aNode );
3723 if( p->iChild && bFirst==0 ) p->iChild++;
3724 if( p->iOff>=p->nNode ){
3725 /* EOF */
3726 p->aNode = 0;
3727 }else{
3728 if( bFirst==0 ){
3729 p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
3731 p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
3733 blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
3734 if( rc==SQLITE_OK ){
3735 memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
3736 p->term.n = nPrefix+nSuffix;
3737 p->iOff += nSuffix;
3738 if( p->iChild==0 ){
3739 p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
3740 p->aDoclist = &p->aNode[p->iOff];
3741 p->iOff += p->nDoclist;
3746 assert( p->iOff<=p->nNode );
3748 return rc;
3752 ** Release all dynamic resources held by node-reader object *p.
3754 static void nodeReaderRelease(NodeReader *p){
3755 sqlite3_free(p->term.a);
3759 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
3761 ** If successful, SQLITE_OK is returned and the NodeReader object set to
3762 ** point to the first entry on the node (if any). Otherwise, an SQLite
3763 ** error code is returned.
3765 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
3766 memset(p, 0, sizeof(NodeReader));
3767 p->aNode = aNode;
3768 p->nNode = nNode;
3770 /* Figure out if this is a leaf or an internal node. */
3771 if( p->aNode[0] ){
3772 /* An internal node. */
3773 p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
3774 }else{
3775 p->iOff = 1;
3778 return nodeReaderNext(p);
3782 ** This function is called while writing an FTS segment each time a leaf o
3783 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
3784 ** to be greater than the largest key on the node just written, but smaller
3785 ** than or equal to the first key that will be written to the next leaf
3786 ** node.
3788 ** The block id of the leaf node just written to disk may be found in
3789 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
3791 static int fts3IncrmergePush(
3792 Fts3Table *p, /* Fts3 table handle */
3793 IncrmergeWriter *pWriter, /* Writer object */
3794 const char *zTerm, /* Term to write to internal node */
3795 int nTerm /* Bytes at zTerm */
3797 sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
3798 int iLayer;
3800 assert( nTerm>0 );
3801 for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
3802 sqlite3_int64 iNextPtr = 0;
3803 NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
3804 int rc = SQLITE_OK;
3805 int nPrefix;
3806 int nSuffix;
3807 int nSpace;
3809 /* Figure out how much space the key will consume if it is written to
3810 ** the current node of layer iLayer. Due to the prefix compression,
3811 ** the space required changes depending on which node the key is to
3812 ** be added to. */
3813 nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
3814 nSuffix = nTerm - nPrefix;
3815 nSpace = sqlite3Fts3VarintLen(nPrefix);
3816 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
3818 if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
3819 /* If the current node of layer iLayer contains zero keys, or if adding
3820 ** the key to it will not cause it to grow to larger than nNodeSize
3821 ** bytes in size, write the key here. */
3823 Blob *pBlk = &pNode->block;
3824 if( pBlk->n==0 ){
3825 blobGrowBuffer(pBlk, p->nNodeSize, &rc);
3826 if( rc==SQLITE_OK ){
3827 pBlk->a[0] = (char)iLayer;
3828 pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
3831 blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
3832 blobGrowBuffer(&pNode->key, nTerm, &rc);
3834 if( rc==SQLITE_OK ){
3835 if( pNode->key.n ){
3836 pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
3838 pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
3839 memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
3840 pBlk->n += nSuffix;
3842 memcpy(pNode->key.a, zTerm, nTerm);
3843 pNode->key.n = nTerm;
3845 }else{
3846 /* Otherwise, flush the current node of layer iLayer to disk.
3847 ** Then allocate a new, empty sibling node. The key will be written
3848 ** into the parent of this node. */
3849 rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
3851 assert( pNode->block.nAlloc>=p->nNodeSize );
3852 pNode->block.a[0] = (char)iLayer;
3853 pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
3855 iNextPtr = pNode->iBlock;
3856 pNode->iBlock++;
3857 pNode->key.n = 0;
3860 if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
3861 iPtr = iNextPtr;
3864 assert( 0 );
3865 return 0;
3869 ** Append a term and (optionally) doclist to the FTS segment node currently
3870 ** stored in blob *pNode. The node need not contain any terms, but the
3871 ** header must be written before this function is called.
3873 ** A node header is a single 0x00 byte for a leaf node, or a height varint
3874 ** followed by the left-hand-child varint for an internal node.
3876 ** The term to be appended is passed via arguments zTerm/nTerm. For a
3877 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
3878 ** node, both aDoclist and nDoclist must be passed 0.
3880 ** If the size of the value in blob pPrev is zero, then this is the first
3881 ** term written to the node. Otherwise, pPrev contains a copy of the
3882 ** previous term. Before this function returns, it is updated to contain a
3883 ** copy of zTerm/nTerm.
3885 ** It is assumed that the buffer associated with pNode is already large
3886 ** enough to accommodate the new entry. The buffer associated with pPrev
3887 ** is extended by this function if requrired.
3889 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
3890 ** returned. Otherwise, SQLITE_OK.
3892 static int fts3AppendToNode(
3893 Blob *pNode, /* Current node image to append to */
3894 Blob *pPrev, /* Buffer containing previous term written */
3895 const char *zTerm, /* New term to write */
3896 int nTerm, /* Size of zTerm in bytes */
3897 const char *aDoclist, /* Doclist (or NULL) to write */
3898 int nDoclist /* Size of aDoclist in bytes */
3900 int rc = SQLITE_OK; /* Return code */
3901 int bFirst = (pPrev->n==0); /* True if this is the first term written */
3902 int nPrefix; /* Size of term prefix in bytes */
3903 int nSuffix; /* Size of term suffix in bytes */
3905 /* Node must have already been started. There must be a doclist for a
3906 ** leaf node, and there must not be a doclist for an internal node. */
3907 assert( pNode->n>0 );
3908 assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
3910 blobGrowBuffer(pPrev, nTerm, &rc);
3911 if( rc!=SQLITE_OK ) return rc;
3913 nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
3914 nSuffix = nTerm - nPrefix;
3915 memcpy(pPrev->a, zTerm, nTerm);
3916 pPrev->n = nTerm;
3918 if( bFirst==0 ){
3919 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
3921 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
3922 memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
3923 pNode->n += nSuffix;
3925 if( aDoclist ){
3926 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
3927 memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
3928 pNode->n += nDoclist;
3931 assert( pNode->n<=pNode->nAlloc );
3933 return SQLITE_OK;
3937 ** Append the current term and doclist pointed to by cursor pCsr to the
3938 ** appendable b-tree segment opened for writing by pWriter.
3940 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
3942 static int fts3IncrmergeAppend(
3943 Fts3Table *p, /* Fts3 table handle */
3944 IncrmergeWriter *pWriter, /* Writer object */
3945 Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
3947 const char *zTerm = pCsr->zTerm;
3948 int nTerm = pCsr->nTerm;
3949 const char *aDoclist = pCsr->aDoclist;
3950 int nDoclist = pCsr->nDoclist;
3951 int rc = SQLITE_OK; /* Return code */
3952 int nSpace; /* Total space in bytes required on leaf */
3953 int nPrefix; /* Size of prefix shared with previous term */
3954 int nSuffix; /* Size of suffix (nTerm - nPrefix) */
3955 NodeWriter *pLeaf; /* Object used to write leaf nodes */
3957 pLeaf = &pWriter->aNodeWriter[0];
3958 nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
3959 nSuffix = nTerm - nPrefix;
3961 nSpace = sqlite3Fts3VarintLen(nPrefix);
3962 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
3963 nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
3965 /* If the current block is not empty, and if adding this term/doclist
3966 ** to the current block would make it larger than Fts3Table.nNodeSize
3967 ** bytes, write this block out to the database. */
3968 if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
3969 rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
3970 pWriter->nWork++;
3972 /* Add the current term to the parent node. The term added to the
3973 ** parent must:
3975 ** a) be greater than the largest term on the leaf node just written
3976 ** to the database (still available in pLeaf->key), and
3978 ** b) be less than or equal to the term about to be added to the new
3979 ** leaf node (zTerm/nTerm).
3981 ** In other words, it must be the prefix of zTerm 1 byte longer than
3982 ** the common prefix (if any) of zTerm and pWriter->zTerm.
3984 if( rc==SQLITE_OK ){
3985 rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
3988 /* Advance to the next output block */
3989 pLeaf->iBlock++;
3990 pLeaf->key.n = 0;
3991 pLeaf->block.n = 0;
3993 nSuffix = nTerm;
3994 nSpace = 1;
3995 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
3996 nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
3999 pWriter->nLeafData += nSpace;
4000 blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
4001 if( rc==SQLITE_OK ){
4002 if( pLeaf->block.n==0 ){
4003 pLeaf->block.n = 1;
4004 pLeaf->block.a[0] = '\0';
4006 rc = fts3AppendToNode(
4007 &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
4011 return rc;
4015 ** This function is called to release all dynamic resources held by the
4016 ** merge-writer object pWriter, and if no error has occurred, to flush
4017 ** all outstanding node buffers held by pWriter to disk.
4019 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
4020 ** is made to write any data to disk. Instead, this function serves only
4021 ** to release outstanding resources.
4023 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
4024 ** flushing buffers to disk, *pRc is set to an SQLite error code before
4025 ** returning.
4027 static void fts3IncrmergeRelease(
4028 Fts3Table *p, /* FTS3 table handle */
4029 IncrmergeWriter *pWriter, /* Merge-writer object */
4030 int *pRc /* IN/OUT: Error code */
4032 int i; /* Used to iterate through non-root layers */
4033 int iRoot; /* Index of root in pWriter->aNodeWriter */
4034 NodeWriter *pRoot; /* NodeWriter for root node */
4035 int rc = *pRc; /* Error code */
4037 /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
4038 ** root node. If the segment fits entirely on a single leaf node, iRoot
4039 ** will be set to 0. If the root node is the parent of the leaves, iRoot
4040 ** will be 1. And so on. */
4041 for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
4042 NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
4043 if( pNode->block.n>0 ) break;
4044 assert( *pRc || pNode->block.nAlloc==0 );
4045 assert( *pRc || pNode->key.nAlloc==0 );
4046 sqlite3_free(pNode->block.a);
4047 sqlite3_free(pNode->key.a);
4050 /* Empty output segment. This is a no-op. */
4051 if( iRoot<0 ) return;
4053 /* The entire output segment fits on a single node. Normally, this means
4054 ** the node would be stored as a blob in the "root" column of the %_segdir
4055 ** table. However, this is not permitted in this case. The problem is that
4056 ** space has already been reserved in the %_segments table, and so the
4057 ** start_block and end_block fields of the %_segdir table must be populated.
4058 ** And, by design or by accident, released versions of FTS cannot handle
4059 ** segments that fit entirely on the root node with start_block!=0.
4061 ** Instead, create a synthetic root node that contains nothing but a
4062 ** pointer to the single content node. So that the segment consists of a
4063 ** single leaf and a single interior (root) node.
4065 ** Todo: Better might be to defer allocating space in the %_segments
4066 ** table until we are sure it is needed.
4068 if( iRoot==0 ){
4069 Blob *pBlock = &pWriter->aNodeWriter[1].block;
4070 blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
4071 if( rc==SQLITE_OK ){
4072 pBlock->a[0] = 0x01;
4073 pBlock->n = 1 + sqlite3Fts3PutVarint(
4074 &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
4077 iRoot = 1;
4079 pRoot = &pWriter->aNodeWriter[iRoot];
4081 /* Flush all currently outstanding nodes to disk. */
4082 for(i=0; i<iRoot; i++){
4083 NodeWriter *pNode = &pWriter->aNodeWriter[i];
4084 if( pNode->block.n>0 && rc==SQLITE_OK ){
4085 rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
4087 sqlite3_free(pNode->block.a);
4088 sqlite3_free(pNode->key.a);
4091 /* Write the %_segdir record. */
4092 if( rc==SQLITE_OK ){
4093 rc = fts3WriteSegdir(p,
4094 pWriter->iAbsLevel+1, /* level */
4095 pWriter->iIdx, /* idx */
4096 pWriter->iStart, /* start_block */
4097 pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
4098 pWriter->iEnd, /* end_block */
4099 (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
4100 pRoot->block.a, pRoot->block.n /* root */
4103 sqlite3_free(pRoot->block.a);
4104 sqlite3_free(pRoot->key.a);
4106 *pRc = rc;
4110 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
4111 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
4112 ** the other, it is considered to be smaller than the other.
4114 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
4115 ** if it is greater.
4117 static int fts3TermCmp(
4118 const char *zLhs, int nLhs, /* LHS of comparison */
4119 const char *zRhs, int nRhs /* RHS of comparison */
4121 int nCmp = MIN(nLhs, nRhs);
4122 int res;
4124 res = memcmp(zLhs, zRhs, nCmp);
4125 if( res==0 ) res = nLhs - nRhs;
4127 return res;
4132 ** Query to see if the entry in the %_segments table with blockid iEnd is
4133 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
4134 ** returning. Otherwise, set *pbRes to 0.
4136 ** Or, if an error occurs while querying the database, return an SQLite
4137 ** error code. The final value of *pbRes is undefined in this case.
4139 ** This is used to test if a segment is an "appendable" segment. If it
4140 ** is, then a NULL entry has been inserted into the %_segments table
4141 ** with blockid %_segdir.end_block.
4143 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
4144 int bRes = 0; /* Result to set *pbRes to */
4145 sqlite3_stmt *pCheck = 0; /* Statement to query database with */
4146 int rc; /* Return code */
4148 rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
4149 if( rc==SQLITE_OK ){
4150 sqlite3_bind_int64(pCheck, 1, iEnd);
4151 if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
4152 rc = sqlite3_reset(pCheck);
4155 *pbRes = bRes;
4156 return rc;
4160 ** This function is called when initializing an incremental-merge operation.
4161 ** It checks if the existing segment with index value iIdx at absolute level
4162 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
4163 ** merge-writer object *pWriter is initialized to write to it.
4165 ** An existing segment can be appended to by an incremental merge if:
4167 ** * It was initially created as an appendable segment (with all required
4168 ** space pre-allocated), and
4170 ** * The first key read from the input (arguments zKey and nKey) is
4171 ** greater than the largest key currently stored in the potential
4172 ** output segment.
4174 static int fts3IncrmergeLoad(
4175 Fts3Table *p, /* Fts3 table handle */
4176 sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
4177 int iIdx, /* Index of candidate output segment */
4178 const char *zKey, /* First key to write */
4179 int nKey, /* Number of bytes in nKey */
4180 IncrmergeWriter *pWriter /* Populate this object */
4182 int rc; /* Return code */
4183 sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
4185 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
4186 if( rc==SQLITE_OK ){
4187 sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
4188 sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
4189 sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
4190 const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
4191 int nRoot = 0; /* Size of aRoot[] in bytes */
4192 int rc2; /* Return code from sqlite3_reset() */
4193 int bAppendable = 0; /* Set to true if segment is appendable */
4195 /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
4196 sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
4197 sqlite3_bind_int(pSelect, 2, iIdx);
4198 if( sqlite3_step(pSelect)==SQLITE_ROW ){
4199 iStart = sqlite3_column_int64(pSelect, 1);
4200 iLeafEnd = sqlite3_column_int64(pSelect, 2);
4201 fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
4202 if( pWriter->nLeafData<0 ){
4203 pWriter->nLeafData = pWriter->nLeafData * -1;
4205 pWriter->bNoLeafData = (pWriter->nLeafData==0);
4206 nRoot = sqlite3_column_bytes(pSelect, 4);
4207 aRoot = sqlite3_column_blob(pSelect, 4);
4208 }else{
4209 return sqlite3_reset(pSelect);
4212 /* Check for the zero-length marker in the %_segments table */
4213 rc = fts3IsAppendable(p, iEnd, &bAppendable);
4215 /* Check that zKey/nKey is larger than the largest key the candidate */
4216 if( rc==SQLITE_OK && bAppendable ){
4217 char *aLeaf = 0;
4218 int nLeaf = 0;
4220 rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
4221 if( rc==SQLITE_OK ){
4222 NodeReader reader;
4223 for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
4224 rc==SQLITE_OK && reader.aNode;
4225 rc = nodeReaderNext(&reader)
4227 assert( reader.aNode );
4229 if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
4230 bAppendable = 0;
4232 nodeReaderRelease(&reader);
4234 sqlite3_free(aLeaf);
4237 if( rc==SQLITE_OK && bAppendable ){
4238 /* It is possible to append to this segment. Set up the IncrmergeWriter
4239 ** object to do so. */
4240 int i;
4241 int nHeight = (int)aRoot[0];
4242 NodeWriter *pNode;
4244 pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
4245 pWriter->iStart = iStart;
4246 pWriter->iEnd = iEnd;
4247 pWriter->iAbsLevel = iAbsLevel;
4248 pWriter->iIdx = iIdx;
4250 for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
4251 pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
4254 pNode = &pWriter->aNodeWriter[nHeight];
4255 pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
4256 blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
4257 if( rc==SQLITE_OK ){
4258 memcpy(pNode->block.a, aRoot, nRoot);
4259 pNode->block.n = nRoot;
4262 for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
4263 NodeReader reader;
4264 pNode = &pWriter->aNodeWriter[i];
4266 rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
4267 while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
4268 blobGrowBuffer(&pNode->key, reader.term.n, &rc);
4269 if( rc==SQLITE_OK ){
4270 memcpy(pNode->key.a, reader.term.a, reader.term.n);
4271 pNode->key.n = reader.term.n;
4272 if( i>0 ){
4273 char *aBlock = 0;
4274 int nBlock = 0;
4275 pNode = &pWriter->aNodeWriter[i-1];
4276 pNode->iBlock = reader.iChild;
4277 rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
4278 blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
4279 if( rc==SQLITE_OK ){
4280 memcpy(pNode->block.a, aBlock, nBlock);
4281 pNode->block.n = nBlock;
4283 sqlite3_free(aBlock);
4286 nodeReaderRelease(&reader);
4290 rc2 = sqlite3_reset(pSelect);
4291 if( rc==SQLITE_OK ) rc = rc2;
4294 return rc;
4298 ** Determine the largest segment index value that exists within absolute
4299 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
4300 ** one before returning SQLITE_OK. Or, if there are no segments at all
4301 ** within level iAbsLevel, set *piIdx to zero.
4303 ** If an error occurs, return an SQLite error code. The final value of
4304 ** *piIdx is undefined in this case.
4306 static int fts3IncrmergeOutputIdx(
4307 Fts3Table *p, /* FTS Table handle */
4308 sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
4309 int *piIdx /* OUT: Next free index at iAbsLevel+1 */
4311 int rc;
4312 sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
4314 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
4315 if( rc==SQLITE_OK ){
4316 sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
4317 sqlite3_step(pOutputIdx);
4318 *piIdx = sqlite3_column_int(pOutputIdx, 0);
4319 rc = sqlite3_reset(pOutputIdx);
4322 return rc;
4326 ** Allocate an appendable output segment on absolute level iAbsLevel+1
4327 ** with idx value iIdx.
4329 ** In the %_segdir table, a segment is defined by the values in three
4330 ** columns:
4332 ** start_block
4333 ** leaves_end_block
4334 ** end_block
4336 ** When an appendable segment is allocated, it is estimated that the
4337 ** maximum number of leaf blocks that may be required is the sum of the
4338 ** number of leaf blocks consumed by the input segments, plus the number
4339 ** of input segments, multiplied by two. This value is stored in stack
4340 ** variable nLeafEst.
4342 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
4343 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
4344 ** array of leaf nodes starts at the first block allocated. The array
4345 ** of interior nodes that are parents of the leaf nodes start at block
4346 ** (start_block + (1 + end_block - start_block) / 16). And so on.
4348 ** In the actual code below, the value "16" is replaced with the
4349 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
4351 static int fts3IncrmergeWriter(
4352 Fts3Table *p, /* Fts3 table handle */
4353 sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
4354 int iIdx, /* Index of new output segment */
4355 Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
4356 IncrmergeWriter *pWriter /* Populate this object */
4358 int rc; /* Return Code */
4359 int i; /* Iterator variable */
4360 int nLeafEst = 0; /* Blocks allocated for leaf nodes */
4361 sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
4362 sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
4364 /* Calculate nLeafEst. */
4365 rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
4366 if( rc==SQLITE_OK ){
4367 sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
4368 sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
4369 if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
4370 nLeafEst = sqlite3_column_int(pLeafEst, 0);
4372 rc = sqlite3_reset(pLeafEst);
4374 if( rc!=SQLITE_OK ) return rc;
4376 /* Calculate the first block to use in the output segment */
4377 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
4378 if( rc==SQLITE_OK ){
4379 if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
4380 pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
4381 pWriter->iEnd = pWriter->iStart - 1;
4382 pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
4384 rc = sqlite3_reset(pFirstBlock);
4386 if( rc!=SQLITE_OK ) return rc;
4388 /* Insert the marker in the %_segments table to make sure nobody tries
4389 ** to steal the space just allocated. This is also used to identify
4390 ** appendable segments. */
4391 rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
4392 if( rc!=SQLITE_OK ) return rc;
4394 pWriter->iAbsLevel = iAbsLevel;
4395 pWriter->nLeafEst = nLeafEst;
4396 pWriter->iIdx = iIdx;
4398 /* Set up the array of NodeWriter objects */
4399 for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
4400 pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
4402 return SQLITE_OK;
4406 ** Remove an entry from the %_segdir table. This involves running the
4407 ** following two statements:
4409 ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
4410 ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
4412 ** The DELETE statement removes the specific %_segdir level. The UPDATE
4413 ** statement ensures that the remaining segments have contiguously allocated
4414 ** idx values.
4416 static int fts3RemoveSegdirEntry(
4417 Fts3Table *p, /* FTS3 table handle */
4418 sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
4419 int iIdx /* Index of %_segdir entry to delete */
4421 int rc; /* Return code */
4422 sqlite3_stmt *pDelete = 0; /* DELETE statement */
4424 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
4425 if( rc==SQLITE_OK ){
4426 sqlite3_bind_int64(pDelete, 1, iAbsLevel);
4427 sqlite3_bind_int(pDelete, 2, iIdx);
4428 sqlite3_step(pDelete);
4429 rc = sqlite3_reset(pDelete);
4432 return rc;
4436 ** One or more segments have just been removed from absolute level iAbsLevel.
4437 ** Update the 'idx' values of the remaining segments in the level so that
4438 ** the idx values are a contiguous sequence starting from 0.
4440 static int fts3RepackSegdirLevel(
4441 Fts3Table *p, /* FTS3 table handle */
4442 sqlite3_int64 iAbsLevel /* Absolute level to repack */
4444 int rc; /* Return code */
4445 int *aIdx = 0; /* Array of remaining idx values */
4446 int nIdx = 0; /* Valid entries in aIdx[] */
4447 int nAlloc = 0; /* Allocated size of aIdx[] */
4448 int i; /* Iterator variable */
4449 sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
4450 sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
4452 rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
4453 if( rc==SQLITE_OK ){
4454 int rc2;
4455 sqlite3_bind_int64(pSelect, 1, iAbsLevel);
4456 while( SQLITE_ROW==sqlite3_step(pSelect) ){
4457 if( nIdx>=nAlloc ){
4458 int *aNew;
4459 nAlloc += 16;
4460 aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
4461 if( !aNew ){
4462 rc = SQLITE_NOMEM;
4463 break;
4465 aIdx = aNew;
4467 aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
4469 rc2 = sqlite3_reset(pSelect);
4470 if( rc==SQLITE_OK ) rc = rc2;
4473 if( rc==SQLITE_OK ){
4474 rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
4476 if( rc==SQLITE_OK ){
4477 sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
4480 assert( p->bIgnoreSavepoint==0 );
4481 p->bIgnoreSavepoint = 1;
4482 for(i=0; rc==SQLITE_OK && i<nIdx; i++){
4483 if( aIdx[i]!=i ){
4484 sqlite3_bind_int(pUpdate, 3, aIdx[i]);
4485 sqlite3_bind_int(pUpdate, 1, i);
4486 sqlite3_step(pUpdate);
4487 rc = sqlite3_reset(pUpdate);
4490 p->bIgnoreSavepoint = 0;
4492 sqlite3_free(aIdx);
4493 return rc;
4496 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
4497 pNode->a[0] = (char)iHeight;
4498 if( iChild ){
4499 assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
4500 pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
4501 }else{
4502 assert( pNode->nAlloc>=1 );
4503 pNode->n = 1;
4508 ** The first two arguments are a pointer to and the size of a segment b-tree
4509 ** node. The node may be a leaf or an internal node.
4511 ** This function creates a new node image in blob object *pNew by copying
4512 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
4513 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
4515 static int fts3TruncateNode(
4516 const char *aNode, /* Current node image */
4517 int nNode, /* Size of aNode in bytes */
4518 Blob *pNew, /* OUT: Write new node image here */
4519 const char *zTerm, /* Omit all terms smaller than this */
4520 int nTerm, /* Size of zTerm in bytes */
4521 sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
4523 NodeReader reader; /* Reader object */
4524 Blob prev = {0, 0, 0}; /* Previous term written to new node */
4525 int rc = SQLITE_OK; /* Return code */
4526 int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
4528 /* Allocate required output space */
4529 blobGrowBuffer(pNew, nNode, &rc);
4530 if( rc!=SQLITE_OK ) return rc;
4531 pNew->n = 0;
4533 /* Populate new node buffer */
4534 for(rc = nodeReaderInit(&reader, aNode, nNode);
4535 rc==SQLITE_OK && reader.aNode;
4536 rc = nodeReaderNext(&reader)
4538 if( pNew->n==0 ){
4539 int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
4540 if( res<0 || (bLeaf==0 && res==0) ) continue;
4541 fts3StartNode(pNew, (int)aNode[0], reader.iChild);
4542 *piBlock = reader.iChild;
4544 rc = fts3AppendToNode(
4545 pNew, &prev, reader.term.a, reader.term.n,
4546 reader.aDoclist, reader.nDoclist
4548 if( rc!=SQLITE_OK ) break;
4550 if( pNew->n==0 ){
4551 fts3StartNode(pNew, (int)aNode[0], reader.iChild);
4552 *piBlock = reader.iChild;
4554 assert( pNew->n<=pNew->nAlloc );
4556 nodeReaderRelease(&reader);
4557 sqlite3_free(prev.a);
4558 return rc;
4562 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
4563 ** level iAbsLevel. This may involve deleting entries from the %_segments
4564 ** table, and modifying existing entries in both the %_segments and %_segdir
4565 ** tables.
4567 ** SQLITE_OK is returned if the segment is updated successfully. Or an
4568 ** SQLite error code otherwise.
4570 static int fts3TruncateSegment(
4571 Fts3Table *p, /* FTS3 table handle */
4572 sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
4573 int iIdx, /* Index within level of segment to modify */
4574 const char *zTerm, /* Remove terms smaller than this */
4575 int nTerm /* Number of bytes in buffer zTerm */
4577 int rc = SQLITE_OK; /* Return code */
4578 Blob root = {0,0,0}; /* New root page image */
4579 Blob block = {0,0,0}; /* Buffer used for any other block */
4580 sqlite3_int64 iBlock = 0; /* Block id */
4581 sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
4582 sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
4583 sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
4585 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
4586 if( rc==SQLITE_OK ){
4587 int rc2; /* sqlite3_reset() return code */
4588 sqlite3_bind_int64(pFetch, 1, iAbsLevel);
4589 sqlite3_bind_int(pFetch, 2, iIdx);
4590 if( SQLITE_ROW==sqlite3_step(pFetch) ){
4591 const char *aRoot = sqlite3_column_blob(pFetch, 4);
4592 int nRoot = sqlite3_column_bytes(pFetch, 4);
4593 iOldStart = sqlite3_column_int64(pFetch, 1);
4594 rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
4596 rc2 = sqlite3_reset(pFetch);
4597 if( rc==SQLITE_OK ) rc = rc2;
4600 while( rc==SQLITE_OK && iBlock ){
4601 char *aBlock = 0;
4602 int nBlock = 0;
4603 iNewStart = iBlock;
4605 rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
4606 if( rc==SQLITE_OK ){
4607 rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
4609 if( rc==SQLITE_OK ){
4610 rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
4612 sqlite3_free(aBlock);
4615 /* Variable iNewStart now contains the first valid leaf node. */
4616 if( rc==SQLITE_OK && iNewStart ){
4617 sqlite3_stmt *pDel = 0;
4618 rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
4619 if( rc==SQLITE_OK ){
4620 sqlite3_bind_int64(pDel, 1, iOldStart);
4621 sqlite3_bind_int64(pDel, 2, iNewStart-1);
4622 sqlite3_step(pDel);
4623 rc = sqlite3_reset(pDel);
4627 if( rc==SQLITE_OK ){
4628 sqlite3_stmt *pChomp = 0;
4629 rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
4630 if( rc==SQLITE_OK ){
4631 sqlite3_bind_int64(pChomp, 1, iNewStart);
4632 sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
4633 sqlite3_bind_int64(pChomp, 3, iAbsLevel);
4634 sqlite3_bind_int(pChomp, 4, iIdx);
4635 sqlite3_step(pChomp);
4636 rc = sqlite3_reset(pChomp);
4637 sqlite3_bind_null(pChomp, 2);
4641 sqlite3_free(root.a);
4642 sqlite3_free(block.a);
4643 return rc;
4647 ** This function is called after an incrmental-merge operation has run to
4648 ** merge (or partially merge) two or more segments from absolute level
4649 ** iAbsLevel.
4651 ** Each input segment is either removed from the db completely (if all of
4652 ** its data was copied to the output segment by the incrmerge operation)
4653 ** or modified in place so that it no longer contains those entries that
4654 ** have been duplicated in the output segment.
4656 static int fts3IncrmergeChomp(
4657 Fts3Table *p, /* FTS table handle */
4658 sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
4659 Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
4660 int *pnRem /* Number of segments not deleted */
4662 int i;
4663 int nRem = 0;
4664 int rc = SQLITE_OK;
4666 for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
4667 Fts3SegReader *pSeg = 0;
4668 int j;
4670 /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
4671 ** somewhere in the pCsr->apSegment[] array. */
4672 for(j=0; ALWAYS(j<pCsr->nSegment); j++){
4673 pSeg = pCsr->apSegment[j];
4674 if( pSeg->iIdx==i ) break;
4676 assert( j<pCsr->nSegment && pSeg->iIdx==i );
4678 if( pSeg->aNode==0 ){
4679 /* Seg-reader is at EOF. Remove the entire input segment. */
4680 rc = fts3DeleteSegment(p, pSeg);
4681 if( rc==SQLITE_OK ){
4682 rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
4684 *pnRem = 0;
4685 }else{
4686 /* The incremental merge did not copy all the data from this
4687 ** segment to the upper level. The segment is modified in place
4688 ** so that it contains no keys smaller than zTerm/nTerm. */
4689 const char *zTerm = pSeg->zTerm;
4690 int nTerm = pSeg->nTerm;
4691 rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
4692 nRem++;
4696 if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
4697 rc = fts3RepackSegdirLevel(p, iAbsLevel);
4700 *pnRem = nRem;
4701 return rc;
4705 ** Store an incr-merge hint in the database.
4707 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
4708 sqlite3_stmt *pReplace = 0;
4709 int rc; /* Return code */
4711 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
4712 if( rc==SQLITE_OK ){
4713 sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
4714 sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
4715 sqlite3_step(pReplace);
4716 rc = sqlite3_reset(pReplace);
4717 sqlite3_bind_null(pReplace, 2);
4720 return rc;
4724 ** Load an incr-merge hint from the database. The incr-merge hint, if one
4725 ** exists, is stored in the rowid==1 row of the %_stat table.
4727 ** If successful, populate blob *pHint with the value read from the %_stat
4728 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
4729 ** SQLite error code.
4731 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
4732 sqlite3_stmt *pSelect = 0;
4733 int rc;
4735 pHint->n = 0;
4736 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
4737 if( rc==SQLITE_OK ){
4738 int rc2;
4739 sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
4740 if( SQLITE_ROW==sqlite3_step(pSelect) ){
4741 const char *aHint = sqlite3_column_blob(pSelect, 0);
4742 int nHint = sqlite3_column_bytes(pSelect, 0);
4743 if( aHint ){
4744 blobGrowBuffer(pHint, nHint, &rc);
4745 if( rc==SQLITE_OK ){
4746 memcpy(pHint->a, aHint, nHint);
4747 pHint->n = nHint;
4751 rc2 = sqlite3_reset(pSelect);
4752 if( rc==SQLITE_OK ) rc = rc2;
4755 return rc;
4759 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
4760 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
4761 ** consists of two varints, the absolute level number of the input segments
4762 ** and the number of input segments.
4764 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
4765 ** set *pRc to an SQLite error code before returning.
4767 static void fts3IncrmergeHintPush(
4768 Blob *pHint, /* Hint blob to append to */
4769 i64 iAbsLevel, /* First varint to store in hint */
4770 int nInput, /* Second varint to store in hint */
4771 int *pRc /* IN/OUT: Error code */
4773 blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
4774 if( *pRc==SQLITE_OK ){
4775 pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
4776 pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
4781 ** Read the last entry (most recently pushed) from the hint blob *pHint
4782 ** and then remove the entry. Write the two values read to *piAbsLevel and
4783 ** *pnInput before returning.
4785 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
4786 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
4788 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
4789 const int nHint = pHint->n;
4790 int i;
4792 i = pHint->n-2;
4793 while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
4794 while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
4796 pHint->n = i;
4797 i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
4798 i += fts3GetVarint32(&pHint->a[i], pnInput);
4799 if( i!=nHint ) return FTS_CORRUPT_VTAB;
4801 return SQLITE_OK;
4806 ** Attempt an incremental merge that writes nMerge leaf blocks.
4808 ** Incremental merges happen nMin segments at a time. The segments
4809 ** to be merged are the nMin oldest segments (the ones with the smallest
4810 ** values for the _segdir.idx field) in the highest level that contains
4811 ** at least nMin segments. Multiple merges might occur in an attempt to
4812 ** write the quota of nMerge leaf blocks.
4814 int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
4815 int rc; /* Return code */
4816 int nRem = nMerge; /* Number of leaf pages yet to be written */
4817 Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
4818 Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
4819 IncrmergeWriter *pWriter; /* Writer object */
4820 int nSeg = 0; /* Number of input segments */
4821 sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
4822 Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
4823 int bDirtyHint = 0; /* True if blob 'hint' has been modified */
4825 /* Allocate space for the cursor, filter and writer objects */
4826 const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
4827 pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
4828 if( !pWriter ) return SQLITE_NOMEM;
4829 pFilter = (Fts3SegFilter *)&pWriter[1];
4830 pCsr = (Fts3MultiSegReader *)&pFilter[1];
4832 rc = fts3IncrmergeHintLoad(p, &hint);
4833 while( rc==SQLITE_OK && nRem>0 ){
4834 const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
4835 sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
4836 int bUseHint = 0; /* True if attempting to append */
4837 int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
4839 /* Search the %_segdir table for the absolute level with the smallest
4840 ** relative level number that contains at least nMin segments, if any.
4841 ** If one is found, set iAbsLevel to the absolute level number and
4842 ** nSeg to nMin. If no level with at least nMin segments can be found,
4843 ** set nSeg to -1.
4845 rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
4846 sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
4847 if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
4848 iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
4849 nSeg = sqlite3_column_int(pFindLevel, 1);
4850 assert( nSeg>=2 );
4851 }else{
4852 nSeg = -1;
4854 rc = sqlite3_reset(pFindLevel);
4856 /* If the hint read from the %_stat table is not empty, check if the
4857 ** last entry in it specifies a relative level smaller than or equal
4858 ** to the level identified by the block above (if any). If so, this
4859 ** iteration of the loop will work on merging at the hinted level.
4861 if( rc==SQLITE_OK && hint.n ){
4862 int nHint = hint.n;
4863 sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
4864 int nHintSeg = 0; /* Hint number of segments */
4866 rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
4867 if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
4868 iAbsLevel = iHintAbsLevel;
4869 nSeg = nHintSeg;
4870 bUseHint = 1;
4871 bDirtyHint = 1;
4872 }else{
4873 /* This undoes the effect of the HintPop() above - so that no entry
4874 ** is removed from the hint blob. */
4875 hint.n = nHint;
4879 /* If nSeg is less that zero, then there is no level with at least
4880 ** nMin segments and no hint in the %_stat table. No work to do.
4881 ** Exit early in this case. */
4882 if( nSeg<0 ) break;
4884 /* Open a cursor to iterate through the contents of the oldest nSeg
4885 ** indexes of absolute level iAbsLevel. If this cursor is opened using
4886 ** the 'hint' parameters, it is possible that there are less than nSeg
4887 ** segments available in level iAbsLevel. In this case, no work is
4888 ** done on iAbsLevel - fall through to the next iteration of the loop
4889 ** to start work on some other level. */
4890 memset(pWriter, 0, nAlloc);
4891 pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
4893 if( rc==SQLITE_OK ){
4894 rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
4895 assert( bUseHint==1 || bUseHint==0 );
4896 if( iIdx==0 || (bUseHint && iIdx==1) ){
4897 int bIgnore = 0;
4898 rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
4899 if( bIgnore ){
4900 pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
4905 if( rc==SQLITE_OK ){
4906 rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
4908 if( SQLITE_OK==rc && pCsr->nSegment==nSeg
4909 && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
4910 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
4912 if( bUseHint && iIdx>0 ){
4913 const char *zKey = pCsr->zTerm;
4914 int nKey = pCsr->nTerm;
4915 rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
4916 }else{
4917 rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
4920 if( rc==SQLITE_OK && pWriter->nLeafEst ){
4921 fts3LogMerge(nSeg, iAbsLevel);
4922 do {
4923 rc = fts3IncrmergeAppend(p, pWriter, pCsr);
4924 if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
4925 if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
4926 }while( rc==SQLITE_ROW );
4928 /* Update or delete the input segments */
4929 if( rc==SQLITE_OK ){
4930 nRem -= (1 + pWriter->nWork);
4931 rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
4932 if( nSeg!=0 ){
4933 bDirtyHint = 1;
4934 fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
4939 if( nSeg!=0 ){
4940 pWriter->nLeafData = pWriter->nLeafData * -1;
4942 fts3IncrmergeRelease(p, pWriter, &rc);
4943 if( nSeg==0 && pWriter->bNoLeafData==0 ){
4944 fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
4948 sqlite3Fts3SegReaderFinish(pCsr);
4951 /* Write the hint values into the %_stat table for the next incr-merger */
4952 if( bDirtyHint && rc==SQLITE_OK ){
4953 rc = fts3IncrmergeHintStore(p, &hint);
4956 sqlite3_free(pWriter);
4957 sqlite3_free(hint.a);
4958 return rc;
4962 ** Convert the text beginning at *pz into an integer and return
4963 ** its value. Advance *pz to point to the first character past
4964 ** the integer.
4966 ** This function used for parameters to merge= and incrmerge=
4967 ** commands.
4969 static int fts3Getint(const char **pz){
4970 const char *z = *pz;
4971 int i = 0;
4972 while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
4973 *pz = z;
4974 return i;
4978 ** Process statements of the form:
4980 ** INSERT INTO table(table) VALUES('merge=A,B');
4982 ** A and B are integers that decode to be the number of leaf pages
4983 ** written for the merge, and the minimum number of segments on a level
4984 ** before it will be selected for a merge, respectively.
4986 static int fts3DoIncrmerge(
4987 Fts3Table *p, /* FTS3 table handle */
4988 const char *zParam /* Nul-terminated string containing "A,B" */
4990 int rc;
4991 int nMin = (FTS3_MERGE_COUNT / 2);
4992 int nMerge = 0;
4993 const char *z = zParam;
4995 /* Read the first integer value */
4996 nMerge = fts3Getint(&z);
4998 /* If the first integer value is followed by a ',', read the second
4999 ** integer value. */
5000 if( z[0]==',' && z[1]!='\0' ){
5001 z++;
5002 nMin = fts3Getint(&z);
5005 if( z[0]!='\0' || nMin<2 ){
5006 rc = SQLITE_ERROR;
5007 }else{
5008 rc = SQLITE_OK;
5009 if( !p->bHasStat ){
5010 assert( p->bFts4==0 );
5011 sqlite3Fts3CreateStatTable(&rc, p);
5013 if( rc==SQLITE_OK ){
5014 rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
5016 sqlite3Fts3SegmentsClose(p);
5018 return rc;
5022 ** Process statements of the form:
5024 ** INSERT INTO table(table) VALUES('automerge=X');
5026 ** where X is an integer. X==0 means to turn automerge off. X!=0 means
5027 ** turn it on. The setting is persistent.
5029 static int fts3DoAutoincrmerge(
5030 Fts3Table *p, /* FTS3 table handle */
5031 const char *zParam /* Nul-terminated string containing boolean */
5033 int rc = SQLITE_OK;
5034 sqlite3_stmt *pStmt = 0;
5035 p->nAutoincrmerge = fts3Getint(&zParam);
5036 if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
5037 p->nAutoincrmerge = 8;
5039 if( !p->bHasStat ){
5040 assert( p->bFts4==0 );
5041 sqlite3Fts3CreateStatTable(&rc, p);
5042 if( rc ) return rc;
5044 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
5045 if( rc ) return rc;
5046 sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
5047 sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
5048 sqlite3_step(pStmt);
5049 rc = sqlite3_reset(pStmt);
5050 return rc;
5054 ** Return a 64-bit checksum for the FTS index entry specified by the
5055 ** arguments to this function.
5057 static u64 fts3ChecksumEntry(
5058 const char *zTerm, /* Pointer to buffer containing term */
5059 int nTerm, /* Size of zTerm in bytes */
5060 int iLangid, /* Language id for current row */
5061 int iIndex, /* Index (0..Fts3Table.nIndex-1) */
5062 i64 iDocid, /* Docid for current row. */
5063 int iCol, /* Column number */
5064 int iPos /* Position */
5066 int i;
5067 u64 ret = (u64)iDocid;
5069 ret += (ret<<3) + iLangid;
5070 ret += (ret<<3) + iIndex;
5071 ret += (ret<<3) + iCol;
5072 ret += (ret<<3) + iPos;
5073 for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
5075 return ret;
5079 ** Return a checksum of all entries in the FTS index that correspond to
5080 ** language id iLangid. The checksum is calculated by XORing the checksums
5081 ** of each individual entry (see fts3ChecksumEntry()) together.
5083 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
5084 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
5085 ** return value is undefined in this case.
5087 static u64 fts3ChecksumIndex(
5088 Fts3Table *p, /* FTS3 table handle */
5089 int iLangid, /* Language id to return cksum for */
5090 int iIndex, /* Index to cksum (0..p->nIndex-1) */
5091 int *pRc /* OUT: Return code */
5093 Fts3SegFilter filter;
5094 Fts3MultiSegReader csr;
5095 int rc;
5096 u64 cksum = 0;
5098 assert( *pRc==SQLITE_OK );
5100 memset(&filter, 0, sizeof(filter));
5101 memset(&csr, 0, sizeof(csr));
5102 filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
5103 filter.flags |= FTS3_SEGMENT_SCAN;
5105 rc = sqlite3Fts3SegReaderCursor(
5106 p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
5108 if( rc==SQLITE_OK ){
5109 rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
5112 if( rc==SQLITE_OK ){
5113 while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
5114 char *pCsr = csr.aDoclist;
5115 char *pEnd = &pCsr[csr.nDoclist];
5117 i64 iDocid = 0;
5118 i64 iCol = 0;
5119 i64 iPos = 0;
5121 pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
5122 while( pCsr<pEnd ){
5123 i64 iVal = 0;
5124 pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
5125 if( pCsr<pEnd ){
5126 if( iVal==0 || iVal==1 ){
5127 iCol = 0;
5128 iPos = 0;
5129 if( iVal ){
5130 pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
5131 }else{
5132 pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
5133 iDocid += iVal;
5135 }else{
5136 iPos += (iVal - 2);
5137 cksum = cksum ^ fts3ChecksumEntry(
5138 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
5139 (int)iCol, (int)iPos
5146 sqlite3Fts3SegReaderFinish(&csr);
5148 *pRc = rc;
5149 return cksum;
5153 ** Check if the contents of the FTS index match the current contents of the
5154 ** content table. If no error occurs and the contents do match, set *pbOk
5155 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
5156 ** to false before returning.
5158 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
5159 ** code. The final value of *pbOk is undefined in this case.
5161 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
5162 int rc = SQLITE_OK; /* Return code */
5163 u64 cksum1 = 0; /* Checksum based on FTS index contents */
5164 u64 cksum2 = 0; /* Checksum based on %_content contents */
5165 sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
5167 /* This block calculates the checksum according to the FTS index. */
5168 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
5169 if( rc==SQLITE_OK ){
5170 int rc2;
5171 sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
5172 sqlite3_bind_int(pAllLangid, 2, p->nIndex);
5173 while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
5174 int iLangid = sqlite3_column_int(pAllLangid, 0);
5175 int i;
5176 for(i=0; i<p->nIndex; i++){
5177 cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
5180 rc2 = sqlite3_reset(pAllLangid);
5181 if( rc==SQLITE_OK ) rc = rc2;
5184 /* This block calculates the checksum according to the %_content table */
5185 if( rc==SQLITE_OK ){
5186 sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
5187 sqlite3_stmt *pStmt = 0;
5188 char *zSql;
5190 zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
5191 if( !zSql ){
5192 rc = SQLITE_NOMEM;
5193 }else{
5194 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5195 sqlite3_free(zSql);
5198 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
5199 i64 iDocid = sqlite3_column_int64(pStmt, 0);
5200 int iLang = langidFromSelect(p, pStmt);
5201 int iCol;
5203 for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
5204 if( p->abNotindexed[iCol]==0 ){
5205 const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
5206 int nText = sqlite3_column_bytes(pStmt, iCol+1);
5207 sqlite3_tokenizer_cursor *pT = 0;
5209 rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
5210 while( rc==SQLITE_OK ){
5211 char const *zToken; /* Buffer containing token */
5212 int nToken = 0; /* Number of bytes in token */
5213 int iDum1 = 0, iDum2 = 0; /* Dummy variables */
5214 int iPos = 0; /* Position of token in zText */
5216 rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
5217 if( rc==SQLITE_OK ){
5218 int i;
5219 cksum2 = cksum2 ^ fts3ChecksumEntry(
5220 zToken, nToken, iLang, 0, iDocid, iCol, iPos
5222 for(i=1; i<p->nIndex; i++){
5223 if( p->aIndex[i].nPrefix<=nToken ){
5224 cksum2 = cksum2 ^ fts3ChecksumEntry(
5225 zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
5231 if( pT ) pModule->xClose(pT);
5232 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
5237 sqlite3_finalize(pStmt);
5240 *pbOk = (cksum1==cksum2);
5241 return rc;
5245 ** Run the integrity-check. If no error occurs and the current contents of
5246 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
5247 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
5249 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
5250 ** error code.
5252 ** The integrity-check works as follows. For each token and indexed token
5253 ** prefix in the document set, a 64-bit checksum is calculated (by code
5254 ** in fts3ChecksumEntry()) based on the following:
5256 ** + The index number (0 for the main index, 1 for the first prefix
5257 ** index etc.),
5258 ** + The token (or token prefix) text itself,
5259 ** + The language-id of the row it appears in,
5260 ** + The docid of the row it appears in,
5261 ** + The column it appears in, and
5262 ** + The tokens position within that column.
5264 ** The checksums for all entries in the index are XORed together to create
5265 ** a single checksum for the entire index.
5267 ** The integrity-check code calculates the same checksum in two ways:
5269 ** 1. By scanning the contents of the FTS index, and
5270 ** 2. By scanning and tokenizing the content table.
5272 ** If the two checksums are identical, the integrity-check is deemed to have
5273 ** passed.
5275 static int fts3DoIntegrityCheck(
5276 Fts3Table *p /* FTS3 table handle */
5278 int rc;
5279 int bOk = 0;
5280 rc = fts3IntegrityCheck(p, &bOk);
5281 if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
5282 return rc;
5286 ** Handle a 'special' INSERT of the form:
5288 ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
5290 ** Argument pVal contains the result of <expr>. Currently the only
5291 ** meaningful value to insert is the text 'optimize'.
5293 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
5294 int rc; /* Return Code */
5295 const char *zVal = (const char *)sqlite3_value_text(pVal);
5296 int nVal = sqlite3_value_bytes(pVal);
5298 if( !zVal ){
5299 return SQLITE_NOMEM;
5300 }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
5301 rc = fts3DoOptimize(p, 0);
5302 }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
5303 rc = fts3DoRebuild(p);
5304 }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
5305 rc = fts3DoIntegrityCheck(p);
5306 }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
5307 rc = fts3DoIncrmerge(p, &zVal[6]);
5308 }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
5309 rc = fts3DoAutoincrmerge(p, &zVal[10]);
5310 #ifdef SQLITE_TEST
5311 }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
5312 p->nNodeSize = atoi(&zVal[9]);
5313 rc = SQLITE_OK;
5314 }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
5315 p->nMaxPendingData = atoi(&zVal[11]);
5316 rc = SQLITE_OK;
5317 }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
5318 p->bNoIncrDoclist = atoi(&zVal[21]);
5319 rc = SQLITE_OK;
5320 #endif
5321 }else{
5322 rc = SQLITE_ERROR;
5325 return rc;
5328 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
5330 ** Delete all cached deferred doclists. Deferred doclists are cached
5331 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
5333 void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
5334 Fts3DeferredToken *pDef;
5335 for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
5336 fts3PendingListDelete(pDef->pList);
5337 pDef->pList = 0;
5342 ** Free all entries in the pCsr->pDeffered list. Entries are added to
5343 ** this list using sqlite3Fts3DeferToken().
5345 void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
5346 Fts3DeferredToken *pDef;
5347 Fts3DeferredToken *pNext;
5348 for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
5349 pNext = pDef->pNext;
5350 fts3PendingListDelete(pDef->pList);
5351 sqlite3_free(pDef);
5353 pCsr->pDeferred = 0;
5357 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
5358 ** based on the row that pCsr currently points to.
5360 ** A deferred-doclist is like any other doclist with position information
5361 ** included, except that it only contains entries for a single row of the
5362 ** table, not for all rows.
5364 int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
5365 int rc = SQLITE_OK; /* Return code */
5366 if( pCsr->pDeferred ){
5367 int i; /* Used to iterate through table columns */
5368 sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
5369 Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
5371 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
5372 sqlite3_tokenizer *pT = p->pTokenizer;
5373 sqlite3_tokenizer_module const *pModule = pT->pModule;
5375 assert( pCsr->isRequireSeek==0 );
5376 iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
5378 for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
5379 if( p->abNotindexed[i]==0 ){
5380 const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
5381 sqlite3_tokenizer_cursor *pTC = 0;
5383 rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
5384 while( rc==SQLITE_OK ){
5385 char const *zToken; /* Buffer containing token */
5386 int nToken = 0; /* Number of bytes in token */
5387 int iDum1 = 0, iDum2 = 0; /* Dummy variables */
5388 int iPos = 0; /* Position of token in zText */
5390 rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
5391 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
5392 Fts3PhraseToken *pPT = pDef->pToken;
5393 if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
5394 && (pPT->bFirst==0 || iPos==0)
5395 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
5396 && (0==memcmp(zToken, pPT->z, pPT->n))
5398 fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
5402 if( pTC ) pModule->xClose(pTC);
5403 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
5407 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
5408 if( pDef->pList ){
5409 rc = fts3PendingListAppendVarint(&pDef->pList, 0);
5414 return rc;
5417 int sqlite3Fts3DeferredTokenList(
5418 Fts3DeferredToken *p,
5419 char **ppData,
5420 int *pnData
5422 char *pRet;
5423 int nSkip;
5424 sqlite3_int64 dummy;
5426 *ppData = 0;
5427 *pnData = 0;
5429 if( p->pList==0 ){
5430 return SQLITE_OK;
5433 pRet = (char *)sqlite3_malloc(p->pList->nData);
5434 if( !pRet ) return SQLITE_NOMEM;
5436 nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
5437 *pnData = p->pList->nData - nSkip;
5438 *ppData = pRet;
5440 memcpy(pRet, &p->pList->aData[nSkip], *pnData);
5441 return SQLITE_OK;
5445 ** Add an entry for token pToken to the pCsr->pDeferred list.
5447 int sqlite3Fts3DeferToken(
5448 Fts3Cursor *pCsr, /* Fts3 table cursor */
5449 Fts3PhraseToken *pToken, /* Token to defer */
5450 int iCol /* Column that token must appear in (or -1) */
5452 Fts3DeferredToken *pDeferred;
5453 pDeferred = sqlite3_malloc(sizeof(*pDeferred));
5454 if( !pDeferred ){
5455 return SQLITE_NOMEM;
5457 memset(pDeferred, 0, sizeof(*pDeferred));
5458 pDeferred->pToken = pToken;
5459 pDeferred->pNext = pCsr->pDeferred;
5460 pDeferred->iCol = iCol;
5461 pCsr->pDeferred = pDeferred;
5463 assert( pToken->pDeferred==0 );
5464 pToken->pDeferred = pDeferred;
5466 return SQLITE_OK;
5468 #endif
5471 ** SQLite value pRowid contains the rowid of a row that may or may not be
5472 ** present in the FTS3 table. If it is, delete it and adjust the contents
5473 ** of subsiduary data structures accordingly.
5475 static int fts3DeleteByRowid(
5476 Fts3Table *p,
5477 sqlite3_value *pRowid,
5478 int *pnChng, /* IN/OUT: Decrement if row is deleted */
5479 u32 *aSzDel
5481 int rc = SQLITE_OK; /* Return code */
5482 int bFound = 0; /* True if *pRowid really is in the table */
5484 fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
5485 if( bFound && rc==SQLITE_OK ){
5486 int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
5487 rc = fts3IsEmpty(p, pRowid, &isEmpty);
5488 if( rc==SQLITE_OK ){
5489 if( isEmpty ){
5490 /* Deleting this row means the whole table is empty. In this case
5491 ** delete the contents of all three tables and throw away any
5492 ** data in the pendingTerms hash table. */
5493 rc = fts3DeleteAll(p, 1);
5494 *pnChng = 0;
5495 memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
5496 }else{
5497 *pnChng = *pnChng - 1;
5498 if( p->zContentTbl==0 ){
5499 fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
5501 if( p->bHasDocsize ){
5502 fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
5508 return rc;
5512 ** This function does the work for the xUpdate method of FTS3 virtual
5513 ** tables. The schema of the virtual table being:
5515 ** CREATE TABLE <table name>(
5516 ** <user columns>,
5517 ** <table name> HIDDEN,
5518 ** docid HIDDEN,
5519 ** <langid> HIDDEN
5520 ** );
5524 int sqlite3Fts3UpdateMethod(
5525 sqlite3_vtab *pVtab, /* FTS3 vtab object */
5526 int nArg, /* Size of argument array */
5527 sqlite3_value **apVal, /* Array of arguments */
5528 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
5530 Fts3Table *p = (Fts3Table *)pVtab;
5531 int rc = SQLITE_OK; /* Return Code */
5532 u32 *aSzIns = 0; /* Sizes of inserted documents */
5533 u32 *aSzDel = 0; /* Sizes of deleted documents */
5534 int nChng = 0; /* Net change in number of documents */
5535 int bInsertDone = 0;
5537 /* At this point it must be known if the %_stat table exists or not.
5538 ** So bHasStat may not be 2. */
5539 assert( p->bHasStat==0 || p->bHasStat==1 );
5541 assert( p->pSegments==0 );
5542 assert(
5543 nArg==1 /* DELETE operations */
5544 || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
5547 /* Check for a "special" INSERT operation. One of the form:
5549 ** INSERT INTO xyz(xyz) VALUES('command');
5551 if( nArg>1
5552 && sqlite3_value_type(apVal[0])==SQLITE_NULL
5553 && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
5555 rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
5556 goto update_out;
5559 if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
5560 rc = SQLITE_CONSTRAINT;
5561 goto update_out;
5564 /* Allocate space to hold the change in document sizes */
5565 aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
5566 if( aSzDel==0 ){
5567 rc = SQLITE_NOMEM;
5568 goto update_out;
5570 aSzIns = &aSzDel[p->nColumn+1];
5571 memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
5573 rc = fts3Writelock(p);
5574 if( rc!=SQLITE_OK ) goto update_out;
5576 /* If this is an INSERT operation, or an UPDATE that modifies the rowid
5577 ** value, then this operation requires constraint handling.
5579 ** If the on-conflict mode is REPLACE, this means that the existing row
5580 ** should be deleted from the database before inserting the new row. Or,
5581 ** if the on-conflict mode is other than REPLACE, then this method must
5582 ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
5583 ** modify the database file.
5585 if( nArg>1 && p->zContentTbl==0 ){
5586 /* Find the value object that holds the new rowid value. */
5587 sqlite3_value *pNewRowid = apVal[3+p->nColumn];
5588 if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
5589 pNewRowid = apVal[1];
5592 if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
5593 sqlite3_value_type(apVal[0])==SQLITE_NULL
5594 || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
5596 /* The new rowid is not NULL (in this case the rowid will be
5597 ** automatically assigned and there is no chance of a conflict), and
5598 ** the statement is either an INSERT or an UPDATE that modifies the
5599 ** rowid column. So if the conflict mode is REPLACE, then delete any
5600 ** existing row with rowid=pNewRowid.
5602 ** Or, if the conflict mode is not REPLACE, insert the new record into
5603 ** the %_content table. If we hit the duplicate rowid constraint (or any
5604 ** other error) while doing so, return immediately.
5606 ** This branch may also run if pNewRowid contains a value that cannot
5607 ** be losslessly converted to an integer. In this case, the eventual
5608 ** call to fts3InsertData() (either just below or further on in this
5609 ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
5610 ** invoked, it will delete zero rows (since no row will have
5611 ** docid=$pNewRowid if $pNewRowid is not an integer value).
5613 if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
5614 rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
5615 }else{
5616 rc = fts3InsertData(p, apVal, pRowid);
5617 bInsertDone = 1;
5621 if( rc!=SQLITE_OK ){
5622 goto update_out;
5625 /* If this is a DELETE or UPDATE operation, remove the old record. */
5626 if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
5627 assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
5628 rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
5631 /* If this is an INSERT or UPDATE operation, insert the new record. */
5632 if( nArg>1 && rc==SQLITE_OK ){
5633 int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
5634 if( bInsertDone==0 ){
5635 rc = fts3InsertData(p, apVal, pRowid);
5636 if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
5637 rc = FTS_CORRUPT_VTAB;
5640 if( rc==SQLITE_OK ){
5641 rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
5643 if( rc==SQLITE_OK ){
5644 assert( p->iPrevDocid==*pRowid );
5645 rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
5647 if( p->bHasDocsize ){
5648 fts3InsertDocsize(&rc, p, aSzIns);
5650 nChng++;
5653 if( p->bFts4 ){
5654 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
5657 update_out:
5658 sqlite3_free(aSzDel);
5659 sqlite3Fts3SegmentsClose(p);
5660 return rc;
5664 ** Flush any data in the pending-terms hash table to disk. If successful,
5665 ** merge all segments in the database (including the new segment, if
5666 ** there was any data to flush) into a single segment.
5668 int sqlite3Fts3Optimize(Fts3Table *p){
5669 int rc;
5670 rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
5671 if( rc==SQLITE_OK ){
5672 rc = fts3DoOptimize(p, 1);
5673 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
5674 int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
5675 if( rc2!=SQLITE_OK ) rc = rc2;
5676 }else{
5677 sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
5678 sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
5681 sqlite3Fts3SegmentsClose(p);
5682 return rc;
5685 #endif