interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / fts5 / fts5_index.c

9650 lines · 303594 bytes Raw Blame History
1/*
2** 2014 May 31
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
13** Low level access to the FTS index stored in the database file. The
14** routines in this file file implement all read and write access to the
15** %_data table. Other parts of the system access this functionality via
16** the interface defined in fts5Int.h.
17*/
18
19
20#include "fts5Int.h"
21
22/*
23** Overview:
24**
25** The %_data table contains all the FTS indexes for an FTS5 virtual table.
26** As well as the main term index, there may be up to 31 prefix indexes.
27** The format is similar to FTS3/4, except that:
28**
29** * all segment b-tree leaf data is stored in fixed size page records
30** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
31** taken to ensure it is possible to iterate in either direction through
32** the entries in a doclist, or to seek to a specific entry within a
33** doclist, without loading it into memory.
34**
35** * large doclists that span many pages have associated "doclist index"
36** records that contain a copy of the first rowid on each page spanned by
37** the doclist. This is used to speed up seek operations, and merges of
38** large doclists with very small doclists.
39**
40** * extra fields in the "structure record" record the state of ongoing
41** incremental merge operations.
42**
43*/
44
45
46#define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
47#define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
48
49#define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
50
51#define FTS5_MAIN_PREFIX '0'
52
53#if FTS5_MAX_PREFIX_INDEXES > 31
54# error "FTS5_MAX_PREFIX_INDEXES is too large"
55#endif
56
57#define FTS5_MAX_LEVEL 64
58
59/*
60** There are two versions of the format used for the structure record:
61**
62** 1. the legacy format, that may be read by all fts5 versions, and
63**
64** 2. the V2 format, which is used by contentless_delete=1 databases.
65**
66** Both begin with a 4-byte "configuration cookie" value. Then, a legacy
67** format structure record contains a varint - the number of levels in
68** the structure. Whereas a V2 structure record contains the constant
69** 4 bytes [0xff 0x00 0x00 0x01]. This is unambiguous as the value of a
70** varint has to be at least 16256 to begin with "0xFF". And the default
71** maximum number of levels is 64.
72**
73** See below for more on structure record formats.
74*/
75#define FTS5_STRUCTURE_V2 "\xFF\x00\x00\x01"
76
77/*
78** Details:
79**
80** The %_data table managed by this module,
81**
82** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
83**
84** , contains the following 6 types of records. See the comments surrounding
85** the FTS5_*_ROWID macros below for a description of how %_data rowids are
86** assigned to each fo them.
87**
88** 1. Structure Records:
89**
90** The set of segments that make up an index - the index structure - are
91** recorded in a single record within the %_data table. The record consists
92** of a single 32-bit configuration cookie value followed by a list of
93** SQLite varints.
94**
95** If the structure record is a V2 record, the configuration cookie is
96** followed by the following 4 bytes: [0xFF 0x00 0x00 0x01].
97**
98** Next, the record continues with three varints:
99**
100** + number of levels,
101** + total number of segments on all levels,
102** + value of write counter.
103**
104** Then, for each level from 0 to nMax:
105**
106** + number of input segments in ongoing merge.
107** + total number of segments in level.
108** + for each segment from oldest to newest:
109** + segment id (always > 0)
110** + first leaf page number (often 1, always greater than 0)
111** + final leaf page number
112**
113** Then, for V2 structures only:
114**
115** + lower origin counter value,
116** + upper origin counter value,
117** + the number of tombstone hash pages.
118**
119** 2. The Averages Record:
120**
121** A single record within the %_data table. The data is a list of varints.
122** The first value is the number of rows in the index. Then, for each column
123** from left to right, the total number of tokens in the column for all
124** rows of the table.
125**
126** 3. Segment leaves:
127**
128** TERM/DOCLIST FORMAT:
129**
130** Most of each segment leaf is taken up by term/doclist data. The
131** general format of term/doclist, starting with the first term
132** on the leaf page, is:
133**
134** varint : size of first term
135** blob: first term data
136** doclist: first doclist
137** zero-or-more {
138** varint: number of bytes in common with previous term
139** varint: number of bytes of new term data (nNew)
140** blob: nNew bytes of new term data
141** doclist: next doclist
142** }
143**
144** doclist format:
145**
146** varint: first rowid
147** poslist: first poslist
148** zero-or-more {
149** varint: rowid delta (always > 0)
150** poslist: next poslist
151** }
152**
153** poslist format:
154**
155** varint: size of poslist in bytes multiplied by 2, not including
156** this field. Plus 1 if this entry carries the "delete" flag.
157** collist: collist for column 0
158** zero-or-more {
159** 0x01 byte
160** varint: column number (I)
161** collist: collist for column I
162** }
163**
164** collist format:
165**
166** varint: first offset + 2
167** zero-or-more {
168** varint: offset delta + 2
169** }
170**
171** PAGE FORMAT
172**
173** Each leaf page begins with a 4-byte header containing 2 16-bit
174** unsigned integer fields in big-endian format. They are:
175**
176** * The byte offset of the first rowid on the page, if it exists
177** and occurs before the first term (otherwise 0).
178**
179** * The byte offset of the start of the page footer. If the page
180** footer is 0 bytes in size, then this field is the same as the
181** size of the leaf page in bytes.
182**
183** The page footer consists of a single varint for each term located
184** on the page. Each varint is the byte offset of the current term
185** within the page, delta-compressed against the previous value. In
186** other words, the first varint in the footer is the byte offset of
187** the first term, the second is the byte offset of the second less that
188** of the first, and so on.
189**
190** The term/doclist format described above is accurate if the entire
191** term/doclist data fits on a single leaf page. If this is not the case,
192** the format is changed in two ways:
193**
194** + if the first rowid on a page occurs before the first term, it
195** is stored as a literal value:
196**
197** varint: first rowid
198**
199** + the first term on each page is stored in the same way as the
200** very first term of the segment:
201**
202** varint : size of first term
203** blob: first term data
204**
205** 5. Segment doclist indexes:
206**
207** Doclist indexes are themselves b-trees, however they usually consist of
208** a single leaf record only. The format of each doclist index leaf page
209** is:
210**
211** * Flags byte. Bits are:
212** 0x01: Clear if leaf is also the root page, otherwise set.
213**
214** * Page number of fts index leaf page. As a varint.
215**
216** * First rowid on page indicated by previous field. As a varint.
217**
218** * A list of varints, one for each subsequent termless page. A
219** positive delta if the termless page contains at least one rowid,
220** or an 0x00 byte otherwise.
221**
222** Internal doclist index nodes are:
223**
224** * Flags byte. Bits are:
225** 0x01: Clear for root page, otherwise set.
226**
227** * Page number of first child page. As a varint.
228**
229** * Copy of first rowid on page indicated by previous field. As a varint.
230**
231** * A list of delta-encoded varints - the first rowid on each subsequent
232** child page.
233**
234** 6. Tombstone Hash Page
235**
236** These records are only ever present in contentless_delete=1 tables.
237** There are zero or more of these associated with each segment. They
238** are used to store the tombstone rowids for rows contained in the
239** associated segments.
240**
241** The set of nHashPg tombstone hash pages associated with a single
242** segment together form a single hash table containing tombstone rowids.
243** To find the page of the hash on which a key might be stored:
244**
245** iPg = (rowid % nHashPg)
246**
247** Then, within page iPg, which has nSlot slots:
248**
249** iSlot = (rowid / nHashPg) % nSlot
250**
251** Each tombstone hash page begins with an 8 byte header:
252**
253** 1-byte: Key-size (the size in bytes of each slot). Either 4 or 8.
254** 1-byte: rowid-0-tombstone flag. This flag is only valid on the
255** first tombstone hash page for each segment (iPg=0). If set,
256** the hash table contains rowid 0. If clear, it does not.
257** Rowid 0 is handled specially.
258** 2-bytes: unused.
259** 4-bytes: Big-endian integer containing number of entries on page.
260**
261** Following this are nSlot 4 or 8 byte slots (depending on the key-size
262** in the first byte of the page header). The number of slots may be
263** determined based on the size of the page record and the key-size:
264**
265** nSlot = (nByte - 8) / key-size
266*/
267
268/*
269** Rowids for the averages and structure records in the %_data table.
270*/
271#define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
272#define FTS5_STRUCTURE_ROWID 10 /* The structure record */
273
274/*
275** Macros determining the rowids used by segment leaves and dlidx leaves
276** and nodes. All nodes and leaves are stored in the %_data table with large
277** positive rowids.
278**
279** Each segment has a unique non-zero 16-bit id.
280**
281** The rowid for each segment leaf is found by passing the segment id and
282** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
283** sequentially starting from 1.
284*/
285#define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
286#define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
287#define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
288#define FTS5_DATA_PAGE_B 31 /* 31-bit page numbers */
289
290/* Maximum page number within a segment. Declare any structure read from
291** the database with a page number greater than this corrupt. It is not
292** actually possible to create a database this large. */
293#define FTS5_MAX_PGNO 0x7FFFFF00
294
295#define fts5_dri(segid, dlidx, height, pgno) ( \
296 ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
297 ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
298 ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
299 ((i64)(pgno)) \
300)
301
302#define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
303#define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
304#define FTS5_TOMBSTONE_ROWID(segid,ipg) fts5_dri(segid+(1<<16), 0, 0, ipg)
305
306#ifdef SQLITE_DEBUG
307int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
308#endif
309
310
311/*
312** Each time a blob is read from the %_data table, it is padded with this
313** many zero bytes. This makes it easier to decode the various record formats
314** without overreading if the records are corrupt.
315*/
316#define FTS5_DATA_ZERO_PADDING 8
317#define FTS5_DATA_PADDING 20
318
319typedef struct Fts5Data Fts5Data;
320typedef struct Fts5DlidxIter Fts5DlidxIter;
321typedef struct Fts5DlidxLvl Fts5DlidxLvl;
322typedef struct Fts5DlidxWriter Fts5DlidxWriter;
323typedef struct Fts5Iter Fts5Iter;
324typedef struct Fts5PageWriter Fts5PageWriter;
325typedef struct Fts5SegIter Fts5SegIter;
326typedef struct Fts5DoclistIter Fts5DoclistIter;
327typedef struct Fts5SegWriter Fts5SegWriter;
328typedef struct Fts5Structure Fts5Structure;
329typedef struct Fts5StructureLevel Fts5StructureLevel;
330typedef struct Fts5StructureSegment Fts5StructureSegment;
331typedef struct Fts5TokenDataIter Fts5TokenDataIter;
332typedef struct Fts5TokenDataMap Fts5TokenDataMap;
333typedef struct Fts5TombstoneArray Fts5TombstoneArray;
334
335struct Fts5Data {
336 u8 *p; /* Pointer to buffer containing record */
337 int nn; /* Size of record in bytes */
338 int szLeaf; /* Size of leaf without page-index */
339};
340
341/*
342** One object per %_data table.
343**
344** nContentlessDelete:
345** The number of contentless delete operations since the most recent
346** call to fts5IndexFlush() or fts5IndexDiscardData(). This is tracked
347** so that extra auto-merge work can be done by fts5IndexFlush() to
348** account for the delete operations.
349*/
350struct Fts5Index {
351 Fts5Config *pConfig; /* Virtual table configuration */
352 char *zDataTbl; /* Name of %_data table */
353 int nWorkUnit; /* Leaf pages in a "unit" of work */
354
355 /*
356 ** Variables related to the accumulation of tokens and doclists within the
357 ** in-memory hash tables before they are flushed to disk.
358 */
359 Fts5Hash *pHash; /* Hash table for in-memory data */
360 int nPendingData; /* Current bytes of pending data */
361 i64 iWriteRowid; /* Rowid for current doc being written */
362 int bDelete; /* Current write is a delete */
363 int nContentlessDelete; /* Number of contentless delete ops */
364 int nPendingRow; /* Number of INSERT in hash table */
365
366 /* Error state. */
367 int rc; /* Current error code */
368 int flushRc;
369
370 /* State used by the fts5DataXXX() functions. */
371 sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
372 sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
373 sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
374 sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
375 sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=?" */
376 sqlite3_stmt *pIdxSelect;
377 sqlite3_stmt *pIdxNextSelect;
378 int nRead; /* Total number of blocks read */
379
380 sqlite3_stmt *pDeleteFromIdx;
381
382 sqlite3_stmt *pDataVersion;
383 i64 iStructVersion; /* data_version when pStruct read */
384 Fts5Structure *pStruct; /* Current db structure (or NULL) */
385};
386
387struct Fts5DoclistIter {
388 u8 *aEof; /* Pointer to 1 byte past end of doclist */
389
390 /* Output variables. aPoslist==0 at EOF */
391 i64 iRowid;
392 u8 *aPoslist;
393 int nPoslist;
394 int nSize;
395};
396
397/*
398** The contents of the "structure" record for each index are represented
399** using an Fts5Structure record in memory. Which uses instances of the
400** other Fts5StructureXXX types as components.
401**
402** nOriginCntr:
403** This value is set to non-zero for structure records created for
404** contentlessdelete=1 tables only. In that case it represents the
405** origin value to apply to the next top-level segment created.
406*/
407struct Fts5StructureSegment {
408 int iSegid; /* Segment id */
409 int pgnoFirst; /* First leaf page number in segment */
410 int pgnoLast; /* Last leaf page number in segment */
411
412 /* contentlessdelete=1 tables only: */
413 u64 iOrigin1;
414 u64 iOrigin2;
415 int nPgTombstone; /* Number of tombstone hash table pages */
416 u64 nEntryTombstone; /* Number of tombstone entries that "count" */
417 u64 nEntry; /* Number of rows in this segment */
418};
419struct Fts5StructureLevel {
420 int nMerge; /* Number of segments in incr-merge */
421 int nSeg; /* Total number of segments on level */
422 Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
423};
424struct Fts5Structure {
425 int nRef; /* Object reference count */
426 u64 nWriteCounter; /* Total leaves written to level 0 */
427 u64 nOriginCntr; /* Origin value for next top-level segment */
428 int nSegment; /* Total segments in this structure */
429 int nLevel; /* Number of levels in this index */
430 Fts5StructureLevel aLevel[FLEXARRAY]; /* Array of nLevel level objects */
431};
432
433/* Size (in bytes) of an Fts5Structure object holding up to N levels */
434#define SZ_FTS5STRUCTURE(N) \
435 (offsetof(Fts5Structure,aLevel) + (N)*sizeof(Fts5StructureLevel))
436
437/*
438** An object of type Fts5SegWriter is used to write to segments.
439*/
440struct Fts5PageWriter {
441 int pgno; /* Page number for this page */
442 int iPrevPgidx; /* Previous value written into pgidx */
443 Fts5Buffer buf; /* Buffer containing leaf data */
444 Fts5Buffer pgidx; /* Buffer containing page-index */
445 Fts5Buffer term; /* Buffer containing previous term on page */
446};
447struct Fts5DlidxWriter {
448 int pgno; /* Page number for this page */
449 int bPrevValid; /* True if iPrev is valid */
450 i64 iPrev; /* Previous rowid value written to page */
451 Fts5Buffer buf; /* Buffer containing page data */
452};
453struct Fts5SegWriter {
454 int iSegid; /* Segid to write to */
455 Fts5PageWriter writer; /* PageWriter object */
456 i64 iPrevRowid; /* Previous rowid written to current leaf */
457 u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
458 u8 bFirstRowidInPage; /* True if next rowid is first in page */
459 /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
460 u8 bFirstTermInPage; /* True if next term will be first in leaf */
461 int nLeafWritten; /* Number of leaf pages written */
462 int nEmpty; /* Number of contiguous term-less nodes */
463
464 int nDlidx; /* Allocated size of aDlidx[] array */
465 Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
466
467 /* Values to insert into the %_idx table */
468 Fts5Buffer btterm; /* Next term to insert into %_idx table */
469 int iBtPage; /* Page number corresponding to btterm */
470};
471
472typedef struct Fts5CResult Fts5CResult;
473struct Fts5CResult {
474 u16 iFirst; /* aSeg[] index of firstest iterator */
475 u8 bTermEq; /* True if the terms are equal */
476};
477
478/*
479** Object for iterating through a single segment, visiting each term/rowid
480** pair in the segment.
481**
482** pSeg:
483** The segment to iterate through.
484**
485** iLeafPgno:
486** Current leaf page number within segment.
487**
488** iLeafOffset:
489** Byte offset within the current leaf that is the first byte of the
490** position list data (one byte passed the position-list size field).
491**
492** pLeaf:
493** Buffer containing current leaf page data. Set to NULL at EOF.
494**
495** iTermLeafPgno, iTermLeafOffset:
496** Leaf page number containing the last term read from the segment. And
497** the offset immediately following the term data.
498**
499** flags:
500** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
501**
502** FTS5_SEGITER_ONETERM:
503** If set, set the iterator to point to EOF after the current doclist
504** has been exhausted. Do not proceed to the next term in the segment.
505**
506** FTS5_SEGITER_REVERSE:
507** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
508** it is set, iterate through rowid in descending order instead of the
509** default ascending order.
510**
511** iRowidOffset/nRowidOffset/aRowidOffset:
512** These are used if the FTS5_SEGITER_REVERSE flag is set.
513**
514** For each rowid on the page corresponding to the current term, the
515** corresponding aRowidOffset[] entry is set to the byte offset of the
516** start of the "position-list-size" field within the page.
517**
518** iTermIdx:
519** Index of current term on iTermLeafPgno.
520**
521** apTombstone/nTombstone:
522** These are used for contentless_delete=1 tables only. When the cursor
523** is first allocated, the apTombstone[] array is allocated so that it
524** is large enough for all tombstones hash pages associated with the
525** segment. The pages themselves are loaded lazily from the database as
526** they are required.
527*/
528struct Fts5SegIter {
529 Fts5StructureSegment *pSeg; /* Segment to iterate through */
530 int flags; /* Mask of configuration flags */
531 int iLeafPgno; /* Current leaf page number */
532 Fts5Data *pLeaf; /* Current leaf data */
533 Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
534 i64 iLeafOffset; /* Byte offset within current leaf */
535 Fts5TombstoneArray *pTombArray; /* Array of tombstone pages */
536
537 /* Next method */
538 void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
539
540 /* The page and offset from which the current term was read. The offset
541 ** is the offset of the first rowid in the current doclist. */
542 int iTermLeafPgno;
543 int iTermLeafOffset;
544
545 int iPgidxOff; /* Next offset in pgidx */
546 int iEndofDoclist;
547
548 /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
549 int iRowidOffset; /* Current entry in aRowidOffset[] */
550 int nRowidOffset; /* Allocated size of aRowidOffset[] array */
551 int *aRowidOffset; /* Array of offset to rowid fields */
552
553 Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
554
555 /* Variables populated based on current entry. */
556 Fts5Buffer term; /* Current term */
557 i64 iRowid; /* Current rowid */
558 int nPos; /* Number of bytes in current position list */
559 u8 bDel; /* True if the delete flag is set */
560
561 /* True if the current entry shadows an entry that has the delete flag set */
562 u8 bDelDup;
563};
564
565static int fts5IndexCorruptRowid(Fts5Index *pIdx, i64 iRowid){
566 pIdx->rc = FTS5_CORRUPT;
567 sqlite3Fts5ConfigErrmsg(pIdx->pConfig,
568 "fts5: corruption found reading blob %lld from table \"%s\"",
569 iRowid, pIdx->pConfig->zName
570 );
571 return SQLITE_CORRUPT_VTAB;
572}
573#define FTS5_CORRUPT_ROWID(pIdx, iRowid) fts5IndexCorruptRowid(pIdx, iRowid)
574
575static int fts5IndexCorruptIter(Fts5Index *pIdx, Fts5SegIter *pIter){
576 pIdx->rc = FTS5_CORRUPT;
577 sqlite3Fts5ConfigErrmsg(pIdx->pConfig,
578 "fts5: corruption on page %d, segment %d, table \"%s\"",
579 pIter->iLeafPgno, pIter->pSeg->iSegid, pIdx->pConfig->zName
580 );
581 return SQLITE_CORRUPT_VTAB;
582}
583#define FTS5_CORRUPT_ITER(pIdx, pIter) fts5IndexCorruptIter(pIdx, pIter)
584
585static int fts5IndexCorruptIdx(Fts5Index *pIdx){
586 pIdx->rc = FTS5_CORRUPT;
587 sqlite3Fts5ConfigErrmsg(pIdx->pConfig,
588 "fts5: corruption in table \"%s\"", pIdx->pConfig->zName
589 );
590 return SQLITE_CORRUPT_VTAB;
591}
592#define FTS5_CORRUPT_IDX(pIdx) fts5IndexCorruptIdx(pIdx)
593
594
595/*
596** Array of tombstone pages. Reference counted.
597*/
598struct Fts5TombstoneArray {
599 int nRef; /* Number of pointers to this object */
600 int nTombstone;
601 Fts5Data *apTombstone[FLEXARRAY]; /* Array of tombstone pages */
602};
603
604/* Size (in bytes) of an Fts5TombstoneArray holding up to N tombstones */
605#define SZ_FTS5TOMBSTONEARRAY(N) \
606 (offsetof(Fts5TombstoneArray,apTombstone)+(N)*sizeof(Fts5Data*))
607
608/*
609** Argument is a pointer to an Fts5Data structure that contains a
610** leaf page.
611*/
612#define ASSERT_SZLEAF_OK(x) assert( \
613 (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
614)
615
616#define FTS5_SEGITER_ONETERM 0x01
617#define FTS5_SEGITER_REVERSE 0x02
618
619/*
620** Argument is a pointer to an Fts5Data structure that contains a leaf
621** page. This macro evaluates to true if the leaf contains no terms, or
622** false if it contains at least one term.
623*/
624#define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
625
626#define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
627
628#define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
629
630/*
631** Object for iterating through the merged results of one or more segments,
632** visiting each term/rowid pair in the merged data.
633**
634** nSeg is always a power of two greater than or equal to the number of
635** segments that this object is merging data from. Both the aSeg[] and
636** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
637** with zeroed objects - these are handled as if they were iterators opened
638** on empty segments.
639**
640** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
641** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
642** comparison in this context is the index of the iterator that currently
643** points to the smaller term/rowid combination. Iterators at EOF are
644** considered to be greater than all other iterators.
645**
646** aFirst[1] contains the index in aSeg[] of the iterator that points to
647** the smallest key overall. aFirst[0] is unused.
648**
649** poslist:
650** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
651** There is no way to tell if this is populated or not.
652**
653** pColset:
654** If not NULL, points to an object containing a set of column indices.
655** Only matches that occur in one of these columns will be returned.
656** The Fts5Iter does not own the Fts5Colset object, and so it is not
657** freed when the iterator is closed - it is owned by the upper layer.
658*/
659struct Fts5Iter {
660 Fts5IndexIter base; /* Base class containing output vars */
661 Fts5TokenDataIter *pTokenDataIter;
662
663 Fts5Index *pIndex; /* Index that owns this iterator */
664 Fts5Buffer poslist; /* Buffer containing current poslist */
665 Fts5Colset *pColset; /* Restrict matches to these columns */
666
667 /* Invoked to set output variables. */
668 void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
669
670 int nSeg; /* Size of aSeg[] array */
671 int bRev; /* True to iterate in reverse order */
672 u8 bSkipEmpty; /* True to skip deleted entries */
673
674 i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
675 Fts5CResult *aFirst; /* Current merge state (see above) */
676 Fts5SegIter aSeg[FLEXARRAY]; /* Array of segment iterators */
677};
678
679/* Size (in bytes) of an Fts5Iter object holding up to N segment iterators */
680#define SZ_FTS5ITER(N) (offsetof(Fts5Iter,aSeg)+(N)*sizeof(Fts5SegIter))
681
682/*
683** An instance of the following type is used to iterate through the contents
684** of a doclist-index record.
685**
686** pData:
687** Record containing the doclist-index data.
688**
689** bEof:
690** Set to true once iterator has reached EOF.
691**
692** iOff:
693** Set to the current offset within record pData.
694*/
695struct Fts5DlidxLvl {
696 Fts5Data *pData; /* Data for current page of this level */
697 int iOff; /* Current offset into pData */
698 int bEof; /* At EOF already */
699 int iFirstOff; /* Used by reverse iterators */
700
701 /* Output variables */
702 int iLeafPgno; /* Page number of current leaf page */
703 i64 iRowid; /* First rowid on leaf iLeafPgno */
704};
705struct Fts5DlidxIter {
706 int nLvl;
707 int iSegid;
708 Fts5DlidxLvl aLvl[FLEXARRAY];
709};
710
711/* Size (in bytes) of an Fts5DlidxIter object with up to N levels */
712#define SZ_FTS5DLIDXITER(N) \
713 (offsetof(Fts5DlidxIter,aLvl)+(N)*sizeof(Fts5DlidxLvl))
714
715static void fts5PutU16(u8 *aOut, u16 iVal){
716 aOut[0] = (iVal>>8);
717 aOut[1] = (iVal&0xFF);
718}
719
720static u16 fts5GetU16(const u8 *aIn){
721 return ((u16)aIn[0] << 8) + aIn[1];
722}
723
724/*
725** The only argument points to a buffer at least 8 bytes in size. This
726** function interprets the first 8 bytes of the buffer as a 64-bit big-endian
727** unsigned integer and returns the result.
728*/
729static u64 fts5GetU64(u8 *a){
730 return ((u64)a[0] << 56)
731 + ((u64)a[1] << 48)
732 + ((u64)a[2] << 40)
733 + ((u64)a[3] << 32)
734 + ((u64)a[4] << 24)
735 + ((u64)a[5] << 16)
736 + ((u64)a[6] << 8)
737 + ((u64)a[7] << 0);
738}
739
740/*
741** The only argument points to a buffer at least 4 bytes in size. This
742** function interprets the first 4 bytes of the buffer as a 32-bit big-endian
743** unsigned integer and returns the result.
744*/
745static u32 fts5GetU32(const u8 *a){
746 return ((u32)a[0] << 24)
747 + ((u32)a[1] << 16)
748 + ((u32)a[2] << 8)
749 + ((u32)a[3] << 0);
750}
751
752/*
753** Write iVal, formated as a 64-bit big-endian unsigned integer, to the
754** buffer indicated by the first argument.
755*/
756static void fts5PutU64(u8 *a, u64 iVal){
757 a[0] = ((iVal >> 56) & 0xFF);
758 a[1] = ((iVal >> 48) & 0xFF);
759 a[2] = ((iVal >> 40) & 0xFF);
760 a[3] = ((iVal >> 32) & 0xFF);
761 a[4] = ((iVal >> 24) & 0xFF);
762 a[5] = ((iVal >> 16) & 0xFF);
763 a[6] = ((iVal >> 8) & 0xFF);
764 a[7] = ((iVal >> 0) & 0xFF);
765}
766
767/*
768** Write iVal, formated as a 32-bit big-endian unsigned integer, to the
769** buffer indicated by the first argument.
770*/
771static void fts5PutU32(u8 *a, u32 iVal){
772 a[0] = ((iVal >> 24) & 0xFF);
773 a[1] = ((iVal >> 16) & 0xFF);
774 a[2] = ((iVal >> 8) & 0xFF);
775 a[3] = ((iVal >> 0) & 0xFF);
776}
777
778/*
779** Allocate and return a buffer at least nByte bytes in size.
780**
781** If an OOM error is encountered, return NULL and set the error code in
782** the Fts5Index handle passed as the first argument.
783*/
784static void *fts5IdxMalloc(Fts5Index *p, sqlite3_int64 nByte){
785 return sqlite3Fts5MallocZero(&p->rc, nByte);
786}
787
788/*
789** Compare the contents of the pLeft buffer with the pRight/nRight blob.
790**
791** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
792** +ve if pRight is smaller than pLeft. In other words:
793**
794** res = *pLeft - *pRight
795*/
796#ifdef SQLITE_DEBUG
797static int fts5BufferCompareBlob(
798 Fts5Buffer *pLeft, /* Left hand side of comparison */
799 const u8 *pRight, int nRight /* Right hand side of comparison */
800){
801 int nCmp = MIN(pLeft->n, nRight);
802 int res = memcmp(pLeft->p, pRight, nCmp);
803 return (res==0 ? (pLeft->n - nRight) : res);
804}
805#endif
806
807/*
808** Compare the contents of the two buffers using memcmp(). If one buffer
809** is a prefix of the other, it is considered the lesser.
810**
811** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
812** +ve if pRight is smaller than pLeft. In other words:
813**
814** res = *pLeft - *pRight
815*/
816static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
817 int nCmp, res;
818 nCmp = MIN(pLeft->n, pRight->n);
819 assert( nCmp<=0 || pLeft->p!=0 );
820 assert( nCmp<=0 || pRight->p!=0 );
821 res = fts5Memcmp(pLeft->p, pRight->p, nCmp);
822 return (res==0 ? (pLeft->n - pRight->n) : res);
823}
824
825static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
826 int ret;
827 fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
828 return ret;
829}
830
831/*
832** Close the read-only blob handle, if it is open.
833*/
834static void fts5IndexCloseReader(Fts5Index *p){
835 if( p->pReader ){
836 int rc;
837 sqlite3_blob *pReader = p->pReader;
838 p->pReader = 0;
839 rc = sqlite3_blob_close(pReader);
840 if( p->rc==SQLITE_OK ) p->rc = rc;
841 }
842}
843
844/*
845** Retrieve a record from the %_data table.
846**
847** If an error occurs, NULL is returned and an error left in the
848** Fts5Index object.
849*/
850static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
851 Fts5Data *pRet = 0;
852 if( p->rc==SQLITE_OK ){
853 int rc = SQLITE_OK;
854
855 if( p->pReader ){
856 /* This call may return SQLITE_ABORT if there has been a savepoint
857 ** rollback since it was last used. In this case a new blob handle
858 ** is required. */
859 sqlite3_blob *pBlob = p->pReader;
860 p->pReader = 0;
861 rc = sqlite3_blob_reopen(pBlob, iRowid);
862 assert( p->pReader==0 );
863 p->pReader = pBlob;
864 if( rc!=SQLITE_OK ){
865 fts5IndexCloseReader(p);
866 }
867 if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
868 }
869
870 /* If the blob handle is not open at this point, open it and seek
871 ** to the requested entry. */
872 if( p->pReader==0 && rc==SQLITE_OK ){
873 Fts5Config *pConfig = p->pConfig;
874 rc = sqlite3_blob_open(pConfig->db,
875 pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
876 );
877 }
878
879 /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
880 ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
881 ** All the reasons those functions might return SQLITE_ERROR - missing
882 ** table, missing row, non-blob/text in block column - indicate
883 ** backing store corruption. */
884 if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT_ROWID(p, iRowid);
885
886 if( rc==SQLITE_OK ){
887 u8 *aOut = 0; /* Read blob data into this buffer */
888 i64 nByte = sqlite3_blob_bytes(p->pReader);
889 i64 szData = (sizeof(Fts5Data) + 7) & ~7;
890 i64 nAlloc = szData + nByte + FTS5_DATA_PADDING;
891 pRet = (Fts5Data*)sqlite3_malloc64(nAlloc);
892 if( pRet ){
893 pRet->nn = nByte;
894 pRet->szLeaf = 0;
895 aOut = pRet->p = (u8*)pRet + szData;
896 }else{
897 rc = SQLITE_NOMEM;
898 }
899
900 if( rc==SQLITE_OK ){
901 rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
902 }
903 if( rc!=SQLITE_OK ){
904 sqlite3_free(pRet);
905 pRet = 0;
906 }else{
907 memset(&pRet->p[nByte], 0, FTS5_DATA_PADDING);
908 }
909 }
910 p->rc = rc;
911 p->nRead++;
912 }
913
914 assert( (pRet==0)==(p->rc!=SQLITE_OK) );
915 assert( pRet==0 || EIGHT_BYTE_ALIGNMENT( pRet->p ) );
916 return pRet;
917}
918
919
920/*
921** Release a reference to data record returned by an earlier call to
922** fts5DataRead().
923*/
924static void fts5DataRelease(Fts5Data *pData){
925 sqlite3_free(pData);
926}
927
928/*
929** Read a leaf-page record. This is similar to fts5DataRead(), except that
930** it fills in the Fts5Data.szLeaf value before returning.
931*/
932static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
933 Fts5Data *pRet = fts5DataRead(p, iRowid);
934 if( pRet ){
935 assert( pRet->szLeaf==0 );
936 if( pRet->nn>=4 ){
937 pRet->szLeaf = fts5GetU16(&pRet->p[2]);
938 }
939 if( pRet->szLeaf<4 || pRet->szLeaf>pRet->nn ){
940 FTS5_CORRUPT_ROWID(p, iRowid);
941 fts5DataRelease(pRet);
942 pRet = 0;
943 }
944 }
945 return pRet;
946}
947
948static int fts5IndexPrepareStmt(
949 Fts5Index *p,
950 sqlite3_stmt **ppStmt,
951 char *zSql
952){
953 if( p->rc==SQLITE_OK ){
954 if( zSql ){
955 int rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
956 SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB
957 |SQLITE_PREPARE_FROM_DDL,
958 ppStmt, 0);
959 /* If this prepare() call fails with SQLITE_ERROR, then one of the
960 ** %_idx or %_data tables has been removed or modified. Call this
961 ** corruption. */
962 p->rc = (rc==SQLITE_ERROR ? SQLITE_CORRUPT : rc);
963 }else{
964 p->rc = SQLITE_NOMEM;
965 }
966 }
967 sqlite3_free(zSql);
968 return p->rc;
969}
970
971/*
972** If *pRc is other than SQLITE_OK when this function is called, it is a
973** no-op. Otherwise, call sqlite3_step() and then sqlite3_reset() on the
974** supplied statement pointer. Set (*pRc) to the result of sqlite3_reset().
975*/
976static void fts5StepAndReset(int *pRc, sqlite3_stmt *pStmt){
977 if( *pRc==SQLITE_OK ){
978 sqlite3_step(pStmt);
979 *pRc = sqlite3_reset(pStmt);
980 }
981}
982
983/*
984** INSERT OR REPLACE a record into the %_data table.
985*/
986static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
987 if( p->rc!=SQLITE_OK ) return;
988
989 if( p->pWriter==0 ){
990 Fts5Config *pConfig = p->pConfig;
991 fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
992 "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
993 pConfig->zDb, pConfig->zName
994 ));
995 if( p->rc ) return;
996 }
997
998 sqlite3_bind_int64(p->pWriter, 1, iRowid);
999 p->rc = sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
1000 fts5StepAndReset(&p->rc, p->pWriter);
1001 sqlite3_bind_null(p->pWriter, 2);
1002}
1003
1004/*
1005** Execute the following SQL:
1006**
1007** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
1008*/
1009static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
1010 if( p->rc!=SQLITE_OK ) return;
1011
1012 if( p->pDeleter==0 ){
1013 Fts5Config *pConfig = p->pConfig;
1014 char *zSql = sqlite3_mprintf(
1015 "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
1016 pConfig->zDb, pConfig->zName
1017 );
1018 if( fts5IndexPrepareStmt(p, &p->pDeleter, zSql) ) return;
1019 }
1020
1021 sqlite3_bind_int64(p->pDeleter, 1, iFirst);
1022 sqlite3_bind_int64(p->pDeleter, 2, iLast);
1023 sqlite3_step(p->pDeleter);
1024 p->rc = sqlite3_reset(p->pDeleter);
1025}
1026
1027/*
1028** Remove all records associated with segment iSegid.
1029*/
1030static void fts5DataRemoveSegment(Fts5Index *p, Fts5StructureSegment *pSeg){
1031 int iSegid = pSeg->iSegid;
1032 i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
1033 i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
1034 fts5DataDelete(p, iFirst, iLast);
1035
1036 if( pSeg->nPgTombstone ){
1037 i64 iTomb1 = FTS5_TOMBSTONE_ROWID(iSegid, 0);
1038 i64 iTomb2 = FTS5_TOMBSTONE_ROWID(iSegid, pSeg->nPgTombstone-1);
1039 fts5DataDelete(p, iTomb1, iTomb2);
1040 }
1041 if( p->pIdxDeleter==0 ){
1042 Fts5Config *pConfig = p->pConfig;
1043 fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
1044 "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
1045 pConfig->zDb, pConfig->zName
1046 ));
1047 }
1048 if( p->rc==SQLITE_OK ){
1049 sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
1050 sqlite3_step(p->pIdxDeleter);
1051 p->rc = sqlite3_reset(p->pIdxDeleter);
1052 }
1053}
1054
1055/*
1056** Release a reference to an Fts5Structure object returned by an earlier
1057** call to fts5StructureRead() or fts5StructureDecode().
1058*/
1059static void fts5StructureRelease(Fts5Structure *pStruct){
1060 if( pStruct && 0>=(--pStruct->nRef) ){
1061 int i;
1062 assert( pStruct->nRef==0 );
1063 for(i=0; i<pStruct->nLevel; i++){
1064 sqlite3_free(pStruct->aLevel[i].aSeg);
1065 }
1066 sqlite3_free(pStruct);
1067 }
1068}
1069
1070static void fts5StructureRef(Fts5Structure *pStruct){
1071 pStruct->nRef++;
1072}
1073
1074void *sqlite3Fts5StructureRef(Fts5Index *p){
1075 fts5StructureRef(p->pStruct);
1076 return (void*)p->pStruct;
1077}
1078void sqlite3Fts5StructureRelease(void *p){
1079 if( p ){
1080 fts5StructureRelease((Fts5Structure*)p);
1081 }
1082}
1083int sqlite3Fts5StructureTest(Fts5Index *p, void *pStruct){
1084 if( p->pStruct!=(Fts5Structure*)pStruct ){
1085 return SQLITE_ABORT;
1086 }
1087 return SQLITE_OK;
1088}
1089
1090/*
1091** Ensure that structure object (*pp) is writable.
1092**
1093** This function is a no-op if (*pRc) is not SQLITE_OK when it is called. If
1094** an error occurs, (*pRc) is set to an SQLite error code before returning.
1095*/
1096static void fts5StructureMakeWritable(int *pRc, Fts5Structure **pp){
1097 Fts5Structure *p = *pp;
1098 if( *pRc==SQLITE_OK && p->nRef>1 ){
1099 i64 nByte = SZ_FTS5STRUCTURE(p->nLevel);
1100 Fts5Structure *pNew;
1101 pNew = (Fts5Structure*)sqlite3Fts5MallocZero(pRc, nByte);
1102 if( pNew ){
1103 int i;
1104 memcpy(pNew, p, nByte);
1105 for(i=0; i<p->nLevel; i++) pNew->aLevel[i].aSeg = 0;
1106 for(i=0; i<p->nLevel; i++){
1107 Fts5StructureLevel *pLvl = &pNew->aLevel[i];
1108 nByte = sizeof(Fts5StructureSegment) * pNew->aLevel[i].nSeg;
1109 pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(pRc, nByte);
1110 if( pLvl->aSeg==0 ){
1111 for(i=0; i<p->nLevel; i++){
1112 sqlite3_free(pNew->aLevel[i].aSeg);
1113 }
1114 sqlite3_free(pNew);
1115 return;
1116 }
1117 memcpy(pLvl->aSeg, p->aLevel[i].aSeg, nByte);
1118 }
1119 p->nRef--;
1120 pNew->nRef = 1;
1121 }
1122 *pp = pNew;
1123 }
1124}
1125
1126/*
1127** Deserialize and return the structure record currently stored in serialized
1128** form within buffer pData/nData.
1129**
1130** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
1131** are over-allocated by one slot. This allows the structure contents
1132** to be more easily edited.
1133**
1134** If an error occurs, *ppOut is set to NULL and an SQLite error code
1135** returned. Otherwise, *ppOut is set to point to the new object and
1136** SQLITE_OK returned.
1137*/
1138static int fts5StructureDecode(
1139 const u8 *pData, /* Buffer containing serialized structure */
1140 int nData, /* Size of buffer pData in bytes */
1141 int *piCookie, /* Configuration cookie value */
1142 Fts5Structure **ppOut /* OUT: Deserialized object */
1143){
1144 int rc = SQLITE_OK;
1145 int i = 0;
1146 int iLvl;
1147 int nLevel = 0;
1148 int nSegment = 0;
1149 sqlite3_int64 nByte; /* Bytes of space to allocate at pRet */
1150 Fts5Structure *pRet = 0; /* Structure object to return */
1151 int bStructureV2 = 0; /* True for FTS5_STRUCTURE_V2 */
1152 u64 nOriginCntr = 0; /* Largest origin value seen so far */
1153
1154 /* Grab the cookie value */
1155 if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
1156 i = 4;
1157
1158 /* Check if this is a V2 structure record. Set bStructureV2 if it is. */
1159 if( 0==memcmp(&pData[i], FTS5_STRUCTURE_V2, 4) ){
1160 i += 4;
1161 bStructureV2 = 1;
1162 }
1163
1164 /* Read the total number of levels and segments from the start of the
1165 ** structure record. */
1166 i += fts5GetVarint32(&pData[i], nLevel);
1167 i += fts5GetVarint32(&pData[i], nSegment);
1168 if( nLevel>FTS5_MAX_SEGMENT || nLevel<0
1169 || nSegment>FTS5_MAX_SEGMENT || nSegment<0
1170 ){
1171 return FTS5_CORRUPT;
1172 }
1173 nByte = SZ_FTS5STRUCTURE(nLevel);
1174 pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
1175
1176 if( pRet ){
1177 pRet->nRef = 1;
1178 pRet->nLevel = nLevel;
1179 pRet->nSegment = nSegment;
1180 i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
1181
1182 for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
1183 Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
1184 int nTotal = 0;
1185 int iSeg;
1186
1187 if( i>=nData ){
1188 rc = FTS5_CORRUPT;
1189 }else{
1190 i += fts5GetVarint32(&pData[i], pLvl->nMerge);
1191 i += fts5GetVarint32(&pData[i], nTotal);
1192 if( nTotal<pLvl->nMerge ) rc = FTS5_CORRUPT;
1193 pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
1194 (i64)nTotal * sizeof(Fts5StructureSegment)
1195 );
1196 nSegment -= nTotal;
1197 }
1198
1199 if( rc==SQLITE_OK ){
1200 pLvl->nSeg = nTotal;
1201 for(iSeg=0; iSeg<nTotal; iSeg++){
1202 Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
1203 if( i>=nData ){
1204 rc = FTS5_CORRUPT;
1205 break;
1206 }
1207 assert( pSeg!=0 );
1208 i += fts5GetVarint32(&pData[i], pSeg->iSegid);
1209 i += fts5GetVarint32(&pData[i], pSeg->pgnoFirst);
1210 i += fts5GetVarint32(&pData[i], pSeg->pgnoLast);
1211 if( bStructureV2 ){
1212 i += fts5GetVarint(&pData[i], &pSeg->iOrigin1);
1213 i += fts5GetVarint(&pData[i], &pSeg->iOrigin2);
1214 i += fts5GetVarint32(&pData[i], pSeg->nPgTombstone);
1215 i += fts5GetVarint(&pData[i], &pSeg->nEntryTombstone);
1216 i += fts5GetVarint(&pData[i], &pSeg->nEntry);
1217 nOriginCntr = MAX(nOriginCntr, pSeg->iOrigin2);
1218 }
1219 if( pSeg->pgnoLast<pSeg->pgnoFirst || pSeg->pgnoLast>FTS5_MAX_PGNO ){
1220 rc = FTS5_CORRUPT;
1221 break;
1222 }
1223 }
1224 if( iLvl>0 && pLvl[-1].nMerge && nTotal==0 ) rc = FTS5_CORRUPT;
1225 if( iLvl==nLevel-1 && pLvl->nMerge ) rc = FTS5_CORRUPT;
1226 }
1227 }
1228 if( nSegment!=0 && rc==SQLITE_OK ) rc = FTS5_CORRUPT;
1229 if( bStructureV2 ){
1230 pRet->nOriginCntr = nOriginCntr+1;
1231 }
1232
1233 if( rc!=SQLITE_OK ){
1234 fts5StructureRelease(pRet);
1235 pRet = 0;
1236 }
1237 }
1238
1239 *ppOut = pRet;
1240 return rc;
1241}
1242
1243/*
1244** Add a level to the Fts5Structure.aLevel[] array of structure object
1245** (*ppStruct).
1246*/
1247static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
1248 fts5StructureMakeWritable(pRc, ppStruct);
1249 assert( (ppStruct!=0 && (*ppStruct)!=0) || (*pRc)!=SQLITE_OK );
1250 if( *pRc==SQLITE_OK ){
1251 Fts5Structure *pStruct = *ppStruct;
1252 int nLevel = pStruct->nLevel;
1253 sqlite3_int64 nByte = SZ_FTS5STRUCTURE(nLevel+2);
1254
1255 pStruct = sqlite3_realloc64(pStruct, nByte);
1256 if( pStruct ){
1257 memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
1258 pStruct->nLevel++;
1259 *ppStruct = pStruct;
1260 }else{
1261 *pRc = SQLITE_NOMEM;
1262 }
1263 }
1264}
1265
1266/*
1267** Extend level iLvl so that there is room for at least nExtra more
1268** segments.
1269*/
1270static void fts5StructureExtendLevel(
1271 int *pRc,
1272 Fts5Structure *pStruct,
1273 int iLvl,
1274 int nExtra,
1275 int bInsert
1276){
1277 if( *pRc==SQLITE_OK ){
1278 Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
1279 Fts5StructureSegment *aNew;
1280 sqlite3_int64 nByte;
1281
1282 nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
1283 aNew = sqlite3_realloc64(pLvl->aSeg, nByte);
1284 if( aNew ){
1285 if( bInsert==0 ){
1286 memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
1287 }else{
1288 int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
1289 memmove(&aNew[nExtra], aNew, nMove);
1290 memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
1291 }
1292 pLvl->aSeg = aNew;
1293 }else{
1294 *pRc = SQLITE_NOMEM;
1295 }
1296 }
1297}
1298
1299static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
1300 Fts5Structure *pRet = 0;
1301 Fts5Config *pConfig = p->pConfig;
1302 int iCookie; /* Configuration cookie */
1303 Fts5Data *pData;
1304
1305 pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
1306 if( p->rc==SQLITE_OK ){
1307 /* TODO: Do we need this if the leaf-index is appended? Probably... */
1308 memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
1309 p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
1310 if( p->rc==SQLITE_OK ){
1311 if( (pConfig->pgsz==0 || pConfig->iCookie!=iCookie) ){
1312 p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
1313 }
1314 }else if( p->rc==SQLITE_CORRUPT_VTAB ){
1315 sqlite3Fts5ConfigErrmsg(p->pConfig,
1316 "fts5: corrupt structure record for table \"%s\"", p->pConfig->zName
1317 );
1318 }
1319 fts5DataRelease(pData);
1320 if( p->rc!=SQLITE_OK ){
1321 fts5StructureRelease(pRet);
1322 pRet = 0;
1323 }
1324 }
1325
1326 return pRet;
1327}
1328
1329static i64 fts5IndexDataVersion(Fts5Index *p){
1330 i64 iVersion = 0;
1331
1332 if( p->rc==SQLITE_OK ){
1333 if( p->pDataVersion==0 ){
1334 p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
1335 sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
1336 );
1337 if( p->rc ) return 0;
1338 }
1339
1340 if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
1341 iVersion = sqlite3_column_int64(p->pDataVersion, 0);
1342 }
1343 p->rc = sqlite3_reset(p->pDataVersion);
1344 }
1345
1346 return iVersion;
1347}
1348
1349/*
1350** Read, deserialize and return the structure record.
1351**
1352** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
1353** are over-allocated as described for function fts5StructureDecode()
1354** above.
1355**
1356** If an error occurs, NULL is returned and an error code left in the
1357** Fts5Index handle. If an error has already occurred when this function
1358** is called, it is a no-op.
1359*/
1360static Fts5Structure *fts5StructureRead(Fts5Index *p){
1361
1362 if( p->pStruct==0 ){
1363 p->iStructVersion = fts5IndexDataVersion(p);
1364 if( p->rc==SQLITE_OK ){
1365 p->pStruct = fts5StructureReadUncached(p);
1366 }
1367 }
1368
1369#if 0
1370 else{
1371 Fts5Structure *pTest = fts5StructureReadUncached(p);
1372 if( pTest ){
1373 int i, j;
1374 assert_nc( p->pStruct->nSegment==pTest->nSegment );
1375 assert_nc( p->pStruct->nLevel==pTest->nLevel );
1376 for(i=0; i<pTest->nLevel; i++){
1377 assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
1378 assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
1379 for(j=0; j<pTest->aLevel[i].nSeg; j++){
1380 Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
1381 Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
1382 assert_nc( p1->iSegid==p2->iSegid );
1383 assert_nc( p1->pgnoFirst==p2->pgnoFirst );
1384 assert_nc( p1->pgnoLast==p2->pgnoLast );
1385 }
1386 }
1387 fts5StructureRelease(pTest);
1388 }
1389 }
1390#endif
1391
1392 if( p->rc!=SQLITE_OK ) return 0;
1393 assert( p->iStructVersion!=0 );
1394 assert( p->pStruct!=0 );
1395 fts5StructureRef(p->pStruct);
1396 return p->pStruct;
1397}
1398
1399static void fts5StructureInvalidate(Fts5Index *p){
1400 if( p->pStruct ){
1401 fts5StructureRelease(p->pStruct);
1402 p->pStruct = 0;
1403 }
1404}
1405
1406/*
1407** Return the total number of segments in index structure pStruct. This
1408** function is only ever used as part of assert() conditions.
1409*/
1410#ifdef SQLITE_DEBUG
1411static int fts5StructureCountSegments(Fts5Structure *pStruct){
1412 int nSegment = 0; /* Total number of segments */
1413 if( pStruct ){
1414 int iLvl; /* Used to iterate through levels */
1415 for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
1416 nSegment += pStruct->aLevel[iLvl].nSeg;
1417 }
1418 }
1419
1420 return nSegment;
1421}
1422#endif
1423
1424#define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
1425 assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
1426 memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
1427 (pBuf)->n += nBlob; \
1428}
1429
1430#define fts5BufferSafeAppendVarint(pBuf, iVal) { \
1431 (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
1432 assert( (pBuf)->nSpace>=(pBuf)->n ); \
1433}
1434
1435
1436/*
1437** Serialize and store the "structure" record.
1438**
1439** If an error occurs, leave an error code in the Fts5Index object. If an
1440** error has already occurred, this function is a no-op.
1441*/
1442static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
1443 if( p->rc==SQLITE_OK ){
1444 Fts5Buffer buf; /* Buffer to serialize record into */
1445 int iLvl; /* Used to iterate through levels */
1446 int iCookie; /* Cookie value to store */
1447 int nHdr = (pStruct->nOriginCntr>0 ? (4+4+9+9+9) : (4+9+9));
1448
1449 assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
1450 memset(&buf, 0, sizeof(Fts5Buffer));
1451
1452 /* Append the current configuration cookie */
1453 iCookie = p->pConfig->iCookie;
1454 if( iCookie<0 ) iCookie = 0;
1455
1456 if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, nHdr) ){
1457 sqlite3Fts5Put32(buf.p, iCookie);
1458 buf.n = 4;
1459 if( pStruct->nOriginCntr>0 ){
1460 fts5BufferSafeAppendBlob(&buf, FTS5_STRUCTURE_V2, 4);
1461 }
1462 fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
1463 fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
1464 fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
1465 }
1466
1467 for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
1468 int iSeg; /* Used to iterate through segments */
1469 Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
1470 fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
1471 fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
1472 assert( pLvl->nMerge<=pLvl->nSeg );
1473
1474 for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
1475 Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
1476 fts5BufferAppendVarint(&p->rc, &buf, pSeg->iSegid);
1477 fts5BufferAppendVarint(&p->rc, &buf, pSeg->pgnoFirst);
1478 fts5BufferAppendVarint(&p->rc, &buf, pSeg->pgnoLast);
1479 if( pStruct->nOriginCntr>0 ){
1480 fts5BufferAppendVarint(&p->rc, &buf, pSeg->iOrigin1);
1481 fts5BufferAppendVarint(&p->rc, &buf, pSeg->iOrigin2);
1482 fts5BufferAppendVarint(&p->rc, &buf, pSeg->nPgTombstone);
1483 fts5BufferAppendVarint(&p->rc, &buf, pSeg->nEntryTombstone);
1484 fts5BufferAppendVarint(&p->rc, &buf, pSeg->nEntry);
1485 }
1486 }
1487 }
1488
1489 fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
1490 fts5BufferFree(&buf);
1491 }
1492}
1493
1494#if 0
1495static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
1496static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
1497 int rc = SQLITE_OK;
1498 Fts5Buffer buf;
1499 memset(&buf, 0, sizeof(buf));
1500 fts5DebugStructure(&rc, &buf, pStruct);
1501 fprintf(stdout, "%s: %s\n", zCaption, buf.p);
1502 fflush(stdout);
1503 fts5BufferFree(&buf);
1504}
1505#else
1506# define fts5PrintStructure(x,y)
1507#endif
1508
1509static int fts5SegmentSize(Fts5StructureSegment *pSeg){
1510 return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
1511}
1512
1513/*
1514** Return a copy of index structure pStruct. Except, promote as many
1515** segments as possible to level iPromote. If an OOM occurs, NULL is
1516** returned.
1517*/
1518static void fts5StructurePromoteTo(
1519 Fts5Index *p,
1520 int iPromote,
1521 int szPromote,
1522 Fts5Structure *pStruct
1523){
1524 int il, is;
1525 Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
1526
1527 if( pOut->nMerge==0 ){
1528 for(il=iPromote+1; il<pStruct->nLevel; il++){
1529 Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
1530 if( pLvl->nMerge ) return;
1531 for(is=pLvl->nSeg-1; is>=0; is--){
1532 int sz = fts5SegmentSize(&pLvl->aSeg[is]);
1533 if( sz>szPromote ) return;
1534 fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
1535 if( p->rc ) return;
1536 memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
1537 pOut->nSeg++;
1538 pLvl->nSeg--;
1539 }
1540 }
1541 }
1542}
1543
1544/*
1545** A new segment has just been written to level iLvl of index structure
1546** pStruct. This function determines if any segments should be promoted
1547** as a result. Segments are promoted in two scenarios:
1548**
1549** a) If the segment just written is smaller than one or more segments
1550** within the previous populated level, it is promoted to the previous
1551** populated level.
1552**
1553** b) If the segment just written is larger than the newest segment on
1554** the next populated level, then that segment, and any other adjacent
1555** segments that are also smaller than the one just written, are
1556** promoted.
1557**
1558** If one or more segments are promoted, the structure object is updated
1559** to reflect this.
1560*/
1561static void fts5StructurePromote(
1562 Fts5Index *p, /* FTS5 backend object */
1563 int iLvl, /* Index level just updated */
1564 Fts5Structure *pStruct /* Index structure */
1565){
1566 if( p->rc==SQLITE_OK ){
1567 int iTst;
1568 int iPromote = -1;
1569 int szPromote = 0; /* Promote anything this size or smaller */
1570 Fts5StructureSegment *pSeg; /* Segment just written */
1571 int szSeg; /* Size of segment just written */
1572 int nSeg = pStruct->aLevel[iLvl].nSeg;
1573
1574 if( nSeg==0 ) return;
1575 pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
1576 szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
1577
1578 /* Check for condition (a) */
1579 for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
1580 if( iTst>=0 ){
1581 int i;
1582 int szMax = 0;
1583 Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
1584 assert( pTst->nMerge==0 );
1585 for(i=0; i<pTst->nSeg; i++){
1586 int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
1587 if( sz>szMax ) szMax = sz;
1588 }
1589 if( szMax>=szSeg ){
1590 /* Condition (a) is true. Promote the newest segment on level
1591 ** iLvl to level iTst. */
1592 iPromote = iTst;
1593 szPromote = szMax;
1594 }
1595 }
1596
1597 /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
1598 ** is a no-op if it is not. */
1599 if( iPromote<0 ){
1600 iPromote = iLvl;
1601 szPromote = szSeg;
1602 }
1603 fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
1604 }
1605}
1606
1607/*
1608** Return the page number iPgno+nDelta. If this is larger than FTS5_MAX_PGNO,
1609** which can only happen if the doclist-index record is corrupt, return
1610** FTS5_MAX_PGNO+1 instead. No leaf page with that number may exist, so
1611** this causes the corruption to be detected when the caller attempts to
1612** use the page number.
1613*/
1614static int fts5AddPgno(int iPgno, int nDelta){
1615 i64 iRet = (i64)iPgno + nDelta;
1616 return (int)(iRet>FTS5_MAX_PGNO ? FTS5_MAX_PGNO+1 : iRet);
1617}
1618
1619/*
1620** Advance the iterator passed as the only argument. If the end of the
1621** doclist-index page is reached, return non-zero.
1622*/
1623static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
1624 Fts5Data *pData = pLvl->pData;
1625
1626 if( pLvl->iOff==0 ){
1627 assert( pLvl->bEof==0 );
1628 pLvl->iOff = 1;
1629 pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
1630 pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
1631 pLvl->iFirstOff = pLvl->iOff;
1632 }else{
1633 int iOff;
1634 for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
1635 if( pData->p[iOff] ) break;
1636 }
1637
1638 if( iOff<pData->nn ){
1639 u64 iVal;
1640 pLvl->iLeafPgno = fts5AddPgno(pLvl->iLeafPgno, iOff-pLvl->iOff+1);
1641 iOff += fts5GetVarint(&pData->p[iOff], &iVal);
1642 pLvl->iRowid += iVal;
1643 pLvl->iOff = iOff;
1644 }else{
1645 pLvl->bEof = 1;
1646 }
1647 }
1648
1649 return pLvl->bEof;
1650}
1651
1652/*
1653** Advance the iterator passed as the only argument.
1654*/
1655static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
1656 Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
1657
1658 assert( iLvl<pIter->nLvl );
1659 if( fts5DlidxLvlNext(pLvl) ){
1660 if( (iLvl+1) < pIter->nLvl ){
1661 fts5DlidxIterNextR(p, pIter, iLvl+1);
1662 if( pLvl[1].bEof==0 ){
1663 fts5DataRelease(pLvl->pData);
1664 memset(pLvl, 0, sizeof(Fts5DlidxLvl));
1665 pLvl->pData = fts5DataRead(p,
1666 FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
1667 );
1668 if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
1669 }
1670 }
1671 }
1672
1673 return pIter->aLvl[0].bEof;
1674}
1675static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
1676 return fts5DlidxIterNextR(p, pIter, 0);
1677}
1678
1679/*
1680** The iterator passed as the first argument has the following fields set
1681** as follows. This function sets up the rest of the iterator so that it
1682** points to the first rowid in the doclist-index.
1683**
1684** pData:
1685** pointer to doclist-index record,
1686**
1687** When this function is called pIter->iLeafPgno is the page number the
1688** doclist is associated with (the one featuring the term).
1689*/
1690static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
1691 int i;
1692 for(i=0; i<pIter->nLvl; i++){
1693 fts5DlidxLvlNext(&pIter->aLvl[i]);
1694 }
1695 return pIter->aLvl[0].bEof;
1696}
1697
1698
1699static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
1700 return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
1701}
1702
1703static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
1704 int i;
1705
1706 /* Advance each level to the last entry on the last page */
1707 for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
1708 Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
1709 while( fts5DlidxLvlNext(pLvl)==0 );
1710 pLvl->bEof = 0;
1711
1712 if( i>0 ){
1713 Fts5DlidxLvl *pChild = &pLvl[-1];
1714 fts5DataRelease(pChild->pData);
1715 memset(pChild, 0, sizeof(Fts5DlidxLvl));
1716 pChild->pData = fts5DataRead(p,
1717 FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
1718 );
1719 }
1720 }
1721}
1722
1723/*
1724** Move the iterator passed as the only argument to the previous entry.
1725*/
1726static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
1727 int iOff = pLvl->iOff;
1728
1729 assert( pLvl->bEof==0 );
1730 if( iOff<=pLvl->iFirstOff ){
1731 pLvl->bEof = 1;
1732 }else{
1733 u8 *a = pLvl->pData->p;
1734 int nn = pLvl->pData->nn;
1735
1736 pLvl->iOff = 0;
1737 fts5DlidxLvlNext(pLvl);
1738 while( 1 ){
1739 int nZero = 0;
1740 int ii = pLvl->iOff;
1741 u64 delta = 0;
1742
1743 while( ii<nn && a[ii]==0 ){
1744 nZero++;
1745 ii++;
1746 }
1747 ii += sqlite3Fts5GetVarint(&a[ii], &delta);
1748
1749 if( ii>=iOff ) break;
1750 pLvl->iLeafPgno = fts5AddPgno(pLvl->iLeafPgno, nZero+1);
1751 pLvl->iRowid += delta;
1752 pLvl->iOff = ii;
1753 }
1754 }
1755
1756 return pLvl->bEof;
1757}
1758
1759static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
1760 Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
1761
1762 assert( iLvl<pIter->nLvl );
1763 if( fts5DlidxLvlPrev(pLvl) ){
1764 if( (iLvl+1) < pIter->nLvl ){
1765 fts5DlidxIterPrevR(p, pIter, iLvl+1);
1766 if( pLvl[1].bEof==0 ){
1767 fts5DataRelease(pLvl->pData);
1768 memset(pLvl, 0, sizeof(Fts5DlidxLvl));
1769 pLvl->pData = fts5DataRead(p,
1770 FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
1771 );
1772 if( pLvl->pData ){
1773 while( fts5DlidxLvlNext(pLvl)==0 );
1774 pLvl->bEof = 0;
1775 }
1776 }
1777 }
1778 }
1779
1780 return pIter->aLvl[0].bEof;
1781}
1782static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
1783 return fts5DlidxIterPrevR(p, pIter, 0);
1784}
1785
1786/*
1787** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
1788*/
1789static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
1790 if( pIter ){
1791 int i;
1792 for(i=0; i<pIter->nLvl; i++){
1793 fts5DataRelease(pIter->aLvl[i].pData);
1794 }
1795 sqlite3_free(pIter);
1796 }
1797}
1798
1799static Fts5DlidxIter *fts5DlidxIterInit(
1800 Fts5Index *p, /* Fts5 Backend to iterate within */
1801 int bRev, /* True for ORDER BY ASC */
1802 int iSegid, /* Segment id */
1803 int iLeafPg /* Leaf page number to load dlidx for */
1804){
1805 Fts5DlidxIter *pIter = 0;
1806 int i;
1807 int bDone = 0;
1808
1809 for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
1810 sqlite3_int64 nByte = SZ_FTS5DLIDXITER(i+1);
1811 Fts5DlidxIter *pNew;
1812
1813 pNew = (Fts5DlidxIter*)sqlite3_realloc64(pIter, nByte);
1814 if( pNew==0 ){
1815 p->rc = SQLITE_NOMEM;
1816 }else{
1817 i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
1818 Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
1819 pIter = pNew;
1820 memset(pLvl, 0, sizeof(Fts5DlidxLvl));
1821 pLvl->pData = fts5DataRead(p, iRowid);
1822 if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
1823 bDone = 1;
1824 }
1825 pIter->nLvl = i+1;
1826 if( pIter->nLvl > (1<<FTS5_DATA_HEIGHT_B) ){
1827 p->rc = FTS5_CORRUPT;
1828 }
1829 }
1830 }
1831
1832 if( p->rc==SQLITE_OK ){
1833 pIter->iSegid = iSegid;
1834 if( bRev==0 ){
1835 fts5DlidxIterFirst(pIter);
1836 }else{
1837 fts5DlidxIterLast(p, pIter);
1838 }
1839 }
1840
1841 if( p->rc!=SQLITE_OK ){
1842 fts5DlidxIterFree(pIter);
1843 pIter = 0;
1844 }
1845
1846 return pIter;
1847}
1848
1849static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
1850 return pIter->aLvl[0].iRowid;
1851}
1852static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
1853 return pIter->aLvl[0].iLeafPgno;
1854}
1855
1856/*
1857** Load the next leaf page into the segment iterator.
1858*/
1859static void fts5SegIterNextPage(
1860 Fts5Index *p, /* FTS5 backend object */
1861 Fts5SegIter *pIter /* Iterator to advance to next page */
1862){
1863 Fts5Data *pLeaf;
1864 Fts5StructureSegment *pSeg = pIter->pSeg;
1865 fts5DataRelease(pIter->pLeaf);
1866 pIter->iLeafPgno++;
1867 if( pIter->pNextLeaf ){
1868 pIter->pLeaf = pIter->pNextLeaf;
1869 pIter->pNextLeaf = 0;
1870 }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
1871 pIter->pLeaf = fts5LeafRead(p,
1872 FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
1873 );
1874 }else{
1875 pIter->pLeaf = 0;
1876 }
1877 pLeaf = pIter->pLeaf;
1878
1879 if( pLeaf ){
1880 pIter->iPgidxOff = pLeaf->szLeaf;
1881 if( fts5LeafIsTermless(pLeaf) ){
1882 pIter->iEndofDoclist = pLeaf->nn+1;
1883 }else{
1884 pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
1885 pIter->iEndofDoclist
1886 );
1887 }
1888 }
1889}
1890
1891/*
1892** Argument p points to a buffer containing a varint to be interpreted as a
1893** position list size field. Read the varint and return the number of bytes
1894** read. Before returning, set *pnSz to the number of bytes in the position
1895** list, and *pbDel to true if the delete flag is set, or false otherwise.
1896*/
1897static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
1898 int nSz;
1899 int n = 0;
1900 fts5FastGetVarint32(p, n, nSz);
1901 assert_nc( nSz>=0 );
1902 *pnSz = nSz/2;
1903 *pbDel = nSz & 0x0001;
1904 return n;
1905}
1906
1907/*
1908** Fts5SegIter.iLeafOffset currently points to the first byte of a
1909** position-list size field. Read the value of the field and store it
1910** in the following variables:
1911**
1912** Fts5SegIter.nPos
1913** Fts5SegIter.bDel
1914**
1915** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
1916** position list content (if any).
1917*/
1918static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
1919 if( p->rc==SQLITE_OK ){
1920 int iOff = pIter->iLeafOffset; /* Offset to read at */
1921 ASSERT_SZLEAF_OK(pIter->pLeaf);
1922 if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
1923 int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
1924 pIter->bDel = 0;
1925 pIter->nPos = 1;
1926 if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
1927 pIter->bDel = 1;
1928 iOff++;
1929 if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
1930 pIter->nPos = 1;
1931 iOff++;
1932 }else{
1933 pIter->nPos = 0;
1934 }
1935 }
1936 }else{
1937 int nSz;
1938 fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
1939 pIter->bDel = (nSz & 0x0001);
1940 pIter->nPos = nSz>>1;
1941 assert_nc( pIter->nPos>=0 );
1942 }
1943 pIter->iLeafOffset = iOff;
1944 }
1945}
1946
1947static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
1948 u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
1949 i64 iOff = pIter->iLeafOffset;
1950
1951 ASSERT_SZLEAF_OK(pIter->pLeaf);
1952 while( iOff>=pIter->pLeaf->szLeaf ){
1953 fts5SegIterNextPage(p, pIter);
1954 if( pIter->pLeaf==0 ){
1955 if( p->rc==SQLITE_OK ) FTS5_CORRUPT_ITER(p, pIter);
1956 return;
1957 }
1958 iOff = 4;
1959 a = pIter->pLeaf->p;
1960 }
1961 iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
1962 pIter->iLeafOffset = iOff;
1963}
1964
1965/*
1966** Fts5SegIter.iLeafOffset currently points to the first byte of the
1967** "nSuffix" field of a term. Function parameter nKeep contains the value
1968** of the "nPrefix" field (if there was one - it is passed 0 if this is
1969** the first term in the segment).
1970**
1971** This function populates:
1972**
1973** Fts5SegIter.term
1974** Fts5SegIter.rowid
1975**
1976** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
1977** the first position list. The position list belonging to document
1978** (Fts5SegIter.iRowid).
1979*/
1980static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
1981 u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
1982 i64 iOff = pIter->iLeafOffset; /* Offset to read at */
1983 int nNew; /* Bytes of new data */
1984
1985 iOff += fts5GetVarint32(&a[iOff], nNew);
1986 if( iOff+nNew>pIter->pLeaf->szLeaf || nKeep>pIter->term.n || nNew==0 ){
1987 FTS5_CORRUPT_ITER(p, pIter);
1988 return;
1989 }
1990 pIter->term.n = nKeep;
1991 fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
1992 assert( pIter->term.n<=pIter->term.nSpace );
1993 iOff += nNew;
1994 pIter->iTermLeafOffset = iOff;
1995 pIter->iTermLeafPgno = pIter->iLeafPgno;
1996 pIter->iLeafOffset = iOff;
1997
1998 if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
1999 pIter->iEndofDoclist = pIter->pLeaf->nn+1;
2000 }else{
2001 int nExtra;
2002 pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
2003 pIter->iEndofDoclist += nExtra;
2004 }
2005
2006 fts5SegIterLoadRowid(p, pIter);
2007}
2008
2009static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
2010static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
2011static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
2012
2013static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
2014 if( pIter->flags & FTS5_SEGITER_REVERSE ){
2015 pIter->xNext = fts5SegIterNext_Reverse;
2016 }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
2017 pIter->xNext = fts5SegIterNext_None;
2018 }else{
2019 pIter->xNext = fts5SegIterNext;
2020 }
2021}
2022
2023/*
2024** Allocate a tombstone hash page array object (pIter->pTombArray) for
2025** the iterator passed as the second argument. If an OOM error occurs,
2026** leave an error in the Fts5Index object.
2027*/
2028static void fts5SegIterAllocTombstone(Fts5Index *p, Fts5SegIter *pIter){
2029 const i64 nTomb = (i64)pIter->pSeg->nPgTombstone;
2030 if( nTomb>0 ){
2031 i64 nByte = SZ_FTS5TOMBSTONEARRAY(nTomb+1);
2032 Fts5TombstoneArray *pNew;
2033 pNew = (Fts5TombstoneArray*)sqlite3Fts5MallocZero(&p->rc, nByte);
2034 if( pNew ){
2035 pNew->nTombstone = nTomb;
2036 pNew->nRef = 1;
2037 pIter->pTombArray = pNew;
2038 }
2039 }
2040}
2041
2042/*
2043** Initialize the iterator object pIter to iterate through the entries in
2044** segment pSeg. The iterator is left pointing to the first entry when
2045** this function returns.
2046**
2047** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
2048** an error has already occurred when this function is called, it is a no-op.
2049*/
2050static void fts5SegIterInit(
2051 Fts5Index *p, /* FTS index object */
2052 Fts5StructureSegment *pSeg, /* Description of segment */
2053 Fts5SegIter *pIter /* Object to populate */
2054){
2055 if( pSeg->pgnoFirst==0 ){
2056 /* This happens if the segment is being used as an input to an incremental
2057 ** merge and all data has already been "trimmed". See function
2058 ** fts5TrimSegments() for details. In this case leave the iterator empty.
2059 ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
2060 ** at EOF already. */
2061 assert( pIter->pLeaf==0 );
2062 return;
2063 }
2064
2065 if( p->rc==SQLITE_OK ){
2066 memset(pIter, 0, sizeof(*pIter));
2067 fts5SegIterSetNext(p, pIter);
2068 pIter->pSeg = pSeg;
2069 pIter->iLeafPgno = pSeg->pgnoFirst-1;
2070 do {
2071 fts5SegIterNextPage(p, pIter);
2072 }while( p->rc==SQLITE_OK && pIter->pLeaf && pIter->pLeaf->nn==4 );
2073 }
2074
2075 if( p->rc==SQLITE_OK && pIter->pLeaf ){
2076 pIter->iLeafOffset = 4;
2077 assert( pIter->pLeaf!=0 );
2078 assert_nc( pIter->pLeaf->nn>4 );
2079 assert_nc( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
2080 pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
2081 fts5SegIterLoadTerm(p, pIter, 0);
2082 fts5SegIterLoadNPos(p, pIter);
2083 fts5SegIterAllocTombstone(p, pIter);
2084 }
2085}
2086
2087/*
2088** This function is only ever called on iterators created by calls to
2089** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
2090**
2091** The iterator is in an unusual state when this function is called: the
2092** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
2093** the position-list size field for the first relevant rowid on the page.
2094** Fts5SegIter.rowid is set, but nPos and bDel are not.
2095**
2096** This function advances the iterator so that it points to the last
2097** relevant rowid on the page and, if necessary, initializes the
2098** aRowidOffset[] and iRowidOffset variables. At this point the iterator
2099** is in its regular state - Fts5SegIter.iLeafOffset points to the first
2100** byte of the position list content associated with said rowid.
2101*/
2102static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
2103 int eDetail = p->pConfig->eDetail;
2104 int n = pIter->pLeaf->szLeaf;
2105 int i = pIter->iLeafOffset;
2106 u8 *a = pIter->pLeaf->p;
2107 int iRowidOffset = 0;
2108
2109 if( n>pIter->iEndofDoclist ){
2110 n = pIter->iEndofDoclist;
2111 }
2112
2113 ASSERT_SZLEAF_OK(pIter->pLeaf);
2114 while( 1 ){
2115 u64 iDelta = 0;
2116
2117 if( i>=n ) break;
2118 if( eDetail==FTS5_DETAIL_NONE ){
2119 /* todo */
2120 if( i<n && a[i]==0 ){
2121 i++;
2122 if( i<n && a[i]==0 ) i++;
2123 }
2124 }else{
2125 int nPos;
2126 int bDummy;
2127 i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
2128 i += nPos;
2129 }
2130 if( i>=n ) break;
2131 i += fts5GetVarint(&a[i], &iDelta);
2132 pIter->iRowid += iDelta;
2133
2134 /* If necessary, grow the pIter->aRowidOffset[] array. */
2135 if( iRowidOffset>=pIter->nRowidOffset ){
2136 i64 nNew = pIter->nRowidOffset + 8;
2137 int *aNew = (int*)sqlite3_realloc64(pIter->aRowidOffset,nNew*sizeof(int));
2138 if( aNew==0 ){
2139 p->rc = SQLITE_NOMEM;
2140 break;
2141 }
2142 pIter->aRowidOffset = aNew;
2143 pIter->nRowidOffset = nNew;
2144 }
2145
2146 pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
2147 pIter->iLeafOffset = i;
2148 }
2149 pIter->iRowidOffset = iRowidOffset;
2150 fts5SegIterLoadNPos(p, pIter);
2151}
2152
2153/*
2154**
2155*/
2156static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
2157 assert( pIter->flags & FTS5_SEGITER_REVERSE );
2158 assert( pIter->flags & FTS5_SEGITER_ONETERM );
2159
2160 fts5DataRelease(pIter->pLeaf);
2161 pIter->pLeaf = 0;
2162 while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
2163 Fts5Data *pNew;
2164 pIter->iLeafPgno--;
2165 pNew = fts5LeafRead(p, FTS5_SEGMENT_ROWID(
2166 pIter->pSeg->iSegid, pIter->iLeafPgno
2167 ));
2168 if( pNew ){
2169 /* iTermLeafOffset may be equal to szLeaf if the term is the last
2170 ** thing on the page - i.e. the first rowid is on the following page.
2171 ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
2172 if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
2173 assert( pIter->pLeaf==0 );
2174 if( pIter->iTermLeafOffset<pNew->szLeaf ){
2175 pIter->pLeaf = pNew;
2176 pIter->iLeafOffset = pIter->iTermLeafOffset;
2177 }
2178 }else{
2179 int iRowidOff;
2180 iRowidOff = fts5LeafFirstRowidOff(pNew);
2181 if( iRowidOff ){
2182 if( iRowidOff>=pNew->szLeaf ){
2183 FTS5_CORRUPT_ITER(p, pIter);
2184 }else{
2185 pIter->pLeaf = pNew;
2186 pIter->iLeafOffset = iRowidOff;
2187 }
2188 }
2189 }
2190
2191 if( pIter->pLeaf ){
2192 u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
2193 pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
2194 break;
2195 }else{
2196 fts5DataRelease(pNew);
2197 }
2198 }
2199 }
2200
2201 if( pIter->pLeaf ){
2202 pIter->iEndofDoclist = pIter->pLeaf->nn+1;
2203 fts5SegIterReverseInitPage(p, pIter);
2204 }
2205}
2206
2207/*
2208** Return true if the iterator passed as the second argument currently
2209** points to a delete marker. A delete marker is an entry with a 0 byte
2210** position-list.
2211*/
2212static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
2213 Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
2214 return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
2215}
2216
2217/*
2218** Advance iterator pIter to the next entry.
2219**
2220** This version of fts5SegIterNext() is only used by reverse iterators.
2221*/
2222static void fts5SegIterNext_Reverse(
2223 Fts5Index *p, /* FTS5 backend object */
2224 Fts5SegIter *pIter, /* Iterator to advance */
2225 int *pbUnused /* Unused */
2226){
2227 assert( pIter->flags & FTS5_SEGITER_REVERSE );
2228 assert( pIter->pNextLeaf==0 );
2229 UNUSED_PARAM(pbUnused);
2230
2231 if( pIter->iRowidOffset>0 ){
2232 u8 *a = pIter->pLeaf->p;
2233 int iOff;
2234 u64 iDelta;
2235
2236 pIter->iRowidOffset--;
2237 pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
2238 fts5SegIterLoadNPos(p, pIter);
2239 iOff = pIter->iLeafOffset;
2240 if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
2241 iOff += pIter->nPos;
2242 }
2243 fts5GetVarint(&a[iOff], &iDelta);
2244 pIter->iRowid -= iDelta;
2245 }else{
2246 fts5SegIterReverseNewPage(p, pIter);
2247 }
2248}
2249
2250/*
2251** Advance iterator pIter to the next entry.
2252**
2253** This version of fts5SegIterNext() is only used if detail=none and the
2254** iterator is not a reverse direction iterator.
2255*/
2256static void fts5SegIterNext_None(
2257 Fts5Index *p, /* FTS5 backend object */
2258 Fts5SegIter *pIter, /* Iterator to advance */
2259 int *pbNewTerm /* OUT: Set for new term */
2260){
2261 int iOff;
2262
2263 assert( p->rc==SQLITE_OK );
2264 assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
2265 assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
2266
2267 ASSERT_SZLEAF_OK(pIter->pLeaf);
2268 iOff = pIter->iLeafOffset;
2269
2270 /* Next entry is on the next page */
2271 while( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
2272 fts5SegIterNextPage(p, pIter);
2273 if( p->rc || pIter->pLeaf==0 ) return;
2274 pIter->iRowid = 0;
2275 iOff = 4;
2276 }
2277
2278 if( iOff<pIter->iEndofDoclist ){
2279 /* Next entry is on the current page */
2280 u64 iDelta;
2281 iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
2282 pIter->iLeafOffset = iOff;
2283 pIter->iRowid += iDelta;
2284 }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
2285 if( pIter->pSeg ){
2286 int nKeep = 0;
2287 if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
2288 iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
2289 }
2290 pIter->iLeafOffset = iOff;
2291 fts5SegIterLoadTerm(p, pIter, nKeep);
2292 }else{
2293 const u8 *pList = 0;
2294 const char *zTerm = 0;
2295 int nTerm = 0;
2296 int nList;
2297 sqlite3Fts5HashScanNext(p->pHash);
2298 sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &nTerm, &pList, &nList);
2299 if( pList==0 ) goto next_none_eof;
2300 pIter->pLeaf->p = (u8*)pList;
2301 pIter->pLeaf->nn = nList;
2302 pIter->pLeaf->szLeaf = nList;
2303 pIter->iEndofDoclist = nList;
2304 sqlite3Fts5BufferSet(&p->rc,&pIter->term, nTerm, (u8*)zTerm);
2305 pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
2306 }
2307
2308 if( pbNewTerm ) *pbNewTerm = 1;
2309 }else{
2310 goto next_none_eof;
2311 }
2312
2313 fts5SegIterLoadNPos(p, pIter);
2314
2315 return;
2316 next_none_eof:
2317 fts5DataRelease(pIter->pLeaf);
2318 pIter->pLeaf = 0;
2319}
2320
2321
2322/*
2323** Advance iterator pIter to the next entry.
2324**
2325** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
2326** is not considered an error if the iterator reaches EOF. If an error has
2327** already occurred when this function is called, it is a no-op.
2328*/
2329static void fts5SegIterNext(
2330 Fts5Index *p, /* FTS5 backend object */
2331 Fts5SegIter *pIter, /* Iterator to advance */
2332 int *pbNewTerm /* OUT: Set for new term */
2333){
2334 Fts5Data *pLeaf = pIter->pLeaf;
2335 int iOff;
2336 int bNewTerm = 0;
2337 int nKeep = 0;
2338 u8 *a;
2339 int n;
2340
2341 assert( pbNewTerm==0 || *pbNewTerm==0 );
2342 assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
2343
2344 /* Search for the end of the position list within the current page. */
2345 a = pLeaf->p;
2346 n = pLeaf->szLeaf;
2347
2348 ASSERT_SZLEAF_OK(pLeaf);
2349 iOff = pIter->iLeafOffset + pIter->nPos;
2350
2351 if( iOff<n ){
2352 /* The next entry is on the current page. */
2353 assert_nc( iOff<=pIter->iEndofDoclist );
2354 if( iOff>=pIter->iEndofDoclist ){
2355 bNewTerm = 1;
2356 if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
2357 iOff += fts5GetVarint32(&a[iOff], nKeep);
2358 }
2359 }else{
2360 u64 iDelta;
2361 iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
2362 pIter->iRowid += iDelta;
2363 assert_nc( iDelta>0 );
2364 }
2365 pIter->iLeafOffset = iOff;
2366
2367 }else if( pIter->pSeg==0 ){
2368 const u8 *pList = 0;
2369 const char *zTerm = 0;
2370 int nTerm = 0;
2371 int nList = 0;
2372 assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
2373 if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
2374 sqlite3Fts5HashScanNext(p->pHash);
2375 sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &nTerm, &pList, &nList);
2376 }
2377 if( pList==0 ){
2378 fts5DataRelease(pIter->pLeaf);
2379 pIter->pLeaf = 0;
2380 }else{
2381 pIter->pLeaf->p = (u8*)pList;
2382 pIter->pLeaf->nn = nList;
2383 pIter->pLeaf->szLeaf = nList;
2384 pIter->iEndofDoclist = nList+1;
2385 sqlite3Fts5BufferSet(&p->rc, &pIter->term, nTerm, (u8*)zTerm);
2386 pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
2387 *pbNewTerm = 1;
2388 }
2389 }else{
2390 iOff = 0;
2391 /* Next entry is not on the current page */
2392 while( iOff==0 ){
2393 fts5SegIterNextPage(p, pIter);
2394 pLeaf = pIter->pLeaf;
2395 if( pLeaf==0 ) break;
2396 ASSERT_SZLEAF_OK(pLeaf);
2397 if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
2398 iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
2399 pIter->iLeafOffset = iOff;
2400
2401 if( pLeaf->nn>pLeaf->szLeaf ){
2402 pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
2403 &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
2404 );
2405 }
2406 }
2407 else if( pLeaf->nn>pLeaf->szLeaf ){
2408 pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
2409 &pLeaf->p[pLeaf->szLeaf], iOff
2410 );
2411 pIter->iLeafOffset = iOff;
2412 pIter->iEndofDoclist = iOff;
2413 bNewTerm = 1;
2414 }
2415 assert_nc( iOff<pLeaf->szLeaf );
2416 if( iOff>pLeaf->szLeaf ){
2417 FTS5_CORRUPT_ITER(p, pIter);
2418 return;
2419 }
2420 }
2421 }
2422
2423 /* Check if the iterator is now at EOF. If so, return early. */
2424 if( pIter->pLeaf ){
2425 if( bNewTerm ){
2426 if( pIter->flags & FTS5_SEGITER_ONETERM ){
2427 fts5DataRelease(pIter->pLeaf);
2428 pIter->pLeaf = 0;
2429 }else{
2430 fts5SegIterLoadTerm(p, pIter, nKeep);
2431 fts5SegIterLoadNPos(p, pIter);
2432 if( pbNewTerm ) *pbNewTerm = 1;
2433 }
2434 }else{
2435 /* The following could be done by calling fts5SegIterLoadNPos(). But
2436 ** this block is particularly performance critical, so equivalent
2437 ** code is inlined. */
2438 int nSz;
2439 assert_nc( pIter->iLeafOffset<=pIter->pLeaf->nn );
2440 fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
2441 pIter->bDel = (nSz & 0x0001);
2442 pIter->nPos = nSz>>1;
2443 assert_nc( pIter->nPos>=0 );
2444 }
2445 }
2446}
2447
2448#define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
2449
2450#define fts5IndexSkipVarint(a, iOff) { \
2451 int iEnd = iOff+9; \
2452 while( (a[iOff++] & 0x80) && iOff<iEnd ); \
2453}
2454
2455/*
2456** Iterator pIter currently points to the first rowid in a doclist. This
2457** function sets the iterator up so that iterates in reverse order through
2458** the doclist.
2459*/
2460static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
2461 Fts5DlidxIter *pDlidx = pIter->pDlidx;
2462 Fts5Data *pLast = 0;
2463 int pgnoLast = 0;
2464
2465 if( pDlidx && p->pConfig->iVersion==FTS5_CURRENT_VERSION ){
2466 int iSegid = pIter->pSeg->iSegid;
2467 pgnoLast = fts5DlidxIterPgno(pDlidx);
2468 pLast = fts5LeafRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
2469 }else{
2470 Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
2471
2472 /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
2473 ** position-list content for the current rowid. Back it up so that it
2474 ** points to the start of the position-list size field. */
2475 int iPoslist;
2476 if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
2477 iPoslist = pIter->iTermLeafOffset;
2478 }else{
2479 iPoslist = 4;
2480 }
2481 fts5IndexSkipVarint(pLeaf->p, iPoslist);
2482 pIter->iLeafOffset = iPoslist;
2483
2484 /* If this condition is true then the largest rowid for the current
2485 ** term may not be stored on the current page. So search forward to
2486 ** see where said rowid really is. */
2487 if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
2488 int pgno;
2489 Fts5StructureSegment *pSeg = pIter->pSeg;
2490
2491 /* The last rowid in the doclist may not be on the current page. Search
2492 ** forward to find the page containing the last rowid. */
2493 for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
2494 i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
2495 Fts5Data *pNew = fts5LeafRead(p, iAbs);
2496 if( pNew ){
2497 int iRowid, bTermless;
2498 iRowid = fts5LeafFirstRowidOff(pNew);
2499 bTermless = fts5LeafIsTermless(pNew);
2500 if( iRowid ){
2501 SWAPVAL(Fts5Data*, pNew, pLast);
2502 pgnoLast = pgno;
2503 }
2504 fts5DataRelease(pNew);
2505 if( bTermless==0 ) break;
2506 }
2507 }
2508 }
2509 }
2510
2511 /* If pLast is NULL at this point, then the last rowid for this doclist
2512 ** lies on the page currently indicated by the iterator. In this case
2513 ** pIter->iLeafOffset is already set to point to the position-list size
2514 ** field associated with the first relevant rowid on the page.
2515 **
2516 ** Or, if pLast is non-NULL, then it is the page that contains the last
2517 ** rowid. In this case configure the iterator so that it points to the
2518 ** first rowid on this page.
2519 */
2520 if( pLast ){
2521 int iOff;
2522 fts5DataRelease(pIter->pLeaf);
2523 pIter->pLeaf = pLast;
2524 pIter->iLeafPgno = pgnoLast;
2525 if( p->rc==SQLITE_OK ){
2526 iOff = fts5LeafFirstRowidOff(pLast);
2527 if( iOff>pLast->szLeaf ){
2528 FTS5_CORRUPT_ITER(p, pIter);
2529 return;
2530 }
2531 iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
2532 pIter->iLeafOffset = iOff;
2533
2534 if( fts5LeafIsTermless(pLast) ){
2535 pIter->iEndofDoclist = pLast->nn+1;
2536 }else{
2537 pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
2538 }
2539 }
2540 }
2541
2542 fts5SegIterReverseInitPage(p, pIter);
2543}
2544
2545/*
2546** Iterator pIter currently points to the first rowid of a doclist.
2547** There is a doclist-index associated with the final term on the current
2548** page. If the current term is the last term on the page, load the
2549** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
2550*/
2551static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
2552 int iSeg = pIter->pSeg->iSegid;
2553 int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
2554 Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
2555
2556 assert( pIter->flags & FTS5_SEGITER_ONETERM );
2557 assert( pIter->pDlidx==0 );
2558
2559 /* Check if the current doclist ends on this page. If it does, return
2560 ** early without loading the doclist-index (as it belongs to a different
2561 ** term. */
2562 if( pIter->iTermLeafPgno==pIter->iLeafPgno
2563 && pIter->iEndofDoclist<pLeaf->szLeaf
2564 ){
2565 return;
2566 }
2567
2568 pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
2569}
2570
2571/*
2572** The iterator object passed as the second argument currently contains
2573** no valid values except for the Fts5SegIter.pLeaf member variable. This
2574** function searches the leaf page for a term matching (pTerm/nTerm).
2575**
2576** If the specified term is found on the page, then the iterator is left
2577** pointing to it. If argument bGe is zero and the term is not found,
2578** the iterator is left pointing at EOF.
2579**
2580** If bGe is non-zero and the specified term is not found, then the
2581** iterator is left pointing to the smallest term in the segment that
2582** is larger than the specified term, even if this term is not on the
2583** current page.
2584*/
2585static void fts5LeafSeek(
2586 Fts5Index *p, /* Leave any error code here */
2587 int bGe, /* True for a >= search */
2588 Fts5SegIter *pIter, /* Iterator to seek */
2589 const u8 *pTerm, int nTerm /* Term to search for */
2590){
2591 u32 iOff;
2592 const u8 *a = pIter->pLeaf->p;
2593 u32 n = (u32)pIter->pLeaf->nn;
2594
2595 u32 nMatch = 0;
2596 u32 nKeep = 0;
2597 u32 nNew = 0;
2598 u32 iTermOff;
2599 u32 iPgidx; /* Current offset in pgidx */
2600 int bEndOfPage = 0;
2601
2602 assert( p->rc==SQLITE_OK );
2603
2604 iPgidx = (u32)pIter->pLeaf->szLeaf;
2605 iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
2606 iOff = iTermOff;
2607 if( iOff>n ){
2608 FTS5_CORRUPT_ITER(p, pIter);
2609 return;
2610 }
2611
2612 while( 1 ){
2613
2614 /* Figure out how many new bytes are in this term */
2615 fts5FastGetVarint32(a, iOff, nNew);
2616 if( nKeep<nMatch ){
2617 goto search_failed;
2618 }
2619 if( (iOff+nNew)>n ){
2620 FTS5_CORRUPT_ITER(p, pIter);
2621 return;
2622 }
2623
2624 assert( nKeep>=nMatch );
2625 if( nKeep==nMatch ){
2626 u32 nCmp;
2627 u32 i;
2628 nCmp = (u32)MIN(nNew, nTerm-nMatch);
2629 for(i=0; i<nCmp; i++){
2630 if( a[iOff+i]!=pTerm[nMatch+i] ) break;
2631 }
2632 nMatch += i;
2633
2634 if( (u32)nTerm==nMatch ){
2635 if( i==nNew ){
2636 goto search_success;
2637 }else{
2638 goto search_failed;
2639 }
2640 }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
2641 goto search_failed;
2642 }
2643 }
2644
2645 if( iPgidx>=n ){
2646 bEndOfPage = 1;
2647 break;
2648 }
2649
2650 iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
2651 iTermOff += nKeep;
2652 iOff = iTermOff;
2653
2654 if( iOff>=n ){
2655 FTS5_CORRUPT_ITER(p, pIter);
2656 return;
2657 }
2658
2659 /* Read the nKeep field of the next term. */
2660 fts5FastGetVarint32(a, iOff, nKeep);
2661 }
2662
2663 search_failed:
2664 if( bGe==0 ){
2665 fts5DataRelease(pIter->pLeaf);
2666 pIter->pLeaf = 0;
2667 return;
2668 }else if( bEndOfPage ){
2669 do {
2670 fts5SegIterNextPage(p, pIter);
2671 if( pIter->pLeaf==0 ) return;
2672 a = pIter->pLeaf->p;
2673 if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
2674 iPgidx = (u32)pIter->pLeaf->szLeaf;
2675 iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
2676 if( iOff<4 || (i64)iOff>=pIter->pLeaf->szLeaf ){
2677 FTS5_CORRUPT_ITER(p, pIter);
2678 return;
2679 }else{
2680 nKeep = 0;
2681 iTermOff = iOff;
2682 n = (u32)pIter->pLeaf->nn;
2683 iOff += fts5GetVarint32(&a[iOff], nNew);
2684 break;
2685 }
2686 }
2687 }while( 1 );
2688 }
2689
2690 search_success:
2691 if( (i64)iOff+nNew>n || nNew<1 ){
2692 FTS5_CORRUPT_ITER(p, pIter);
2693 return;
2694 }
2695 pIter->iLeafOffset = iOff + nNew;
2696 pIter->iTermLeafOffset = pIter->iLeafOffset;
2697 pIter->iTermLeafPgno = pIter->iLeafPgno;
2698
2699 fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
2700 fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
2701
2702 if( iPgidx>=n ){
2703 pIter->iEndofDoclist = pIter->pLeaf->nn+1;
2704 }else{
2705 int nExtra;
2706 iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
2707 pIter->iEndofDoclist = iTermOff + nExtra;
2708 }
2709 pIter->iPgidxOff = iPgidx;
2710
2711 fts5SegIterLoadRowid(p, pIter);
2712 fts5SegIterLoadNPos(p, pIter);
2713}
2714
2715static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
2716 if( p->pIdxSelect==0 ){
2717 Fts5Config *pConfig = p->pConfig;
2718 fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
2719 "SELECT pgno FROM '%q'.'%q_idx' WHERE "
2720 "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
2721 pConfig->zDb, pConfig->zName
2722 ));
2723 }
2724 return p->pIdxSelect;
2725}
2726
2727/*
2728** Initialize the object pIter to point to term pTerm/nTerm within segment
2729** pSeg. If there is no such term in the index, the iterator is set to EOF.
2730**
2731** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
2732** an error has already occurred when this function is called, it is a no-op.
2733*/
2734static void fts5SegIterSeekInit(
2735 Fts5Index *p, /* FTS5 backend */
2736 const u8 *pTerm, int nTerm, /* Term to seek to */
2737 int flags, /* Mask of FTS5INDEX_XXX flags */
2738 Fts5StructureSegment *pSeg, /* Description of segment */
2739 Fts5SegIter *pIter /* Object to populate */
2740){
2741 int iPg = 1;
2742 int bGe = (flags & FTS5INDEX_QUERY_SCAN);
2743 int bDlidx = 0; /* True if there is a doclist-index */
2744 sqlite3_stmt *pIdxSelect = 0;
2745
2746 assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
2747 assert( pTerm && nTerm );
2748 memset(pIter, 0, sizeof(*pIter));
2749 pIter->pSeg = pSeg;
2750
2751 /* This block sets stack variable iPg to the leaf page number that may
2752 ** contain term (pTerm/nTerm), if it is present in the segment. */
2753 pIdxSelect = fts5IdxSelectStmt(p);
2754 if( p->rc ) return;
2755 sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
2756 p->rc = sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
2757 if( p->rc ) return;
2758 if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
2759 i64 val = sqlite3_column_int(pIdxSelect, 0);
2760 iPg = (int)(val>>1);
2761 bDlidx = (val & 0x0001);
2762 }
2763 p->rc = sqlite3_reset(pIdxSelect);
2764 sqlite3_bind_null(pIdxSelect, 2);
2765
2766 if( iPg<pSeg->pgnoFirst ){
2767 iPg = pSeg->pgnoFirst;
2768 bDlidx = 0;
2769 }
2770
2771 pIter->iLeafPgno = iPg - 1;
2772 fts5SegIterNextPage(p, pIter);
2773
2774 if( pIter->pLeaf ){
2775 fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
2776 }
2777
2778 if( p->rc==SQLITE_OK && (bGe==0 || (flags & FTS5INDEX_QUERY_SCANONETERM)) ){
2779 pIter->flags |= FTS5_SEGITER_ONETERM;
2780 if( pIter->pLeaf ){
2781 if( flags & FTS5INDEX_QUERY_DESC ){
2782 pIter->flags |= FTS5_SEGITER_REVERSE;
2783 }
2784 if( bDlidx && iPg==pIter->iTermLeafPgno ){
2785 fts5SegIterLoadDlidx(p, pIter);
2786 }
2787 if( flags & FTS5INDEX_QUERY_DESC ){
2788 fts5SegIterReverse(p, pIter);
2789 }
2790 }
2791 }
2792
2793 fts5SegIterSetNext(p, pIter);
2794 if( 0==(flags & FTS5INDEX_QUERY_SCANONETERM) ){
2795 fts5SegIterAllocTombstone(p, pIter);
2796 }
2797
2798 /* Either:
2799 **
2800 ** 1) an error has occurred, or
2801 ** 2) the iterator points to EOF, or
2802 ** 3) the iterator points to an entry with term (pTerm/nTerm), or
2803 ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
2804 ** to an entry with a term greater than or equal to (pTerm/nTerm).
2805 */
2806 assert_nc( p->rc!=SQLITE_OK /* 1 */
2807 || pIter->pLeaf==0 /* 2 */
2808 || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
2809 || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
2810 );
2811}
2812
2813
2814/*
2815** SQL used by fts5SegIterNextInit() to find the page to open.
2816*/
2817static sqlite3_stmt *fts5IdxNextStmt(Fts5Index *p){
2818 if( p->pIdxNextSelect==0 ){
2819 Fts5Config *pConfig = p->pConfig;
2820 fts5IndexPrepareStmt(p, &p->pIdxNextSelect, sqlite3_mprintf(
2821 "SELECT pgno FROM '%q'.'%q_idx' WHERE "
2822 "segid=? AND term>? ORDER BY term ASC LIMIT 1",
2823 pConfig->zDb, pConfig->zName
2824 ));
2825
2826 }
2827 return p->pIdxNextSelect;
2828}
2829
2830/*
2831** This is similar to fts5SegIterSeekInit(), except that it initializes
2832** the segment iterator to point to the first term following the page
2833** with pToken/nToken on it.
2834*/
2835static void fts5SegIterNextInit(
2836 Fts5Index *p,
2837 const char *pTerm, int nTerm,
2838 Fts5StructureSegment *pSeg, /* Description of segment */
2839 Fts5SegIter *pIter /* Object to populate */
2840){
2841 int iPg = -1; /* Page of segment to open */
2842 int bDlidx = 0;
2843 sqlite3_stmt *pSel = 0; /* SELECT to find iPg */
2844
2845 pSel = fts5IdxNextStmt(p);
2846 if( pSel ){
2847 assert( p->rc==SQLITE_OK );
2848 sqlite3_bind_int(pSel, 1, pSeg->iSegid);
2849 p->rc = sqlite3_bind_blob(pSel, 2, pTerm, nTerm, SQLITE_STATIC);
2850 if( p->rc ) return;
2851 if( sqlite3_step(pSel)==SQLITE_ROW ){
2852 i64 val = sqlite3_column_int64(pSel, 0);
2853 iPg = (int)(val>>1);
2854 bDlidx = (val & 0x0001);
2855 }
2856 p->rc = sqlite3_reset(pSel);
2857 sqlite3_bind_null(pSel, 2);
2858 if( p->rc ) return;
2859 }
2860
2861 memset(pIter, 0, sizeof(*pIter));
2862 pIter->pSeg = pSeg;
2863 pIter->flags |= FTS5_SEGITER_ONETERM;
2864 if( iPg>=0 ){
2865 pIter->iLeafPgno = iPg - 1;
2866 fts5SegIterNextPage(p, pIter);
2867 fts5SegIterSetNext(p, pIter);
2868 }
2869 if( pIter->pLeaf ){
2870 const u8 *a = pIter->pLeaf->p;
2871 int iTermOff = 0;
2872
2873 pIter->iPgidxOff = pIter->pLeaf->szLeaf;
2874 pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], iTermOff);
2875 if( iTermOff > pIter->pLeaf->szLeaf ){
2876 p->rc = FTS5_CORRUPT;
2877 return;
2878 }
2879 pIter->iLeafOffset = iTermOff;
2880 fts5SegIterLoadTerm(p, pIter, 0);
2881 fts5SegIterLoadNPos(p, pIter);
2882 if( bDlidx ) fts5SegIterLoadDlidx(p, pIter);
2883
2884 assert( p->rc!=SQLITE_OK ||
2885 fts5BufferCompareBlob(&pIter->term, (const u8*)pTerm, nTerm)>0
2886 );
2887 }
2888}
2889
2890/*
2891** Initialize the object pIter to point to term pTerm/nTerm within the
2892** in-memory hash table. If there is no such term in the hash-table, the
2893** iterator is set to EOF.
2894**
2895** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
2896** an error has already occurred when this function is called, it is a no-op.
2897*/
2898static void fts5SegIterHashInit(
2899 Fts5Index *p, /* FTS5 backend */
2900 const u8 *pTerm, int nTerm, /* Term to seek to */
2901 int flags, /* Mask of FTS5INDEX_XXX flags */
2902 Fts5SegIter *pIter /* Object to populate */
2903){
2904 int nList = 0;
2905 const u8 *z = 0;
2906 int n = 0;
2907 Fts5Data *pLeaf = 0;
2908
2909 assert( p->pHash );
2910 assert( p->rc==SQLITE_OK );
2911
2912 if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
2913 const u8 *pList = 0;
2914
2915 p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
2916 sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &n, &pList, &nList);
2917 if( pList ){
2918 pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
2919 if( pLeaf ){
2920 pLeaf->p = (u8*)pList;
2921 }
2922 }
2923
2924 /* The call to sqlite3Fts5HashScanInit() causes the hash table to
2925 ** fill the size field of all existing position lists. This means they
2926 ** can no longer be appended to. Since the only scenario in which they
2927 ** can be appended to is if the previous operation on this table was
2928 ** a DELETE, by clearing the Fts5Index.bDelete flag we can avoid this
2929 ** possibility altogether. */
2930 p->bDelete = 0;
2931 }else{
2932 p->rc = sqlite3Fts5HashQuery(p->pHash, sizeof(Fts5Data),
2933 (const char*)pTerm, nTerm, (void**)&pLeaf, &nList
2934 );
2935 if( pLeaf ){
2936 pLeaf->p = (u8*)&pLeaf[1];
2937 }
2938 z = pTerm;
2939 n = nTerm;
2940 pIter->flags |= FTS5_SEGITER_ONETERM;
2941 }
2942
2943 if( pLeaf ){
2944 sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
2945 pLeaf->nn = pLeaf->szLeaf = nList;
2946 pIter->pLeaf = pLeaf;
2947 pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
2948 pIter->iEndofDoclist = pLeaf->nn;
2949
2950 if( flags & FTS5INDEX_QUERY_DESC ){
2951 pIter->flags |= FTS5_SEGITER_REVERSE;
2952 fts5SegIterReverseInitPage(p, pIter);
2953 }else{
2954 fts5SegIterLoadNPos(p, pIter);
2955 }
2956 }
2957
2958 fts5SegIterSetNext(p, pIter);
2959}
2960
2961/*
2962** Array ap[] contains n elements. Release each of these elements using
2963** fts5DataRelease(). Then free the array itself using sqlite3_free().
2964*/
2965static void fts5IndexFreeArray(Fts5Data **ap, int n){
2966 if( ap ){
2967 int ii;
2968 for(ii=0; ii<n; ii++){
2969 fts5DataRelease(ap[ii]);
2970 }
2971 sqlite3_free(ap);
2972 }
2973}
2974
2975/*
2976** Decrement the ref-count of the object passed as the only argument. If it
2977** reaches 0, free it and its contents.
2978*/
2979static void fts5TombstoneArrayDelete(Fts5TombstoneArray *p){
2980 if( p ){
2981 p->nRef--;
2982 if( p->nRef<=0 ){
2983 int ii;
2984 for(ii=0; ii<p->nTombstone; ii++){
2985 fts5DataRelease(p->apTombstone[ii]);
2986 }
2987 sqlite3_free(p);
2988 }
2989 }
2990}
2991
2992/*
2993** Zero the iterator passed as the only argument.
2994*/
2995static void fts5SegIterClear(Fts5SegIter *pIter){
2996 fts5BufferFree(&pIter->term);
2997 fts5DataRelease(pIter->pLeaf);
2998 fts5DataRelease(pIter->pNextLeaf);
2999 fts5TombstoneArrayDelete(pIter->pTombArray);
3000 fts5DlidxIterFree(pIter->pDlidx);
3001 sqlite3_free(pIter->aRowidOffset);
3002 memset(pIter, 0, sizeof(Fts5SegIter));
3003}
3004
3005#ifdef SQLITE_DEBUG
3006
3007/*
3008** This function is used as part of the big assert() procedure implemented by
3009** fts5AssertMultiIterSetup(). It ensures that the result currently stored
3010** in *pRes is the correct result of comparing the current positions of the
3011** two iterators.
3012*/
3013static void fts5AssertComparisonResult(
3014 Fts5Iter *pIter,
3015 Fts5SegIter *p1,
3016 Fts5SegIter *p2,
3017 Fts5CResult *pRes
3018){
3019 int i1 = p1 - pIter->aSeg;
3020 int i2 = p2 - pIter->aSeg;
3021
3022 if( p1->pLeaf || p2->pLeaf ){
3023 if( p1->pLeaf==0 ){
3024 assert( pRes->iFirst==i2 );
3025 }else if( p2->pLeaf==0 ){
3026 assert( pRes->iFirst==i1 );
3027 }else{
3028 int nMin = MIN(p1->term.n, p2->term.n);
3029 int res = fts5Memcmp(p1->term.p, p2->term.p, nMin);
3030 if( res==0 ) res = p1->term.n - p2->term.n;
3031
3032 if( res==0 ){
3033 assert( pRes->bTermEq==1 );
3034 assert( p1->iRowid!=p2->iRowid );
3035 res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
3036 }else{
3037 assert( pRes->bTermEq==0 );
3038 }
3039
3040 if( res<0 ){
3041 assert( pRes->iFirst==i1 );
3042 }else{
3043 assert( pRes->iFirst==i2 );
3044 }
3045 }
3046 }
3047}
3048
3049/*
3050** This function is a no-op unless SQLITE_DEBUG is defined when this module
3051** is compiled. In that case, this function is essentially an assert()
3052** statement used to verify that the contents of the pIter->aFirst[] array
3053** are correct.
3054*/
3055static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
3056 if( p->rc==SQLITE_OK ){
3057 Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
3058 int i;
3059
3060 assert( (pFirst->pLeaf==0)==pIter->base.bEof );
3061
3062 /* Check that pIter->iSwitchRowid is set correctly. */
3063 for(i=0; i<pIter->nSeg; i++){
3064 Fts5SegIter *p1 = &pIter->aSeg[i];
3065 assert( p1==pFirst
3066 || p1->pLeaf==0
3067 || fts5BufferCompare(&pFirst->term, &p1->term)
3068 || p1->iRowid==pIter->iSwitchRowid
3069 || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
3070 );
3071 }
3072
3073 for(i=0; i<pIter->nSeg; i+=2){
3074 Fts5SegIter *p1 = &pIter->aSeg[i];
3075 Fts5SegIter *p2 = &pIter->aSeg[i+1];
3076 Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
3077 fts5AssertComparisonResult(pIter, p1, p2, pRes);
3078 }
3079
3080 for(i=1; i<(pIter->nSeg / 2); i+=2){
3081 Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
3082 Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
3083 Fts5CResult *pRes = &pIter->aFirst[i];
3084 fts5AssertComparisonResult(pIter, p1, p2, pRes);
3085 }
3086 }
3087}
3088#else
3089# define fts5AssertMultiIterSetup(x,y)
3090#endif
3091
3092/*
3093** Do the comparison necessary to populate pIter->aFirst[iOut].
3094**
3095** If the returned value is non-zero, then it is the index of an entry
3096** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
3097** to a key that is a duplicate of another, higher priority,
3098** segment-iterator in the pSeg->aSeg[] array.
3099*/
3100static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
3101 int i1; /* Index of left-hand Fts5SegIter */
3102 int i2; /* Index of right-hand Fts5SegIter */
3103 int iRes;
3104 Fts5SegIter *p1; /* Left-hand Fts5SegIter */
3105 Fts5SegIter *p2; /* Right-hand Fts5SegIter */
3106 Fts5CResult *pRes = &pIter->aFirst[iOut];
3107
3108 assert( iOut<pIter->nSeg && iOut>0 );
3109 assert( pIter->bRev==0 || pIter->bRev==1 );
3110
3111 if( iOut>=(pIter->nSeg/2) ){
3112 i1 = (iOut - pIter->nSeg/2) * 2;
3113 i2 = i1 + 1;
3114 }else{
3115 i1 = pIter->aFirst[iOut*2].iFirst;
3116 i2 = pIter->aFirst[iOut*2+1].iFirst;
3117 }
3118 p1 = &pIter->aSeg[i1];
3119 p2 = &pIter->aSeg[i2];
3120
3121 pRes->bTermEq = 0;
3122 if( p1->pLeaf==0 ){ /* If p1 is at EOF */
3123 iRes = i2;
3124 }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
3125 iRes = i1;
3126 }else{
3127 int res = fts5BufferCompare(&p1->term, &p2->term);
3128 if( res==0 ){
3129 assert_nc( i2>i1 );
3130 assert_nc( i2!=0 );
3131 pRes->bTermEq = 1;
3132 if( p1->iRowid==p2->iRowid ){
3133 /* p2 is about to be advanced past this entry. If it, or an entry
3134 ** it shadowed, has the delete flag set, record this on p1. */
3135 p1->bDelDup |= (p2->bDel | p2->bDelDup);
3136 p2->bDelDup = 0;
3137 return i2;
3138 }
3139 res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
3140 }
3141 assert( res!=0 );
3142 if( res<0 ){
3143 iRes = i1;
3144 }else{
3145 iRes = i2;
3146 }
3147 }
3148
3149 pRes->iFirst = (u16)iRes;
3150 return 0;
3151}
3152
3153/*
3154** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
3155** It is an error if leaf iLeafPgno does not exist. Unless the db is
3156** a 'secure-delete' db, if it contains no rowids then this is also an error.
3157*/
3158static void fts5SegIterGotoPage(
3159 Fts5Index *p, /* FTS5 backend object */
3160 Fts5SegIter *pIter, /* Iterator to advance */
3161 int iLeafPgno
3162){
3163 assert( iLeafPgno>pIter->iLeafPgno );
3164
3165 if( iLeafPgno>pIter->pSeg->pgnoLast ){
3166 FTS5_CORRUPT_IDX(p);
3167 }else{
3168 fts5DataRelease(pIter->pNextLeaf);
3169 pIter->pNextLeaf = 0;
3170 pIter->iLeafPgno = iLeafPgno-1;
3171
3172 while( p->rc==SQLITE_OK ){
3173 int iOff;
3174 fts5SegIterNextPage(p, pIter);
3175 if( pIter->pLeaf==0 ) break;
3176 iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
3177 if( iOff>0 ){
3178 u8 *a = pIter->pLeaf->p;
3179 int n = pIter->pLeaf->szLeaf;
3180 if( iOff<4 || iOff>=n ){
3181 FTS5_CORRUPT_IDX(p);
3182 }else{
3183 iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
3184 pIter->iLeafOffset = iOff;
3185 fts5SegIterLoadNPos(p, pIter);
3186 }
3187 break;
3188 }else if( !fts5LeafIsTermless(pIter->pLeaf) ){
3189 /* There are no rowids on this page, but there is another term.
3190 ** Since there are no more rowids for the current term, set the
3191 ** iterator to EOF. */
3192 fts5DataRelease(pIter->pLeaf);
3193 pIter->pLeaf = 0;
3194 break;
3195 }
3196 }
3197 }
3198}
3199
3200/*
3201** Advance the iterator passed as the second argument until it is at or
3202** past rowid iFrom. Regardless of the value of iFrom, the iterator is
3203** always advanced at least once.
3204*/
3205static void fts5SegIterNextFrom(
3206 Fts5Index *p, /* FTS5 backend object */
3207 Fts5SegIter *pIter, /* Iterator to advance */
3208 i64 iMatch /* Advance iterator at least this far */
3209){
3210 int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
3211 Fts5DlidxIter *pDlidx = pIter->pDlidx;
3212 int iLeafPgno = pIter->iLeafPgno;
3213 int bMove = 1;
3214
3215 assert( pIter->flags & FTS5_SEGITER_ONETERM );
3216 assert( pIter->pDlidx );
3217 assert( pIter->pLeaf );
3218
3219 if( bRev==0 ){
3220 while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
3221 iLeafPgno = fts5DlidxIterPgno(pDlidx);
3222 fts5DlidxIterNext(p, pDlidx);
3223 }
3224 assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
3225 if( iLeafPgno>pIter->iLeafPgno ){
3226 fts5SegIterGotoPage(p, pIter, iLeafPgno);
3227 bMove = 0;
3228 }
3229 }else{
3230 assert( pIter->pNextLeaf==0 );
3231 assert( iMatch<pIter->iRowid );
3232 while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
3233 fts5DlidxIterPrev(p, pDlidx);
3234 }
3235 iLeafPgno = fts5DlidxIterPgno(pDlidx);
3236
3237 assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
3238
3239 if( iLeafPgno<pIter->iLeafPgno ){
3240 pIter->iLeafPgno = iLeafPgno+1;
3241 fts5SegIterReverseNewPage(p, pIter);
3242 bMove = 0;
3243 }
3244 }
3245
3246 do{
3247 if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
3248 if( pIter->pLeaf==0 ) break;
3249 if( bRev==0 && pIter->iRowid>=iMatch ) break;
3250 if( bRev!=0 && pIter->iRowid<=iMatch ) break;
3251 bMove = 1;
3252 }while( p->rc==SQLITE_OK );
3253}
3254
3255/*
3256** Free the iterator object passed as the second argument.
3257*/
3258static void fts5MultiIterFree(Fts5Iter *pIter){
3259 if( pIter ){
3260 int i;
3261 for(i=0; i<pIter->nSeg; i++){
3262 fts5SegIterClear(&pIter->aSeg[i]);
3263 }
3264 fts5BufferFree(&pIter->poslist);
3265 sqlite3_free(pIter);
3266 }
3267}
3268
3269static void fts5MultiIterAdvanced(
3270 Fts5Index *p, /* FTS5 backend to iterate within */
3271 Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
3272 int iChanged, /* Index of sub-iterator just advanced */
3273 int iMinset /* Minimum entry in aFirst[] to set */
3274){
3275 int i;
3276 for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
3277 int iEq;
3278 if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
3279 Fts5SegIter *pSeg = &pIter->aSeg[iEq];
3280 assert( p->rc==SQLITE_OK );
3281 pSeg->xNext(p, pSeg, 0);
3282 i = pIter->nSeg + iEq;
3283 }
3284 }
3285}
3286
3287/*
3288** Sub-iterator iChanged of iterator pIter has just been advanced. It still
3289** points to the same term though - just a different rowid. This function
3290** attempts to update the contents of the pIter->aFirst[] accordingly.
3291** If it does so successfully, 0 is returned. Otherwise 1.
3292**
3293** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
3294** on the iterator instead. That function does the same as this one, except
3295** that it deals with more complicated cases as well.
3296*/
3297static int fts5MultiIterAdvanceRowid(
3298 Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
3299 int iChanged, /* Index of sub-iterator just advanced */
3300 Fts5SegIter **ppFirst
3301){
3302 Fts5SegIter *pNew = &pIter->aSeg[iChanged];
3303
3304 if( pNew->iRowid==pIter->iSwitchRowid
3305 || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
3306 ){
3307 int i;
3308 Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
3309 pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
3310 for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
3311 Fts5CResult *pRes = &pIter->aFirst[i];
3312
3313 assert( pNew->pLeaf );
3314 assert( pRes->bTermEq==0 || pOther->pLeaf );
3315
3316 if( pRes->bTermEq ){
3317 if( pNew->iRowid==pOther->iRowid ){
3318 return 1;
3319 }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
3320 pIter->iSwitchRowid = pOther->iRowid;
3321 pNew = pOther;
3322 }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
3323 pIter->iSwitchRowid = pOther->iRowid;
3324 }
3325 }
3326 pRes->iFirst = (u16)(pNew - pIter->aSeg);
3327 if( i==1 ) break;
3328
3329 pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
3330 }
3331 }
3332
3333 *ppFirst = pNew;
3334 return 0;
3335}
3336
3337/*
3338** Set the pIter->bEof variable based on the state of the sub-iterators.
3339*/
3340static void fts5MultiIterSetEof(Fts5Iter *pIter){
3341 Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
3342 pIter->base.bEof = pSeg->pLeaf==0;
3343 pIter->iSwitchRowid = pSeg->iRowid;
3344}
3345
3346/*
3347** The argument to this macro must be an Fts5Data structure containing a
3348** tombstone hash page. This macro returns the key-size of the hash-page.
3349*/
3350#define TOMBSTONE_KEYSIZE(pPg) (pPg->p[0]==4 ? 4 : 8)
3351
3352#define TOMBSTONE_NSLOT(pPg) \
3353 ((pPg->nn > 16) ? ((pPg->nn-8) / TOMBSTONE_KEYSIZE(pPg)) : 1)
3354
3355/*
3356** Query a single tombstone hash table for rowid iRowid. Return true if
3357** it is found or false otherwise. The tombstone hash table is one of
3358** nHashTable tables.
3359*/
3360static int fts5IndexTombstoneQuery(
3361 Fts5Data *pHash, /* Hash table page to query */
3362 int nHashTable, /* Number of pages attached to segment */
3363 u64 iRowid /* Rowid to query hash for */
3364){
3365 const int szKey = TOMBSTONE_KEYSIZE(pHash);
3366 const int nSlot = TOMBSTONE_NSLOT(pHash);
3367 int iSlot = (iRowid / nHashTable) % nSlot;
3368 int nCollide = nSlot;
3369
3370 if( iRowid==0 ){
3371 return pHash->p[1];
3372 }else if( szKey==4 ){
3373 u32 *aSlot = (u32*)&pHash->p[8];
3374 while( aSlot[iSlot] ){
3375 if( fts5GetU32((u8*)&aSlot[iSlot])==iRowid ) return 1;
3376 if( nCollide--==0 ) break;
3377 iSlot = (iSlot+1)%nSlot;
3378 }
3379 }else{
3380 u64 *aSlot = (u64*)&pHash->p[8];
3381 while( aSlot[iSlot] ){
3382 if( fts5GetU64((u8*)&aSlot[iSlot])==iRowid ) return 1;
3383 if( nCollide--==0 ) break;
3384 iSlot = (iSlot+1)%nSlot;
3385 }
3386 }
3387
3388 return 0;
3389}
3390
3391/*
3392** Return true if the iterator passed as the only argument points
3393** to an segment entry for which there is a tombstone. Return false
3394** if there is no tombstone or if the iterator is already at EOF.
3395*/
3396static int fts5MultiIterIsDeleted(Fts5Iter *pIter){
3397 int iFirst = pIter->aFirst[1].iFirst;
3398 Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
3399 Fts5TombstoneArray *pArray = pSeg->pTombArray;
3400
3401 if( pSeg->pLeaf && pArray ){
3402 /* Figure out which page the rowid might be present on. */
3403 int iPg = ((u64)pSeg->iRowid) % pArray->nTombstone;
3404 assert( iPg>=0 );
3405
3406 /* If tombstone hash page iPg has not yet been loaded from the
3407 ** database, load it now. */
3408 if( pArray->apTombstone[iPg]==0 ){
3409 pArray->apTombstone[iPg] = fts5DataRead(pIter->pIndex,
3410 FTS5_TOMBSTONE_ROWID(pSeg->pSeg->iSegid, iPg)
3411 );
3412 if( pArray->apTombstone[iPg]==0 ) return 0;
3413 }
3414
3415 return fts5IndexTombstoneQuery(
3416 pArray->apTombstone[iPg],
3417 pArray->nTombstone,
3418 pSeg->iRowid
3419 );
3420 }
3421
3422 return 0;
3423}
3424
3425/*
3426** Move the iterator to the next entry.
3427**
3428** If an error occurs, an error code is left in Fts5Index.rc. It is not
3429** considered an error if the iterator reaches EOF, or if it is already at
3430** EOF when this function is called.
3431*/
3432static void fts5MultiIterNext(
3433 Fts5Index *p,
3434 Fts5Iter *pIter,
3435 int bFrom, /* True if argument iFrom is valid */
3436 i64 iFrom /* Advance at least as far as this */
3437){
3438 int bUseFrom = bFrom;
3439 assert( pIter->base.bEof==0 );
3440 while( p->rc==SQLITE_OK ){
3441 int iFirst = pIter->aFirst[1].iFirst;
3442 int bNewTerm = 0;
3443 Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
3444 assert( p->rc==SQLITE_OK );
3445 if( bUseFrom && pSeg->pDlidx ){
3446 fts5SegIterNextFrom(p, pSeg, iFrom);
3447 }else{
3448 pSeg->xNext(p, pSeg, &bNewTerm);
3449 }
3450
3451 if( pSeg->pLeaf==0 || bNewTerm
3452 || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
3453 ){
3454 fts5MultiIterAdvanced(p, pIter, iFirst, 1);
3455 fts5MultiIterSetEof(pIter);
3456 pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
3457 if( pSeg->pLeaf==0 ) return;
3458 }
3459
3460 fts5AssertMultiIterSetup(p, pIter);
3461 assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
3462 if( (pIter->bSkipEmpty==0 || pSeg->nPos)
3463 && 0==fts5MultiIterIsDeleted(pIter)
3464 ){
3465 pIter->xSetOutputs(pIter, pSeg);
3466 return;
3467 }
3468 bUseFrom = 0;
3469 }
3470}
3471
3472static void fts5MultiIterNext2(
3473 Fts5Index *p,
3474 Fts5Iter *pIter,
3475 int *pbNewTerm /* OUT: True if *might* be new term */
3476){
3477 assert( pIter->bSkipEmpty );
3478 if( p->rc==SQLITE_OK ){
3479 *pbNewTerm = 0;
3480 do{
3481 int iFirst = pIter->aFirst[1].iFirst;
3482 Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
3483 int bNewTerm = 0;
3484
3485 assert( p->rc==SQLITE_OK );
3486 pSeg->xNext(p, pSeg, &bNewTerm);
3487 if( pSeg->pLeaf==0 || bNewTerm
3488 || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
3489 ){
3490 fts5MultiIterAdvanced(p, pIter, iFirst, 1);
3491 fts5MultiIterSetEof(pIter);
3492 *pbNewTerm = 1;
3493 }
3494 fts5AssertMultiIterSetup(p, pIter);
3495
3496 }while( (fts5MultiIterIsEmpty(p, pIter) || fts5MultiIterIsDeleted(pIter))
3497 && (p->rc==SQLITE_OK)
3498 );
3499 }
3500}
3501
3502static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
3503 UNUSED_PARAM2(pUnused1, pUnused2);
3504}
3505
3506static Fts5Iter *fts5MultiIterAlloc(
3507 Fts5Index *p, /* FTS5 backend to iterate within */
3508 int nSeg
3509){
3510 Fts5Iter *pNew;
3511 i64 nSlot; /* Power of two >= nSeg */
3512
3513 for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
3514 pNew = fts5IdxMalloc(p,
3515 SZ_FTS5ITER(nSlot) + /* pNew + pNew->aSeg[] */
3516 sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
3517 );
3518 if( pNew ){
3519 pNew->nSeg = nSlot;
3520 pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
3521 pNew->pIndex = p;
3522 pNew->xSetOutputs = fts5IterSetOutputs_Noop;
3523 }
3524 return pNew;
3525}
3526
3527static void fts5PoslistCallback(
3528 Fts5Index *pUnused,
3529 void *pContext,
3530 const u8 *pChunk, int nChunk
3531){
3532 UNUSED_PARAM(pUnused);
3533 assert_nc( nChunk>=0 );
3534 if( nChunk>0 ){
3535 fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
3536 }
3537}
3538
3539typedef struct PoslistCallbackCtx PoslistCallbackCtx;
3540struct PoslistCallbackCtx {
3541 Fts5Buffer *pBuf; /* Append to this buffer */
3542 Fts5Colset *pColset; /* Restrict matches to this column */
3543 int eState; /* See above */
3544};
3545
3546typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
3547struct PoslistOffsetsCtx {
3548 Fts5Buffer *pBuf; /* Append to this buffer */
3549 Fts5Colset *pColset; /* Restrict matches to this column */
3550 int iRead;
3551 int iWrite;
3552};
3553
3554/*
3555** TODO: Make this more efficient!
3556*/
3557static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
3558 int i;
3559 for(i=0; i<pColset->nCol; i++){
3560 if( pColset->aiCol[i]==iCol ) return 1;
3561 }
3562 return 0;
3563}
3564
3565static void fts5PoslistOffsetsCallback(
3566 Fts5Index *pUnused,
3567 void *pContext,
3568 const u8 *pChunk, int nChunk
3569){
3570 PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
3571 UNUSED_PARAM(pUnused);
3572 assert_nc( nChunk>=0 );
3573 if( nChunk>0 ){
3574 int i = 0;
3575 while( i<nChunk ){
3576 int iVal;
3577 i += fts5GetVarint32(&pChunk[i], iVal);
3578 iVal += pCtx->iRead - 2;
3579 pCtx->iRead = iVal;
3580 if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
3581 fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
3582 pCtx->iWrite = iVal;
3583 }
3584 }
3585 }
3586}
3587
3588static void fts5PoslistFilterCallback(
3589 Fts5Index *pUnused,
3590 void *pContext,
3591 const u8 *pChunk, int nChunk
3592){
3593 PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
3594 UNUSED_PARAM(pUnused);
3595 assert_nc( nChunk>=0 );
3596 if( nChunk>0 ){
3597 /* Search through to find the first varint with value 1. This is the
3598 ** start of the next columns hits. */
3599 int i = 0;
3600 int iStart = 0;
3601
3602 if( pCtx->eState==2 ){
3603 int iCol;
3604 fts5FastGetVarint32(pChunk, i, iCol);
3605 if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
3606 pCtx->eState = 1;
3607 fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
3608 }else{
3609 pCtx->eState = 0;
3610 }
3611 }
3612
3613 do {
3614 while( i<nChunk && pChunk[i]!=0x01 ){
3615 fts5IndexSkipVarint(pChunk, i);
3616 }
3617 if( pCtx->eState ){
3618 fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
3619 }
3620 if( i<nChunk ){
3621 int iCol;
3622 iStart = i;
3623 i++;
3624 if( i>=nChunk ){
3625 pCtx->eState = 2;
3626 }else{
3627 fts5FastGetVarint32(pChunk, i, iCol);
3628 pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
3629 if( pCtx->eState ){
3630 fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
3631 iStart = i;
3632 }
3633 }
3634 }
3635 }while( i<nChunk );
3636 }
3637}
3638
3639static void fts5ChunkIterate(
3640 Fts5Index *p, /* Index object */
3641 Fts5SegIter *pSeg, /* Poslist of this iterator */
3642 void *pCtx, /* Context pointer for xChunk callback */
3643 void (*xChunk)(Fts5Index*, void*, const u8*, int)
3644){
3645 int nRem = pSeg->nPos; /* Number of bytes still to come */
3646 Fts5Data *pData = 0;
3647 u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
3648 int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
3649 int pgno = pSeg->iLeafPgno;
3650 int pgnoSave = 0;
3651
3652 /* This function does not work with detail=none databases. */
3653 assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
3654
3655 if( nChunk<0 ){
3656 FTS5_CORRUPT_IDX(p);
3657 return;
3658 }
3659
3660 if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
3661 pgnoSave = pgno+1;
3662 }
3663
3664 while( 1 ){
3665 xChunk(p, pCtx, pChunk, nChunk);
3666 nRem -= nChunk;
3667 fts5DataRelease(pData);
3668 if( nRem<=0 ){
3669 break;
3670 }else if( pSeg->pSeg==0 ){
3671 FTS5_CORRUPT_IDX(p);
3672 return;
3673 }else{
3674 pgno++;
3675 pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
3676 if( pData==0 ) break;
3677 pChunk = &pData->p[4];
3678 nChunk = MIN(nRem, pData->szLeaf - 4);
3679 if( pgno==pgnoSave ){
3680 assert( pSeg->pNextLeaf==0 );
3681 pSeg->pNextLeaf = pData;
3682 pData = 0;
3683 }
3684 }
3685 }
3686}
3687
3688/*
3689** Iterator pIter currently points to a valid entry (not EOF). This
3690** function appends the position list data for the current entry to
3691** buffer pBuf. It does not make a copy of the position-list size
3692** field.
3693*/
3694static void fts5SegiterPoslist(
3695 Fts5Index *p,
3696 Fts5SegIter *pSeg,
3697 Fts5Colset *pColset,
3698 Fts5Buffer *pBuf
3699){
3700 assert( pBuf!=0 );
3701 assert( pSeg!=0 );
3702 if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos+FTS5_DATA_ZERO_PADDING) ){
3703 assert( pBuf->p!=0 );
3704 assert( pBuf->nSpace >= pBuf->n+pSeg->nPos+FTS5_DATA_ZERO_PADDING );
3705 memset(&pBuf->p[pBuf->n+pSeg->nPos], 0, FTS5_DATA_ZERO_PADDING);
3706 if( pColset==0 ){
3707 fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
3708 }else{
3709 if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
3710 PoslistCallbackCtx sCtx;
3711 sCtx.pBuf = pBuf;
3712 sCtx.pColset = pColset;
3713 sCtx.eState = fts5IndexColsetTest(pColset, 0);
3714 assert( sCtx.eState==0 || sCtx.eState==1 );
3715 fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
3716 }else{
3717 PoslistOffsetsCtx sCtx;
3718 memset(&sCtx, 0, sizeof(sCtx));
3719 sCtx.pBuf = pBuf;
3720 sCtx.pColset = pColset;
3721 fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
3722 }
3723 }
3724 }
3725}
3726
3727/*
3728** Parameter pPos points to a buffer containing a position list, size nPos.
3729** This function filters it according to pColset (which must be non-NULL)
3730** and sets pIter->base.pData/nData to point to the new position list.
3731** If memory is required for the new position list, use buffer pIter->poslist.
3732** Or, if the new position list is a contiguous subset of the input, set
3733** pIter->base.pData/nData to point directly to it.
3734**
3735** This function is a no-op if *pRc is other than SQLITE_OK when it is
3736** called. If an OOM error is encountered, *pRc is set to SQLITE_NOMEM
3737** before returning.
3738*/
3739static void fts5IndexExtractColset(
3740 int *pRc,
3741 Fts5Colset *pColset, /* Colset to filter on */
3742 const u8 *pPos, int nPos, /* Position list */
3743 Fts5Iter *pIter
3744){
3745 if( *pRc==SQLITE_OK ){
3746 const u8 *p = pPos;
3747 const u8 *aCopy = p;
3748 const u8 *pEnd = &p[nPos]; /* One byte past end of position list */
3749 int i = 0;
3750 int iCurrent = 0;
3751
3752 if( pColset->nCol>1 && sqlite3Fts5BufferSize(pRc, &pIter->poslist, nPos) ){
3753 return;
3754 }
3755
3756 while( 1 ){
3757 while( pColset->aiCol[i]<iCurrent ){
3758 i++;
3759 if( i==pColset->nCol ){
3760 pIter->base.pData = pIter->poslist.p;
3761 pIter->base.nData = pIter->poslist.n;
3762 return;
3763 }
3764 }
3765
3766 /* Advance pointer p until it points to pEnd or an 0x01 byte that is
3767 ** not part of a varint */
3768 while( p<pEnd && *p!=0x01 ){
3769 while( p<pEnd && (*p++ & 0x80) );
3770 }
3771
3772 if( pColset->aiCol[i]==iCurrent ){
3773 if( pColset->nCol==1 ){
3774 pIter->base.pData = aCopy;
3775 pIter->base.nData = p-aCopy;
3776 return;
3777 }
3778 fts5BufferSafeAppendBlob(&pIter->poslist, aCopy, p-aCopy);
3779 }
3780 if( p>=pEnd ){
3781 pIter->base.pData = pIter->poslist.p;
3782 pIter->base.nData = pIter->poslist.n;
3783 return;
3784 }
3785 aCopy = p++;
3786 iCurrent = *p++;
3787 if( iCurrent & 0x80 ){
3788 p--;
3789 p += fts5GetVarint32(p, iCurrent);
3790 }
3791 }
3792 }
3793
3794}
3795
3796/*
3797** xSetOutputs callback used by detail=none tables.
3798*/
3799static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
3800 assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
3801 pIter->base.iRowid = pSeg->iRowid;
3802 pIter->base.nData = pSeg->nPos;
3803}
3804
3805/*
3806** xSetOutputs callback used by detail=full and detail=col tables when no
3807** column filters are specified.
3808*/
3809static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
3810 pIter->base.iRowid = pSeg->iRowid;
3811 pIter->base.nData = pSeg->nPos;
3812
3813 assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
3814 assert( pIter->pColset==0 );
3815
3816 if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
3817 /* All data is stored on the current page. Populate the output
3818 ** variables to point into the body of the page object. */
3819 pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
3820 }else{
3821 /* The data is distributed over two or more pages. Copy it into the
3822 ** Fts5Iter.poslist buffer and then set the output pointer to point
3823 ** to this buffer. */
3824 fts5BufferZero(&pIter->poslist);
3825 fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
3826 pIter->base.pData = pIter->poslist.p;
3827 }
3828}
3829
3830/*
3831** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
3832** against no columns at all).
3833*/
3834static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
3835 UNUSED_PARAM(pSeg);
3836 pIter->base.nData = 0;
3837 pIter->base.bEof = 1;
3838}
3839
3840/*
3841** xSetOutputs callback used by detail=col when there is a column filter
3842** and there are 100 or more columns. Also called as a fallback from
3843** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
3844*/
3845static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
3846 fts5BufferZero(&pIter->poslist);
3847 fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
3848 pIter->base.iRowid = pSeg->iRowid;
3849 pIter->base.pData = pIter->poslist.p;
3850 pIter->base.nData = pIter->poslist.n;
3851}
3852
3853/*
3854** xSetOutputs callback used when:
3855**
3856** * detail=col,
3857** * there is a column filter, and
3858** * the table contains 100 or fewer columns.
3859**
3860** The last point is to ensure all column numbers are stored as
3861** single-byte varints.
3862*/
3863static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
3864
3865 assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
3866 assert( pIter->pColset );
3867 assert( pIter->poslist.nSpace>=pIter->pIndex->pConfig->nCol );
3868
3869 if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf
3870 || pSeg->nPos>pIter->pIndex->pConfig->nCol
3871 ){
3872 fts5IterSetOutputs_Col(pIter, pSeg);
3873 }else{
3874 u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
3875 u8 *pEnd = (u8*)&a[pSeg->nPos];
3876 int iPrev = 0;
3877 int *aiCol = pIter->pColset->aiCol;
3878 int *aiColEnd = &aiCol[pIter->pColset->nCol];
3879
3880 u8 *aOut = pIter->poslist.p;
3881 int iPrevOut = 0;
3882
3883 pIter->base.iRowid = pSeg->iRowid;
3884
3885 while( a<pEnd ){
3886 iPrev += (int)a++[0] - 2;
3887 while( *aiCol<iPrev ){
3888 aiCol++;
3889 if( aiCol==aiColEnd ) goto setoutputs_col_out;
3890 }
3891 if( *aiCol==iPrev ){
3892 *aOut++ = (u8)((iPrev - iPrevOut) + 2);
3893 iPrevOut = iPrev;
3894 }
3895 }
3896
3897setoutputs_col_out:
3898 pIter->base.pData = pIter->poslist.p;
3899 pIter->base.nData = aOut - pIter->poslist.p;
3900 }
3901}
3902
3903/*
3904** xSetOutputs callback used by detail=full when there is a column filter.
3905*/
3906static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
3907 Fts5Colset *pColset = pIter->pColset;
3908 pIter->base.iRowid = pSeg->iRowid;
3909
3910 assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
3911 assert( pColset );
3912
3913 if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
3914 /* All data is stored on the current page. Populate the output
3915 ** variables to point into the body of the page object. */
3916 const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
3917 int *pRc = &pIter->pIndex->rc;
3918 fts5BufferZero(&pIter->poslist);
3919 fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, pIter);
3920 }else{
3921 /* The data is distributed over two or more pages. Copy it into the
3922 ** Fts5Iter.poslist buffer and then set the output pointer to point
3923 ** to this buffer. */
3924 fts5BufferZero(&pIter->poslist);
3925 fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
3926 pIter->base.pData = pIter->poslist.p;
3927 pIter->base.nData = pIter->poslist.n;
3928 }
3929}
3930
3931static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
3932 assert( pIter!=0 || (*pRc)!=SQLITE_OK );
3933 if( *pRc==SQLITE_OK ){
3934 Fts5Config *pConfig = pIter->pIndex->pConfig;
3935 if( pConfig->eDetail==FTS5_DETAIL_NONE ){
3936 pIter->xSetOutputs = fts5IterSetOutputs_None;
3937 }
3938
3939 else if( pIter->pColset==0 ){
3940 pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
3941 }
3942
3943 else if( pIter->pColset->nCol==0 ){
3944 pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
3945 }
3946
3947 else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
3948 pIter->xSetOutputs = fts5IterSetOutputs_Full;
3949 }
3950
3951 else{
3952 assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
3953 if( pConfig->nCol<=100 ){
3954 pIter->xSetOutputs = fts5IterSetOutputs_Col100;
3955 sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
3956 }else{
3957 pIter->xSetOutputs = fts5IterSetOutputs_Col;
3958 }
3959 }
3960 }
3961}
3962
3963/*
3964** All the component segment-iterators of pIter have been set up. This
3965** functions finishes setup for iterator pIter itself.
3966*/
3967static void fts5MultiIterFinishSetup(Fts5Index *p, Fts5Iter *pIter){
3968 int iIter;
3969 for(iIter=pIter->nSeg-1; iIter>0; iIter--){
3970 int iEq;
3971 if( (iEq = fts5MultiIterDoCompare(pIter, iIter)) ){
3972 Fts5SegIter *pSeg = &pIter->aSeg[iEq];
3973 if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
3974 fts5MultiIterAdvanced(p, pIter, iEq, iIter);
3975 }
3976 }
3977 fts5MultiIterSetEof(pIter);
3978 fts5AssertMultiIterSetup(p, pIter);
3979
3980 if( (pIter->bSkipEmpty && fts5MultiIterIsEmpty(p, pIter))
3981 || fts5MultiIterIsDeleted(pIter)
3982 ){
3983 fts5MultiIterNext(p, pIter, 0, 0);
3984 }else if( pIter->base.bEof==0 ){
3985 Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
3986 pIter->xSetOutputs(pIter, pSeg);
3987 }
3988}
3989
3990/*
3991** Allocate a new Fts5Iter object.
3992**
3993** The new object will be used to iterate through data in structure pStruct.
3994** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
3995** is zero or greater, data from the first nSegment segments on level iLevel
3996** is merged.
3997**
3998** The iterator initially points to the first term/rowid entry in the
3999** iterated data.
4000*/
4001static void fts5MultiIterNew(
4002 Fts5Index *p, /* FTS5 backend to iterate within */
4003 Fts5Structure *pStruct, /* Structure of specific index */
4004 int flags, /* FTS5INDEX_QUERY_XXX flags */
4005 Fts5Colset *pColset, /* Colset to filter on (or NULL) */
4006 const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
4007 int iLevel, /* Level to iterate (-1 for all) */
4008 int nSegment, /* Number of segments to merge (iLevel>=0) */
4009 Fts5Iter **ppOut /* New object */
4010){
4011 int nSeg = 0; /* Number of segment-iters in use */
4012 int iIter = 0; /* */
4013 int iSeg; /* Used to iterate through segments */
4014 Fts5StructureLevel *pLvl;
4015 Fts5Iter *pNew;
4016
4017 assert( (pTerm==0 && nTerm==0) || iLevel<0 );
4018
4019 /* Allocate space for the new multi-seg-iterator. */
4020 if( p->rc==SQLITE_OK ){
4021 if( iLevel<0 ){
4022 assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
4023 nSeg = pStruct->nSegment;
4024 nSeg += (p->pHash && 0==(flags & FTS5INDEX_QUERY_SKIPHASH));
4025 }else{
4026 nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
4027 }
4028 }
4029 *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
4030 if( pNew==0 ){
4031 assert( p->rc!=SQLITE_OK );
4032 goto fts5MultiIterNew_post_check;
4033 }
4034 pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
4035 pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
4036 pNew->pColset = pColset;
4037 if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
4038 fts5IterSetOutputCb(&p->rc, pNew);
4039 }
4040
4041 /* Initialize each of the component segment iterators. */
4042 if( p->rc==SQLITE_OK ){
4043 if( iLevel<0 ){
4044 Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
4045 if( p->pHash && 0==(flags & FTS5INDEX_QUERY_SKIPHASH) ){
4046 /* Add a segment iterator for the current contents of the hash table. */
4047 Fts5SegIter *pIter = &pNew->aSeg[iIter++];
4048 fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
4049 }
4050 for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
4051 for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
4052 Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
4053 Fts5SegIter *pIter = &pNew->aSeg[iIter++];
4054 if( pTerm==0 ){
4055 fts5SegIterInit(p, pSeg, pIter);
4056 }else{
4057 fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
4058 }
4059 }
4060 }
4061 }else{
4062 pLvl = &pStruct->aLevel[iLevel];
4063 for(iSeg=nSeg-1; iSeg>=0; iSeg--){
4064 fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
4065 }
4066 }
4067 assert( iIter==nSeg );
4068 }
4069
4070 /* If the above was successful, each component iterator now points
4071 ** to the first entry in its segment. In this case initialize the
4072 ** aFirst[] array. Or, if an error has occurred, free the iterator
4073 ** object and set the output variable to NULL. */
4074 if( p->rc==SQLITE_OK ){
4075 fts5MultiIterFinishSetup(p, pNew);
4076 }else{
4077 fts5MultiIterFree(pNew);
4078 *ppOut = 0;
4079 }
4080
4081fts5MultiIterNew_post_check:
4082 assert( (*ppOut)!=0 || p->rc!=SQLITE_OK );
4083 return;
4084}
4085
4086/*
4087** Create an Fts5Iter that iterates through the doclist provided
4088** as the second argument.
4089*/
4090static void fts5MultiIterNew2(
4091 Fts5Index *p, /* FTS5 backend to iterate within */
4092 Fts5Data *pData, /* Doclist to iterate through */
4093 int bDesc, /* True for descending rowid order */
4094 Fts5Iter **ppOut /* New object */
4095){
4096 Fts5Iter *pNew;
4097 pNew = fts5MultiIterAlloc(p, 2);
4098 if( pNew ){
4099 Fts5SegIter *pIter = &pNew->aSeg[1];
4100 pIter->flags = FTS5_SEGITER_ONETERM;
4101 if( pData->szLeaf>0 ){
4102 pIter->pLeaf = pData;
4103 pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
4104 pIter->iEndofDoclist = pData->nn;
4105 pNew->aFirst[1].iFirst = 1;
4106 if( bDesc ){
4107 pNew->bRev = 1;
4108 pIter->flags |= FTS5_SEGITER_REVERSE;
4109 fts5SegIterReverseInitPage(p, pIter);
4110 }else{
4111 fts5SegIterLoadNPos(p, pIter);
4112 }
4113 pData = 0;
4114 }else{
4115 pNew->base.bEof = 1;
4116 }
4117 fts5SegIterSetNext(p, pIter);
4118
4119 *ppOut = pNew;
4120 }
4121
4122 fts5DataRelease(pData);
4123}
4124
4125/*
4126** Return true if the iterator is at EOF or if an error has occurred.
4127** False otherwise.
4128*/
4129static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
4130 assert( pIter!=0 || p->rc!=SQLITE_OK );
4131 assert( p->rc!=SQLITE_OK
4132 || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
4133 );
4134 return (p->rc || pIter->base.bEof);
4135}
4136
4137/*
4138** Return the rowid of the entry that the iterator currently points
4139** to. If the iterator points to EOF when this function is called the
4140** results are undefined.
4141*/
4142static i64 fts5MultiIterRowid(Fts5Iter *pIter){
4143 assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
4144 return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
4145}
4146
4147/*
4148** Move the iterator to the next entry at or following iMatch.
4149*/
4150static void fts5MultiIterNextFrom(
4151 Fts5Index *p,
4152 Fts5Iter *pIter,
4153 i64 iMatch
4154){
4155 while( 1 ){
4156 i64 iRowid;
4157 fts5MultiIterNext(p, pIter, 1, iMatch);
4158 if( fts5MultiIterEof(p, pIter) ) break;
4159 iRowid = fts5MultiIterRowid(pIter);
4160 if( pIter->bRev==0 && iRowid>=iMatch ) break;
4161 if( pIter->bRev!=0 && iRowid<=iMatch ) break;
4162 }
4163}
4164
4165/*
4166** Return a pointer to a buffer containing the term associated with the
4167** entry that the iterator currently points to.
4168*/
4169static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
4170 Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
4171 *pn = p->term.n;
4172 return p->term.p;
4173}
4174
4175/*
4176** Allocate a new segment-id for the structure pStruct. The new segment
4177** id must be between 1 and 65335 inclusive, and must not be used by
4178** any currently existing segment. If a free segment id cannot be found,
4179** SQLITE_FULL is returned.
4180**
4181** If an error has already occurred, this function is a no-op. 0 is
4182** returned in this case.
4183*/
4184static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
4185 int iSegid = 0;
4186
4187 if( p->rc==SQLITE_OK ){
4188 if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
4189 p->rc = SQLITE_FULL;
4190 }else{
4191 /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
4192 ** array is 63 elements, or 252 bytes, in size. */
4193 u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
4194 int iLvl, iSeg;
4195 int i;
4196 u32 mask;
4197 memset(aUsed, 0, sizeof(aUsed));
4198 for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
4199 for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
4200 int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
4201 if( iId<=FTS5_MAX_SEGMENT && iId>0 ){
4202 aUsed[(iId-1) / 32] |= (u32)1 << ((iId-1) % 32);
4203 }
4204 }
4205 }
4206
4207 for(i=0; aUsed[i]==0xFFFFFFFF; i++);
4208 mask = aUsed[i];
4209 for(iSegid=0; mask & ((u32)1 << iSegid); iSegid++);
4210 iSegid += 1 + i*32;
4211
4212#ifdef SQLITE_DEBUG
4213 for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
4214 for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
4215 assert_nc( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
4216 }
4217 }
4218 assert_nc( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
4219
4220 {
4221 sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
4222 if( p->rc==SQLITE_OK ){
4223 u8 aBlob[2] = {0xff, 0xff};
4224 sqlite3_bind_int(pIdxSelect, 1, iSegid);
4225 sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
4226 assert_nc( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
4227 p->rc = sqlite3_reset(pIdxSelect);
4228 sqlite3_bind_null(pIdxSelect, 2);
4229 }
4230 }
4231#endif
4232 }
4233 }
4234
4235 return iSegid;
4236}
4237
4238/*
4239** Discard all data currently cached in the hash-tables.
4240*/
4241static void fts5IndexDiscardData(Fts5Index *p){
4242 assert( p->pHash || p->nPendingData==0 );
4243 if( p->pHash ){
4244 sqlite3Fts5HashClear(p->pHash);
4245 p->nPendingData = 0;
4246 p->nPendingRow = 0;
4247 p->flushRc = SQLITE_OK;
4248 }
4249 p->nContentlessDelete = 0;
4250}
4251
4252/*
4253** Return the size of the prefix, in bytes, that buffer
4254** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
4255**
4256** Buffer (pNew/<length-unknown>) is guaranteed to be greater
4257** than buffer (pOld/nOld).
4258*/
4259static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
4260 int i;
4261 for(i=0; i<nOld; i++){
4262 if( pOld[i]!=pNew[i] ) break;
4263 }
4264 return i;
4265}
4266
4267static void fts5WriteDlidxClear(
4268 Fts5Index *p,
4269 Fts5SegWriter *pWriter,
4270 int bFlush /* If true, write dlidx to disk */
4271){
4272 int i;
4273 assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
4274 for(i=0; i<pWriter->nDlidx; i++){
4275 Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
4276 if( pDlidx->buf.n==0 ) break;
4277 if( bFlush ){
4278 assert( pDlidx->pgno!=0 );
4279 fts5DataWrite(p,
4280 FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
4281 pDlidx->buf.p, pDlidx->buf.n
4282 );
4283 }
4284 sqlite3Fts5BufferZero(&pDlidx->buf);
4285 pDlidx->bPrevValid = 0;
4286 }
4287}
4288
4289/*
4290** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
4291** Any new array elements are zeroed before returning.
4292*/
4293static int fts5WriteDlidxGrow(
4294 Fts5Index *p,
4295 Fts5SegWriter *pWriter,
4296 int nLvl
4297){
4298 if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
4299 Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc64(
4300 pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
4301 );
4302 if( aDlidx==0 ){
4303 p->rc = SQLITE_NOMEM;
4304 }else{
4305 size_t nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
4306 memset(&aDlidx[pWriter->nDlidx], 0, nByte);
4307 pWriter->aDlidx = aDlidx;
4308 pWriter->nDlidx = nLvl;
4309 }
4310 }
4311 return p->rc;
4312}
4313
4314/*
4315** If the current doclist-index accumulating in pWriter->aDlidx[] is large
4316** enough, flush it to disk and return 1. Otherwise discard it and return
4317** zero.
4318*/
4319static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
4320 int bFlag = 0;
4321
4322 /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
4323 ** to the database, also write the doclist-index to disk. */
4324 if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
4325 bFlag = 1;
4326 }
4327 fts5WriteDlidxClear(p, pWriter, bFlag);
4328 pWriter->nEmpty = 0;
4329 return bFlag;
4330}
4331
4332/*
4333** This function is called whenever processing of the doclist for the
4334** last term on leaf page (pWriter->iBtPage) is completed.
4335**
4336** The doclist-index for that term is currently stored in-memory within the
4337** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
4338** writes it out to disk. Or, if it is too small to bother with, discards
4339** it.
4340**
4341** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
4342*/
4343static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
4344 int bFlag;
4345
4346 assert( pWriter->iBtPage || pWriter->nEmpty==0 );
4347 if( pWriter->iBtPage==0 ) return;
4348 bFlag = fts5WriteFlushDlidx(p, pWriter);
4349
4350 if( p->rc==SQLITE_OK ){
4351 const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
4352 /* The following was already done in fts5WriteInit(): */
4353 /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
4354 p->rc = sqlite3_bind_blob(
4355 p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC
4356 );
4357 sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
4358 fts5StepAndReset(&p->rc, p->pIdxWriter);
4359 sqlite3_bind_null(p->pIdxWriter, 2);
4360 }
4361 pWriter->iBtPage = 0;
4362}
4363
4364/*
4365** This is called once for each leaf page except the first that contains
4366** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
4367** is larger than all terms written to earlier leaves, and equal to or
4368** smaller than the first term on the new leaf.
4369**
4370** If an error occurs, an error code is left in Fts5Index.rc. If an error
4371** has already occurred when this function is called, it is a no-op.
4372*/
4373static void fts5WriteBtreeTerm(
4374 Fts5Index *p, /* FTS5 backend object */
4375 Fts5SegWriter *pWriter, /* Writer object */
4376 int nTerm, const u8 *pTerm /* First term on new page */
4377){
4378 fts5WriteFlushBtree(p, pWriter);
4379 if( p->rc==SQLITE_OK ){
4380 fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
4381 pWriter->iBtPage = pWriter->writer.pgno;
4382 }
4383}
4384
4385/*
4386** This function is called when flushing a leaf page that contains no
4387** terms at all to disk.
4388*/
4389static void fts5WriteBtreeNoTerm(
4390 Fts5Index *p, /* FTS5 backend object */
4391 Fts5SegWriter *pWriter /* Writer object */
4392){
4393 /* If there were no rowids on the leaf page either and the doclist-index
4394 ** has already been started, append an 0x00 byte to it. */
4395 if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
4396 Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
4397 assert( pDlidx->bPrevValid );
4398 sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
4399 }
4400
4401 /* Increment the "number of sequential leaves without a term" counter. */
4402 pWriter->nEmpty++;
4403}
4404
4405static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
4406 i64 iRowid;
4407 int iOff;
4408
4409 iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
4410 fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
4411 return iRowid;
4412}
4413
4414/*
4415** Rowid iRowid has just been appended to the current leaf page. It is the
4416** first on the page. This function appends an appropriate entry to the current
4417** doclist-index.
4418*/
4419static void fts5WriteDlidxAppend(
4420 Fts5Index *p,
4421 Fts5SegWriter *pWriter,
4422 i64 iRowid
4423){
4424 int i;
4425 int bDone = 0;
4426
4427 for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
4428 i64 iVal;
4429 Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
4430
4431 if( pDlidx->buf.n>=p->pConfig->pgsz ){
4432 /* The current doclist-index page is full. Write it to disk and push
4433 ** a copy of iRowid (which will become the first rowid on the next
4434 ** doclist-index leaf page) up into the next level of the b-tree
4435 ** hierarchy. If the node being flushed is currently the root node,
4436 ** also push its first rowid upwards. */
4437 pDlidx->buf.p[0] = 0x01; /* Not the root node */
4438 fts5DataWrite(p,
4439 FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
4440 pDlidx->buf.p, pDlidx->buf.n
4441 );
4442 fts5WriteDlidxGrow(p, pWriter, i+2);
4443 pDlidx = &pWriter->aDlidx[i];
4444 if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
4445 i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
4446
4447 /* This was the root node. Push its first rowid up to the new root. */
4448 pDlidx[1].pgno = pDlidx->pgno;
4449 sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
4450 sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
4451 sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
4452 pDlidx[1].bPrevValid = 1;
4453 pDlidx[1].iPrev = iFirst;
4454 }
4455
4456 sqlite3Fts5BufferZero(&pDlidx->buf);
4457 pDlidx->bPrevValid = 0;
4458 pDlidx->pgno++;
4459 }else{
4460 bDone = 1;
4461 }
4462
4463 if( pDlidx->bPrevValid ){
4464 iVal = (u64)iRowid - (u64)pDlidx->iPrev;
4465 }else{
4466 i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
4467 assert( pDlidx->buf.n==0 );
4468 sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
4469 sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
4470 iVal = iRowid;
4471 }
4472
4473 sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
4474 pDlidx->bPrevValid = 1;
4475 pDlidx->iPrev = iRowid;
4476 }
4477}
4478
4479static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
4480 static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
4481 Fts5PageWriter *pPage = &pWriter->writer;
4482 i64 iRowid;
4483
4484 assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
4485
4486 /* Set the szLeaf header field. */
4487 assert( 0==fts5GetU16(&pPage->buf.p[2]) );
4488 fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
4489
4490 if( pWriter->bFirstTermInPage ){
4491 /* No term was written to this page. */
4492 assert( pPage->pgidx.n==0 );
4493 fts5WriteBtreeNoTerm(p, pWriter);
4494 }else{
4495 /* Append the pgidx to the page buffer. Set the szLeaf header field. */
4496 fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
4497 }
4498
4499 /* Write the page out to disk */
4500 iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
4501 fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
4502
4503 /* Initialize the next page. */
4504 fts5BufferZero(&pPage->buf);
4505 fts5BufferZero(&pPage->pgidx);
4506 fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
4507 pPage->iPrevPgidx = 0;
4508 pPage->pgno++;
4509
4510 /* Increase the leaves written counter */
4511 pWriter->nLeafWritten++;
4512
4513 /* The new leaf holds no terms or rowids */
4514 pWriter->bFirstTermInPage = 1;
4515 pWriter->bFirstRowidInPage = 1;
4516}
4517
4518/*
4519** Append term pTerm/nTerm to the segment being written by the writer passed
4520** as the second argument.
4521**
4522** If an error occurs, set the Fts5Index.rc error code. If an error has
4523** already occurred, this function is a no-op.
4524*/
4525static void fts5WriteAppendTerm(
4526 Fts5Index *p,
4527 Fts5SegWriter *pWriter,
4528 int nTerm, const u8 *pTerm
4529){
4530 int nPrefix; /* Bytes of prefix compression for term */
4531 Fts5PageWriter *pPage = &pWriter->writer;
4532 Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
4533 int nMin = MIN(pPage->term.n, nTerm);
4534
4535 assert( p->rc==SQLITE_OK );
4536 assert( pPage->buf.n>=4 );
4537 assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
4538
4539 /* If the current leaf page is full, flush it to disk. */
4540 if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
4541 if( pPage->buf.n>4 ){
4542 fts5WriteFlushLeaf(p, pWriter);
4543 if( p->rc!=SQLITE_OK ) return;
4544 }
4545 fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
4546 }
4547
4548 /* TODO1: Updating pgidx here. */
4549 pPgidx->n += sqlite3Fts5PutVarint(
4550 &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
4551 );
4552 pPage->iPrevPgidx = pPage->buf.n;
4553#if 0
4554 fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
4555 pPgidx->n += 2;
4556#endif
4557
4558 if( pWriter->bFirstTermInPage ){
4559 nPrefix = 0;
4560 if( pPage->pgno!=1 ){
4561 /* This is the first term on a leaf that is not the leftmost leaf in
4562 ** the segment b-tree. In this case it is necessary to add a term to
4563 ** the b-tree hierarchy that is (a) larger than the largest term
4564 ** already written to the segment and (b) smaller than or equal to
4565 ** this term. In other words, a prefix of (pTerm/nTerm) that is one
4566 ** byte longer than the longest prefix (pTerm/nTerm) shares with the
4567 ** previous term.
4568 **
4569 ** Usually, the previous term is available in pPage->term. The exception
4570 ** is if this is the first term written in an incremental-merge step.
4571 ** In this case the previous term is not available, so just write a
4572 ** copy of (pTerm/nTerm) into the parent node. This is slightly
4573 ** inefficient, but still correct. */
4574 int n = nTerm;
4575 if( pPage->term.n ){
4576 n = 1 + fts5PrefixCompress(nMin, pPage->term.p, pTerm);
4577 }
4578 fts5WriteBtreeTerm(p, pWriter, n, pTerm);
4579 if( p->rc!=SQLITE_OK ) return;
4580 pPage = &pWriter->writer;
4581 }
4582 }else{
4583 nPrefix = fts5PrefixCompress(nMin, pPage->term.p, pTerm);
4584 fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
4585 }
4586
4587 /* Append the number of bytes of new data, then the term data itself
4588 ** to the page. */
4589 fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
4590 fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
4591
4592 /* Update the Fts5PageWriter.term field. */
4593 fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
4594 pWriter->bFirstTermInPage = 0;
4595
4596 pWriter->bFirstRowidInPage = 0;
4597 pWriter->bFirstRowidInDoclist = 1;
4598
4599 assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
4600 pWriter->aDlidx[0].pgno = pPage->pgno;
4601}
4602
4603/*
4604** Append a rowid and position-list size field to the writers output.
4605*/
4606static void fts5WriteAppendRowid(
4607 Fts5Index *p,
4608 Fts5SegWriter *pWriter,
4609 i64 iRowid
4610){
4611 if( p->rc==SQLITE_OK ){
4612 Fts5PageWriter *pPage = &pWriter->writer;
4613
4614 if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
4615 fts5WriteFlushLeaf(p, pWriter);
4616 }
4617
4618 /* If this is to be the first rowid written to the page, set the
4619 ** rowid-pointer in the page-header. Also append a value to the dlidx
4620 ** buffer, in case a doclist-index is required. */
4621 if( pWriter->bFirstRowidInPage ){
4622 fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
4623 fts5WriteDlidxAppend(p, pWriter, iRowid);
4624 }
4625
4626 /* Write the rowid. */
4627 if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
4628 fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
4629 }else{
4630 assert_nc( p->rc || iRowid>pWriter->iPrevRowid );
4631 fts5BufferAppendVarint(&p->rc, &pPage->buf,
4632 (u64)iRowid - (u64)pWriter->iPrevRowid
4633 );
4634 }
4635 pWriter->iPrevRowid = iRowid;
4636 pWriter->bFirstRowidInDoclist = 0;
4637 pWriter->bFirstRowidInPage = 0;
4638 }
4639}
4640
4641static void fts5WriteAppendPoslistData(
4642 Fts5Index *p,
4643 Fts5SegWriter *pWriter,
4644 const u8 *aData,
4645 int nData
4646){
4647 Fts5PageWriter *pPage = &pWriter->writer;
4648 const u8 *a = aData;
4649 int n = nData;
4650
4651 assert( p->pConfig->pgsz>0 || p->rc!=SQLITE_OK );
4652 while( p->rc==SQLITE_OK
4653 && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
4654 ){
4655 int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
4656 int nCopy = 0;
4657 while( nCopy<nReq ){
4658 i64 dummy;
4659 nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
4660 }
4661 fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
4662 a += nCopy;
4663 n -= nCopy;
4664 fts5WriteFlushLeaf(p, pWriter);
4665 }
4666 if( n>0 ){
4667 fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
4668 }
4669}
4670
4671/*
4672** Flush any data cached by the writer object to the database. Free any
4673** allocations associated with the writer.
4674*/
4675static void fts5WriteFinish(
4676 Fts5Index *p,
4677 Fts5SegWriter *pWriter, /* Writer object */
4678 int *pnLeaf /* OUT: Number of leaf pages in b-tree */
4679){
4680 int i;
4681 Fts5PageWriter *pLeaf = &pWriter->writer;
4682 if( p->rc==SQLITE_OK ){
4683 assert( pLeaf->pgno>=1 );
4684 if( pLeaf->buf.n>4 ){
4685 fts5WriteFlushLeaf(p, pWriter);
4686 }
4687 *pnLeaf = pLeaf->pgno-1;
4688 if( pLeaf->pgno>1 ){
4689 fts5WriteFlushBtree(p, pWriter);
4690 }
4691 }
4692 fts5BufferFree(&pLeaf->term);
4693 fts5BufferFree(&pLeaf->buf);
4694 fts5BufferFree(&pLeaf->pgidx);
4695 fts5BufferFree(&pWriter->btterm);
4696
4697 for(i=0; i<pWriter->nDlidx; i++){
4698 sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
4699 }
4700 sqlite3_free(pWriter->aDlidx);
4701}
4702
4703static void fts5WriteInit(
4704 Fts5Index *p,
4705 Fts5SegWriter *pWriter,
4706 int iSegid
4707){
4708 const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
4709
4710 memset(pWriter, 0, sizeof(Fts5SegWriter));
4711 pWriter->iSegid = iSegid;
4712
4713 fts5WriteDlidxGrow(p, pWriter, 1);
4714 pWriter->writer.pgno = 1;
4715 pWriter->bFirstTermInPage = 1;
4716 pWriter->iBtPage = 1;
4717
4718 assert( pWriter->writer.buf.n==0 );
4719 assert( pWriter->writer.pgidx.n==0 );
4720
4721 /* Grow the two buffers to pgsz + padding bytes in size. */
4722 sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
4723 sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
4724
4725 if( p->pIdxWriter==0 ){
4726 Fts5Config *pConfig = p->pConfig;
4727 fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
4728 "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
4729 pConfig->zDb, pConfig->zName
4730 ));
4731 }
4732
4733 if( p->rc==SQLITE_OK ){
4734 /* Initialize the 4-byte leaf-page header to 0x00. */
4735 memset(pWriter->writer.buf.p, 0, 4);
4736 pWriter->writer.buf.n = 4;
4737
4738 /* Bind the current output segment id to the index-writer. This is an
4739 ** optimization over binding the same value over and over as rows are
4740 ** inserted into %_idx by the current writer. */
4741 sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
4742 }
4743}
4744
4745/*
4746** Iterator pIter was used to iterate through the input segments of on an
4747** incremental merge operation. This function is called if the incremental
4748** merge step has finished but the input has not been completely exhausted.
4749*/
4750static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
4751 int i;
4752 Fts5Buffer buf;
4753 memset(&buf, 0, sizeof(Fts5Buffer));
4754 for(i=0; i<pIter->nSeg && p->rc==SQLITE_OK; i++){
4755 Fts5SegIter *pSeg = &pIter->aSeg[i];
4756 if( pSeg->pSeg==0 ){
4757 /* no-op */
4758 }else if( pSeg->pLeaf==0 ){
4759 /* All keys from this input segment have been transfered to the output.
4760 ** Set both the first and last page-numbers to 0 to indicate that the
4761 ** segment is now empty. */
4762 pSeg->pSeg->pgnoLast = 0;
4763 pSeg->pSeg->pgnoFirst = 0;
4764 }else{
4765 int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
4766 i64 iLeafRowid;
4767 Fts5Data *pData;
4768 int iId = pSeg->pSeg->iSegid;
4769 u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
4770
4771 iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
4772 pData = fts5LeafRead(p, iLeafRowid);
4773 if( pData ){
4774 if( iOff>pData->szLeaf ){
4775 /* This can occur if the pages that the segments occupy overlap - if
4776 ** a single page has been assigned to more than one segment. In
4777 ** this case a prior iteration of this loop may have corrupted the
4778 ** segment currently being trimmed. */
4779 FTS5_CORRUPT_ROWID(p, iLeafRowid);
4780 }else{
4781 fts5BufferZero(&buf);
4782 fts5BufferGrow(&p->rc, &buf, pData->nn);
4783 fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
4784 fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
4785 fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
4786 fts5BufferAppendBlob(&p->rc, &buf,pData->szLeaf-iOff,&pData->p[iOff]);
4787 if( p->rc==SQLITE_OK ){
4788 /* Set the szLeaf field */
4789 fts5PutU16(&buf.p[2], (u16)buf.n);
4790 }
4791
4792 /* Set up the new page-index array */
4793 fts5BufferAppendVarint(&p->rc, &buf, 4);
4794 if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
4795 && pSeg->iEndofDoclist<pData->szLeaf
4796 && pSeg->iPgidxOff<=pData->nn
4797 ){
4798 int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
4799 fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
4800 fts5BufferAppendBlob(&p->rc, &buf,
4801 pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
4802 );
4803 }
4804
4805 pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
4806 fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
4807 fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
4808 }
4809 fts5DataRelease(pData);
4810 }
4811 }
4812 }
4813 fts5BufferFree(&buf);
4814}
4815
4816static void fts5MergeChunkCallback(
4817 Fts5Index *p,
4818 void *pCtx,
4819 const u8 *pChunk, int nChunk
4820){
4821 Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
4822 fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
4823}
4824
4825/*
4826**
4827*/
4828static void fts5IndexMergeLevel(
4829 Fts5Index *p, /* FTS5 backend object */
4830 Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
4831 int iLvl, /* Level to read input from */
4832 int *pnRem /* Write up to this many output leaves */
4833){
4834 Fts5Structure *pStruct = *ppStruct;
4835 Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
4836 Fts5StructureLevel *pLvlOut;
4837 Fts5Iter *pIter = 0; /* Iterator to read input data */
4838 int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
4839 int nInput; /* Number of input segments */
4840 Fts5SegWriter writer; /* Writer object */
4841 Fts5StructureSegment *pSeg; /* Output segment */
4842 Fts5Buffer term;
4843 int bOldest; /* True if the output segment is the oldest */
4844 int eDetail = p->pConfig->eDetail;
4845 const int flags = FTS5INDEX_QUERY_NOOUTPUT;
4846 int bTermWritten = 0; /* True if current term already output */
4847
4848 assert( iLvl<pStruct->nLevel );
4849 assert( pLvl->nMerge<=pLvl->nSeg );
4850
4851 memset(&writer, 0, sizeof(Fts5SegWriter));
4852 memset(&term, 0, sizeof(Fts5Buffer));
4853 if( pLvl->nMerge ){
4854 pLvlOut = &pStruct->aLevel[iLvl+1];
4855 assert( pLvlOut->nSeg>0 );
4856 nInput = pLvl->nMerge;
4857 pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
4858
4859 fts5WriteInit(p, &writer, pSeg->iSegid);
4860 writer.writer.pgno = pSeg->pgnoLast+1;
4861 writer.iBtPage = 0;
4862 }else{
4863 int iSegid = fts5AllocateSegid(p, pStruct);
4864
4865 /* Extend the Fts5Structure object as required to ensure the output
4866 ** segment exists. */
4867 if( iLvl==pStruct->nLevel-1 ){
4868 fts5StructureAddLevel(&p->rc, ppStruct);
4869 pStruct = *ppStruct;
4870 }
4871 fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
4872 if( p->rc ) return;
4873 pLvl = &pStruct->aLevel[iLvl];
4874 pLvlOut = &pStruct->aLevel[iLvl+1];
4875
4876 fts5WriteInit(p, &writer, iSegid);
4877
4878 /* Add the new segment to the output level */
4879 pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
4880 pLvlOut->nSeg++;
4881 pSeg->pgnoFirst = 1;
4882 pSeg->iSegid = iSegid;
4883 pStruct->nSegment++;
4884
4885 /* Read input from all segments in the input level */
4886 nInput = pLvl->nSeg;
4887
4888 /* Set the range of origins that will go into the output segment. */
4889 if( pStruct->nOriginCntr>0 ){
4890 pSeg->iOrigin1 = pLvl->aSeg[0].iOrigin1;
4891 pSeg->iOrigin2 = pLvl->aSeg[pLvl->nSeg-1].iOrigin2;
4892 }
4893 }
4894 bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
4895
4896 assert( iLvl>=0 );
4897 for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
4898 fts5MultiIterEof(p, pIter)==0;
4899 fts5MultiIterNext(p, pIter, 0, 0)
4900 ){
4901 Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
4902 int nPos; /* position-list size field value */
4903 int nTerm;
4904 const u8 *pTerm;
4905 int bDel; /* True to set delete flag on output */
4906
4907 /* If this entry has the delete flag set, or shadows an entry with the
4908 ** delete flag set, set the delete flag on the output. Unless the output
4909 ** will be the oldest segment in the table - in that case the delete flag
4910 ** may be discarded. */
4911 bDel = bOldest ? 0 : (pSegIter->bDel || pSegIter->bDelDup);
4912 pSegIter->bDelDup = 0;
4913
4914 pTerm = fts5MultiIterTerm(pIter, &nTerm);
4915 if( nTerm!=term.n || fts5Memcmp(pTerm, term.p, nTerm) ){
4916 if( pnRem && writer.nLeafWritten>nRem ){
4917 break;
4918 }
4919 fts5BufferSet(&p->rc, &term, nTerm, pTerm);
4920 bTermWritten =0;
4921 }
4922
4923 /* Check for key annihilation. */
4924 if( pSegIter->nPos==0 && (bOldest || bDel==0) ) continue;
4925
4926 if( p->rc==SQLITE_OK && bTermWritten==0 ){
4927 /* This is a new term. Append a term to the output segment. */
4928 fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
4929 bTermWritten = 1;
4930 }
4931
4932 /* Append the rowid to the output */
4933 /* WRITEPOSLISTSIZE */
4934 fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
4935
4936 if( eDetail==FTS5_DETAIL_NONE ){
4937 if( bDel ){
4938 fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
4939 if( pSegIter->nPos>0 ){
4940 fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
4941 }
4942 }
4943 }else{
4944 /* Append the position-list data to the output */
4945 nPos = pSegIter->nPos*2 + bDel;
4946 fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
4947 fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
4948 }
4949 }
4950
4951 /* Flush the last leaf page to disk. Set the output segment b-tree height
4952 ** and last leaf page number at the same time. */
4953 fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
4954
4955 assert( pIter!=0 || p->rc!=SQLITE_OK );
4956 if( fts5MultiIterEof(p, pIter) ){
4957 int i;
4958
4959 /* Remove the redundant segments from the %_data table */
4960 assert( pSeg->nEntry==0 );
4961 for(i=0; i<nInput; i++){
4962 Fts5StructureSegment *pOld = &pLvl->aSeg[i];
4963 pSeg->nEntry += (pOld->nEntry - pOld->nEntryTombstone);
4964 fts5DataRemoveSegment(p, pOld);
4965 }
4966
4967 /* Remove the redundant segments from the input level */
4968 if( pLvl->nSeg!=nInput ){
4969 int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
4970 memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
4971 }
4972 pStruct->nSegment -= nInput;
4973 pLvl->nSeg -= nInput;
4974 pLvl->nMerge = 0;
4975 if( pSeg->pgnoLast==0 ){
4976 pLvlOut->nSeg--;
4977 pStruct->nSegment--;
4978 }
4979 }else{
4980 assert( pSeg->pgnoLast>0 );
4981 fts5TrimSegments(p, pIter);
4982 pLvl->nMerge = nInput;
4983 }
4984
4985 fts5MultiIterFree(pIter);
4986 fts5BufferFree(&term);
4987 if( pnRem ) *pnRem -= writer.nLeafWritten;
4988}
4989
4990/*
4991** If this is not a contentless_delete=1 table, or if the 'deletemerge'
4992** configuration option is set to 0, then this function always returns -1.
4993** Otherwise, it searches the structure object passed as the second argument
4994** for a level suitable for merging due to having a large number of
4995** tombstones in the tombstone hash. If one is found, its index is returned.
4996** Otherwise, if there is no suitable level, -1.
4997*/
4998static int fts5IndexFindDeleteMerge(Fts5Index *p, Fts5Structure *pStruct){
4999 Fts5Config *pConfig = p->pConfig;
5000 int iRet = -1;
5001 if( pConfig->bContentlessDelete && pConfig->nDeleteMerge>0 ){
5002 int ii;
5003 int nBest = 0;
5004
5005 for(ii=0; ii<pStruct->nLevel; ii++){
5006 Fts5StructureLevel *pLvl = &pStruct->aLevel[ii];
5007 i64 nEntry = 0;
5008 i64 nTomb = 0;
5009 int iSeg;
5010 for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
5011 nEntry += pLvl->aSeg[iSeg].nEntry;
5012 nTomb += pLvl->aSeg[iSeg].nEntryTombstone;
5013 }
5014 assert_nc( nEntry>0 || pLvl->nSeg==0 );
5015 if( nEntry>0 ){
5016 int nPercent = (nTomb * 100) / nEntry;
5017 if( nPercent>=pConfig->nDeleteMerge && nPercent>nBest ){
5018 iRet = ii;
5019 nBest = nPercent;
5020 }
5021 }
5022
5023 /* If pLvl is already the input level to an ongoing merge, look no
5024 ** further for a merge candidate. The caller should be allowed to
5025 ** continue merging from pLvl first. */
5026 if( pLvl->nMerge ) break;
5027 }
5028 }
5029 return iRet;
5030}
5031
5032/*
5033** Do up to nPg pages of automerge work on the index.
5034**
5035** Return true if any changes were actually made, or false otherwise.
5036*/
5037static int fts5IndexMerge(
5038 Fts5Index *p, /* FTS5 backend object */
5039 Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
5040 int nPg, /* Pages of work to do */
5041 int nMin /* Minimum number of segments to merge */
5042){
5043 int nRem = nPg;
5044 int bRet = 0;
5045 Fts5Structure *pStruct = *ppStruct;
5046 while( nRem>0 && p->rc==SQLITE_OK ){
5047 int iLvl; /* To iterate through levels */
5048 int iBestLvl = 0; /* Level offering the most input segments */
5049 int nBest = 0; /* Number of input segments on best level */
5050
5051 /* Set iBestLvl to the level to read input segments from. Or to -1 if
5052 ** there is no level suitable to merge segments from. */
5053 assert( pStruct->nLevel>0 );
5054 for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
5055 Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
5056 if( pLvl->nMerge ){
5057 if( pLvl->nMerge>nBest ){
5058 iBestLvl = iLvl;
5059 nBest = nMin;
5060 }
5061 break;
5062 }
5063 if( pLvl->nSeg>nBest ){
5064 nBest = pLvl->nSeg;
5065 iBestLvl = iLvl;
5066 }
5067 }
5068 if( nBest<nMin ){
5069 iBestLvl = fts5IndexFindDeleteMerge(p, pStruct);
5070 }
5071
5072 if( iBestLvl<0 ) break;
5073 bRet = 1;
5074 fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
5075 if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
5076 fts5StructurePromote(p, iBestLvl+1, pStruct);
5077 }
5078
5079 if( nMin==1 ) nMin = 2;
5080 }
5081 *ppStruct = pStruct;
5082 return bRet;
5083}
5084
5085/*
5086** A total of nLeaf leaf pages of data has just been flushed to a level-0
5087** segment. This function updates the write-counter accordingly and, if
5088** necessary, performs incremental merge work.
5089**
5090** If an error occurs, set the Fts5Index.rc error code. If an error has
5091** already occurred, this function is a no-op.
5092*/
5093static void fts5IndexAutomerge(
5094 Fts5Index *p, /* FTS5 backend object */
5095 Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
5096 int nLeaf /* Number of output leaves just written */
5097){
5098 if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 && ALWAYS((*ppStruct)!=0) ){
5099 Fts5Structure *pStruct = *ppStruct;
5100 u64 nWrite; /* Initial value of write-counter */
5101 int nWork; /* Number of work-quanta to perform */
5102 int nRem; /* Number of leaf pages left to write */
5103
5104 /* Update the write-counter. While doing so, set nWork. */
5105 nWrite = pStruct->nWriteCounter;
5106 nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
5107 pStruct->nWriteCounter += nLeaf;
5108 nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
5109
5110 fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
5111 }
5112}
5113
5114static void fts5IndexCrisismerge(
5115 Fts5Index *p, /* FTS5 backend object */
5116 Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
5117){
5118 const int nCrisis = p->pConfig->nCrisisMerge;
5119 Fts5Structure *pStruct = *ppStruct;
5120 if( pStruct && pStruct->nLevel>0 ){
5121 int iLvl = 0;
5122 while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
5123 fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
5124 assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
5125 fts5StructurePromote(p, iLvl+1, pStruct);
5126 iLvl++;
5127 }
5128 *ppStruct = pStruct;
5129 }
5130}
5131
5132static int fts5IndexReturn(Fts5Index *p){
5133 int rc = p->rc;
5134 p->rc = SQLITE_OK;
5135 return rc;
5136}
5137
5138/*
5139** Close the read-only blob handle, if it is open.
5140*/
5141void sqlite3Fts5IndexCloseReader(Fts5Index *p){
5142 fts5IndexCloseReader(p);
5143 fts5IndexReturn(p);
5144}
5145
5146typedef struct Fts5FlushCtx Fts5FlushCtx;
5147struct Fts5FlushCtx {
5148 Fts5Index *pIdx;
5149 Fts5SegWriter writer;
5150};
5151
5152/*
5153** Buffer aBuf[] contains a list of varints, all small enough to fit
5154** in a 32-bit integer. Return the size of the largest prefix of this
5155** list nMax bytes or less in size.
5156*/
5157static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
5158 int ret;
5159 u32 dummy;
5160 ret = fts5GetVarint32(aBuf, dummy);
5161 if( ret<nMax ){
5162 while( 1 ){
5163 int i = fts5GetVarint32(&aBuf[ret], dummy);
5164 if( (ret + i) > nMax ) break;
5165 ret += i;
5166 }
5167 }
5168 return ret;
5169}
5170
5171/*
5172** Execute the SQL statement:
5173**
5174** DELETE FROM %_idx WHERE (segid, (pgno/2)) = ($iSegid, $iPgno);
5175**
5176** This is used when a secure-delete operation removes the last term
5177** from a segment leaf page. In that case the %_idx entry is removed
5178** too. This is done to ensure that if all instances of a token are
5179** removed from an fts5 database in secure-delete mode, no trace of
5180** the token itself remains in the database.
5181*/
5182static void fts5SecureDeleteIdxEntry(
5183 Fts5Index *p, /* FTS5 backend object */
5184 int iSegid, /* Id of segment to delete entry for */
5185 int iPgno /* Page number within segment */
5186){
5187 if( iPgno!=1 ){
5188 assert( p->pConfig->iVersion==FTS5_CURRENT_VERSION_SECUREDELETE );
5189 if( p->pDeleteFromIdx==0 ){
5190 fts5IndexPrepareStmt(p, &p->pDeleteFromIdx, sqlite3_mprintf(
5191 "DELETE FROM '%q'.'%q_idx' WHERE (segid, (pgno/2)) = (?1, ?2)",
5192 p->pConfig->zDb, p->pConfig->zName
5193 ));
5194 }
5195 if( p->rc==SQLITE_OK ){
5196 sqlite3_bind_int(p->pDeleteFromIdx, 1, iSegid);
5197 sqlite3_bind_int(p->pDeleteFromIdx, 2, iPgno);
5198 sqlite3_step(p->pDeleteFromIdx);
5199 p->rc = sqlite3_reset(p->pDeleteFromIdx);
5200 }
5201 }
5202}
5203
5204/*
5205** This is called when a secure-delete operation removes a position-list
5206** that overflows onto segment page iPgno of segment pSeg. This function
5207** rewrites node iPgno, and possibly one or more of its right-hand peers,
5208** to remove this portion of the position list.
5209**
5210** Output variable (*pbLastInDoclist) is set to true if the position-list
5211** removed is followed by a new term or the end-of-segment, or false if
5212** it is followed by another rowid/position list.
5213*/
5214static void fts5SecureDeleteOverflow(
5215 Fts5Index *p,
5216 Fts5StructureSegment *pSeg,
5217 int iPgno,
5218 int *pbLastInDoclist
5219){
5220 const int bDetailNone = (p->pConfig->eDetail==FTS5_DETAIL_NONE);
5221 int pgno;
5222 Fts5Data *pLeaf = 0;
5223 assert( iPgno!=1 );
5224
5225 *pbLastInDoclist = 1;
5226 for(pgno=iPgno; p->rc==SQLITE_OK && pgno<=pSeg->pgnoLast; pgno++){
5227 i64 iRowid = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
5228 int iNext = 0;
5229 u8 *aPg = 0;
5230
5231 pLeaf = fts5LeafRead(p, iRowid);
5232 if( pLeaf==0 ) break;
5233 aPg = pLeaf->p;
5234
5235 iNext = fts5GetU16(&aPg[0]);
5236 if( iNext!=0 ){
5237 *pbLastInDoclist = 0;
5238 }
5239 if( iNext==0 && pLeaf->szLeaf<pLeaf->nn ){
5240 fts5GetVarint32(&aPg[pLeaf->szLeaf], iNext);
5241 }
5242
5243 if( iNext==0 ){
5244 /* The page contains no terms or rowids. Replace it with an empty
5245 ** page and move on to the right-hand peer. */
5246 const u8 aEmpty[] = {0x00, 0x00, 0x00, 0x04};
5247 assert_nc( bDetailNone==0 || pLeaf->nn==4 );
5248 if( bDetailNone==0 ) fts5DataWrite(p, iRowid, aEmpty, sizeof(aEmpty));
5249 fts5DataRelease(pLeaf);
5250 pLeaf = 0;
5251 }else if( bDetailNone ){
5252 break;
5253 }else if( iNext>=pLeaf->szLeaf || pLeaf->nn<pLeaf->szLeaf || iNext<4 ){
5254 FTS5_CORRUPT_ROWID(p, iRowid);
5255 break;
5256 }else{
5257 int nShift = iNext - 4;
5258 int nPg;
5259
5260 int nIdx = 0;
5261 u8 *aIdx = 0;
5262
5263 /* Unless the current page footer is 0 bytes in size (in which case
5264 ** the new page footer will be as well), allocate and populate a
5265 ** buffer containing the new page footer. Set stack variables aIdx
5266 ** and nIdx accordingly. */
5267 if( pLeaf->nn>pLeaf->szLeaf ){
5268 int iFirst = 0;
5269 int i1 = pLeaf->szLeaf;
5270 int i2 = 0;
5271
5272 i1 += fts5GetVarint32(&aPg[i1], iFirst);
5273 if( iFirst<iNext ){
5274 FTS5_CORRUPT_ROWID(p, iRowid);
5275 break;
5276 }
5277 aIdx = sqlite3Fts5MallocZero(&p->rc, (pLeaf->nn-pLeaf->szLeaf)+2);
5278 if( aIdx==0 ) break;
5279 i2 = sqlite3Fts5PutVarint(aIdx, iFirst-nShift);
5280 if( i1<pLeaf->nn ){
5281 memcpy(&aIdx[i2], &aPg[i1], pLeaf->nn-i1);
5282 i2 += (pLeaf->nn-i1);
5283 }
5284 nIdx = i2;
5285 }
5286
5287 /* Modify the contents of buffer aPg[]. Set nPg to the new size
5288 ** in bytes. The new page is always smaller than the old. */
5289 nPg = pLeaf->szLeaf - nShift;
5290 memmove(&aPg[4], &aPg[4+nShift], nPg-4);
5291 fts5PutU16(&aPg[2], nPg);
5292 if( fts5GetU16(&aPg[0]) ) fts5PutU16(&aPg[0], 4);
5293 if( nIdx>0 ){
5294 memcpy(&aPg[nPg], aIdx, nIdx);
5295 nPg += nIdx;
5296 }
5297 sqlite3_free(aIdx);
5298
5299 /* Write the new page to disk and exit the loop */
5300 assert( nPg>4 || fts5GetU16(aPg)==0 );
5301 fts5DataWrite(p, iRowid, aPg, nPg);
5302 break;
5303 }
5304 }
5305 fts5DataRelease(pLeaf);
5306}
5307
5308/*
5309** Completely remove the entry that pSeg currently points to from
5310** the database.
5311*/
5312static void fts5DoSecureDelete(
5313 Fts5Index *p,
5314 Fts5SegIter *pSeg
5315){
5316 const int bDetailNone = (p->pConfig->eDetail==FTS5_DETAIL_NONE);
5317 int iSegid = pSeg->pSeg->iSegid;
5318 u8 *aPg = pSeg->pLeaf->p;
5319 int nPg = pSeg->pLeaf->nn;
5320 int iPgIdx = pSeg->pLeaf->szLeaf; /* Offset of page footer */
5321
5322 u64 iDelta = 0;
5323 int iNextOff = 0;
5324 int iOff = 0;
5325 int nIdx = 0;
5326 u8 *aIdx = 0;
5327 int bLastInDoclist = 0;
5328 int iIdx = 0;
5329 int iStart = 0;
5330 int iDelKeyOff = 0; /* Offset of deleted key, if any */
5331
5332 nIdx = nPg-iPgIdx;
5333 aIdx = sqlite3Fts5MallocZero(&p->rc, ((i64)nIdx)+16);
5334 if( p->rc ) return;
5335 memcpy(aIdx, &aPg[iPgIdx], nIdx);
5336
5337 /* At this point segment iterator pSeg points to the entry
5338 ** this function should remove from the b-tree segment.
5339 **
5340 ** In detail=full or detail=column mode, pSeg->iLeafOffset is the
5341 ** offset of the first byte in the position-list for the entry to
5342 ** remove. Immediately before this comes two varints that will also
5343 ** need to be removed:
5344 **
5345 ** + the rowid or delta rowid value for the entry, and
5346 ** + the size of the position list in bytes.
5347 **
5348 ** Or, in detail=none mode, there is a single varint prior to
5349 ** pSeg->iLeafOffset - the rowid or delta rowid value.
5350 **
5351 ** This block sets the following variables:
5352 **
5353 ** iStart:
5354 ** The offset of the first byte of the rowid or delta-rowid
5355 ** value for the doclist entry being removed.
5356 **
5357 ** iDelta:
5358 ** The value of the rowid or delta-rowid value for the doclist
5359 ** entry being removed.
5360 **
5361 ** iNextOff:
5362 ** The offset of the next entry following the position list
5363 ** for the one being removed. If the position list for this
5364 ** entry overflows onto the next leaf page, this value will be
5365 ** greater than pLeaf->szLeaf.
5366 */
5367 {
5368 int iSOP; /* Start-Of-Position-list */
5369 if( pSeg->iLeafPgno==pSeg->iTermLeafPgno ){
5370 iStart = pSeg->iTermLeafOffset;
5371 }else{
5372 iStart = fts5GetU16(&aPg[0]);
5373 }
5374 if( iStart>nPg ){
5375 FTS5_CORRUPT_IDX(p);
5376 sqlite3_free(aIdx);
5377 return;
5378 }
5379
5380 iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
5381 assert_nc( iSOP<=pSeg->iLeafOffset );
5382
5383 if( bDetailNone ){
5384 int iEnd = pSeg->iLeafOffset - (pSeg->bDel ? 1 + pSeg->nPos : 0);
5385 while( iSOP<iEnd ){
5386 if( aPg[iSOP]==0x00 ) iSOP++;
5387 if( aPg[iSOP]==0x00 ) iSOP++;
5388 iStart = iSOP;
5389 iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
5390 }
5391
5392 iNextOff = iSOP;
5393 if( iNextOff<pSeg->iEndofDoclist && aPg[iNextOff]==0x00 ) iNextOff++;
5394 if( iNextOff<pSeg->iEndofDoclist && aPg[iNextOff]==0x00 ) iNextOff++;
5395
5396 }else{
5397 int nPos = 0;
5398 iSOP += fts5GetVarint32(&aPg[iSOP], nPos);
5399 while( iSOP<pSeg->iLeafOffset ){
5400 iStart = iSOP + (nPos/2);
5401 iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
5402 iSOP += fts5GetVarint32(&aPg[iSOP], nPos);
5403 }
5404 assert_nc( iSOP==pSeg->iLeafOffset );
5405 iNextOff = iSOP + pSeg->nPos;
5406 }
5407 }
5408
5409 iOff = iStart;
5410
5411 /* If the position-list for the entry being removed flows over past
5412 ** the end of this page, delete the portion of the position-list on the
5413 ** next page and beyond.
5414 **
5415 ** Set variable bLastInDoclist to true if this entry happens
5416 ** to be the last rowid in the doclist for its term. */
5417 if( iNextOff>=iPgIdx ){
5418 int pgno = pSeg->iLeafPgno+1;
5419 fts5SecureDeleteOverflow(p, pSeg->pSeg, pgno, &bLastInDoclist);
5420 iNextOff = iPgIdx;
5421 }
5422
5423 if( pSeg->bDel==0 ){
5424 if( iNextOff!=iPgIdx ){
5425 /* Loop through the page-footer. If iNextOff (offset of the
5426 ** entry following the one we are removing) is equal to the
5427 ** offset of a key on this page, then the entry is the last
5428 ** in its doclist. */
5429 int iKeyOff = 0;
5430 for(iIdx=0; iIdx<nIdx; /* no-op */){
5431 u32 iVal = 0;
5432 iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
5433 iKeyOff += iVal;
5434 if( iKeyOff==iNextOff ){
5435 bLastInDoclist = 1;
5436 }
5437 }
5438 }
5439
5440 /* If this is (a) the first rowid on a page and (b) is not followed by
5441 ** another position list on the same page, set the "first-rowid" field
5442 ** of the header to 0. */
5443 if( fts5GetU16(&aPg[0])==iStart && (bLastInDoclist || iNextOff==iPgIdx) ){
5444 fts5PutU16(&aPg[0], 0);
5445 }
5446 }
5447
5448 if( pSeg->bDel ){
5449 iOff += sqlite3Fts5PutVarint(&aPg[iOff], iDelta);
5450 aPg[iOff++] = bDetailNone ? 0x00 : 0x01;
5451 }else if( bLastInDoclist==0 ){
5452 if( iNextOff!=iPgIdx ){
5453 u64 iNextDelta = 0;
5454 iNextOff += fts5GetVarint(&aPg[iNextOff], &iNextDelta);
5455 iOff += sqlite3Fts5PutVarint(&aPg[iOff], iDelta + iNextDelta);
5456 }
5457 }else if(
5458 pSeg->iLeafPgno==pSeg->iTermLeafPgno
5459 && iStart==pSeg->iTermLeafOffset
5460 ){
5461 /* The entry being removed was the only position list in its
5462 ** doclist. Therefore the term needs to be removed as well. */
5463 int iKey = 0;
5464 int iKeyOff = 0;
5465
5466 /* Set iKeyOff to the offset of the term that will be removed - the
5467 ** last offset in the footer that is not greater than iStart. */
5468 for(iIdx=0; iIdx<nIdx; iKey++){
5469 u32 iVal = 0;
5470 iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
5471 if( (iKeyOff+iVal)>(u32)iStart ) break;
5472 iKeyOff += iVal;
5473 }
5474 assert_nc( iKey>=1 );
5475
5476 /* Set iDelKeyOff to the value of the footer entry to remove from
5477 ** the page. */
5478 iDelKeyOff = iOff = iKeyOff;
5479
5480 if( iNextOff!=iPgIdx ){
5481 /* This is the only position-list associated with the term, and there
5482 ** is another term following it on this page. So the subsequent term
5483 ** needs to be moved to replace the term associated with the entry
5484 ** being removed. */
5485 u64 nPrefix = 0;
5486 u64 nSuffix = 0;
5487 u64 nPrefix2 = 0;
5488 u64 nSuffix2 = 0;
5489
5490 iDelKeyOff = iNextOff;
5491 iNextOff += fts5GetVarint(&aPg[iNextOff], &nPrefix2);
5492 iNextOff += fts5GetVarint(&aPg[iNextOff], &nSuffix2);
5493
5494 if( iKey!=1 ){
5495 iKeyOff += fts5GetVarint(&aPg[iKeyOff], &nPrefix);
5496 }
5497 iKeyOff += fts5GetVarint(&aPg[iKeyOff], &nSuffix);
5498
5499 nPrefix = MIN(nPrefix, nPrefix2);
5500 nSuffix = (nPrefix2 + nSuffix2) - nPrefix;
5501
5502 if( (iKeyOff+nSuffix)>(u64)iPgIdx || (iNextOff+nSuffix2)>(u64)iPgIdx ){
5503 FTS5_CORRUPT_IDX(p);
5504 }else{
5505 if( iKey!=1 ){
5506 iOff += sqlite3Fts5PutVarint(&aPg[iOff], nPrefix);
5507 }
5508 iOff += sqlite3Fts5PutVarint(&aPg[iOff], nSuffix);
5509 if( nPrefix2>(u64)pSeg->term.n ){
5510 FTS5_CORRUPT_IDX(p);
5511 }else if( nPrefix2>nPrefix ){
5512 memcpy(&aPg[iOff], &pSeg->term.p[nPrefix], nPrefix2-nPrefix);
5513 iOff += (nPrefix2-nPrefix);
5514 }
5515 memmove(&aPg[iOff], &aPg[iNextOff], nSuffix2);
5516 iOff += nSuffix2;
5517 iNextOff += nSuffix2;
5518 }
5519 }
5520 }else if( iStart==4 ){
5521 int iPgno;
5522
5523 assert_nc( pSeg->iLeafPgno>pSeg->iTermLeafPgno );
5524 /* The entry being removed may be the only position list in
5525 ** its doclist. */
5526 for(iPgno=pSeg->iLeafPgno-1; iPgno>pSeg->iTermLeafPgno; iPgno-- ){
5527 Fts5Data *pPg = fts5LeafRead(p, FTS5_SEGMENT_ROWID(iSegid, iPgno));
5528 int bEmpty = (pPg && pPg->nn==4);
5529 fts5DataRelease(pPg);
5530 if( bEmpty==0 ) break;
5531 }
5532
5533 if( iPgno==pSeg->iTermLeafPgno ){
5534 i64 iId = FTS5_SEGMENT_ROWID(iSegid, pSeg->iTermLeafPgno);
5535 Fts5Data *pTerm = fts5LeafRead(p, iId);
5536 if( pTerm && pTerm->szLeaf==pSeg->iTermLeafOffset ){
5537 u8 *aTermIdx = &pTerm->p[pTerm->szLeaf];
5538 int nTermIdx = pTerm->nn - pTerm->szLeaf;
5539 int iTermIdx = 0;
5540 i64 iTermOff = 0;
5541
5542 while( 1 ){
5543 u32 iVal = 0;
5544 int nByte = fts5GetVarint32(&aTermIdx[iTermIdx], iVal);
5545 iTermOff += iVal;
5546 if( (iTermIdx+nByte)>=nTermIdx ) break;
5547 iTermIdx += nByte;
5548 }
5549 nTermIdx = iTermIdx;
5550
5551 if( iTermOff>pTerm->szLeaf ){
5552 FTS5_CORRUPT_IDX(p);
5553 }else{
5554 memmove(&pTerm->p[iTermOff], &pTerm->p[pTerm->szLeaf], nTermIdx);
5555 fts5PutU16(&pTerm->p[2], iTermOff);
5556 fts5DataWrite(p, iId, pTerm->p, iTermOff+nTermIdx);
5557 if( nTermIdx==0 ){
5558 fts5SecureDeleteIdxEntry(p, iSegid, pSeg->iTermLeafPgno);
5559 }
5560 }
5561 }
5562 fts5DataRelease(pTerm);
5563 }
5564 }
5565
5566 /* Assuming no error has occurred, this block does final edits to the
5567 ** leaf page before writing it back to disk. Input variables are:
5568 **
5569 ** nPg: Total initial size of leaf page.
5570 ** iPgIdx: Initial offset of page footer.
5571 **
5572 ** iOff: Offset to move data to
5573 ** iNextOff: Offset to move data from
5574 */
5575 if( p->rc==SQLITE_OK ){
5576 const int nMove = nPg - iNextOff; /* Number of bytes to move */
5577 int nShift = iNextOff - iOff; /* Distance to move them */
5578 int nNewPg = 0;
5579 int iPrevKeyOut = 0;
5580 i64 iKeyIn = 0;
5581
5582 if( nMove>0 ){
5583 memmove(&aPg[iOff], &aPg[iNextOff], nMove);
5584 }
5585 iPgIdx -= nShift;
5586 nNewPg = iPgIdx;
5587 fts5PutU16(&aPg[2], iPgIdx);
5588
5589 for(iIdx=0; iIdx<nIdx; /* no-op */){
5590 u32 iVal = 0;
5591 iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
5592 iKeyIn += iVal;
5593 if( iKeyIn>nPg ){
5594 FTS5_CORRUPT_IDX(p);
5595 break;
5596 }
5597 if( iKeyIn!=iDelKeyOff ){
5598 int iKeyOut = (iKeyIn - (iKeyIn>iOff ? nShift : 0));
5599 nNewPg += sqlite3Fts5PutVarint(&aPg[nNewPg], iKeyOut - iPrevKeyOut);
5600 iPrevKeyOut = iKeyOut;
5601 }
5602 }
5603
5604 if( p->rc==SQLITE_OK && iPgIdx==nNewPg && nIdx>0 && pSeg->iLeafPgno!=1 ){
5605 fts5SecureDeleteIdxEntry(p, iSegid, pSeg->iLeafPgno);
5606 }
5607
5608 assert_nc( nNewPg>4 || fts5GetU16(aPg)==0 );
5609 fts5DataWrite(p, FTS5_SEGMENT_ROWID(iSegid,pSeg->iLeafPgno), aPg, nNewPg);
5610 }
5611 sqlite3_free(aIdx);
5612}
5613
5614/*
5615** This is called as part of flushing a delete to disk in 'secure-delete'
5616** mode. It edits the segments within the database described by argument
5617** pStruct to remove the entries for term zTerm, rowid iRowid.
5618**
5619** Return SQLITE_OK if successful, or an SQLite error code if an error
5620** has occurred. Any error code is also stored in the Fts5Index handle.
5621*/
5622static int fts5FlushSecureDelete(
5623 Fts5Index *p,
5624 Fts5Structure *pStruct,
5625 const char *zTerm,
5626 int nTerm,
5627 i64 iRowid
5628){
5629 const int f = FTS5INDEX_QUERY_SKIPHASH;
5630 Fts5Iter *pIter = 0; /* Used to find term instance */
5631
5632 /* If the version number has not been set to SECUREDELETE, do so now. */
5633 if( p->pConfig->iVersion!=FTS5_CURRENT_VERSION_SECUREDELETE ){
5634 Fts5Config *pConfig = p->pConfig;
5635 sqlite3_stmt *pStmt = 0;
5636 fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
5637 "REPLACE INTO %Q.'%q_config' VALUES ('version', %d)",
5638 pConfig->zDb, pConfig->zName, FTS5_CURRENT_VERSION_SECUREDELETE
5639 ));
5640 if( p->rc==SQLITE_OK ){
5641 int rc;
5642 sqlite3_step(pStmt);
5643 rc = sqlite3_finalize(pStmt);
5644 if( p->rc==SQLITE_OK ) p->rc = rc;
5645 pConfig->iCookie++;
5646 pConfig->iVersion = FTS5_CURRENT_VERSION_SECUREDELETE;
5647 }
5648 }
5649
5650 fts5MultiIterNew(p, pStruct, f, 0, (const u8*)zTerm, nTerm, -1, 0, &pIter);
5651 if( fts5MultiIterEof(p, pIter)==0 ){
5652 i64 iThis = fts5MultiIterRowid(pIter);
5653 if( iThis<iRowid ){
5654 fts5MultiIterNextFrom(p, pIter, iRowid);
5655 }
5656
5657 if( p->rc==SQLITE_OK
5658 && fts5MultiIterEof(p, pIter)==0
5659 && iRowid==fts5MultiIterRowid(pIter)
5660 ){
5661 Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
5662 fts5DoSecureDelete(p, pSeg);
5663 }
5664 }
5665
5666 fts5MultiIterFree(pIter);
5667 return p->rc;
5668}
5669
5670
5671/*
5672** Flush the contents of in-memory hash table iHash to a new level-0
5673** segment on disk. Also update the corresponding structure record.
5674**
5675** If an error occurs, set the Fts5Index.rc error code. If an error has
5676** already occurred, this function is a no-op.
5677*/
5678static void fts5FlushOneHash(Fts5Index *p){
5679 Fts5Hash *pHash = p->pHash;
5680 Fts5Structure *pStruct;
5681 int iSegid;
5682 int pgnoLast = 0; /* Last leaf page number in segment */
5683
5684 /* Obtain a reference to the index structure and allocate a new segment-id
5685 ** for the new level-0 segment. */
5686 pStruct = fts5StructureRead(p);
5687 fts5StructureInvalidate(p);
5688
5689 if( sqlite3Fts5HashIsEmpty(pHash)==0 ){
5690 iSegid = fts5AllocateSegid(p, pStruct);
5691 if( iSegid ){
5692 const int pgsz = p->pConfig->pgsz;
5693 int eDetail = p->pConfig->eDetail;
5694 int bSecureDelete = p->pConfig->bSecureDelete;
5695 Fts5StructureSegment *pSeg; /* New segment within pStruct */
5696 Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
5697 Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
5698
5699 Fts5SegWriter writer;
5700 fts5WriteInit(p, &writer, iSegid);
5701
5702 pBuf = &writer.writer.buf;
5703 pPgidx = &writer.writer.pgidx;
5704
5705 /* fts5WriteInit() should have initialized the buffers to (most likely)
5706 ** the maximum space required. */
5707 assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
5708 assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
5709
5710 /* Begin scanning through hash table entries. This loop runs once for each
5711 ** term/doclist currently stored within the hash table. */
5712 if( p->rc==SQLITE_OK ){
5713 p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
5714 }
5715 while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
5716 const char *zTerm; /* Buffer containing term */
5717 int nTerm; /* Size of zTerm in bytes */
5718 const u8 *pDoclist; /* Pointer to doclist for this term */
5719 int nDoclist; /* Size of doclist in bytes */
5720
5721 /* Get the term and doclist for this entry. */
5722 sqlite3Fts5HashScanEntry(pHash, &zTerm, &nTerm, &pDoclist, &nDoclist);
5723 if( bSecureDelete==0 ){
5724 fts5WriteAppendTerm(p, &writer, nTerm, (const u8*)zTerm);
5725 if( p->rc!=SQLITE_OK ) break;
5726 assert( writer.bFirstRowidInPage==0 );
5727 }
5728
5729 if( !bSecureDelete && pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
5730 /* The entire doclist will fit on the current leaf. */
5731 fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
5732 }else{
5733 int bTermWritten = !bSecureDelete;
5734 i64 iRowid = 0;
5735 i64 iPrev = 0;
5736 int iOff = 0;
5737
5738 /* The entire doclist will not fit on this leaf. The following
5739 ** loop iterates through the poslists that make up the current
5740 ** doclist. */
5741 while( p->rc==SQLITE_OK && iOff<nDoclist ){
5742 u64 iDelta = 0;
5743 iOff += fts5GetVarint(&pDoclist[iOff], &iDelta);
5744 iRowid += iDelta;
5745
5746 /* If in secure delete mode, and if this entry in the poslist is
5747 ** in fact a delete, then edit the existing segments directly
5748 ** using fts5FlushSecureDelete(). */
5749 if( bSecureDelete ){
5750 if( eDetail==FTS5_DETAIL_NONE ){
5751 if( iOff<nDoclist && pDoclist[iOff]==0x00
5752 && !fts5FlushSecureDelete(p, pStruct, zTerm, nTerm, iRowid)
5753 ){
5754 iOff++;
5755 if( iOff<nDoclist && pDoclist[iOff]==0x00 ){
5756 iOff++;
5757 }else{
5758 continue;
5759 }
5760 }
5761 }else if( (pDoclist[iOff] & 0x01)
5762 && !fts5FlushSecureDelete(p, pStruct, zTerm, nTerm, iRowid)
5763 ){
5764 if( p->rc!=SQLITE_OK || pDoclist[iOff]==0x01 ){
5765 iOff++;
5766 continue;
5767 }
5768 }
5769 }
5770
5771 if( p->rc==SQLITE_OK && bTermWritten==0 ){
5772 fts5WriteAppendTerm(p, &writer, nTerm, (const u8*)zTerm);
5773 bTermWritten = 1;
5774 assert( p->rc!=SQLITE_OK || writer.bFirstRowidInPage==0 );
5775 }
5776
5777 if( writer.bFirstRowidInPage ){
5778 fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
5779 pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
5780 writer.bFirstRowidInPage = 0;
5781 fts5WriteDlidxAppend(p, &writer, iRowid);
5782 }else{
5783 u64 iRowidDelta = (u64)iRowid - (u64)iPrev;
5784 pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowidDelta);
5785 }
5786 if( p->rc!=SQLITE_OK ) break;
5787 assert( pBuf->n<=pBuf->nSpace );
5788 iPrev = iRowid;
5789
5790 if( eDetail==FTS5_DETAIL_NONE ){
5791 if( iOff<nDoclist && pDoclist[iOff]==0 ){
5792 pBuf->p[pBuf->n++] = 0;
5793 iOff++;
5794 if( iOff<nDoclist && pDoclist[iOff]==0 ){
5795 pBuf->p[pBuf->n++] = 0;
5796 iOff++;
5797 }
5798 }
5799 if( (pBuf->n + pPgidx->n)>=pgsz ){
5800 fts5WriteFlushLeaf(p, &writer);
5801 }
5802 }else{
5803 int bDel = 0;
5804 int nPos = 0;
5805 int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDel);
5806 if( bDel && bSecureDelete ){
5807 fts5BufferAppendVarint(&p->rc, pBuf, nPos*2);
5808 iOff += nCopy;
5809 nCopy = nPos;
5810 }else{
5811 nCopy += nPos;
5812 }
5813 if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
5814 /* The entire poslist will fit on the current leaf. So copy
5815 ** it in one go. */
5816 fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
5817 }else{
5818 /* The entire poslist will not fit on this leaf. So it needs
5819 ** to be broken into sections. The only qualification being
5820 ** that each varint must be stored contiguously. */
5821 const u8 *pPoslist = &pDoclist[iOff];
5822 int iPos = 0;
5823 while( p->rc==SQLITE_OK ){
5824 int nSpace = pgsz - pBuf->n - pPgidx->n;
5825 int n = 0;
5826 if( (nCopy - iPos)<=nSpace ){
5827 n = nCopy - iPos;
5828 }else{
5829 n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
5830 }
5831 assert( n>0 );
5832 fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
5833 iPos += n;
5834 if( (pBuf->n + pPgidx->n)>=pgsz ){
5835 fts5WriteFlushLeaf(p, &writer);
5836 }
5837 if( iPos>=nCopy ) break;
5838 }
5839 }
5840 iOff += nCopy;
5841 }
5842 }
5843 }
5844
5845 /* TODO2: Doclist terminator written here. */
5846 /* pBuf->p[pBuf->n++] = '\0'; */
5847 assert( pBuf->n<=pBuf->nSpace );
5848 if( p->rc==SQLITE_OK ) sqlite3Fts5HashScanNext(pHash);
5849 }
5850 fts5WriteFinish(p, &writer, &pgnoLast);
5851
5852 assert( p->rc!=SQLITE_OK || bSecureDelete || pgnoLast>0 );
5853 if( pgnoLast>0 ){
5854 /* Update the Fts5Structure. It is written back to the database by the
5855 ** fts5StructureRelease() call below. */
5856 if( pStruct->nLevel==0 ){
5857 fts5StructureAddLevel(&p->rc, &pStruct);
5858 }
5859 fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
5860 if( p->rc==SQLITE_OK ){
5861 pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
5862 pSeg->iSegid = iSegid;
5863 pSeg->pgnoFirst = 1;
5864 pSeg->pgnoLast = pgnoLast;
5865 if( pStruct->nOriginCntr>0 ){
5866 pSeg->iOrigin1 = pStruct->nOriginCntr;
5867 pSeg->iOrigin2 = pStruct->nOriginCntr;
5868 pSeg->nEntry = p->nPendingRow;
5869 pStruct->nOriginCntr++;
5870 }
5871 pStruct->nSegment++;
5872 }
5873 fts5StructurePromote(p, 0, pStruct);
5874 }
5875 }
5876 }
5877
5878 fts5IndexAutomerge(p, &pStruct, pgnoLast + p->nContentlessDelete);
5879 fts5IndexCrisismerge(p, &pStruct);
5880 fts5StructureWrite(p, pStruct);
5881 fts5StructureRelease(pStruct);
5882}
5883
5884/*
5885** Flush any data stored in the in-memory hash tables to the database.
5886*/
5887static void fts5IndexFlush(Fts5Index *p){
5888 /* Unless it is empty, flush the hash table to disk */
5889 if( p->flushRc ){
5890 p->rc = p->flushRc;
5891 return;
5892 }
5893 if( p->nPendingData || p->nContentlessDelete ){
5894 assert( p->pHash );
5895 fts5FlushOneHash(p);
5896 if( p->rc==SQLITE_OK ){
5897 sqlite3Fts5HashClear(p->pHash);
5898 p->nPendingData = 0;
5899 p->nPendingRow = 0;
5900 p->nContentlessDelete = 0;
5901 }else if( p->nPendingData || p->nContentlessDelete ){
5902 p->flushRc = p->rc;
5903 }
5904 }
5905}
5906
5907static Fts5Structure *fts5IndexOptimizeStruct(
5908 Fts5Index *p,
5909 Fts5Structure *pStruct
5910){
5911 Fts5Structure *pNew = 0;
5912 sqlite3_int64 nByte = SZ_FTS5STRUCTURE(1);
5913 int nSeg = pStruct->nSegment;
5914 int i;
5915
5916 /* Figure out if this structure requires optimization. A structure does
5917 ** not require optimization if either:
5918 **
5919 ** 1. it consists of fewer than two segments, or
5920 ** 2. all segments are on the same level, or
5921 ** 3. all segments except one are currently inputs to a merge operation.
5922 **
5923 ** In the first case, if there are no tombstone hash pages, return NULL. In
5924 ** the second, increment the ref-count on *pStruct and return a copy of the
5925 ** pointer to it.
5926 */
5927 if( nSeg==0 ) return 0;
5928 for(i=0; i<pStruct->nLevel; i++){
5929 int nThis = pStruct->aLevel[i].nSeg;
5930 int nMerge = pStruct->aLevel[i].nMerge;
5931 if( nThis>0 && (nThis==nSeg || (nThis==nSeg-1 && nMerge==nThis)) ){
5932 if( nSeg==1 && nThis==1 && pStruct->aLevel[i].aSeg[0].nPgTombstone==0 ){
5933 return 0;
5934 }
5935 fts5StructureRef(pStruct);
5936 return pStruct;
5937 }
5938 assert( pStruct->aLevel[i].nMerge<=nThis );
5939 }
5940
5941 nByte += (((i64)pStruct->nLevel)+1) * sizeof(Fts5StructureLevel);
5942 assert( nByte==(i64)SZ_FTS5STRUCTURE(pStruct->nLevel+2) );
5943 pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
5944
5945 if( pNew ){
5946 Fts5StructureLevel *pLvl;
5947 nByte = nSeg * sizeof(Fts5StructureSegment);
5948 pNew->nLevel = MIN(pStruct->nLevel+1, FTS5_MAX_LEVEL);
5949 pNew->nRef = 1;
5950 pNew->nWriteCounter = pStruct->nWriteCounter;
5951 pNew->nOriginCntr = pStruct->nOriginCntr;
5952 pLvl = &pNew->aLevel[pNew->nLevel-1];
5953 pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
5954 if( pLvl->aSeg ){
5955 int iLvl, iSeg;
5956 int iSegOut = 0;
5957 /* Iterate through all segments, from oldest to newest. Add them to
5958 ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
5959 ** segment in the data structure. */
5960 for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
5961 for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
5962 pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
5963 iSegOut++;
5964 }
5965 }
5966 pNew->nSegment = pLvl->nSeg = nSeg;
5967 }else{
5968 sqlite3_free(pNew);
5969 pNew = 0;
5970 }
5971 }
5972
5973 return pNew;
5974}
5975
5976int sqlite3Fts5IndexOptimize(Fts5Index *p){
5977 Fts5Structure *pStruct;
5978 Fts5Structure *pNew = 0;
5979
5980 assert( p->rc==SQLITE_OK );
5981 fts5IndexFlush(p);
5982 assert( p->rc!=SQLITE_OK || p->nContentlessDelete==0 );
5983 pStruct = fts5StructureRead(p);
5984 assert( p->rc!=SQLITE_OK || pStruct!=0 );
5985 fts5StructureInvalidate(p);
5986
5987 if( pStruct ){
5988 pNew = fts5IndexOptimizeStruct(p, pStruct);
5989 }
5990 fts5StructureRelease(pStruct);
5991
5992 assert( pNew==0 || pNew->nSegment>0 );
5993 if( pNew ){
5994 int iLvl;
5995 for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
5996 while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
5997 int nRem = FTS5_OPT_WORK_UNIT;
5998 fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
5999 }
6000
6001 fts5StructureWrite(p, pNew);
6002 fts5StructureRelease(pNew);
6003 }
6004
6005 return fts5IndexReturn(p);
6006}
6007
6008/*
6009** This is called to implement the special "VALUES('merge', $nMerge)"
6010** INSERT command.
6011*/
6012int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
6013 Fts5Structure *pStruct = 0;
6014
6015 fts5IndexFlush(p);
6016 pStruct = fts5StructureRead(p);
6017 if( pStruct ){
6018 int nMin = p->pConfig->nUsermerge;
6019 fts5StructureInvalidate(p);
6020 if( nMerge<0 ){
6021 Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
6022 fts5StructureRelease(pStruct);
6023 pStruct = pNew;
6024 nMin = 1;
6025 nMerge = (nMerge==SMALLEST_INT32 ? LARGEST_INT32 : (nMerge*-1));
6026 }
6027 if( pStruct && pStruct->nLevel ){
6028 if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
6029 fts5StructureWrite(p, pStruct);
6030 }
6031 }
6032 fts5StructureRelease(pStruct);
6033 }
6034 return fts5IndexReturn(p);
6035}
6036
6037static void fts5AppendRowid(
6038 Fts5Index *p,
6039 u64 iDelta,
6040 Fts5Iter *pUnused,
6041 Fts5Buffer *pBuf
6042){
6043 UNUSED_PARAM(pUnused);
6044 fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
6045}
6046
6047static void fts5AppendPoslist(
6048 Fts5Index *p,
6049 u64 iDelta,
6050 Fts5Iter *pMulti,
6051 Fts5Buffer *pBuf
6052){
6053 int nData = pMulti->base.nData;
6054 int nByte = nData + 9 + 9 + FTS5_DATA_ZERO_PADDING;
6055 assert( nData>0 );
6056 if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nByte) ){
6057 fts5BufferSafeAppendVarint(pBuf, iDelta);
6058 fts5BufferSafeAppendVarint(pBuf, nData*2);
6059 fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
6060 memset(&pBuf->p[pBuf->n], 0, FTS5_DATA_ZERO_PADDING);
6061 }
6062}
6063
6064
6065static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
6066 u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
6067
6068 assert( pIter->aPoslist || (p==0 && pIter->aPoslist==0) );
6069 if( p>=pIter->aEof ){
6070 pIter->aPoslist = 0;
6071 }else{
6072 u64 iDelta;
6073
6074 p += fts5GetVarint(p, &iDelta);
6075 pIter->iRowid += iDelta;
6076
6077 /* Read position list size */
6078 if( p[0] & 0x80 ){
6079 int nPos;
6080 pIter->nSize = fts5GetVarint32(p, nPos);
6081 pIter->nPoslist = (nPos>>1);
6082 }else{
6083 pIter->nPoslist = ((int)(p[0])) >> 1;
6084 pIter->nSize = 1;
6085 }
6086
6087 pIter->aPoslist = p;
6088 if( &pIter->aPoslist[pIter->nPoslist]>pIter->aEof ){
6089 pIter->aPoslist = 0;
6090 }
6091 }
6092}
6093
6094static void fts5DoclistIterInit(
6095 Fts5Buffer *pBuf,
6096 Fts5DoclistIter *pIter
6097){
6098 memset(pIter, 0, sizeof(*pIter));
6099 if( pBuf->n>0 ){
6100 pIter->aPoslist = pBuf->p;
6101 pIter->aEof = &pBuf->p[pBuf->n];
6102 fts5DoclistIterNext(pIter);
6103 }
6104}
6105
6106#if 0
6107/*
6108** Append a doclist to buffer pBuf.
6109**
6110** This function assumes that space within the buffer has already been
6111** allocated.
6112*/
6113static void fts5MergeAppendDocid(
6114 Fts5Buffer *pBuf, /* Buffer to write to */
6115 i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
6116 i64 iRowid /* Rowid to append */
6117){
6118 assert( pBuf->n!=0 || (*piLastRowid)==0 );
6119 fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
6120 *piLastRowid = iRowid;
6121}
6122#endif
6123
6124#define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
6125 assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
6126 fts5BufferSafeAppendVarint((pBuf), (u64)(iRowid) - (u64)(iLastRowid)); \
6127 (iLastRowid) = (iRowid); \
6128}
6129
6130/*
6131** Swap the contents of buffer *p1 with that of *p2.
6132*/
6133static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
6134 Fts5Buffer tmp = *p1;
6135 *p1 = *p2;
6136 *p2 = tmp;
6137}
6138
6139static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
6140 int i = *piOff;
6141 if( i>=pBuf->n ){
6142 *piOff = -1;
6143 }else{
6144 u64 iVal;
6145 *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
6146 *piRowid += iVal;
6147 }
6148}
6149
6150/*
6151** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
6152** In this case the buffers consist of a delta-encoded list of rowids only.
6153*/
6154static void fts5MergeRowidLists(
6155 Fts5Index *p, /* FTS5 backend object */
6156 Fts5Buffer *p1, /* First list to merge */
6157 int nBuf, /* Number of entries in apBuf[] */
6158 Fts5Buffer *aBuf /* Array of other lists to merge into p1 */
6159){
6160 int i1 = 0;
6161 int i2 = 0;
6162 i64 iRowid1 = 0;
6163 i64 iRowid2 = 0;
6164 i64 iOut = 0;
6165 Fts5Buffer *p2 = &aBuf[0];
6166 Fts5Buffer out;
6167
6168 (void)nBuf;
6169 memset(&out, 0, sizeof(out));
6170 assert( nBuf==1 );
6171 sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n + 9);
6172 if( p->rc ) return;
6173
6174 fts5NextRowid(p1, &i1, &iRowid1);
6175 fts5NextRowid(p2, &i2, &iRowid2);
6176 while( i1>=0 || i2>=0 ){
6177 if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
6178 assert( iOut==0 || iRowid1>iOut );
6179 fts5BufferSafeAppendVarint(&out, (u64)iRowid1 - (u64)iOut);
6180 iOut = iRowid1;
6181 fts5NextRowid(p1, &i1, &iRowid1);
6182 }else{
6183 assert( iOut==0 || iRowid2>iOut );
6184 fts5BufferSafeAppendVarint(&out, (u64)iRowid2 - (u64)iOut);
6185 iOut = iRowid2;
6186 if( i1>=0 && iRowid1==iRowid2 ){
6187 fts5NextRowid(p1, &i1, &iRowid1);
6188 }
6189 fts5NextRowid(p2, &i2, &iRowid2);
6190 }
6191 }
6192
6193 fts5BufferSwap(&out, p1);
6194 fts5BufferFree(&out);
6195}
6196
6197typedef struct PrefixMerger PrefixMerger;
6198struct PrefixMerger {
6199 Fts5DoclistIter iter; /* Doclist iterator */
6200 i64 iPos; /* For iterating through a position list */
6201 int iOff;
6202 u8 *aPos;
6203 PrefixMerger *pNext; /* Next in docid/poslist order */
6204};
6205
6206static void fts5PrefixMergerInsertByRowid(
6207 PrefixMerger **ppHead,
6208 PrefixMerger *p
6209){
6210 if( p->iter.aPoslist ){
6211 PrefixMerger **pp = ppHead;
6212 while( *pp && p->iter.iRowid>(*pp)->iter.iRowid ){
6213 pp = &(*pp)->pNext;
6214 }
6215 p->pNext = *pp;
6216 *pp = p;
6217 }
6218}
6219
6220static void fts5PrefixMergerInsertByPosition(
6221 PrefixMerger **ppHead,
6222 PrefixMerger *p
6223){
6224 if( p->iPos>=0 ){
6225 PrefixMerger **pp = ppHead;
6226 while( *pp && p->iPos>(*pp)->iPos ){
6227 pp = &(*pp)->pNext;
6228 }
6229 p->pNext = *pp;
6230 *pp = p;
6231 }
6232}
6233
6234
6235/*
6236** Array aBuf[] contains nBuf doclists. These are all merged in with the
6237** doclist in buffer p1.
6238*/
6239static void fts5MergePrefixLists(
6240 Fts5Index *p, /* FTS5 backend object */
6241 Fts5Buffer *p1, /* First list to merge */
6242 int nBuf, /* Number of buffers in array aBuf[] */
6243 Fts5Buffer *aBuf /* Other lists to merge in */
6244){
6245#define fts5PrefixMergerNextPosition(p) \
6246 sqlite3Fts5PoslistNext64((p)->aPos,(p)->iter.nPoslist,&(p)->iOff,&(p)->iPos)
6247#define FTS5_MERGE_NLIST 16
6248 PrefixMerger aMerger[FTS5_MERGE_NLIST];
6249 PrefixMerger *pHead = 0;
6250 int i;
6251 int nOut = 0;
6252 Fts5Buffer out = {0, 0, 0};
6253 Fts5Buffer tmp = {0, 0, 0};
6254 i64 iLastRowid = 0;
6255
6256 /* Initialize a doclist-iterator for each input buffer. Arrange them in
6257 ** a linked-list starting at pHead in ascending order of rowid. Avoid
6258 ** linking any iterators already at EOF into the linked list at all. */
6259 assert( nBuf+1<=(int)(sizeof(aMerger)/sizeof(aMerger[0])) );
6260 memset(aMerger, 0, sizeof(PrefixMerger)*(nBuf+1));
6261 pHead = &aMerger[nBuf];
6262 fts5DoclistIterInit(p1, &pHead->iter);
6263 for(i=0; i<nBuf; i++){
6264 fts5DoclistIterInit(&aBuf[i], &aMerger[i].iter);
6265 fts5PrefixMergerInsertByRowid(&pHead, &aMerger[i]);
6266 nOut += aBuf[i].n;
6267 }
6268 if( nOut==0 ) return;
6269 nOut += p1->n + 9 + 10*nBuf;
6270
6271 /* The maximum size of the output is equal to the sum of the
6272 ** input sizes + 1 varint (9 bytes). The extra varint is because if the
6273 ** first rowid in one input is a large negative number, and the first in
6274 ** the other a non-negative number, the delta for the non-negative
6275 ** number will be larger on disk than the literal integer value
6276 ** was.
6277 **
6278 ** Or, if the input position-lists are corrupt, then the output might
6279 ** include up to (nBuf+1) extra 10-byte positions created by interpreting -1
6280 ** (the value PoslistNext64() uses for EOF) as a position and appending
6281 ** it to the output. This can happen at most once for each input
6282 ** position-list, hence (nBuf+1) 10 byte paddings. */
6283 if( sqlite3Fts5BufferSize(&p->rc, &out, nOut) ) return;
6284
6285 while( pHead ){
6286 fts5MergeAppendDocid(&out, iLastRowid, pHead->iter.iRowid);
6287
6288 if( pHead->pNext && iLastRowid==pHead->pNext->iter.iRowid ){
6289 /* Merge data from two or more poslists */
6290 i64 iPrev = 0;
6291 int nTmp = FTS5_DATA_ZERO_PADDING;
6292 int nMerge = 0;
6293 PrefixMerger *pSave = pHead;
6294 PrefixMerger *pThis = 0;
6295 int nTail = 0;
6296
6297 pHead = 0;
6298 while( pSave && pSave->iter.iRowid==iLastRowid ){
6299 PrefixMerger *pNext = pSave->pNext;
6300 pSave->iOff = 0;
6301 pSave->iPos = 0;
6302 pSave->aPos = &pSave->iter.aPoslist[pSave->iter.nSize];
6303 fts5PrefixMergerNextPosition(pSave);
6304 nTmp += pSave->iter.nPoslist + 10;
6305 nMerge++;
6306 fts5PrefixMergerInsertByPosition(&pHead, pSave);
6307 pSave = pNext;
6308 }
6309
6310 if( pHead==0 || pHead->pNext==0 ){
6311 FTS5_CORRUPT_IDX(p);
6312 break;
6313 }
6314
6315 /* See the earlier comment in this function for an explanation of why
6316 ** corrupt input position lists might cause the output to consume
6317 ** at most nMerge*10 bytes of unexpected space. */
6318 if( sqlite3Fts5BufferSize(&p->rc, &tmp, nTmp+nMerge*10) ){
6319 break;
6320 }
6321 fts5BufferZero(&tmp);
6322
6323 pThis = pHead;
6324 pHead = pThis->pNext;
6325 sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, pThis->iPos);
6326 fts5PrefixMergerNextPosition(pThis);
6327 fts5PrefixMergerInsertByPosition(&pHead, pThis);
6328
6329 while( pHead->pNext ){
6330 pThis = pHead;
6331 if( pThis->iPos!=iPrev ){
6332 sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, pThis->iPos);
6333 }
6334 fts5PrefixMergerNextPosition(pThis);
6335 pHead = pThis->pNext;
6336 fts5PrefixMergerInsertByPosition(&pHead, pThis);
6337 }
6338
6339 if( pHead->iPos!=iPrev ){
6340 sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, pHead->iPos);
6341 }
6342 nTail = pHead->iter.nPoslist - pHead->iOff;
6343
6344 /* WRITEPOSLISTSIZE */
6345 assert_nc( tmp.n+nTail<=nTmp );
6346 assert( tmp.n+nTail<=nTmp+nMerge*10 );
6347 if( tmp.n+nTail>nTmp-FTS5_DATA_ZERO_PADDING ){
6348 if( p->rc==SQLITE_OK ) FTS5_CORRUPT_IDX(p);
6349 break;
6350 }
6351 fts5BufferSafeAppendVarint(&out, (tmp.n+nTail) * 2);
6352 fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
6353 if( nTail>0 ){
6354 fts5BufferSafeAppendBlob(&out, &pHead->aPos[pHead->iOff], nTail);
6355 }
6356
6357 pHead = pSave;
6358 for(i=0; i<nBuf+1; i++){
6359 PrefixMerger *pX = &aMerger[i];
6360 if( pX->iter.aPoslist && pX->iter.iRowid==iLastRowid ){
6361 fts5DoclistIterNext(&pX->iter);
6362 fts5PrefixMergerInsertByRowid(&pHead, pX);
6363 }
6364 }
6365
6366 }else{
6367 /* Copy poslist from pHead to output */
6368 PrefixMerger *pThis = pHead;
6369 Fts5DoclistIter *pI = &pThis->iter;
6370 fts5BufferSafeAppendBlob(&out, pI->aPoslist, pI->nPoslist+pI->nSize);
6371 fts5DoclistIterNext(pI);
6372 pHead = pThis->pNext;
6373 fts5PrefixMergerInsertByRowid(&pHead, pThis);
6374 }
6375 }
6376
6377 fts5BufferFree(p1);
6378 fts5BufferFree(&tmp);
6379 memset(&out.p[out.n], 0, FTS5_DATA_ZERO_PADDING);
6380 *p1 = out;
6381}
6382
6383
6384/*
6385** Iterate through a range of entries in the FTS index, invoking the xVisit
6386** callback for each of them.
6387**
6388** Parameter pToken points to an nToken buffer containing an FTS index term
6389** (i.e. a document term with the preceding 1 byte index identifier -
6390** FTS5_MAIN_PREFIX or similar). If bPrefix is true, then the call visits
6391** all entries for terms that have pToken/nToken as a prefix. If bPrefix
6392** is false, then only entries with pToken/nToken as the entire key are
6393** visited.
6394**
6395** If the current table is a tokendata=1 table, then if bPrefix is true then
6396** each index term is treated separately. However, if bPrefix is false, then
6397** all index terms corresponding to pToken/nToken are collapsed into a single
6398** term before the callback is invoked.
6399**
6400** The callback invoked for each entry visited is specified by paramter xVisit.
6401** Each time it is invoked, it is passed a pointer to the Fts5Index object,
6402** a copy of the 7th paramter to this function (pCtx) and a pointer to the
6403** iterator that indicates the current entry. If the current entry is the
6404** first with a new term (i.e. different from that of the previous entry,
6405** including the very first term), then the final two parameters are passed
6406** a pointer to the term and its size in bytes, respectively. If the current
6407** entry is not the first associated with its term, these two parameters
6408** are passed 0.
6409**
6410** If parameter pColset is not NULL, then it is used to filter entries before
6411** the callback is invoked.
6412*/
6413static int fts5VisitEntries(
6414 Fts5Index *p, /* Fts5 index object */
6415 Fts5Colset *pColset, /* Columns filter to apply, or NULL */
6416 u8 *pToken, /* Buffer containing token */
6417 int nToken, /* Size of buffer pToken in bytes */
6418 int bPrefix, /* True for a prefix scan */
6419 void (*xVisit)(Fts5Index*, void *pCtx, Fts5Iter *pIter, const u8*, int),
6420 void *pCtx /* Passed as second argument to xVisit() */
6421){
6422 const int flags = (bPrefix ? FTS5INDEX_QUERY_SCAN : 0)
6423 | FTS5INDEX_QUERY_SKIPEMPTY
6424 | FTS5INDEX_QUERY_NOOUTPUT;
6425 Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
6426 int bNewTerm = 1;
6427 Fts5Structure *pStruct = fts5StructureRead(p);
6428
6429 fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
6430 fts5IterSetOutputCb(&p->rc, p1);
6431 for( /* no-op */ ;
6432 fts5MultiIterEof(p, p1)==0;
6433 fts5MultiIterNext2(p, p1, &bNewTerm)
6434 ){
6435 Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
6436 int nNew = 0;
6437 const u8 *pNew = 0;
6438
6439 p1->xSetOutputs(p1, pSeg);
6440 if( p->rc ) break;
6441
6442 if( bNewTerm ){
6443 nNew = pSeg->term.n;
6444 pNew = pSeg->term.p;
6445 if( nNew<nToken || memcmp(pToken, pNew, nToken) ) break;
6446 }
6447
6448 xVisit(p, pCtx, p1, pNew, nNew);
6449 }
6450 fts5MultiIterFree(p1);
6451
6452 fts5StructureRelease(pStruct);
6453 return p->rc;
6454}
6455
6456
6457/*
6458** Usually, a tokendata=1 iterator (struct Fts5TokenDataIter) accumulates an
6459** array of these for each row it visits (so all iRowid fields are the same).
6460** Or, for an iterator used by an "ORDER BY rank" query, it accumulates an
6461** array of these for the entire query (in which case iRowid fields may take
6462** a variety of values).
6463**
6464** Each instance in the array indicates the iterator (and therefore term)
6465** associated with position iPos of rowid iRowid. This is used by the
6466** xInstToken() API.
6467**
6468** iRowid:
6469** Rowid for the current entry.
6470**
6471** iPos:
6472** Position of current entry within row. In the usual ((iCol<<32)+iOff)
6473** format (e.g. see macros FTS5_POS2COLUMN() and FTS5_POS2OFFSET()).
6474**
6475** iIter:
6476** If the Fts5TokenDataIter iterator that the entry is part of is
6477** actually an iterator (i.e. with nIter>0, not just a container for
6478** Fts5TokenDataMap structures), then this variable is an index into
6479** the apIter[] array. The corresponding term is that which the iterator
6480** at apIter[iIter] currently points to.
6481**
6482** Or, if the Fts5TokenDataIter iterator is just a container object
6483** (nIter==0), then iIter is an index into the term.p[] buffer where
6484** the term is stored.
6485**
6486** nByte:
6487** In the case where iIter is an index into term.p[], this variable
6488** is the size of the term in bytes. If iIter is an index into apIter[],
6489** this variable is unused.
6490*/
6491struct Fts5TokenDataMap {
6492 i64 iRowid; /* Row this token is located in */
6493 i64 iPos; /* Position of token */
6494 int iIter; /* Iterator token was read from */
6495 int nByte; /* Length of token in bytes (or 0) */
6496};
6497
6498/*
6499** An object used to supplement Fts5Iter for tokendata=1 iterators.
6500**
6501** This object serves two purposes. The first is as a container for an array
6502** of Fts5TokenDataMap structures, which are used to find the token required
6503** when the xInstToken() API is used. This is done by the nMapAlloc, nMap and
6504** aMap[] variables.
6505*/
6506struct Fts5TokenDataIter {
6507 i64 nMapAlloc; /* Allocated size of aMap[] in entries */
6508 i64 nMap; /* Number of valid entries in aMap[] */
6509 Fts5TokenDataMap *aMap; /* Array of (rowid+pos -> token) mappings */
6510
6511 /* The following are used for prefix-queries only. */
6512 Fts5Buffer terms;
6513
6514 /* The following are used for other full-token tokendata queries only. */
6515 i64 nIter;
6516 i64 nIterAlloc;
6517 Fts5PoslistReader *aPoslistReader;
6518 int *aPoslistToIter;
6519 Fts5Iter *apIter[FLEXARRAY];
6520};
6521
6522/* Size in bytes of an Fts5TokenDataIter object holding up to N iterators */
6523#define SZ_FTS5TOKENDATAITER(N) \
6524 (offsetof(Fts5TokenDataIter,apIter) + (N)*sizeof(Fts5Iter))
6525
6526/*
6527** The two input arrays - a1[] and a2[] - are in sorted order. This function
6528** merges the two arrays together and writes the result to output array
6529** aOut[]. aOut[] is guaranteed to be large enough to hold the result.
6530**
6531** Duplicate entries are copied into the output. So the size of the output
6532** array is always (n1+n2) entries.
6533*/
6534static void fts5TokendataMerge(
6535 Fts5TokenDataMap *a1, int n1, /* Input array 1 */
6536 Fts5TokenDataMap *a2, int n2, /* Input array 2 */
6537 Fts5TokenDataMap *aOut /* Output array */
6538){
6539 int i1 = 0;
6540 int i2 = 0;
6541
6542 assert( n1>=0 && n2>=0 );
6543 while( i1<n1 || i2<n2 ){
6544 Fts5TokenDataMap *pOut = &aOut[i1+i2];
6545 if( i2>=n2 || (i1<n1 && (
6546 a1[i1].iRowid<a2[i2].iRowid
6547 || (a1[i1].iRowid==a2[i2].iRowid && a1[i1].iPos<=a2[i2].iPos)
6548 ))){
6549 memcpy(pOut, &a1[i1], sizeof(Fts5TokenDataMap));
6550 i1++;
6551 }else{
6552 memcpy(pOut, &a2[i2], sizeof(Fts5TokenDataMap));
6553 i2++;
6554 }
6555 }
6556}
6557
6558
6559/*
6560** Append a mapping to the token-map belonging to object pT.
6561*/
6562static void fts5TokendataIterAppendMap(
6563 Fts5Index *p,
6564 Fts5TokenDataIter *pT,
6565 int iIter,
6566 int nByte,
6567 i64 iRowid,
6568 i64 iPos
6569){
6570 if( p->rc==SQLITE_OK ){
6571 if( pT->nMap==pT->nMapAlloc ){
6572 i64 nNew = pT->nMapAlloc ? pT->nMapAlloc*2 : 64;
6573 i64 nAlloc = nNew * sizeof(Fts5TokenDataMap);
6574 Fts5TokenDataMap *aNew;
6575
6576 aNew = (Fts5TokenDataMap*)sqlite3_realloc64(pT->aMap, nAlloc);
6577 if( aNew==0 ){
6578 p->rc = SQLITE_NOMEM;
6579 return;
6580 }
6581
6582 pT->aMap = aNew;
6583 pT->nMapAlloc = nNew;
6584 }
6585
6586 pT->aMap[pT->nMap].iRowid = iRowid;
6587 pT->aMap[pT->nMap].iPos = iPos;
6588 pT->aMap[pT->nMap].iIter = iIter;
6589 pT->aMap[pT->nMap].nByte = nByte;
6590 pT->nMap++;
6591 }
6592}
6593
6594/*
6595** Sort the contents of the pT->aMap[] array.
6596**
6597** The sorting algorithm requires a malloc(). If this fails, an error code
6598** is left in Fts5Index.rc before returning.
6599*/
6600static void fts5TokendataIterSortMap(Fts5Index *p, Fts5TokenDataIter *pT){
6601 Fts5TokenDataMap *aTmp = 0;
6602 i64 nByte = pT->nMap * sizeof(Fts5TokenDataMap);
6603
6604 aTmp = (Fts5TokenDataMap*)sqlite3Fts5MallocZero(&p->rc, nByte);
6605 if( aTmp ){
6606 Fts5TokenDataMap *a1 = pT->aMap;
6607 Fts5TokenDataMap *a2 = aTmp;
6608 i64 nHalf;
6609
6610 for(nHalf=1; nHalf<pT->nMap; nHalf=nHalf*2){
6611 int i1;
6612 for(i1=0; i1<pT->nMap; i1+=(nHalf*2)){
6613 int n1 = MIN(nHalf, pT->nMap-i1);
6614 int n2 = MIN(nHalf, pT->nMap-i1-n1);
6615 fts5TokendataMerge(&a1[i1], n1, &a1[i1+n1], n2, &a2[i1]);
6616 }
6617 SWAPVAL(Fts5TokenDataMap*, a1, a2);
6618 }
6619
6620 if( a1!=pT->aMap ){
6621 memcpy(pT->aMap, a1, pT->nMap*sizeof(Fts5TokenDataMap));
6622 }
6623 sqlite3_free(aTmp);
6624
6625#ifdef SQLITE_DEBUG
6626 {
6627 int ii;
6628 for(ii=1; ii<pT->nMap; ii++){
6629 Fts5TokenDataMap *p1 = &pT->aMap[ii-1];
6630 Fts5TokenDataMap *p2 = &pT->aMap[ii];
6631 assert( p1->iRowid<p2->iRowid
6632 || (p1->iRowid==p2->iRowid && p1->iPos<=p2->iPos)
6633 );
6634 }
6635 }
6636#endif
6637 }
6638}
6639
6640/*
6641** Delete an Fts5TokenDataIter structure and its contents.
6642*/
6643static void fts5TokendataIterDelete(Fts5TokenDataIter *pSet){
6644 if( pSet ){
6645 int ii;
6646 for(ii=0; ii<pSet->nIter; ii++){
6647 fts5MultiIterFree(pSet->apIter[ii]);
6648 }
6649 fts5BufferFree(&pSet->terms);
6650 sqlite3_free(pSet->aPoslistReader);
6651 sqlite3_free(pSet->aMap);
6652 sqlite3_free(pSet);
6653 }
6654}
6655
6656
6657/*
6658** fts5VisitEntries() context object used by fts5SetupPrefixIterTokendata()
6659** to pass data to prefixIterSetupTokendataCb().
6660*/
6661typedef struct TokendataSetupCtx TokendataSetupCtx;
6662struct TokendataSetupCtx {
6663 Fts5TokenDataIter *pT; /* Object being populated with mappings */
6664 int iTermOff; /* Offset of current term in terms.p[] */
6665 int nTermByte; /* Size of current term in bytes */
6666};
6667
6668/*
6669** fts5VisitEntries() callback used by fts5SetupPrefixIterTokendata(). This
6670** callback adds an entry to the Fts5TokenDataIter.aMap[] array for each
6671** position in the current position-list. It doesn't matter that some of
6672** these may be out of order - they will be sorted later.
6673*/
6674static void prefixIterSetupTokendataCb(
6675 Fts5Index *p,
6676 void *pCtx,
6677 Fts5Iter *p1,
6678 const u8 *pNew,
6679 int nNew
6680){
6681 TokendataSetupCtx *pSetup = (TokendataSetupCtx*)pCtx;
6682 int iPosOff = 0;
6683 i64 iPos = 0;
6684
6685 if( pNew ){
6686 pSetup->nTermByte = nNew-1;
6687 pSetup->iTermOff = pSetup->pT->terms.n;
6688 fts5BufferAppendBlob(&p->rc, &pSetup->pT->terms, nNew-1, pNew+1);
6689 }
6690
6691 while( 0==sqlite3Fts5PoslistNext64(
6692 p1->base.pData, p1->base.nData, &iPosOff, &iPos
6693 ) ){
6694 fts5TokendataIterAppendMap(p,
6695 pSetup->pT, pSetup->iTermOff, pSetup->nTermByte, p1->base.iRowid, iPos
6696 );
6697 }
6698}
6699
6700
6701/*
6702** Context object passed by fts5SetupPrefixIter() to fts5VisitEntries().
6703*/
6704typedef struct PrefixSetupCtx PrefixSetupCtx;
6705struct PrefixSetupCtx {
6706 void (*xMerge)(Fts5Index*, Fts5Buffer*, int, Fts5Buffer*);
6707 void (*xAppend)(Fts5Index*, u64, Fts5Iter*, Fts5Buffer*);
6708 i64 iLastRowid;
6709 int nMerge;
6710 Fts5Buffer *aBuf;
6711 int nBuf;
6712 Fts5Buffer doclist;
6713 TokendataSetupCtx *pTokendata;
6714};
6715
6716/*
6717** fts5VisitEntries() callback used by fts5SetupPrefixIter()
6718*/
6719static void prefixIterSetupCb(
6720 Fts5Index *p,
6721 void *pCtx,
6722 Fts5Iter *p1,
6723 const u8 *pNew,
6724 int nNew
6725){
6726 PrefixSetupCtx *pSetup = (PrefixSetupCtx*)pCtx;
6727 const int nMerge = pSetup->nMerge;
6728
6729 if( p1->base.nData>0 ){
6730 if( p1->base.iRowid<=pSetup->iLastRowid && pSetup->doclist.n>0 ){
6731 int i;
6732 for(i=0; p->rc==SQLITE_OK && pSetup->doclist.n; i++){
6733 int i1 = i*nMerge;
6734 int iStore;
6735 assert( i1+nMerge<=pSetup->nBuf );
6736 for(iStore=i1; iStore<i1+nMerge; iStore++){
6737 if( pSetup->aBuf[iStore].n==0 ){
6738 fts5BufferSwap(&pSetup->doclist, &pSetup->aBuf[iStore]);
6739 fts5BufferZero(&pSetup->doclist);
6740 break;
6741 }
6742 }
6743 if( iStore==i1+nMerge ){
6744 pSetup->xMerge(p, &pSetup->doclist, nMerge, &pSetup->aBuf[i1]);
6745 for(iStore=i1; iStore<i1+nMerge; iStore++){
6746 fts5BufferZero(&pSetup->aBuf[iStore]);
6747 }
6748 }
6749 }
6750 pSetup->iLastRowid = 0;
6751 }
6752
6753 pSetup->xAppend(
6754 p, (u64)p1->base.iRowid-(u64)pSetup->iLastRowid, p1, &pSetup->doclist
6755 );
6756 pSetup->iLastRowid = p1->base.iRowid;
6757 }
6758
6759 if( pSetup->pTokendata ){
6760 prefixIterSetupTokendataCb(p, (void*)pSetup->pTokendata, p1, pNew, nNew);
6761 }
6762}
6763
6764static void fts5SetupPrefixIter(
6765 Fts5Index *p, /* Index to read from */
6766 int bDesc, /* True for "ORDER BY rowid DESC" */
6767 int iIdx, /* Index to scan for data */
6768 u8 *pToken, /* Buffer containing prefix to match */
6769 int nToken, /* Size of buffer pToken in bytes */
6770 Fts5Colset *pColset, /* Restrict matches to these columns */
6771 Fts5Iter **ppIter /* OUT: New iterator */
6772){
6773 Fts5Structure *pStruct;
6774 PrefixSetupCtx s;
6775 TokendataSetupCtx s2;
6776
6777 memset(&s, 0, sizeof(s));
6778 memset(&s2, 0, sizeof(s2));
6779
6780 s.nMerge = 1;
6781 s.iLastRowid = 0;
6782 s.nBuf = 32;
6783 if( iIdx==0
6784 && p->pConfig->eDetail==FTS5_DETAIL_FULL
6785 && p->pConfig->bPrefixInsttoken
6786 ){
6787 s.pTokendata = &s2;
6788 s2.pT = (Fts5TokenDataIter*)fts5IdxMalloc(p, SZ_FTS5TOKENDATAITER(1));
6789 }
6790
6791 if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
6792 s.xMerge = fts5MergeRowidLists;
6793 s.xAppend = fts5AppendRowid;
6794 }else{
6795 s.nMerge = FTS5_MERGE_NLIST-1;
6796 s.nBuf = s.nMerge*8; /* Sufficient to merge (16^8)==(2^32) lists */
6797 s.xMerge = fts5MergePrefixLists;
6798 s.xAppend = fts5AppendPoslist;
6799 }
6800
6801 s.aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*s.nBuf);
6802 pStruct = fts5StructureRead(p);
6803 assert( p->rc!=SQLITE_OK || (s.aBuf && pStruct) );
6804
6805 if( p->rc==SQLITE_OK ){
6806 void *pCtx = (void*)&s;
6807 int i;
6808 Fts5Data *pData;
6809
6810 /* If iIdx is non-zero, then it is the number of a prefix-index for
6811 ** prefixes 1 character longer than the prefix being queried for. That
6812 ** index contains all the doclists required, except for the one
6813 ** corresponding to the prefix itself. That one is extracted from the
6814 ** main term index here. */
6815 if( iIdx!=0 ){
6816 pToken[0] = FTS5_MAIN_PREFIX;
6817 fts5VisitEntries(p, pColset, pToken, nToken, 0, prefixIterSetupCb, pCtx);
6818 }
6819
6820 pToken[0] = FTS5_MAIN_PREFIX + iIdx;
6821 fts5VisitEntries(p, pColset, pToken, nToken, 1, prefixIterSetupCb, pCtx);
6822
6823 assert( (s.nBuf%s.nMerge)==0 );
6824 for(i=0; i<s.nBuf; i+=s.nMerge){
6825 int iFree;
6826 if( p->rc==SQLITE_OK ){
6827 s.xMerge(p, &s.doclist, s.nMerge, &s.aBuf[i]);
6828 }
6829 for(iFree=i; iFree<i+s.nMerge; iFree++){
6830 fts5BufferFree(&s.aBuf[iFree]);
6831 }
6832 }
6833
6834 pData = fts5IdxMalloc(p, sizeof(*pData)
6835 + ((i64)s.doclist.n)+FTS5_DATA_ZERO_PADDING);
6836 assert( pData!=0 || p->rc!=SQLITE_OK );
6837 if( pData ){
6838 pData->p = (u8*)&pData[1];
6839 pData->nn = pData->szLeaf = s.doclist.n;
6840 if( s.doclist.n ) memcpy(pData->p, s.doclist.p, s.doclist.n);
6841 fts5MultiIterNew2(p, pData, bDesc, ppIter);
6842 }
6843
6844 assert( (*ppIter)!=0 || p->rc!=SQLITE_OK );
6845 if( p->rc==SQLITE_OK && s.pTokendata ){
6846 fts5TokendataIterSortMap(p, s2.pT);
6847 (*ppIter)->pTokenDataIter = s2.pT;
6848 s2.pT = 0;
6849 }
6850 }
6851
6852 fts5TokendataIterDelete(s2.pT);
6853 fts5BufferFree(&s.doclist);
6854 fts5StructureRelease(pStruct);
6855 sqlite3_free(s.aBuf);
6856}
6857
6858
6859/*
6860** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
6861** to the document with rowid iRowid.
6862*/
6863int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
6864 assert( p->rc==SQLITE_OK );
6865
6866 /* Allocate the hash table if it has not already been allocated */
6867 if( p->pHash==0 ){
6868 p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
6869 }
6870
6871 /* Flush the hash table to disk if required */
6872 if( iRowid<p->iWriteRowid
6873 || (iRowid==p->iWriteRowid && p->bDelete==0)
6874 || (p->nPendingData > p->pConfig->nHashSize)
6875 ){
6876 fts5IndexFlush(p);
6877 }
6878
6879 p->iWriteRowid = iRowid;
6880 p->bDelete = bDelete;
6881 if( bDelete==0 ){
6882 p->nPendingRow++;
6883 }
6884 return fts5IndexReturn(p);
6885}
6886
6887/*
6888** Commit data to disk.
6889*/
6890int sqlite3Fts5IndexSync(Fts5Index *p){
6891 assert( p->rc==SQLITE_OK );
6892 fts5IndexFlush(p);
6893 fts5IndexCloseReader(p);
6894 return fts5IndexReturn(p);
6895}
6896
6897/*
6898** Discard any data stored in the in-memory hash tables. Do not write it
6899** to the database. Additionally, assume that the contents of the %_data
6900** table may have changed on disk. So any in-memory caches of %_data
6901** records must be invalidated.
6902*/
6903int sqlite3Fts5IndexRollback(Fts5Index *p){
6904 fts5IndexCloseReader(p);
6905 fts5IndexDiscardData(p);
6906 fts5StructureInvalidate(p);
6907 return fts5IndexReturn(p);
6908}
6909
6910/*
6911** The %_data table is completely empty when this function is called. This
6912** function populates it with the initial structure objects for each index,
6913** and the initial version of the "averages" record (a zero-byte blob).
6914*/
6915int sqlite3Fts5IndexReinit(Fts5Index *p){
6916 Fts5Structure *pTmp;
6917 union {
6918 Fts5Structure sFts;
6919 u8 tmpSpace[SZ_FTS5STRUCTURE(1)];
6920 } uFts;
6921 fts5StructureInvalidate(p);
6922 fts5IndexDiscardData(p);
6923 pTmp = &uFts.sFts;
6924 memset(uFts.tmpSpace, 0, sizeof(uFts.tmpSpace));
6925 if( p->pConfig->bContentlessDelete ){
6926 pTmp->nOriginCntr = 1;
6927 }
6928 fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
6929 fts5StructureWrite(p, pTmp);
6930 return fts5IndexReturn(p);
6931}
6932
6933/*
6934** Open a new Fts5Index handle. If the bCreate argument is true, create
6935** and initialize the underlying %_data table.
6936**
6937** If successful, set *pp to point to the new object and return SQLITE_OK.
6938** Otherwise, set *pp to NULL and return an SQLite error code.
6939*/
6940int sqlite3Fts5IndexOpen(
6941 Fts5Config *pConfig,
6942 int bCreate,
6943 Fts5Index **pp,
6944 char **pzErr
6945){
6946 int rc = SQLITE_OK;
6947 Fts5Index *p; /* New object */
6948
6949 *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
6950 if( rc==SQLITE_OK ){
6951 p->pConfig = pConfig;
6952 p->nWorkUnit = FTS5_WORK_UNIT;
6953 p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
6954 if( p->zDataTbl && bCreate ){
6955 rc = sqlite3Fts5CreateTable(
6956 pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
6957 );
6958 if( rc==SQLITE_OK ){
6959 rc = sqlite3Fts5CreateTable(pConfig, "idx",
6960 "segid, term, pgno, PRIMARY KEY(segid, term)",
6961 1, pzErr
6962 );
6963 }
6964 if( rc==SQLITE_OK ){
6965 rc = sqlite3Fts5IndexReinit(p);
6966 }
6967 }
6968 }
6969
6970 assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
6971 if( rc ){
6972 sqlite3Fts5IndexClose(p);
6973 *pp = 0;
6974 }
6975 return rc;
6976}
6977
6978/*
6979** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
6980*/
6981int sqlite3Fts5IndexClose(Fts5Index *p){
6982 int rc = SQLITE_OK;
6983 if( p ){
6984 assert( p->pReader==0 );
6985 fts5StructureInvalidate(p);
6986 sqlite3_finalize(p->pWriter);
6987 sqlite3_finalize(p->pDeleter);
6988 sqlite3_finalize(p->pIdxWriter);
6989 sqlite3_finalize(p->pIdxDeleter);
6990 sqlite3_finalize(p->pIdxSelect);
6991 sqlite3_finalize(p->pIdxNextSelect);
6992 sqlite3_finalize(p->pDataVersion);
6993 sqlite3_finalize(p->pDeleteFromIdx);
6994 sqlite3Fts5HashFree(p->pHash);
6995 sqlite3_free(p->zDataTbl);
6996 sqlite3_free(p);
6997 }
6998 return rc;
6999}
7000
7001/*
7002** Argument p points to a buffer containing utf-8 text that is n bytes in
7003** size. Return the number of bytes in the nChar character prefix of the
7004** buffer, or 0 if there are less than nChar characters in total.
7005*/
7006int sqlite3Fts5IndexCharlenToBytelen(
7007 const char *p,
7008 int nByte,
7009 int nChar
7010){
7011 int n = 0;
7012 int i;
7013 for(i=0; i<nChar; i++){
7014 if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
7015 if( (unsigned char)p[n++]>=0xc0 ){
7016 if( n>=nByte ) return 0;
7017 while( (p[n] & 0xc0)==0x80 ){
7018 n++;
7019 if( n>=nByte ){
7020 if( i+1==nChar ) break;
7021 return 0;
7022 }
7023 }
7024 }
7025 }
7026 return n;
7027}
7028
7029/*
7030** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
7031** unicode characters in the string.
7032*/
7033static int fts5IndexCharlen(const char *pIn, int nIn){
7034 int nChar = 0;
7035 int i = 0;
7036 while( i<nIn ){
7037 if( (unsigned char)pIn[i++]>=0xc0 ){
7038 while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
7039 }
7040 nChar++;
7041 }
7042 return nChar;
7043}
7044
7045/*
7046** Insert or remove data to or from the index. Each time a document is
7047** added to or removed from the index, this function is called one or more
7048** times.
7049**
7050** For an insert, it must be called once for each token in the new document.
7051** If the operation is a delete, it must be called (at least) once for each
7052** unique token in the document with an iCol value less than zero. The iPos
7053** argument is ignored for a delete.
7054*/
7055int sqlite3Fts5IndexWrite(
7056 Fts5Index *p, /* Index to write to */
7057 int iCol, /* Column token appears in (-ve -> delete) */
7058 int iPos, /* Position of token within column */
7059 const char *pToken, int nToken /* Token to add or remove to or from index */
7060){
7061 int i; /* Used to iterate through indexes */
7062 int rc = SQLITE_OK; /* Return code */
7063 Fts5Config *pConfig = p->pConfig;
7064
7065 assert( p->rc==SQLITE_OK );
7066 assert( (iCol<0)==p->bDelete );
7067
7068 /* Add the entry to the main terms index. */
7069 rc = sqlite3Fts5HashWrite(
7070 p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
7071 );
7072
7073 for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
7074 const int nChar = pConfig->aPrefix[i];
7075 int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
7076 if( nByte ){
7077 rc = sqlite3Fts5HashWrite(p->pHash,
7078 p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
7079 nByte
7080 );
7081 }
7082 }
7083
7084 return rc;
7085}
7086
7087/*
7088** pToken points to a buffer of size nToken bytes containing a search
7089** term, including the index number at the start, used on a tokendata=1
7090** table. This function returns true if the term in buffer pBuf matches
7091** token pToken/nToken.
7092*/
7093static int fts5IsTokendataPrefix(
7094 Fts5Buffer *pBuf,
7095 const u8 *pToken,
7096 int nToken
7097){
7098 return (
7099 pBuf->n>=nToken
7100 && 0==memcmp(pBuf->p, pToken, nToken)
7101 && (pBuf->n==nToken || pBuf->p[nToken]==0x00)
7102 );
7103}
7104
7105/*
7106** Ensure the segment-iterator passed as the only argument points to EOF.
7107*/
7108static void fts5SegIterSetEOF(Fts5SegIter *pSeg){
7109 fts5DataRelease(pSeg->pLeaf);
7110 pSeg->pLeaf = 0;
7111}
7112
7113static void fts5IterClose(Fts5IndexIter *pIndexIter){
7114 if( pIndexIter ){
7115 Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
7116 Fts5Index *pIndex = pIter->pIndex;
7117 fts5TokendataIterDelete(pIter->pTokenDataIter);
7118 fts5MultiIterFree(pIter);
7119 fts5IndexCloseReader(pIndex);
7120 }
7121}
7122
7123/*
7124** This function appends iterator pAppend to Fts5TokenDataIter pIn and
7125** returns the result.
7126*/
7127static Fts5TokenDataIter *fts5AppendTokendataIter(
7128 Fts5Index *p, /* Index object (for error code) */
7129 Fts5TokenDataIter *pIn, /* Current Fts5TokenDataIter struct */
7130 Fts5Iter *pAppend /* Append this iterator */
7131){
7132 Fts5TokenDataIter *pRet = pIn;
7133
7134 if( p->rc==SQLITE_OK ){
7135 if( pIn==0 || pIn->nIter==pIn->nIterAlloc ){
7136 i64 nAlloc = pIn ? pIn->nIterAlloc*2 : 16;
7137 i64 nByte = SZ_FTS5TOKENDATAITER(nAlloc+1);
7138 Fts5TokenDataIter *pNew;
7139 pNew = (Fts5TokenDataIter*)sqlite3_realloc64(pIn, nByte);
7140
7141 if( pNew==0 ){
7142 p->rc = SQLITE_NOMEM;
7143 }else{
7144 if( pIn==0 ) memset(pNew, 0, nByte);
7145 pRet = pNew;
7146 pNew->nIterAlloc = nAlloc;
7147 }
7148 }
7149 }
7150 if( p->rc ){
7151 fts5IterClose((Fts5IndexIter*)pAppend);
7152 }else{
7153 pRet->apIter[pRet->nIter++] = pAppend;
7154 }
7155 assert( pRet==0 || pRet->nIter<=pRet->nIterAlloc );
7156
7157 return pRet;
7158}
7159
7160/*
7161** The iterator passed as the only argument must be a tokendata=1 iterator
7162** (pIter->pTokenDataIter!=0). This function sets the iterator output
7163** variables (pIter->base.*) according to the contents of the current
7164** row.
7165*/
7166static void fts5IterSetOutputsTokendata(Fts5Iter *pIter){
7167 int ii;
7168 int nHit = 0;
7169 i64 iRowid = SMALLEST_INT64;
7170 int iMin = 0;
7171
7172 Fts5TokenDataIter *pT = pIter->pTokenDataIter;
7173
7174 pIter->base.nData = 0;
7175 pIter->base.pData = 0;
7176
7177 for(ii=0; ii<pT->nIter; ii++){
7178 Fts5Iter *p = pT->apIter[ii];
7179 if( p->base.bEof==0 ){
7180 if( nHit==0 || p->base.iRowid<iRowid ){
7181 iRowid = p->base.iRowid;
7182 nHit = 1;
7183 pIter->base.pData = p->base.pData;
7184 pIter->base.nData = p->base.nData;
7185 iMin = ii;
7186 }else if( p->base.iRowid==iRowid ){
7187 nHit++;
7188 }
7189 }
7190 }
7191
7192 if( nHit==0 ){
7193 pIter->base.bEof = 1;
7194 }else{
7195 int eDetail = pIter->pIndex->pConfig->eDetail;
7196 pIter->base.bEof = 0;
7197 pIter->base.iRowid = iRowid;
7198
7199 if( nHit==1 && eDetail==FTS5_DETAIL_FULL ){
7200 fts5TokendataIterAppendMap(pIter->pIndex, pT, iMin, 0, iRowid, -1);
7201 }else
7202 if( nHit>1 && eDetail!=FTS5_DETAIL_NONE ){
7203 int nReader = 0;
7204 int nByte = 0;
7205 i64 iPrev = 0;
7206
7207 /* Allocate array of iterators if they are not already allocated. */
7208 if( pT->aPoslistReader==0 ){
7209 pT->aPoslistReader = (Fts5PoslistReader*)sqlite3Fts5MallocZero(
7210 &pIter->pIndex->rc,
7211 pT->nIter * (sizeof(Fts5PoslistReader) + sizeof(int))
7212 );
7213 if( pT->aPoslistReader==0 ) return;
7214 pT->aPoslistToIter = (int*)&pT->aPoslistReader[pT->nIter];
7215 }
7216
7217 /* Populate an iterator for each poslist that will be merged */
7218 for(ii=0; ii<pT->nIter; ii++){
7219 Fts5Iter *p = pT->apIter[ii];
7220 if( iRowid==p->base.iRowid ){
7221 pT->aPoslistToIter[nReader] = ii;
7222 sqlite3Fts5PoslistReaderInit(
7223 p->base.pData, p->base.nData, &pT->aPoslistReader[nReader++]
7224 );
7225 nByte += p->base.nData;
7226 }
7227 }
7228
7229 /* Ensure the output buffer is large enough */
7230 if( fts5BufferGrow(&pIter->pIndex->rc, &pIter->poslist, nByte+nHit*10) ){
7231 return;
7232 }
7233
7234 /* Ensure the token-mapping is large enough */
7235 if( eDetail==FTS5_DETAIL_FULL && pT->nMapAlloc<(pT->nMap + nByte) ){
7236 i64 nNew = (pT->nMapAlloc + nByte) * 2;
7237 Fts5TokenDataMap *aNew = (Fts5TokenDataMap*)sqlite3_realloc64(
7238 pT->aMap, nNew*sizeof(Fts5TokenDataMap)
7239 );
7240 if( aNew==0 ){
7241 pIter->pIndex->rc = SQLITE_NOMEM;
7242 return;
7243 }
7244 pT->aMap = aNew;
7245 pT->nMapAlloc = nNew;
7246 }
7247
7248 pIter->poslist.n = 0;
7249
7250 while( 1 ){
7251 i64 iMinPos = LARGEST_INT64;
7252
7253 /* Find smallest position */
7254 iMin = 0;
7255 for(ii=0; ii<nReader; ii++){
7256 Fts5PoslistReader *pReader = &pT->aPoslistReader[ii];
7257 if( pReader->bEof==0 ){
7258 if( pReader->iPos<iMinPos ){
7259 iMinPos = pReader->iPos;
7260 iMin = ii;
7261 }
7262 }
7263 }
7264
7265 /* If all readers were at EOF, break out of the loop. */
7266 if( iMinPos==LARGEST_INT64 ) break;
7267
7268 sqlite3Fts5PoslistSafeAppend(&pIter->poslist, &iPrev, iMinPos);
7269 sqlite3Fts5PoslistReaderNext(&pT->aPoslistReader[iMin]);
7270
7271 if( eDetail==FTS5_DETAIL_FULL ){
7272 pT->aMap[pT->nMap].iPos = iMinPos;
7273 pT->aMap[pT->nMap].iIter = pT->aPoslistToIter[iMin];
7274 pT->aMap[pT->nMap].iRowid = iRowid;
7275 pT->nMap++;
7276 }
7277 }
7278
7279 pIter->base.pData = pIter->poslist.p;
7280 pIter->base.nData = pIter->poslist.n;
7281 }
7282 }
7283}
7284
7285/*
7286** The iterator passed as the only argument must be a tokendata=1 iterator
7287** (pIter->pTokenDataIter!=0). This function advances the iterator. If
7288** argument bFrom is false, then the iterator is advanced to the next
7289** entry. Or, if bFrom is true, it is advanced to the first entry with
7290** a rowid of iFrom or greater.
7291*/
7292static void fts5TokendataIterNext(Fts5Iter *pIter, int bFrom, i64 iFrom){
7293 int ii;
7294 Fts5TokenDataIter *pT = pIter->pTokenDataIter;
7295 Fts5Index *pIndex = pIter->pIndex;
7296
7297 for(ii=0; ii<pT->nIter; ii++){
7298 Fts5Iter *p = pT->apIter[ii];
7299 if( p->base.bEof==0
7300 && (p->base.iRowid==pIter->base.iRowid || (bFrom && p->base.iRowid<iFrom))
7301 ){
7302 if( bFrom ){
7303 fts5MultiIterNextFrom(pIndex, p, iFrom);
7304 }else{
7305 fts5MultiIterNext(pIndex, p, 0, 0);
7306 }
7307 }
7308 }
7309
7310 if( pIndex->rc==SQLITE_OK ){
7311 fts5IterSetOutputsTokendata(pIter);
7312 }
7313}
7314
7315/*
7316** If the segment-iterator passed as the first argument is at EOF, then
7317** set pIter->term to a copy of buffer pTerm.
7318*/
7319static void fts5TokendataSetTermIfEof(Fts5Iter *pIter, Fts5Buffer *pTerm){
7320 if( pIter && pIter->aSeg[0].pLeaf==0 ){
7321 fts5BufferSet(&pIter->pIndex->rc, &pIter->aSeg[0].term, pTerm->n, pTerm->p);
7322 }
7323}
7324
7325/*
7326** This function sets up an iterator to use for a non-prefix query on a
7327** tokendata=1 table.
7328*/
7329static Fts5Iter *fts5SetupTokendataIter(
7330 Fts5Index *p, /* FTS index to query */
7331 const u8 *pToken, /* Buffer containing query term */
7332 int nToken, /* Size of buffer pToken in bytes */
7333 Fts5Colset *pColset /* Colset to filter on */
7334){
7335 Fts5Iter *pRet = 0;
7336 Fts5TokenDataIter *pSet = 0;
7337 Fts5Structure *pStruct = 0;
7338 const int flags = FTS5INDEX_QUERY_SCANONETERM | FTS5INDEX_QUERY_SCAN;
7339
7340 Fts5Buffer bSeek = {0, 0, 0};
7341 Fts5Buffer *pSmall = 0;
7342
7343 fts5IndexFlush(p);
7344 pStruct = fts5StructureRead(p);
7345
7346 while( p->rc==SQLITE_OK ){
7347 Fts5Iter *pPrev = pSet ? pSet->apIter[pSet->nIter-1] : 0;
7348 Fts5Iter *pNew = 0;
7349 Fts5SegIter *pNewIter = 0;
7350 Fts5SegIter *pPrevIter = 0;
7351
7352 int iLvl, iSeg, ii;
7353
7354 pNew = fts5MultiIterAlloc(p, pStruct->nSegment);
7355 if( pSmall ){
7356 fts5BufferSet(&p->rc, &bSeek, pSmall->n, pSmall->p);
7357 fts5BufferAppendBlob(&p->rc, &bSeek, 1, (const u8*)"\0");
7358 }else{
7359 fts5BufferSet(&p->rc, &bSeek, nToken, pToken);
7360 }
7361 if( p->rc ){
7362 fts5IterClose((Fts5IndexIter*)pNew);
7363 break;
7364 }
7365
7366 pNewIter = &pNew->aSeg[0];
7367 pPrevIter = (pPrev ? &pPrev->aSeg[0] : 0);
7368 for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
7369 for(iSeg=pStruct->aLevel[iLvl].nSeg-1; iSeg>=0; iSeg--){
7370 Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
7371 int bDone = 0;
7372
7373 if( pPrevIter ){
7374 if( fts5BufferCompare(pSmall, &pPrevIter->term) ){
7375 memcpy(pNewIter, pPrevIter, sizeof(Fts5SegIter));
7376 memset(pPrevIter, 0, sizeof(Fts5SegIter));
7377 bDone = 1;
7378 }else if( pPrevIter->iEndofDoclist>pPrevIter->pLeaf->szLeaf ){
7379 fts5SegIterNextInit(p,(const char*)bSeek.p,bSeek.n-1,pSeg,pNewIter);
7380 bDone = 1;
7381 }
7382 }
7383
7384 if( bDone==0 ){
7385 fts5SegIterSeekInit(p, bSeek.p, bSeek.n, flags, pSeg, pNewIter);
7386 }
7387
7388 if( pPrevIter ){
7389 if( pPrevIter->pTombArray ){
7390 pNewIter->pTombArray = pPrevIter->pTombArray;
7391 pNewIter->pTombArray->nRef++;
7392 }
7393 }else{
7394 fts5SegIterAllocTombstone(p, pNewIter);
7395 }
7396
7397 pNewIter++;
7398 if( pPrevIter ) pPrevIter++;
7399 if( p->rc ) break;
7400 }
7401 }
7402 fts5TokendataSetTermIfEof(pPrev, pSmall);
7403
7404 pNew->bSkipEmpty = 1;
7405 pNew->pColset = pColset;
7406 fts5IterSetOutputCb(&p->rc, pNew);
7407
7408 /* Loop through all segments in the new iterator. Find the smallest
7409 ** term that any segment-iterator points to. Iterator pNew will be
7410 ** used for this term. Also, set any iterator that points to a term that
7411 ** does not match pToken/nToken to point to EOF */
7412 pSmall = 0;
7413 for(ii=0; ii<pNew->nSeg; ii++){
7414 Fts5SegIter *pII = &pNew->aSeg[ii];
7415 if( 0==fts5IsTokendataPrefix(&pII->term, pToken, nToken) ){
7416 fts5SegIterSetEOF(pII);
7417 }
7418 if( pII->pLeaf && (!pSmall || fts5BufferCompare(pSmall, &pII->term)>0) ){
7419 pSmall = &pII->term;
7420 }
7421 }
7422
7423 /* If pSmall is still NULL at this point, then the new iterator does
7424 ** not point to any terms that match the query. So delete it and break
7425 ** out of the loop - all required iterators have been collected. */
7426 if( pSmall==0 ){
7427 fts5IterClose((Fts5IndexIter*)pNew);
7428 break;
7429 }
7430
7431 /* Append this iterator to the set and continue. */
7432 pSet = fts5AppendTokendataIter(p, pSet, pNew);
7433 }
7434
7435 if( p->rc==SQLITE_OK && pSet ){
7436 int ii;
7437 for(ii=0; ii<pSet->nIter; ii++){
7438 Fts5Iter *pIter = pSet->apIter[ii];
7439 int iSeg;
7440 for(iSeg=0; iSeg<pIter->nSeg; iSeg++){
7441 pIter->aSeg[iSeg].flags |= FTS5_SEGITER_ONETERM;
7442 }
7443 fts5MultiIterFinishSetup(p, pIter);
7444 }
7445 }
7446
7447 if( p->rc==SQLITE_OK ){
7448 pRet = fts5MultiIterAlloc(p, 0);
7449 }
7450 if( pRet ){
7451 pRet->nSeg = 0;
7452 pRet->pTokenDataIter = pSet;
7453 if( pSet ){
7454 fts5IterSetOutputsTokendata(pRet);
7455 }else{
7456 pRet->base.bEof = 1;
7457 }
7458 }else{
7459 fts5TokendataIterDelete(pSet);
7460 }
7461
7462 fts5StructureRelease(pStruct);
7463 fts5BufferFree(&bSeek);
7464 return pRet;
7465}
7466
7467/*
7468** Open a new iterator to iterate though all rowid that match the
7469** specified token or token prefix.
7470*/
7471int sqlite3Fts5IndexQuery(
7472 Fts5Index *p, /* FTS index to query */
7473 const char *pToken, int nToken, /* Token (or prefix) to query for */
7474 int flags, /* Mask of FTS5INDEX_QUERY_X flags */
7475 Fts5Colset *pColset, /* Match these columns only */
7476 Fts5IndexIter **ppIter /* OUT: New iterator object */
7477){
7478 Fts5Config *pConfig = p->pConfig;
7479 Fts5Iter *pRet = 0;
7480 Fts5Buffer buf = {0, 0, 0};
7481
7482 /* If the QUERY_SCAN flag is set, all other flags must be clear. */
7483 assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
7484
7485 if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
7486 int iIdx = 0; /* Index to search */
7487 int iPrefixIdx = 0; /* +1 prefix index */
7488 int bTokendata = pConfig->bTokendata;
7489 assert( buf.p!=0 );
7490 if( nToken>0 ) memcpy(&buf.p[1], pToken, nToken);
7491
7492 /* The NOTOKENDATA flag is set when each token in a tokendata=1 table
7493 ** should be treated individually, instead of merging all those with
7494 ** a common prefix into a single entry. This is used, for example, by
7495 ** queries performed as part of an integrity-check, or by the fts5vocab
7496 ** module. */
7497 if( flags & (FTS5INDEX_QUERY_NOTOKENDATA|FTS5INDEX_QUERY_SCAN) ){
7498 bTokendata = 0;
7499 }
7500
7501 /* fts5SetupTokendataIter() flushes the in-memory hash table to disk.
7502 ** The flush frees the cached Fts5Structure object, which iterators
7503 ** opened earlier by this function point into without holding a
7504 ** reference (for example one opened for a prefix index query in the
7505 ** same MATCH expression). So, on a tokendata=1 table, flush first. */
7506 if( pConfig->bTokendata ){
7507 fts5IndexFlush(p);
7508 }
7509
7510 /* Figure out which index to search and set iIdx accordingly. If this
7511 ** is a prefix query for which there is no prefix index, set iIdx to
7512 ** greater than pConfig->nPrefix to indicate that the query will be
7513 ** satisfied by scanning multiple terms in the main index.
7514 **
7515 ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
7516 ** prefix-query. Instead of using a prefix-index (if one exists),
7517 ** evaluate the prefix query using the main FTS index. This is used
7518 ** for internal sanity checking by the integrity-check in debug
7519 ** mode only. */
7520#ifdef SQLITE_DEBUG
7521 if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
7522 assert( flags & FTS5INDEX_QUERY_PREFIX );
7523 iIdx = 1+pConfig->nPrefix;
7524 }else
7525#endif
7526 if( flags & FTS5INDEX_QUERY_PREFIX ){
7527 int nChar = fts5IndexCharlen(pToken, nToken);
7528 for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
7529 int nIdxChar = pConfig->aPrefix[iIdx-1];
7530 if( nIdxChar==nChar ) break;
7531 if( nIdxChar==nChar+1 ) iPrefixIdx = iIdx;
7532 }
7533 }
7534
7535 if( bTokendata && iIdx==0 ){
7536 buf.p[0] = FTS5_MAIN_PREFIX;
7537 pRet = fts5SetupTokendataIter(p, buf.p, nToken+1, pColset);
7538 }else if( iIdx<=pConfig->nPrefix ){
7539 /* Straight index lookup */
7540 Fts5Structure *pStruct = fts5StructureRead(p);
7541 buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
7542 if( pStruct ){
7543 fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
7544 pColset, buf.p, nToken+1, -1, 0, &pRet
7545 );
7546 fts5StructureRelease(pStruct);
7547 }
7548 }else{
7549 /* Scan multiple terms in the main index for a prefix query. */
7550 int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
7551 fts5SetupPrefixIter(p, bDesc, iPrefixIdx, buf.p, nToken+1, pColset,&pRet);
7552 if( pRet==0 ){
7553 assert( p->rc!=SQLITE_OK );
7554 }else{
7555 assert( pRet->pColset==0 );
7556 fts5IterSetOutputCb(&p->rc, pRet);
7557 if( p->rc==SQLITE_OK ){
7558 Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
7559 if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
7560 }
7561 }
7562 }
7563
7564 if( p->rc ){
7565 fts5IterClose((Fts5IndexIter*)pRet);
7566 pRet = 0;
7567 fts5IndexCloseReader(p);
7568 }
7569
7570 *ppIter = (Fts5IndexIter*)pRet;
7571 sqlite3Fts5BufferFree(&buf);
7572 }
7573 return fts5IndexReturn(p);
7574}
7575
7576/*
7577** Return true if the iterator passed as the only argument is at EOF.
7578*/
7579/*
7580** Move to the next matching rowid.
7581*/
7582int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
7583 Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
7584 assert( pIter->pIndex->rc==SQLITE_OK );
7585 if( pIter->nSeg==0 ){
7586 assert( pIter->pTokenDataIter );
7587 fts5TokendataIterNext(pIter, 0, 0);
7588 }else{
7589 fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
7590 }
7591 return fts5IndexReturn(pIter->pIndex);
7592}
7593
7594/*
7595** Move to the next matching term/rowid. Used by the fts5vocab module.
7596*/
7597int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
7598 Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
7599 Fts5Index *p = pIter->pIndex;
7600
7601 assert( pIter->pIndex->rc==SQLITE_OK );
7602
7603 fts5MultiIterNext(p, pIter, 0, 0);
7604 if( p->rc==SQLITE_OK ){
7605 Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
7606 if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
7607 fts5DataRelease(pSeg->pLeaf);
7608 pSeg->pLeaf = 0;
7609 pIter->base.bEof = 1;
7610 }
7611 }
7612
7613 return fts5IndexReturn(pIter->pIndex);
7614}
7615
7616/*
7617** Move to the next matching rowid that occurs at or after iMatch. The
7618** definition of "at or after" depends on whether this iterator iterates
7619** in ascending or descending rowid order.
7620*/
7621int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
7622 Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
7623 if( pIter->nSeg==0 ){
7624 assert( pIter->pTokenDataIter );
7625 fts5TokendataIterNext(pIter, 1, iMatch);
7626 }else{
7627 fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
7628 }
7629 return fts5IndexReturn(pIter->pIndex);
7630}
7631
7632/*
7633** Return the current term.
7634*/
7635const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
7636 int n;
7637 const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
7638 assert_nc( z || n<=1 );
7639 *pn = n-1;
7640 return (z ? &z[1] : 0);
7641}
7642
7643/*
7644** pIter is a prefix query. This function populates pIter->pTokenDataIter
7645** with an Fts5TokenDataIter object containing mappings for all rows
7646** matched by the query.
7647*/
7648static int fts5SetupPrefixIterTokendata(
7649 Fts5Iter *pIter,
7650 const char *pToken, /* Token prefix to search for */
7651 int nToken /* Size of pToken in bytes */
7652){
7653 Fts5Index *p = pIter->pIndex;
7654 Fts5Buffer token = {0, 0, 0};
7655 TokendataSetupCtx ctx;
7656
7657 memset(&ctx, 0, sizeof(ctx));
7658
7659 fts5BufferGrow(&p->rc, &token, nToken+1);
7660 assert( token.p!=0 || p->rc!=SQLITE_OK );
7661 ctx.pT = (Fts5TokenDataIter*)sqlite3Fts5MallocZero(&p->rc,
7662 SZ_FTS5TOKENDATAITER(1));
7663
7664 if( p->rc==SQLITE_OK ){
7665
7666 /* Fill in the token prefix to search for */
7667 token.p[0] = FTS5_MAIN_PREFIX;
7668 memcpy(&token.p[1], pToken, nToken);
7669 token.n = nToken+1;
7670
7671 fts5VisitEntries(
7672 p, 0, token.p, token.n, 1, prefixIterSetupTokendataCb, (void*)&ctx
7673 );
7674
7675 fts5TokendataIterSortMap(p, ctx.pT);
7676 }
7677
7678 if( p->rc==SQLITE_OK ){
7679 pIter->pTokenDataIter = ctx.pT;
7680 }else{
7681 fts5TokendataIterDelete(ctx.pT);
7682 }
7683 fts5BufferFree(&token);
7684
7685 return fts5IndexReturn(p);
7686}
7687
7688/*
7689** This is used by xInstToken() to access the token at offset iOff, column
7690** iCol of row iRowid. The token is returned via output variables *ppOut
7691** and *pnOut. The iterator passed as the first argument must be a tokendata=1
7692** iterator (pIter->pTokenDataIter!=0).
7693**
7694** pToken/nToken:
7695*/
7696int sqlite3Fts5IterToken(
7697 Fts5IndexIter *pIndexIter,
7698 const char *pToken, int nToken,
7699 i64 iRowid,
7700 int iCol,
7701 int iOff,
7702 const char **ppOut, int *pnOut
7703){
7704 Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
7705 Fts5TokenDataIter *pT = pIter->pTokenDataIter;
7706 i64 iPos = (((i64)iCol)<<32) + iOff;
7707 Fts5TokenDataMap *aMap = 0;
7708 int i1 = 0;
7709 int i2 = 0;
7710 int iTest = 0;
7711
7712 assert( pT || (pToken && pIter->nSeg>0) );
7713 if( pT==0 ){
7714 int rc = fts5SetupPrefixIterTokendata(pIter, pToken, nToken);
7715 if( rc!=SQLITE_OK ) return rc;
7716 pT = pIter->pTokenDataIter;
7717 }
7718
7719 i2 = pT->nMap;
7720 aMap = pT->aMap;
7721
7722 while( i2>i1 ){
7723 iTest = (i1 + i2) / 2;
7724
7725 if( aMap[iTest].iRowid<iRowid ){
7726 i1 = iTest+1;
7727 }else if( aMap[iTest].iRowid>iRowid ){
7728 i2 = iTest;
7729 }else{
7730 if( aMap[iTest].iPos<iPos ){
7731 if( aMap[iTest].iPos<0 ){
7732 break;
7733 }
7734 i1 = iTest+1;
7735 }else if( aMap[iTest].iPos>iPos ){
7736 i2 = iTest;
7737 }else{
7738 break;
7739 }
7740 }
7741 }
7742
7743 if( i2>i1 ){
7744 if( pIter->nSeg==0 ){
7745 Fts5Iter *pMap = pT->apIter[aMap[iTest].iIter];
7746 *ppOut = (const char*)pMap->aSeg[0].term.p+1;
7747 *pnOut = pMap->aSeg[0].term.n-1;
7748 }else{
7749 Fts5TokenDataMap *p = &aMap[iTest];
7750 *ppOut = (const char*)&pT->terms.p[p->iIter];
7751 *pnOut = aMap[iTest].nByte;
7752 }
7753 }
7754
7755 return SQLITE_OK;
7756}
7757
7758/*
7759** Clear any existing entries from the token-map associated with the
7760** iterator passed as the only argument.
7761*/
7762void sqlite3Fts5IndexIterClearTokendata(Fts5IndexIter *pIndexIter){
7763 Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
7764 if( pIter && pIter->pTokenDataIter
7765 && (pIter->nSeg==0 || pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_FULL)
7766 ){
7767 pIter->pTokenDataIter->nMap = 0;
7768 }
7769}
7770
7771/*
7772** Set a token-mapping for the iterator passed as the first argument. This
7773** is used in detail=column or detail=none mode when a token is requested
7774** using the xInstToken() API. In this case the caller tokenizers the
7775** current row and configures the token-mapping via multiple calls to this
7776** function.
7777*/
7778int sqlite3Fts5IndexIterWriteTokendata(
7779 Fts5IndexIter *pIndexIter,
7780 const char *pToken, int nToken,
7781 i64 iRowid, int iCol, int iOff
7782){
7783 Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
7784 Fts5TokenDataIter *pT = pIter->pTokenDataIter;
7785 Fts5Index *p = pIter->pIndex;
7786 i64 iPos = (((i64)iCol)<<32) + iOff;
7787
7788 assert( p->pConfig->eDetail!=FTS5_DETAIL_FULL );
7789 assert( pIter->pTokenDataIter || pIter->nSeg>0 );
7790 if( pIter->nSeg>0 ){
7791 /* This is a prefix term iterator. */
7792 if( pT==0 ){
7793 pT = (Fts5TokenDataIter*)sqlite3Fts5MallocZero(&p->rc,
7794 SZ_FTS5TOKENDATAITER(1));
7795 pIter->pTokenDataIter = pT;
7796 }
7797 if( pT ){
7798 fts5TokendataIterAppendMap(p, pT, pT->terms.n, nToken, iRowid, iPos);
7799 fts5BufferAppendBlob(&p->rc, &pT->terms, nToken, (const u8*)pToken);
7800 }
7801 }else{
7802 int ii;
7803 for(ii=0; ii<pT->nIter; ii++){
7804 Fts5Buffer *pTerm = &pT->apIter[ii]->aSeg[0].term;
7805 if( nToken==pTerm->n-1 && memcmp(pToken, pTerm->p+1, nToken)==0 ) break;
7806 }
7807 if( ii<pT->nIter ){
7808 fts5TokendataIterAppendMap(p, pT, ii, 0, iRowid, iPos);
7809 }
7810 }
7811 return fts5IndexReturn(p);
7812}
7813
7814/*
7815** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
7816*/
7817void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
7818 if( pIndexIter ){
7819 Fts5Index *pIndex = ((Fts5Iter*)pIndexIter)->pIndex;
7820 fts5IterClose(pIndexIter);
7821 fts5IndexReturn(pIndex);
7822 }
7823}
7824
7825/*
7826** Read and decode the "averages" record from the database.
7827**
7828** Parameter anSize must point to an array of size nCol, where nCol is
7829** the number of user defined columns in the FTS table.
7830*/
7831int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
7832 int nCol = p->pConfig->nCol;
7833 Fts5Data *pData;
7834
7835 *pnRow = 0;
7836 memset(anSize, 0, sizeof(i64) * nCol);
7837 pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
7838 if( p->rc==SQLITE_OK && pData->nn ){
7839 int i = 0;
7840 int iCol;
7841 i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
7842 for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
7843 i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
7844 }
7845 }
7846
7847 fts5DataRelease(pData);
7848 return fts5IndexReturn(p);
7849}
7850
7851/*
7852** Replace the current "averages" record with the contents of the buffer
7853** supplied as the second argument.
7854*/
7855int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
7856 assert( p->rc==SQLITE_OK );
7857 fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
7858 return fts5IndexReturn(p);
7859}
7860
7861/*
7862** Return the total number of blocks this module has read from the %_data
7863** table since it was created.
7864*/
7865int sqlite3Fts5IndexReads(Fts5Index *p){
7866 return p->nRead;
7867}
7868
7869/*
7870** Set the 32-bit cookie value stored at the start of all structure
7871** records to the value passed as the second argument.
7872**
7873** Return SQLITE_OK if successful, or an SQLite error code if an error
7874** occurs.
7875*/
7876int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
7877 int rc; /* Return code */
7878 Fts5Config *pConfig = p->pConfig; /* Configuration object */
7879 u8 aCookie[4]; /* Binary representation of iNew */
7880 sqlite3_blob *pBlob = 0;
7881
7882 assert( p->rc==SQLITE_OK );
7883 sqlite3Fts5Put32(aCookie, iNew);
7884
7885 rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
7886 "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
7887 );
7888 if( rc==SQLITE_OK ){
7889 sqlite3_blob_write(pBlob, aCookie, 4, 0);
7890 rc = sqlite3_blob_close(pBlob);
7891 }
7892
7893 return rc;
7894}
7895
7896int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
7897 Fts5Structure *pStruct;
7898 pStruct = fts5StructureRead(p);
7899 fts5StructureRelease(pStruct);
7900 return fts5IndexReturn(p);
7901}
7902
7903/*
7904** Retrieve the origin value that will be used for the segment currently
7905** being accumulated in the in-memory hash table when it is flushed to
7906** disk. If successful, SQLITE_OK is returned and (*piOrigin) set to
7907** the queried value. Or, if an error occurs, an error code is returned
7908** and the final value of (*piOrigin) is undefined.
7909*/
7910int sqlite3Fts5IndexGetOrigin(Fts5Index *p, i64 *piOrigin){
7911 Fts5Structure *pStruct;
7912 pStruct = fts5StructureRead(p);
7913 if( pStruct ){
7914 *piOrigin = pStruct->nOriginCntr;
7915 fts5StructureRelease(pStruct);
7916 }
7917 return fts5IndexReturn(p);
7918}
7919
7920/*
7921** Buffer pPg contains a page of a tombstone hash table - one of nPg pages
7922** associated with the same segment. This function adds rowid iRowid to
7923** the hash table. The caller is required to guarantee that there is at
7924** least one free slot on the page.
7925**
7926** If parameter bForce is false and the hash table is deemed to be full
7927** (more than half of the slots are occupied), then non-zero is returned
7928** and iRowid not inserted. Or, if bForce is true or if the hash table page
7929** is not full, iRowid is inserted and zero returned.
7930*/
7931static int fts5IndexTombstoneAddToPage(
7932 Fts5Data *pPg,
7933 int bForce,
7934 int nPg,
7935 u64 iRowid
7936){
7937 const int szKey = TOMBSTONE_KEYSIZE(pPg);
7938 const int nSlot = TOMBSTONE_NSLOT(pPg);
7939 const int nElem = fts5GetU32(&pPg->p[4]);
7940 int iSlot = (iRowid / nPg) % nSlot;
7941 int nCollide = nSlot;
7942
7943 if( szKey==4 && iRowid>0xFFFFFFFF ) return 2;
7944 if( iRowid==0 ){
7945 pPg->p[1] = 0x01;
7946 return 0;
7947 }
7948
7949 if( bForce==0 && nElem>=(nSlot/2) ){
7950 return 1;
7951 }
7952
7953 fts5PutU32(&pPg->p[4], nElem+1);
7954 if( szKey==4 ){
7955 u32 *aSlot = (u32*)&pPg->p[8];
7956 while( aSlot[iSlot] ){
7957 iSlot = (iSlot + 1) % nSlot;
7958 if( nCollide--==0 ) return 0;
7959 }
7960 fts5PutU32((u8*)&aSlot[iSlot], (u32)iRowid);
7961 }else{
7962 u64 *aSlot = (u64*)&pPg->p[8];
7963 while( aSlot[iSlot] ){
7964 iSlot = (iSlot + 1) % nSlot;
7965 if( nCollide--==0 ) return 0;
7966 }
7967 fts5PutU64((u8*)&aSlot[iSlot], iRowid);
7968 }
7969
7970 return 0;
7971}
7972
7973/*
7974** This function attempts to build a new hash containing all the keys
7975** currently in the tombstone hash table for segment pSeg. The new
7976** hash will be stored in the nOut buffers passed in array apOut[].
7977** All pages of the new hash use key-size szKey (4 or 8).
7978**
7979** Return 0 if the hash is successfully rebuilt into the nOut pages.
7980** Or non-zero if it is not (because one page became overfull). In this
7981** case the caller should retry with a larger nOut parameter.
7982**
7983** Parameter pData1 is page iPg1 of the hash table being rebuilt.
7984*/
7985static int fts5IndexTombstoneRehash(
7986 Fts5Index *p,
7987 Fts5StructureSegment *pSeg, /* Segment to rebuild hash of */
7988 Fts5Data *pData1, /* One page of current hash - or NULL */
7989 int iPg1, /* Which page of the current hash is pData1 */
7990 int szKey, /* 4 or 8, the keysize */
7991 int nOut, /* Number of output pages */
7992 Fts5Data **apOut /* Array of output hash pages */
7993){
7994 int ii;
7995 int res = 0;
7996
7997 /* Initialize the headers of all the output pages */
7998 for(ii=0; ii<nOut; ii++){
7999 apOut[ii]->p[0] = szKey;
8000 fts5PutU32(&apOut[ii]->p[4], 0);
8001 }
8002
8003 /* Loop through the current pages of the hash table. */
8004 for(ii=0; res==0 && ii<pSeg->nPgTombstone; ii++){
8005 Fts5Data *pData = 0; /* Page ii of the current hash table */
8006 Fts5Data *pFree = 0; /* Free this at the end of the loop */
8007
8008 if( iPg1==ii ){
8009 pData = pData1;
8010 }else{
8011 pFree = pData = fts5DataRead(p, FTS5_TOMBSTONE_ROWID(pSeg->iSegid, ii));
8012 }
8013
8014 if( pData ){
8015 int szKeyIn = TOMBSTONE_KEYSIZE(pData);
8016 int nSlotIn = (pData->nn - 8) / szKeyIn;
8017 int iIn;
8018 for(iIn=0; iIn<nSlotIn; iIn++){
8019 u64 iVal = 0;
8020
8021 /* Read the value from slot iIn of the input page into iVal. */
8022 if( szKeyIn==4 ){
8023 u32 *aSlot = (u32*)&pData->p[8];
8024 if( aSlot[iIn] ) iVal = fts5GetU32((u8*)&aSlot[iIn]);
8025 }else{
8026 u64 *aSlot = (u64*)&pData->p[8];
8027 if( aSlot[iIn] ) iVal = fts5GetU64((u8*)&aSlot[iIn]);
8028 }
8029
8030 /* If iVal is not 0 at this point, insert it into the new hash table */
8031 if( iVal ){
8032 Fts5Data *pPg = apOut[(iVal % nOut)];
8033 res = fts5IndexTombstoneAddToPage(pPg, 0, nOut, iVal);
8034 if( res ) break;
8035 }
8036 }
8037
8038 /* If this is page 0 of the old hash, copy the rowid-0-flag from the
8039 ** old hash to the new. */
8040 if( ii==0 ){
8041 apOut[0]->p[1] = pData->p[1];
8042 }
8043 }
8044 fts5DataRelease(pFree);
8045 }
8046
8047 return res;
8048}
8049
8050/*
8051** This is called to rebuild the hash table belonging to segment pSeg.
8052** If parameter pData1 is not NULL, then one page of the existing hash table
8053** has already been loaded - pData1, which is page iPg1. The key-size for
8054** the new hash table is szKey (4 or 8).
8055**
8056** If successful, the new hash table is not written to disk. Instead,
8057** output parameter (*pnOut) is set to the number of pages in the new
8058** hash table, and (*papOut) to point to an array of buffers containing
8059** the new page data.
8060**
8061** If an error occurs, an error code is left in the Fts5Index object and
8062** both output parameters set to 0 before returning.
8063*/
8064static void fts5IndexTombstoneRebuild(
8065 Fts5Index *p,
8066 Fts5StructureSegment *pSeg, /* Segment to rebuild hash of */
8067 Fts5Data *pData1, /* One page of current hash - or NULL */
8068 int iPg1, /* Which page of the current hash is pData1 */
8069 int szKey, /* 4 or 8, the keysize */
8070 int *pnOut, /* OUT: Number of output pages */
8071 Fts5Data ***papOut /* OUT: Output hash pages */
8072){
8073 const int MINSLOT = 32;
8074 int nSlotPerPage = MAX(MINSLOT, (p->pConfig->pgsz - 8) / szKey);
8075 i64 nSlot = 0; /* Number of slots in each output page */
8076 i64 nOut = 0;
8077
8078 /* Figure out how many output pages (nOut) and how many slots per
8079 ** page (nSlot). There are three possibilities:
8080 **
8081 ** 1. The hash table does not yet exist. In this case the new hash
8082 ** table will consist of a single page with MINSLOT slots.
8083 **
8084 ** 2. The hash table exists but is currently a single page. In this
8085 ** case an attempt is made to grow the page to accommodate the new
8086 ** entry. The page is allowed to grow up to nSlotPerPage (see above)
8087 ** slots.
8088 **
8089 ** 3. The hash table already consists of more than one page, or of
8090 ** a single page already so large that it cannot be grown. In this
8091 ** case the new hash consists of (nPg*2+1) pages of nSlotPerPage
8092 ** slots each, where nPg is the current number of pages in the
8093 ** hash table.
8094 */
8095 if( pSeg->nPgTombstone==0 ){
8096 /* Case 1. */
8097 nOut = 1;
8098 nSlot = MINSLOT;
8099 }else if( pSeg->nPgTombstone==1 ){
8100 /* Case 2. */
8101 u32 nElem = fts5GetU32(&pData1->p[4]);
8102 assert( pData1 && iPg1==0 );
8103 if( nElem>((u32)nSlotPerPage/4) ){
8104 nOut = 0;
8105 }else{
8106 nOut = 1;
8107 nSlot = MAX((i64)nElem*4, MINSLOT);
8108 }
8109 }
8110 if( nOut==0 ){
8111 /* Case 3. */
8112 nOut = ((i64)pSeg->nPgTombstone * 2 + 1);
8113 nSlot = nSlotPerPage;
8114 }
8115
8116 /* Allocate the required array and output pages */
8117 while( 1 ){
8118 int res = 0;
8119 i64 ii = 0;
8120 i64 szPage = 0;
8121 Fts5Data **apOut = 0;
8122
8123 /* Allocate space for the new hash table */
8124 assert( nSlot>=MINSLOT );
8125 apOut = (Fts5Data**)sqlite3Fts5MallocZero(&p->rc, sizeof(Fts5Data*) * nOut);
8126 szPage = 8 + nSlot*szKey;
8127 for(ii=0; ii<nOut; ii++){
8128 Fts5Data *pNew = (Fts5Data*)sqlite3Fts5MallocZero(&p->rc,
8129 sizeof(Fts5Data)+szPage
8130 );
8131 if( pNew ){
8132 pNew->nn = szPage;
8133 pNew->p = (u8*)&pNew[1];
8134 apOut[ii] = pNew;
8135 }
8136 }
8137
8138 /* Rebuild the hash table. */
8139 if( p->rc==SQLITE_OK ){
8140 res = fts5IndexTombstoneRehash(p, pSeg, pData1, iPg1, szKey, nOut, apOut);
8141 }
8142 if( res==0 ){
8143 if( p->rc ){
8144 fts5IndexFreeArray(apOut, nOut);
8145 apOut = 0;
8146 nOut = 0;
8147 }
8148 *pnOut = nOut;
8149 *papOut = apOut;
8150 break;
8151 }
8152
8153 /* If control flows to here, it was not possible to rebuild the hash
8154 ** table. Free all buffers and then try again with more pages. */
8155 assert( p->rc==SQLITE_OK );
8156 fts5IndexFreeArray(apOut, nOut);
8157 nSlot = nSlotPerPage;
8158 nOut = nOut*2 + 1;
8159 }
8160}
8161
8162
8163/*
8164** Add a tombstone for rowid iRowid to segment pSeg.
8165*/
8166static void fts5IndexTombstoneAdd(
8167 Fts5Index *p,
8168 Fts5StructureSegment *pSeg,
8169 u64 iRowid
8170){
8171 Fts5Data *pPg = 0;
8172 int iPg = -1;
8173 int szKey = 0;
8174 int nHash = 0;
8175 Fts5Data **apHash = 0;
8176
8177 p->nContentlessDelete++;
8178
8179 if( pSeg->nPgTombstone>0 ){
8180 iPg = iRowid % pSeg->nPgTombstone;
8181 pPg = fts5DataRead(p, FTS5_TOMBSTONE_ROWID(pSeg->iSegid,iPg));
8182 if( pPg==0 ){
8183 assert( p->rc!=SQLITE_OK );
8184 return;
8185 }
8186
8187 if( 0==fts5IndexTombstoneAddToPage(pPg, 0, pSeg->nPgTombstone, iRowid) ){
8188 fts5DataWrite(p, FTS5_TOMBSTONE_ROWID(pSeg->iSegid,iPg), pPg->p, pPg->nn);
8189 fts5DataRelease(pPg);
8190 return;
8191 }
8192 }
8193
8194 /* Have to rebuild the hash table. First figure out the key-size (4 or 8). */
8195 szKey = pPg ? TOMBSTONE_KEYSIZE(pPg) : 4;
8196 if( iRowid>0xFFFFFFFF ) szKey = 8;
8197
8198 /* Rebuild the hash table */
8199 fts5IndexTombstoneRebuild(p, pSeg, pPg, iPg, szKey, &nHash, &apHash);
8200 assert( p->rc==SQLITE_OK || (nHash==0 && apHash==0) );
8201
8202 /* If all has succeeded, write the new rowid into one of the new hash
8203 ** table pages, then write them all out to disk. */
8204 if( nHash ){
8205 int ii = 0;
8206 fts5IndexTombstoneAddToPage(apHash[iRowid % nHash], 1, nHash, iRowid);
8207 for(ii=0; ii<nHash; ii++){
8208 i64 iTombstoneRowid = FTS5_TOMBSTONE_ROWID(pSeg->iSegid, ii);
8209 fts5DataWrite(p, iTombstoneRowid, apHash[ii]->p, apHash[ii]->nn);
8210 }
8211 pSeg->nPgTombstone = nHash;
8212 fts5StructureWrite(p, p->pStruct);
8213 }
8214
8215 fts5DataRelease(pPg);
8216 fts5IndexFreeArray(apHash, nHash);
8217}
8218
8219/*
8220** Add iRowid to the tombstone list of the segment or segments that contain
8221** rows from origin iOrigin. Return SQLITE_OK if successful, or an SQLite
8222** error code otherwise.
8223*/
8224int sqlite3Fts5IndexContentlessDelete(Fts5Index *p, i64 iOrigin, i64 iRowid){
8225 Fts5Structure *pStruct;
8226 pStruct = fts5StructureRead(p);
8227 if( pStruct ){
8228 int bFound = 0; /* True after pSeg->nEntryTombstone incr. */
8229 int iLvl;
8230 for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
8231 int iSeg;
8232 for(iSeg=pStruct->aLevel[iLvl].nSeg-1; iSeg>=0; iSeg--){
8233 Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
8234 if( pSeg->iOrigin1<=(u64)iOrigin && pSeg->iOrigin2>=(u64)iOrigin ){
8235 if( bFound==0 ){
8236 pSeg->nEntryTombstone++;
8237 bFound = 1;
8238 }
8239 fts5IndexTombstoneAdd(p, pSeg, iRowid);
8240 }
8241 }
8242 }
8243 fts5StructureRelease(pStruct);
8244 }
8245 return fts5IndexReturn(p);
8246}
8247
8248/*************************************************************************
8249**************************************************************************
8250** Below this point is the implementation of the integrity-check
8251** functionality.
8252*/
8253
8254/*
8255** Return a simple checksum value based on the arguments.
8256*/
8257u64 sqlite3Fts5IndexEntryCksum(
8258 i64 iRowid,
8259 int iCol,
8260 int iPos,
8261 int iIdx,
8262 const char *pTerm,
8263 int nTerm
8264){
8265 int i;
8266 u64 ret = iRowid;
8267 ret += (ret<<3) + iCol;
8268 ret += (ret<<3) + iPos;
8269 if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
8270 for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
8271 return ret;
8272}
8273
8274#ifdef SQLITE_DEBUG
8275/*
8276** This function is purely an internal test. It does not contribute to
8277** FTS functionality, or even the integrity-check, in any way.
8278**
8279** Instead, it tests that the same set of pgno/rowid combinations are
8280** visited regardless of whether the doclist-index identified by parameters
8281** iSegid/iLeaf is iterated in forwards or reverse order.
8282*/
8283static void fts5TestDlidxReverse(
8284 Fts5Index *p,
8285 int iSegid, /* Segment id to load from */
8286 int iLeaf /* Load doclist-index for this leaf */
8287){
8288 Fts5DlidxIter *pDlidx = 0;
8289 u64 cksum1 = 13;
8290 u64 cksum2 = 13;
8291
8292 for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
8293 fts5DlidxIterEof(p, pDlidx)==0;
8294 fts5DlidxIterNext(p, pDlidx)
8295 ){
8296 i64 iRowid = fts5DlidxIterRowid(pDlidx);
8297 int pgno = fts5DlidxIterPgno(pDlidx);
8298 assert( pgno>iLeaf );
8299 cksum1 += iRowid + ((i64)pgno<<32);
8300 }
8301 fts5DlidxIterFree(pDlidx);
8302 pDlidx = 0;
8303
8304 for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
8305 fts5DlidxIterEof(p, pDlidx)==0;
8306 fts5DlidxIterPrev(p, pDlidx)
8307 ){
8308 i64 iRowid = fts5DlidxIterRowid(pDlidx);
8309 int pgno = fts5DlidxIterPgno(pDlidx);
8310 assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
8311 cksum2 += iRowid + ((i64)pgno<<32);
8312 }
8313 fts5DlidxIterFree(pDlidx);
8314 pDlidx = 0;
8315
8316 if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
8317}
8318
8319static int fts5QueryCksum(
8320 Fts5Index *p, /* Fts5 index object */
8321 int iIdx,
8322 const char *z, /* Index key to query for */
8323 int n, /* Size of index key in bytes */
8324 int flags, /* Flags for Fts5IndexQuery */
8325 u64 *pCksum /* IN/OUT: Checksum value */
8326){
8327 int eDetail = p->pConfig->eDetail;
8328 u64 cksum = *pCksum;
8329 Fts5IndexIter *pIter = 0;
8330 int rc = sqlite3Fts5IndexQuery(
8331 p, z, n, (flags | FTS5INDEX_QUERY_NOTOKENDATA), 0, &pIter
8332 );
8333
8334 while( rc==SQLITE_OK && ALWAYS(pIter!=0) && 0==sqlite3Fts5IterEof(pIter) ){
8335 i64 rowid = pIter->iRowid;
8336
8337 if( eDetail==FTS5_DETAIL_NONE ){
8338 cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
8339 }else{
8340 Fts5PoslistReader sReader;
8341 for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
8342 sReader.bEof==0;
8343 sqlite3Fts5PoslistReaderNext(&sReader)
8344 ){
8345 int iCol = FTS5_POS2COLUMN(sReader.iPos);
8346 int iOff = FTS5_POS2OFFSET(sReader.iPos);
8347 cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
8348 }
8349 }
8350 if( rc==SQLITE_OK ){
8351 rc = sqlite3Fts5IterNext(pIter);
8352 }
8353 }
8354 fts5IterClose(pIter);
8355
8356 *pCksum = cksum;
8357 return rc;
8358}
8359
8360/*
8361** This function is purely an internal test. It does not contribute to
8362** FTS functionality, or even the integrity-check, in any way.
8363**
8364** Check if buffer z[], size n bytes, contains as series of valid utf-8
8365** encoded codepoints. If so, return 0. Otherwise, if the buffer does not
8366** contain valid utf-8, return non-zero.
8367*/
8368static int fts5TestUtf8(const char *z, int n){
8369 int i = 0;
8370 assert_nc( n>0 );
8371 while( i<n ){
8372 if( (z[i] & 0x80)==0x00 ){
8373 i++;
8374 }else
8375 if( (z[i] & 0xE0)==0xC0 ){
8376 if( i+1>=n || (z[i+1] & 0xC0)!=0x80 ) return 1;
8377 i += 2;
8378 }else
8379 if( (z[i] & 0xF0)==0xE0 ){
8380 if( i+2>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1;
8381 i += 3;
8382 }else
8383 if( (z[i] & 0xF8)==0xF0 ){
8384 if( i+3>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1;
8385 if( (z[i+3] & 0xC0)!=0x80 ) return 1;
8386 i += 4;
8387 }else{
8388 return 1;
8389 }
8390 }
8391
8392 return 0;
8393}
8394
8395/*
8396** This function is also purely an internal test. It does not contribute to
8397** FTS functionality, or even the integrity-check, in any way.
8398**
8399** This function sets output variable (*pbFail) to true if the test fails. Or
8400** leaves it unchanged if the test succeeds.
8401*/
8402static void fts5TestTerm(
8403 Fts5Index *p,
8404 Fts5Buffer *pPrev, /* Previous term */
8405 const char *z, int n, /* Possibly new term to test */
8406 u64 expected,
8407 u64 *pCksum,
8408 int *pbFail
8409){
8410 int rc = p->rc;
8411 if( pPrev->n==0 ){
8412 fts5BufferSet(&rc, pPrev, n, (const u8*)z);
8413 }else
8414 if( *pbFail==0
8415 && rc==SQLITE_OK
8416 && (pPrev->n!=n || memcmp(pPrev->p, z, n))
8417 && (p->pHash==0 || p->pHash->nEntry==0)
8418 ){
8419 u64 cksum3 = *pCksum;
8420 const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
8421 int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
8422 int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
8423 int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
8424 u64 ck1 = 0;
8425 u64 ck2 = 0;
8426
8427 /* Check that the results returned for ASC and DESC queries are
8428 ** the same. If not, call this corruption. */
8429 rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
8430 if( rc==SQLITE_OK ){
8431 int f = flags|FTS5INDEX_QUERY_DESC;
8432 rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
8433 }
8434 if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
8435
8436 /* If this is a prefix query, check that the results returned if the
8437 ** the index is disabled are the same. In both ASC and DESC order.
8438 **
8439 ** This check may only be performed if the hash table is empty. This
8440 ** is because the hash table only supports a single scan query at
8441 ** a time, and the multi-iter loop from which this function is called
8442 ** is already performing such a scan.
8443 **
8444 ** Also only do this if buffer zTerm contains nTerm bytes of valid
8445 ** utf-8. Otherwise, the last part of the buffer contents might contain
8446 ** a non-utf-8 sequence that happens to be a prefix of a valid utf-8
8447 ** character stored in the main fts index, which will cause the
8448 ** test to fail. */
8449 if( p->nPendingData==0 && 0==fts5TestUtf8(zTerm, nTerm) ){
8450 if( iIdx>0 && rc==SQLITE_OK ){
8451 int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
8452 ck2 = 0;
8453 rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
8454 if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
8455 }
8456 if( iIdx>0 && rc==SQLITE_OK ){
8457 int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
8458 ck2 = 0;
8459 rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
8460 if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
8461 }
8462 }
8463
8464 cksum3 ^= ck1;
8465 fts5BufferSet(&rc, pPrev, n, (const u8*)z);
8466
8467 if( rc==SQLITE_OK && cksum3!=expected ){
8468 *pbFail = 1;
8469 }
8470 *pCksum = cksum3;
8471 }
8472 p->rc = rc;
8473}
8474
8475#else
8476# define fts5TestDlidxReverse(x,y,z)
8477# define fts5TestTerm(t,u,v,w,x,y,z)
8478#endif
8479
8480/*
8481** Check that:
8482**
8483** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
8484** contain zero terms.
8485** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
8486** contain zero rowids.
8487*/
8488static void fts5IndexIntegrityCheckEmpty(
8489 Fts5Index *p,
8490 Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
8491 int iFirst,
8492 int iNoRowid,
8493 int iLast
8494){
8495 int i;
8496
8497 /* Now check that the iter.nEmpty leaves following the current leaf
8498 ** (a) exist and (b) contain no terms. */
8499 for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
8500 Fts5Data *pLeaf = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
8501 if( pLeaf ){
8502 if( !fts5LeafIsTermless(pLeaf)
8503 || (i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf))
8504 ){
8505 FTS5_CORRUPT_ROWID(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
8506 }
8507 }
8508 fts5DataRelease(pLeaf);
8509 }
8510}
8511
8512static void fts5IntegrityCheckPgidx(Fts5Index *p, i64 iRowid, Fts5Data *pLeaf){
8513 i64 iTermOff = 0;
8514 int ii;
8515
8516 Fts5Buffer buf1 = {0,0,0};
8517 Fts5Buffer buf2 = {0,0,0};
8518
8519 ii = pLeaf->szLeaf;
8520 while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
8521 int res;
8522 i64 iOff;
8523 int nIncr;
8524
8525 ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
8526 iTermOff += nIncr;
8527 iOff = iTermOff;
8528
8529 if( iOff>=pLeaf->szLeaf ){
8530 FTS5_CORRUPT_ROWID(p, iRowid);
8531 }else if( iTermOff==nIncr ){
8532 int nByte;
8533 iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
8534 if( (iOff+nByte)>pLeaf->szLeaf ){
8535 FTS5_CORRUPT_ROWID(p, iRowid);
8536 }else{
8537 fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
8538 }
8539 }else{
8540 int nKeep, nByte;
8541 iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
8542 iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
8543 if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
8544 FTS5_CORRUPT_ROWID(p, iRowid);
8545 }else{
8546 buf1.n = nKeep;
8547 fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
8548 }
8549
8550 if( p->rc==SQLITE_OK ){
8551 res = fts5BufferCompare(&buf1, &buf2);
8552 if( res<=0 ) FTS5_CORRUPT_ROWID(p, iRowid);
8553 }
8554 }
8555 fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
8556 }
8557
8558 fts5BufferFree(&buf1);
8559 fts5BufferFree(&buf2);
8560}
8561
8562static void fts5IndexIntegrityCheckSegment(
8563 Fts5Index *p, /* FTS5 backend object */
8564 Fts5StructureSegment *pSeg /* Segment to check internal consistency */
8565){
8566 Fts5Config *pConfig = p->pConfig;
8567 int bSecureDelete = (pConfig->iVersion==FTS5_CURRENT_VERSION_SECUREDELETE);
8568 sqlite3_stmt *pStmt = 0;
8569 int rc2;
8570 int iIdxPrevLeaf = pSeg->pgnoFirst-1;
8571 int iDlidxPrevLeaf = pSeg->pgnoLast;
8572
8573 if( pSeg->pgnoFirst==0 ) return;
8574
8575 fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
8576 "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d "
8577 "ORDER BY 1, 2",
8578 pConfig->zDb, pConfig->zName, pSeg->iSegid
8579 ));
8580
8581 /* Iterate through the b-tree hierarchy. */
8582 while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
8583 i64 iRow; /* Rowid for this leaf */
8584 Fts5Data *pLeaf; /* Data for this leaf */
8585
8586 const char *zIdxTerm = (const char*)sqlite3_column_blob(pStmt, 1);
8587 int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
8588 int iIdxLeaf = sqlite3_column_int(pStmt, 2);
8589 int bIdxDlidx = sqlite3_column_int(pStmt, 3);
8590
8591 /* If the leaf in question has already been trimmed from the segment,
8592 ** ignore this b-tree entry. Otherwise, load it into memory. */
8593 if( iIdxLeaf<pSeg->pgnoFirst ) continue;
8594 iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
8595 pLeaf = fts5LeafRead(p, iRow);
8596 if( pLeaf==0 ) break;
8597
8598 /* Check that the leaf contains at least one term, and that it is equal
8599 ** to or larger than the split-key in zIdxTerm. Also check that if there
8600 ** is also a rowid pointer within the leaf page header, it points to a
8601 ** location before the term. */
8602 if( pLeaf->nn<=pLeaf->szLeaf ){
8603
8604 if( nIdxTerm==0
8605 && pConfig->iVersion==FTS5_CURRENT_VERSION_SECUREDELETE
8606 && pLeaf->nn==pLeaf->szLeaf
8607 && pLeaf->nn==4
8608 ){
8609 /* special case - the very first page in a segment keeps its %_idx
8610 ** entry even if all the terms are removed from it by secure-delete
8611 ** operations. */
8612 }else{
8613 FTS5_CORRUPT_ROWID(p, iRow);
8614 }
8615
8616 }else{
8617 int iOff; /* Offset of first term on leaf */
8618 int iRowidOff; /* Offset of first rowid on leaf */
8619 int nTerm; /* Size of term on leaf in bytes */
8620 int res; /* Comparison of term and split-key */
8621
8622 iOff = fts5LeafFirstTermOff(pLeaf);
8623 iRowidOff = fts5LeafFirstRowidOff(pLeaf);
8624 if( iRowidOff>=iOff || iOff>=pLeaf->szLeaf ){
8625 FTS5_CORRUPT_ROWID(p, iRow);
8626 }else{
8627 iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
8628 if( (i64)iOff+(i64)nTerm>(i64)pLeaf->szLeaf ){
8629 FTS5_CORRUPT_ROWID(p, iRow);
8630 }else{
8631 res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
8632 if( res==0 ) res = nTerm - nIdxTerm;
8633 if( res<0 ) FTS5_CORRUPT_ROWID(p, iRow);
8634 }
8635 }
8636
8637 fts5IntegrityCheckPgidx(p, iRow, pLeaf);
8638 }
8639 fts5DataRelease(pLeaf);
8640 if( p->rc ) break;
8641
8642 /* Now check that the iter.nEmpty leaves following the current leaf
8643 ** (a) exist and (b) contain no terms. */
8644 fts5IndexIntegrityCheckEmpty(
8645 p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
8646 );
8647 if( p->rc ) break;
8648
8649 /* If there is a doclist-index, check that it looks right. */
8650 if( bIdxDlidx ){
8651 Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
8652 int iPrevLeaf = iIdxLeaf;
8653 int iSegid = pSeg->iSegid;
8654 int iPg = 0;
8655 i64 iKey;
8656
8657 for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
8658 fts5DlidxIterEof(p, pDlidx)==0;
8659 fts5DlidxIterNext(p, pDlidx)
8660 ){
8661
8662 /* Check any rowid-less pages that occur before the current leaf. */
8663 for(iPg=iPrevLeaf+1; p->rc==SQLITE_OK && iPg<fts5DlidxIterPgno(pDlidx);
8664 iPg++
8665 ){
8666 iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
8667 pLeaf = fts5LeafRead(p, iKey);
8668 if( pLeaf ){
8669 if( fts5LeafFirstRowidOff(pLeaf)!=0 ) FTS5_CORRUPT_ROWID(p, iKey);
8670 fts5DataRelease(pLeaf);
8671 }
8672 }
8673 iPrevLeaf = fts5DlidxIterPgno(pDlidx);
8674
8675 /* Check that the leaf page indicated by the iterator really does
8676 ** contain the rowid suggested by the same. */
8677 iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
8678 pLeaf = fts5LeafRead(p, iKey);
8679 if( pLeaf ){
8680 i64 iRowid;
8681 int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
8682 ASSERT_SZLEAF_OK(pLeaf);
8683 if( iRowidOff>=pLeaf->szLeaf ){
8684 FTS5_CORRUPT_ROWID(p, iKey);
8685 }else if( bSecureDelete==0 || iRowidOff>0 ){
8686 i64 iDlRowid = fts5DlidxIterRowid(pDlidx);
8687 fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
8688 if( iRowid<iDlRowid || (bSecureDelete==0 && iRowid!=iDlRowid) ){
8689 FTS5_CORRUPT_ROWID(p, iKey);
8690 }
8691 }
8692 fts5DataRelease(pLeaf);
8693 }
8694 }
8695
8696 iDlidxPrevLeaf = iPg;
8697 fts5DlidxIterFree(pDlidx);
8698 fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
8699 }else{
8700 iDlidxPrevLeaf = pSeg->pgnoLast;
8701 /* TODO: Check there is no doclist index */
8702 }
8703
8704 iIdxPrevLeaf = iIdxLeaf;
8705 }
8706
8707 rc2 = sqlite3_finalize(pStmt);
8708 if( p->rc==SQLITE_OK ) p->rc = rc2;
8709
8710 /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
8711#if 0
8712 if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
8713 p->rc = FTS5_CORRUPT;
8714 }
8715#endif
8716}
8717
8718
8719/*
8720** Run internal checks to ensure that the FTS index (a) is internally
8721** consistent and (b) contains entries for which the XOR of the checksums
8722** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
8723**
8724** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
8725** checksum does not match. Return SQLITE_OK if all checks pass without
8726** error, or some other SQLite error code if another error (e.g. OOM)
8727** occurs.
8728*/
8729int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum, int bUseCksum){
8730 int eDetail = p->pConfig->eDetail;
8731 u64 cksum2 = 0; /* Checksum based on contents of indexes */
8732 Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
8733 Fts5Iter *pIter; /* Used to iterate through entire index */
8734 Fts5Structure *pStruct; /* Index structure */
8735 int iLvl, iSeg;
8736
8737#ifdef SQLITE_DEBUG
8738 /* Used by extra internal tests only run if NDEBUG is not defined */
8739 u64 cksum3 = 0; /* Checksum based on contents of indexes */
8740 Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
8741 int bTestFail = 0;
8742#endif
8743 const int flags = FTS5INDEX_QUERY_NOOUTPUT;
8744
8745 /* Load the FTS index structure */
8746 pStruct = fts5StructureRead(p);
8747 if( pStruct==0 ){
8748 assert( p->rc!=SQLITE_OK );
8749 return fts5IndexReturn(p);
8750 }
8751
8752 /* Check that the internal nodes of each segment match the leaves */
8753 for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
8754 for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
8755 Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
8756 fts5IndexIntegrityCheckSegment(p, pSeg);
8757 }
8758 }
8759
8760 /* The cksum argument passed to this function is a checksum calculated
8761 ** based on all expected entries in the FTS index (including prefix index
8762 ** entries). This block checks that a checksum calculated based on the
8763 ** actual contents of FTS index is identical.
8764 **
8765 ** Two versions of the same checksum are calculated. The first (stack
8766 ** variable cksum2) based on entries extracted from the full-text index
8767 ** while doing a linear scan of each individual index in turn.
8768 **
8769 ** As each term visited by the linear scans, a separate query for the
8770 ** same term is performed. cksum3 is calculated based on the entries
8771 ** extracted by these queries.
8772 */
8773 for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
8774 fts5MultiIterEof(p, pIter)==0;
8775 fts5MultiIterNext(p, pIter, 0, 0)
8776 ){
8777 int n; /* Size of term in bytes */
8778 i64 iPos = 0; /* Position read from poslist */
8779 int iOff = 0; /* Offset within poslist */
8780 i64 iRowid = fts5MultiIterRowid(pIter);
8781 char *z = (char*)fts5MultiIterTerm(pIter, &n);
8782
8783 /* If this is a new term, query for it. Update cksum3 with the results. */
8784 fts5TestTerm(p, &term, z, n, cksum2, &cksum3, &bTestFail);
8785 if( p->rc ) break;
8786
8787 if( eDetail==FTS5_DETAIL_NONE ){
8788 if( 0==fts5MultiIterIsEmpty(p, pIter) ){
8789 cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
8790 }
8791 }else{
8792 poslist.n = 0;
8793 fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
8794 fts5BufferAppendBlob(&p->rc, &poslist, 4, (const u8*)"\0\0\0\0");
8795 while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
8796 int iCol = FTS5_POS2COLUMN(iPos);
8797 int iTokOff = FTS5_POS2OFFSET(iPos);
8798 cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
8799 }
8800 }
8801 }
8802 fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3, &bTestFail);
8803
8804 fts5MultiIterFree(pIter);
8805 if( p->rc==SQLITE_OK && bUseCksum && cksum!=cksum2 ){
8806 p->rc = FTS5_CORRUPT;
8807 sqlite3Fts5ConfigErrmsg(p->pConfig,
8808 "fts5: checksum mismatch for table \"%s\"", p->pConfig->zName
8809 );
8810 }
8811#ifdef SQLITE_DEBUG
8812 /* In SQLITE_DEBUG builds, expensive extra checks were run as part of
8813 ** the integrity-check above. If no other errors were detected, but one
8814 ** of these tests failed, set the result to SQLITE_CORRUPT_VTAB here. */
8815 if( p->rc==SQLITE_OK && bTestFail ){
8816 p->rc = FTS5_CORRUPT;
8817 }
8818 fts5BufferFree(&term);
8819#endif
8820
8821 fts5StructureRelease(pStruct);
8822 fts5BufferFree(&poslist);
8823 return fts5IndexReturn(p);
8824}
8825
8826/*************************************************************************
8827**************************************************************************
8828** Below this point is the implementation of the fts5_decode() scalar
8829** function only.
8830*/
8831
8832#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
8833/*
8834** Decode a segment-data rowid from the %_data table. This function is
8835** the opposite of macro FTS5_SEGMENT_ROWID().
8836*/
8837static void fts5DecodeRowid(
8838 i64 iRowid, /* Rowid from %_data table */
8839 int *pbTombstone, /* OUT: Tombstone hash flag */
8840 int *piSegid, /* OUT: Segment id */
8841 int *pbDlidx, /* OUT: Dlidx flag */
8842 int *piHeight, /* OUT: Height */
8843 int *piPgno /* OUT: Page number */
8844){
8845 *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
8846 iRowid >>= FTS5_DATA_PAGE_B;
8847
8848 *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
8849 iRowid >>= FTS5_DATA_HEIGHT_B;
8850
8851 *pbDlidx = (int)(iRowid & 0x0001);
8852 iRowid >>= FTS5_DATA_DLI_B;
8853
8854 *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
8855 iRowid >>= FTS5_DATA_ID_B;
8856
8857 *pbTombstone = (int)(iRowid & 0x0001);
8858}
8859#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
8860
8861#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
8862static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
8863 int iSegid, iHeight, iPgno, bDlidx, bTomb; /* Rowid components */
8864 fts5DecodeRowid(iKey, &bTomb, &iSegid, &bDlidx, &iHeight, &iPgno);
8865
8866 if( iSegid==0 ){
8867 if( iKey==FTS5_AVERAGES_ROWID ){
8868 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
8869 }else{
8870 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
8871 }
8872 }
8873 else{
8874 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%s%ssegid=%d h=%d pgno=%d}",
8875 bDlidx ? "dlidx " : "",
8876 bTomb ? "tombstone " : "",
8877 iSegid, iHeight, iPgno
8878 );
8879 }
8880}
8881#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
8882
8883#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
8884static void fts5DebugStructure(
8885 int *pRc, /* IN/OUT: error code */
8886 Fts5Buffer *pBuf,
8887 Fts5Structure *p
8888){
8889 int iLvl, iSeg; /* Iterate through levels, segments */
8890
8891 for(iLvl=0; iLvl<p->nLevel; iLvl++){
8892 Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
8893 sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
8894 " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
8895 );
8896 for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
8897 Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
8898 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d",
8899 pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
8900 );
8901 if( pSeg->iOrigin1>0 ){
8902 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " origin=%lld..%lld",
8903 pSeg->iOrigin1, pSeg->iOrigin2
8904 );
8905 }
8906 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
8907 }
8908 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
8909 }
8910}
8911#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
8912
8913#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
8914/*
8915** This is part of the fts5_decode() debugging aid.
8916**
8917** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
8918** function appends a human-readable representation of the same object
8919** to the buffer passed as the second argument.
8920*/
8921static void fts5DecodeStructure(
8922 int *pRc, /* IN/OUT: error code */
8923 Fts5Buffer *pBuf,
8924 const u8 *pBlob, int nBlob
8925){
8926 int rc; /* Return code */
8927 Fts5Structure *p = 0; /* Decoded structure object */
8928
8929 rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
8930 if( rc!=SQLITE_OK ){
8931 *pRc = rc;
8932 return;
8933 }
8934
8935 fts5DebugStructure(pRc, pBuf, p);
8936 fts5StructureRelease(p);
8937}
8938#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
8939
8940#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
8941/*
8942** This is part of the fts5_decode() debugging aid.
8943**
8944** Arguments pBlob/nBlob contain an "averages" record. This function
8945** appends a human-readable representation of record to the buffer passed
8946** as the second argument.
8947*/
8948static void fts5DecodeAverages(
8949 int *pRc, /* IN/OUT: error code */
8950 Fts5Buffer *pBuf,
8951 const u8 *pBlob, int nBlob
8952){
8953 int i = 0;
8954 const char *zSpace = "";
8955
8956 while( i<nBlob ){
8957 u64 iVal;
8958 i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
8959 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
8960 zSpace = " ";
8961 }
8962}
8963#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
8964
8965#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
8966/*
8967** Buffer (a/n) is assumed to contain a list of serialized varints. Read
8968** each varint and append its string representation to buffer pBuf. Return
8969** after either the input buffer is exhausted or a 0 value is read.
8970**
8971** The return value is the number of bytes read from the input buffer.
8972*/
8973static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
8974 int iOff = 0;
8975 while( iOff<n ){
8976 int iVal;
8977 iOff += fts5GetVarint32(&a[iOff], iVal);
8978 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
8979 }
8980 return iOff;
8981}
8982#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
8983
8984#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
8985/*
8986** The start of buffer (a/n) contains the start of a doclist. The doclist
8987** may or may not finish within the buffer. This function appends a text
8988** representation of the part of the doclist that is present to buffer
8989** pBuf.
8990**
8991** The return value is the number of bytes read from the input buffer.
8992*/
8993static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
8994 i64 iDocid = 0;
8995 int iOff = 0;
8996
8997 if( n>0 ){
8998 iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
8999 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
9000 }
9001 while( iOff<n ){
9002 int nPos;
9003 int bDel;
9004 iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
9005 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
9006 iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
9007 if( iOff<n ){
9008 i64 iDelta;
9009 iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
9010 iDocid += iDelta;
9011 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
9012 }
9013 }
9014
9015 return iOff;
9016}
9017#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
9018
9019#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
9020/*
9021** This function is part of the fts5_decode() debugging function. It is
9022** only ever used with detail=none tables.
9023**
9024** Buffer (pData/nData) contains a doclist in the format used by detail=none
9025** tables. This function appends a human-readable version of that list to
9026** buffer pBuf.
9027**
9028** If *pRc is other than SQLITE_OK when this function is called, it is a
9029** no-op. If an OOM or other error occurs within this function, *pRc is
9030** set to an SQLite error code before returning. The final state of buffer
9031** pBuf is undefined in this case.
9032*/
9033static void fts5DecodeRowidList(
9034 int *pRc, /* IN/OUT: Error code */
9035 Fts5Buffer *pBuf, /* Buffer to append text to */
9036 const u8 *pData, int nData /* Data to decode list-of-rowids from */
9037){
9038 int i = 0;
9039 i64 iRowid = 0;
9040
9041 while( i<nData ){
9042 const char *zApp = "";
9043 u64 iVal;
9044 i += sqlite3Fts5GetVarint(&pData[i], &iVal);
9045 iRowid += iVal;
9046
9047 if( i<nData && pData[i]==0x00 ){
9048 i++;
9049 if( i<nData && pData[i]==0x00 ){
9050 i++;
9051 zApp = "+";
9052 }else{
9053 zApp = "*";
9054 }
9055 }
9056
9057 sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
9058 }
9059}
9060#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
9061
9062#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
9063static void fts5BufferAppendTerm(int *pRc, Fts5Buffer *pBuf, Fts5Buffer *pTerm){
9064 int ii;
9065 fts5BufferGrow(pRc, pBuf, pTerm->n*2 + 1);
9066 if( *pRc==SQLITE_OK ){
9067 for(ii=0; ii<pTerm->n; ii++){
9068 if( pTerm->p[ii]==0x00 ){
9069 pBuf->p[pBuf->n++] = '\\';
9070 pBuf->p[pBuf->n++] = '0';
9071 }else{
9072 pBuf->p[pBuf->n++] = pTerm->p[ii];
9073 }
9074 }
9075 pBuf->p[pBuf->n] = 0x00;
9076 }
9077}
9078#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
9079
9080#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
9081/*
9082** The implementation of user-defined scalar function fts5_decode().
9083*/
9084static void fts5DecodeFunction(
9085 sqlite3_context *pCtx, /* Function call context */
9086 int nArg, /* Number of args (always 2) */
9087 sqlite3_value **apVal /* Function arguments */
9088){
9089 i64 iRowid; /* Rowid for record being decoded */
9090 int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
9091 int bTomb;
9092 const u8 *aBlob; int n; /* Record to decode */
9093 u8 *a = 0;
9094 Fts5Buffer s; /* Build up text to return here */
9095 int rc = SQLITE_OK; /* Return code */
9096 sqlite3_int64 nSpace = 0;
9097 int eDetailNone = (sqlite3_user_data(pCtx)!=0);
9098
9099 assert( nArg==2 );
9100 UNUSED_PARAM(nArg);
9101 memset(&s, 0, sizeof(Fts5Buffer));
9102 iRowid = sqlite3_value_int64(apVal[0]);
9103
9104 /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
9105 ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
9106 ** buffer overreads even if the record is corrupt. */
9107 n = sqlite3_value_bytes(apVal[1]);
9108 aBlob = sqlite3_value_blob(apVal[1]);
9109 nSpace = ((i64)n) + FTS5_DATA_ZERO_PADDING;
9110 a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
9111 if( a==0 ) goto decode_out;
9112 if( n>0 ) memcpy(a, aBlob, n);
9113
9114 fts5DecodeRowid(iRowid, &bTomb, &iSegid, &bDlidx, &iHeight, &iPgno);
9115
9116 fts5DebugRowid(&rc, &s, iRowid);
9117 if( bDlidx ){
9118 Fts5Data dlidx;
9119 Fts5DlidxLvl lvl;
9120
9121 dlidx.p = a;
9122 dlidx.nn = n;
9123
9124 memset(&lvl, 0, sizeof(Fts5DlidxLvl));
9125 lvl.pData = &dlidx;
9126 lvl.iLeafPgno = iPgno;
9127
9128 for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
9129 sqlite3Fts5BufferAppendPrintf(&rc, &s,
9130 " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
9131 );
9132 }
9133 }else if( bTomb ){
9134 u32 nElem = fts5GetU32(&a[4]);
9135 int szKey = (aBlob[0]==4 || aBlob[0]==8) ? aBlob[0] : 8;
9136 int nSlot = (n - 8) / szKey;
9137 int ii;
9138 sqlite3Fts5BufferAppendPrintf(&rc, &s, " nElem=%d", (int)nElem);
9139 if( aBlob[1] ){
9140 sqlite3Fts5BufferAppendPrintf(&rc, &s, " 0");
9141 }
9142 for(ii=0; ii<nSlot; ii++){
9143 u64 iVal = 0;
9144 if( szKey==4 ){
9145 u32 *aSlot = (u32*)&aBlob[8];
9146 if( aSlot[ii] ) iVal = fts5GetU32((u8*)&aSlot[ii]);
9147 }else{
9148 u64 *aSlot = (u64*)&aBlob[8];
9149 if( aSlot[ii] ) iVal = fts5GetU64((u8*)&aSlot[ii]);
9150 }
9151 if( iVal!=0 ){
9152 sqlite3Fts5BufferAppendPrintf(&rc, &s, " %lld", (i64)iVal);
9153 }
9154 }
9155 }else if( iSegid==0 ){
9156 if( iRowid==FTS5_AVERAGES_ROWID ){
9157 fts5DecodeAverages(&rc, &s, a, n);
9158 }else{
9159 fts5DecodeStructure(&rc, &s, a, n);
9160 }
9161 }else if( eDetailNone ){
9162 Fts5Buffer term; /* Current term read from page */
9163 int szLeaf;
9164 int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
9165 int iTermOff;
9166 int nKeep = 0;
9167 int iOff;
9168
9169 memset(&term, 0, sizeof(Fts5Buffer));
9170
9171 /* Decode any entries that occur before the first term. */
9172 if( szLeaf<n ){
9173 iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
9174 }else{
9175 iTermOff = szLeaf;
9176 }
9177 fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
9178
9179 iOff = iTermOff;
9180 while( iOff<szLeaf && rc==SQLITE_OK ){
9181 int nAppend;
9182
9183 /* Read the term data for the next term*/
9184 iOff += fts5GetVarint32(&a[iOff], nAppend);
9185 term.n = nKeep;
9186 fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
9187 sqlite3Fts5BufferAppendPrintf(&rc, &s, " term=");
9188 fts5BufferAppendTerm(&rc, &s, &term);
9189 iOff += nAppend;
9190
9191 /* Figure out where the doclist for this term ends */
9192 if( iPgidxOff<n ){
9193 int nIncr;
9194 iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
9195 iTermOff += nIncr;
9196 }else{
9197 iTermOff = szLeaf;
9198 }
9199 if( iTermOff>szLeaf ){
9200 rc = FTS5_CORRUPT;
9201 }else{
9202 fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
9203 }
9204 iOff = iTermOff;
9205 if( iOff<szLeaf ){
9206 iOff += fts5GetVarint32(&a[iOff], nKeep);
9207 }
9208 }
9209
9210 fts5BufferFree(&term);
9211 }else{
9212 Fts5Buffer term; /* Current term read from page */
9213 int szLeaf; /* Offset of pgidx in a[] */
9214 int iPgidxOff;
9215 int iPgidxPrev = 0; /* Previous value read from pgidx */
9216 int iTermOff = 0;
9217 int iRowidOff = 0;
9218 int iOff;
9219 int nDoclist;
9220
9221 memset(&term, 0, sizeof(Fts5Buffer));
9222
9223 if( n<4 ){
9224 sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
9225 goto decode_out;
9226 }else{
9227 iRowidOff = fts5GetU16(&a[0]);
9228 iPgidxOff = szLeaf = fts5GetU16(&a[2]);
9229 if( iPgidxOff<n ){
9230 fts5GetVarint32(&a[iPgidxOff], iTermOff);
9231 }else if( iPgidxOff>n ){
9232 rc = FTS5_CORRUPT;
9233 goto decode_out;
9234 }
9235 }
9236
9237 /* Decode the position list tail at the start of the page */
9238 if( iRowidOff!=0 ){
9239 iOff = iRowidOff;
9240 }else if( iTermOff!=0 ){
9241 iOff = iTermOff;
9242 }else{
9243 iOff = szLeaf;
9244 }
9245 if( iOff>n ){
9246 rc = FTS5_CORRUPT;
9247 goto decode_out;
9248 }
9249 fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
9250
9251 /* Decode any more doclist data that appears on the page before the
9252 ** first term. */
9253 nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
9254 if( nDoclist+iOff>n ){
9255 rc = FTS5_CORRUPT;
9256 goto decode_out;
9257 }
9258 fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
9259
9260 while( iPgidxOff<n && rc==SQLITE_OK ){
9261 int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
9262 int nByte; /* Bytes of data */
9263 int iEnd;
9264
9265 iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
9266 iPgidxPrev += nByte;
9267 iOff = iPgidxPrev;
9268
9269 if( iPgidxOff<n ){
9270 fts5GetVarint32(&a[iPgidxOff], nByte);
9271 iEnd = iPgidxPrev + nByte;
9272 }else{
9273 iEnd = szLeaf;
9274 }
9275 if( iEnd>szLeaf ){
9276 rc = FTS5_CORRUPT;
9277 break;
9278 }
9279
9280 if( bFirst==0 ){
9281 iOff += fts5GetVarint32(&a[iOff], nByte);
9282 if( nByte>term.n ){
9283 rc = FTS5_CORRUPT;
9284 break;
9285 }
9286 term.n = nByte;
9287 }
9288 iOff += fts5GetVarint32(&a[iOff], nByte);
9289 if( iOff+nByte>n ){
9290 rc = FTS5_CORRUPT;
9291 break;
9292 }
9293 fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
9294 iOff += nByte;
9295
9296 sqlite3Fts5BufferAppendPrintf(&rc, &s, " term=");
9297 fts5BufferAppendTerm(&rc, &s, &term);
9298 iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
9299 }
9300
9301 fts5BufferFree(&term);
9302 }
9303
9304 decode_out:
9305 sqlite3_free(a);
9306 if( rc==SQLITE_OK ){
9307 sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
9308 }else{
9309 sqlite3_result_error_code(pCtx, rc);
9310 }
9311 fts5BufferFree(&s);
9312}
9313#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
9314
9315#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
9316/*
9317** The implementation of user-defined scalar function fts5_rowid().
9318*/
9319static void fts5RowidFunction(
9320 sqlite3_context *pCtx, /* Function call context */
9321 int nArg, /* Number of args (always 2) */
9322 sqlite3_value **apVal /* Function arguments */
9323){
9324 const char *zArg;
9325 if( nArg==0 ){
9326 sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
9327 }else{
9328 zArg = (const char*)sqlite3_value_text(apVal[0]);
9329 if( 0==sqlite3_stricmp(zArg, "segment") ){
9330 i64 iRowid;
9331 int segid, pgno;
9332 if( nArg!=3 ){
9333 sqlite3_result_error(pCtx,
9334 "should be: fts5_rowid('segment', segid, pgno))", -1
9335 );
9336 }else{
9337 segid = sqlite3_value_int(apVal[1]);
9338 pgno = sqlite3_value_int(apVal[2]);
9339 iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
9340 sqlite3_result_int64(pCtx, iRowid);
9341 }
9342 }else{
9343 sqlite3_result_error(pCtx,
9344 "first arg to fts5_rowid() must be 'segment'" , -1
9345 );
9346 }
9347 }
9348}
9349#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
9350
9351#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
9352
9353typedef struct Fts5StructVtab Fts5StructVtab;
9354struct Fts5StructVtab {
9355 sqlite3_vtab base;
9356};
9357
9358typedef struct Fts5StructVcsr Fts5StructVcsr;
9359struct Fts5StructVcsr {
9360 sqlite3_vtab_cursor base;
9361 Fts5Structure *pStruct;
9362 int iLevel;
9363 int iSeg;
9364 int iRowid;
9365};
9366
9367/*
9368** Create a new fts5_structure() table-valued function.
9369*/
9370static int fts5structConnectMethod(
9371 sqlite3 *db,
9372 void *pAux,
9373 int argc, const char *const*argv,
9374 sqlite3_vtab **ppVtab,
9375 char **pzErr
9376){
9377 Fts5StructVtab *pNew = 0;
9378 int rc = SQLITE_OK;
9379
9380 rc = sqlite3_declare_vtab(db,
9381 "CREATE TABLE xyz("
9382 "level, segment, merge, segid, leaf1, leaf2, loc1, loc2, "
9383 "npgtombstone, nentrytombstone, nentry, struct HIDDEN);"
9384 );
9385 if( rc==SQLITE_OK ){
9386 pNew = sqlite3Fts5MallocZero(&rc, sizeof(*pNew));
9387 }
9388
9389 *ppVtab = (sqlite3_vtab*)pNew;
9390 return rc;
9391}
9392
9393/*
9394** We must have a single struct=? constraint that will be passed through
9395** into the xFilter method. If there is no valid struct=? constraint,
9396** then return an SQLITE_CONSTRAINT error.
9397*/
9398static int fts5structBestIndexMethod(
9399 sqlite3_vtab *tab,
9400 sqlite3_index_info *pIdxInfo
9401){
9402 int i;
9403 int rc = SQLITE_CONSTRAINT;
9404 struct sqlite3_index_constraint *p;
9405 pIdxInfo->estimatedCost = (double)100;
9406 pIdxInfo->estimatedRows = 100;
9407 pIdxInfo->idxNum = 0;
9408 for(i=0, p=pIdxInfo->aConstraint; i<pIdxInfo->nConstraint; i++, p++){
9409 if( p->usable==0 ) continue;
9410 if( p->op==SQLITE_INDEX_CONSTRAINT_EQ && p->iColumn==11 ){
9411 rc = SQLITE_OK;
9412 pIdxInfo->aConstraintUsage[i].omit = 1;
9413 pIdxInfo->aConstraintUsage[i].argvIndex = 1;
9414 break;
9415 }
9416 }
9417 return rc;
9418}
9419
9420/*
9421** This method is the destructor for bytecodevtab objects.
9422*/
9423static int fts5structDisconnectMethod(sqlite3_vtab *pVtab){
9424 Fts5StructVtab *p = (Fts5StructVtab*)pVtab;
9425 sqlite3_free(p);
9426 return SQLITE_OK;
9427}
9428
9429/*
9430** Constructor for a new bytecodevtab_cursor object.
9431*/
9432static int fts5structOpenMethod(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
9433 int rc = SQLITE_OK;
9434 Fts5StructVcsr *pNew = 0;
9435
9436 pNew = sqlite3Fts5MallocZero(&rc, sizeof(*pNew));
9437 *ppCsr = (sqlite3_vtab_cursor*)pNew;
9438
9439 return SQLITE_OK;
9440}
9441
9442/*
9443** Destructor for a bytecodevtab_cursor.
9444*/
9445static int fts5structCloseMethod(sqlite3_vtab_cursor *cur){
9446 Fts5StructVcsr *pCsr = (Fts5StructVcsr*)cur;
9447 fts5StructureRelease(pCsr->pStruct);
9448 sqlite3_free(pCsr);
9449 return SQLITE_OK;
9450}
9451
9452
9453/*
9454** Advance a bytecodevtab_cursor to its next row of output.
9455*/
9456static int fts5structNextMethod(sqlite3_vtab_cursor *cur){
9457 Fts5StructVcsr *pCsr = (Fts5StructVcsr*)cur;
9458 Fts5Structure *p = pCsr->pStruct;
9459
9460 assert( pCsr->pStruct );
9461 pCsr->iSeg++;
9462 pCsr->iRowid++;
9463 while( pCsr->iLevel<p->nLevel && pCsr->iSeg>=p->aLevel[pCsr->iLevel].nSeg ){
9464 pCsr->iLevel++;
9465 pCsr->iSeg = 0;
9466 }
9467 if( pCsr->iLevel>=p->nLevel ){
9468 fts5StructureRelease(pCsr->pStruct);
9469 pCsr->pStruct = 0;
9470 }
9471 return SQLITE_OK;
9472}
9473
9474/*
9475** Return TRUE if the cursor has been moved off of the last
9476** row of output.
9477*/
9478static int fts5structEofMethod(sqlite3_vtab_cursor *cur){
9479 Fts5StructVcsr *pCsr = (Fts5StructVcsr*)cur;
9480 return pCsr->pStruct==0;
9481}
9482
9483static int fts5structRowidMethod(
9484 sqlite3_vtab_cursor *cur,
9485 sqlite_int64 *piRowid
9486){
9487 Fts5StructVcsr *pCsr = (Fts5StructVcsr*)cur;
9488 *piRowid = pCsr->iRowid;
9489 return SQLITE_OK;
9490}
9491
9492/*
9493** Return values of columns for the row at which the bytecodevtab_cursor
9494** is currently pointing.
9495*/
9496static int fts5structColumnMethod(
9497 sqlite3_vtab_cursor *cur, /* The cursor */
9498 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
9499 int i /* Which column to return */
9500){
9501 Fts5StructVcsr *pCsr = (Fts5StructVcsr*)cur;
9502 Fts5Structure *p = pCsr->pStruct;
9503 Fts5StructureSegment *pSeg = &p->aLevel[pCsr->iLevel].aSeg[pCsr->iSeg];
9504
9505 switch( i ){
9506 case 0: /* level */
9507 sqlite3_result_int(ctx, pCsr->iLevel);
9508 break;
9509 case 1: /* segment */
9510 sqlite3_result_int(ctx, pCsr->iSeg);
9511 break;
9512 case 2: /* merge */
9513 sqlite3_result_int(ctx, pCsr->iSeg < p->aLevel[pCsr->iLevel].nMerge);
9514 break;
9515 case 3: /* segid */
9516 sqlite3_result_int(ctx, pSeg->iSegid);
9517 break;
9518 case 4: /* leaf1 */
9519 sqlite3_result_int(ctx, pSeg->pgnoFirst);
9520 break;
9521 case 5: /* leaf2 */
9522 sqlite3_result_int(ctx, pSeg->pgnoLast);
9523 break;
9524 case 6: /* origin1 */
9525 sqlite3_result_int64(ctx, pSeg->iOrigin1);
9526 break;
9527 case 7: /* origin2 */
9528 sqlite3_result_int64(ctx, pSeg->iOrigin2);
9529 break;
9530 case 8: /* npgtombstone */
9531 sqlite3_result_int(ctx, pSeg->nPgTombstone);
9532 break;
9533 case 9: /* nentrytombstone */
9534 sqlite3_result_int64(ctx, pSeg->nEntryTombstone);
9535 break;
9536 case 10: /* nentry */
9537 sqlite3_result_int64(ctx, pSeg->nEntry);
9538 break;
9539 }
9540 return SQLITE_OK;
9541}
9542
9543/*
9544** Initialize a cursor.
9545**
9546** idxNum==0 means show all subprograms
9547** idxNum==1 means show only the main bytecode and omit subprograms.
9548*/
9549static int fts5structFilterMethod(
9550 sqlite3_vtab_cursor *pVtabCursor,
9551 int idxNum, const char *idxStr,
9552 int argc, sqlite3_value **argv
9553){
9554 Fts5StructVcsr *pCsr = (Fts5StructVcsr *)pVtabCursor;
9555 int rc = SQLITE_OK;
9556
9557 const u8 *aBlob = 0;
9558 int nBlob = 0;
9559
9560 assert( argc==1 );
9561 fts5StructureRelease(pCsr->pStruct);
9562 pCsr->pStruct = 0;
9563
9564 nBlob = sqlite3_value_bytes(argv[0]);
9565 aBlob = (const u8*)sqlite3_value_blob(argv[0]);
9566 rc = fts5StructureDecode(aBlob, nBlob, 0, &pCsr->pStruct);
9567 if( rc==SQLITE_OK ){
9568 pCsr->iLevel = 0;
9569 pCsr->iRowid = 0;
9570 pCsr->iSeg = -1;
9571 rc = fts5structNextMethod(pVtabCursor);
9572 }
9573
9574 return rc;
9575}
9576
9577#endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
9578
9579/*
9580** This is called as part of registering the FTS5 module with database
9581** connection db. It registers several user-defined scalar functions useful
9582** with FTS5.
9583**
9584** If successful, SQLITE_OK is returned. If an error occurs, some other
9585** SQLite error code is returned instead.
9586*/
9587int sqlite3Fts5IndexInit(sqlite3 *db){
9588#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
9589 int rc = sqlite3_create_function(
9590 db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
9591 );
9592
9593 if( rc==SQLITE_OK ){
9594 rc = sqlite3_create_function(
9595 db, "fts5_decode_none", 2,
9596 SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
9597 );
9598 }
9599
9600 if( rc==SQLITE_OK ){
9601 rc = sqlite3_create_function(
9602 db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
9603 );
9604 }
9605
9606 if( rc==SQLITE_OK ){
9607 static const sqlite3_module fts5structure_module = {
9608 0, /* iVersion */
9609 0, /* xCreate */
9610 fts5structConnectMethod, /* xConnect */
9611 fts5structBestIndexMethod, /* xBestIndex */
9612 fts5structDisconnectMethod, /* xDisconnect */
9613 0, /* xDestroy */
9614 fts5structOpenMethod, /* xOpen */
9615 fts5structCloseMethod, /* xClose */
9616 fts5structFilterMethod, /* xFilter */
9617 fts5structNextMethod, /* xNext */
9618 fts5structEofMethod, /* xEof */
9619 fts5structColumnMethod, /* xColumn */
9620 fts5structRowidMethod, /* xRowid */
9621 0, /* xUpdate */
9622 0, /* xBegin */
9623 0, /* xSync */
9624 0, /* xCommit */
9625 0, /* xRollback */
9626 0, /* xFindFunction */
9627 0, /* xRename */
9628 0, /* xSavepoint */
9629 0, /* xRelease */
9630 0, /* xRollbackTo */
9631 0, /* xShadowName */
9632 0 /* xIntegrity */
9633 };
9634 rc = sqlite3_create_module(db, "fts5_structure", &fts5structure_module, 0);
9635 }
9636 return rc;
9637#else
9638 return SQLITE_OK;
9639 UNUSED_PARAM(db);
9640#endif
9641}
9642
9643
9644int sqlite3Fts5IndexReset(Fts5Index *p){
9645 assert( p->pStruct==0 || p->iStructVersion!=0 );
9646 if( fts5IndexDataVersion(p)!=p->iStructVersion ){
9647 fts5StructureInvalidate(p);
9648 }
9649 return fts5IndexReturn(p);
9650}