fts3.c

Go to the documentation of this file.
00001 /*
00002 ** 2006 Oct 10
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 ******************************************************************************
00012 **
00013 ** This is an SQLite module implementing full-text search.
00014 */
00015 
00016 /*
00017 ** The code in this file is only compiled if:
00018 **
00019 **     * The FTS3 module is being built as an extension
00020 **       (in which case SQLITE_CORE is not defined), or
00021 **
00022 **     * The FTS3 module is being built into the core of
00023 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
00024 */
00025 
00026 /* TODO(shess) Consider exporting this comment to an HTML file or the
00027 ** wiki.
00028 */
00029 /* The full-text index is stored in a series of b+tree (-like)
00030 ** structures called segments which map terms to doclists.  The
00031 ** structures are like b+trees in layout, but are constructed from the
00032 ** bottom up in optimal fashion and are not updatable.  Since trees
00033 ** are built from the bottom up, things will be described from the
00034 ** bottom up.
00035 **
00036 **
00037 **** Varints ****
00038 ** The basic unit of encoding is a variable-length integer called a
00039 ** varint.  We encode variable-length integers in little-endian order
00040 ** using seven bits * per byte as follows:
00041 **
00042 ** KEY:
00043 **         A = 0xxxxxxx    7 bits of data and one flag bit
00044 **         B = 1xxxxxxx    7 bits of data and one flag bit
00045 **
00046 **  7 bits - A
00047 ** 14 bits - BA
00048 ** 21 bits - BBA
00049 ** and so on.
00050 **
00051 ** This is identical to how sqlite encodes varints (see util.c).
00052 **
00053 **
00054 **** Document lists ****
00055 ** A doclist (document list) holds a docid-sorted list of hits for a
00056 ** given term.  Doclists hold docids, and can optionally associate
00057 ** token positions and offsets with docids.
00058 **
00059 ** A DL_POSITIONS_OFFSETS doclist is stored like this:
00060 **
00061 ** array {
00062 **   varint docid;
00063 **   array {                (position list for column 0)
00064 **     varint position;     (delta from previous position plus POS_BASE)
00065 **     varint startOffset;  (delta from previous startOffset)
00066 **     varint endOffset;    (delta from startOffset)
00067 **   }
00068 **   array {
00069 **     varint POS_COLUMN;   (marks start of position list for new column)
00070 **     varint column;       (index of new column)
00071 **     array {
00072 **       varint position;   (delta from previous position plus POS_BASE)
00073 **       varint startOffset;(delta from previous startOffset)
00074 **       varint endOffset;  (delta from startOffset)
00075 **     }
00076 **   }
00077 **   varint POS_END;        (marks end of positions for this document.
00078 ** }
00079 **
00080 ** Here, array { X } means zero or more occurrences of X, adjacent in
00081 ** memory.  A "position" is an index of a token in the token stream
00082 ** generated by the tokenizer, while an "offset" is a byte offset,
00083 ** both based at 0.  Note that POS_END and POS_COLUMN occur in the
00084 ** same logical place as the position element, and act as sentinals
00085 ** ending a position list array.
00086 **
00087 ** A DL_POSITIONS doclist omits the startOffset and endOffset
00088 ** information.  A DL_DOCIDS doclist omits both the position and
00089 ** offset information, becoming an array of varint-encoded docids.
00090 **
00091 ** On-disk data is stored as type DL_DEFAULT, so we don't serialize
00092 ** the type.  Due to how deletion is implemented in the segmentation
00093 ** system, on-disk doclists MUST store at least positions.
00094 **
00095 **
00096 **** Segment leaf nodes ****
00097 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
00098 ** nodes are written using LeafWriter, and read using LeafReader (to
00099 ** iterate through a single leaf node's data) and LeavesReader (to
00100 ** iterate through a segment's entire leaf layer).  Leaf nodes have
00101 ** the format:
00102 **
00103 ** varint iHeight;             (height from leaf level, always 0)
00104 ** varint nTerm;               (length of first term)
00105 ** char pTerm[nTerm];          (content of first term)
00106 ** varint nDoclist;            (length of term's associated doclist)
00107 ** char pDoclist[nDoclist];    (content of doclist)
00108 ** array {
00109 **                             (further terms are delta-encoded)
00110 **   varint nPrefix;           (length of prefix shared with previous term)
00111 **   varint nSuffix;           (length of unshared suffix)
00112 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
00113 **   varint nDoclist;          (length of term's associated doclist)
00114 **   char pDoclist[nDoclist];  (content of doclist)
00115 ** }
00116 **
00117 ** Here, array { X } means zero or more occurrences of X, adjacent in
00118 ** memory.
00119 **
00120 ** Leaf nodes are broken into blocks which are stored contiguously in
00121 ** the %_segments table in sorted order.  This means that when the end
00122 ** of a node is reached, the next term is in the node with the next
00123 ** greater node id.
00124 **
00125 ** New data is spilled to a new leaf node when the current node
00126 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
00127 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
00128 ** node (a leaf node with a single term and doclist).  The goal of
00129 ** these settings is to pack together groups of small doclists while
00130 ** making it efficient to directly access large doclists.  The
00131 ** assumption is that large doclists represent terms which are more
00132 ** likely to be query targets.
00133 **
00134 ** TODO(shess) It may be useful for blocking decisions to be more
00135 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
00136 ** node rather than splitting into 2k and .5k nodes.  My intuition is
00137 ** that this might extend through 2x or 4x the pagesize.
00138 **
00139 **
00140 **** Segment interior nodes ****
00141 ** Segment interior nodes store blockids for subtree nodes and terms
00142 ** to describe what data is stored by the each subtree.  Interior
00143 ** nodes are written using InteriorWriter, and read using
00144 ** InteriorReader.  InteriorWriters are created as needed when
00145 ** SegmentWriter creates new leaf nodes, or when an interior node
00146 ** itself grows too big and must be split.  The format of interior
00147 ** nodes:
00148 **
00149 ** varint iHeight;           (height from leaf level, always >0)
00150 ** varint iBlockid;          (block id of node's leftmost subtree)
00151 ** optional {
00152 **   varint nTerm;           (length of first term)
00153 **   char pTerm[nTerm];      (content of first term)
00154 **   array {
00155 **                                (further terms are delta-encoded)
00156 **     varint nPrefix;            (length of shared prefix with previous term)
00157 **     varint nSuffix;            (length of unshared suffix)
00158 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
00159 **   }
00160 ** }
00161 **
00162 ** Here, optional { X } means an optional element, while array { X }
00163 ** means zero or more occurrences of X, adjacent in memory.
00164 **
00165 ** An interior node encodes n terms separating n+1 subtrees.  The
00166 ** subtree blocks are contiguous, so only the first subtree's blockid
00167 ** is encoded.  The subtree at iBlockid will contain all terms less
00168 ** than the first term encoded (or all terms if no term is encoded).
00169 ** Otherwise, for terms greater than or equal to pTerm[i] but less
00170 ** than pTerm[i+1], the subtree for that term will be rooted at
00171 ** iBlockid+i.  Interior nodes only store enough term data to
00172 ** distinguish adjacent children (if the rightmost term of the left
00173 ** child is "something", and the leftmost term of the right child is
00174 ** "wicked", only "w" is stored).
00175 **
00176 ** New data is spilled to a new interior node at the same height when
00177 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
00178 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
00179 ** interior nodes and making the tree too skinny.  The interior nodes
00180 ** at a given height are naturally tracked by interior nodes at
00181 ** height+1, and so on.
00182 **
00183 **
00184 **** Segment directory ****
00185 ** The segment directory in table %_segdir stores meta-information for
00186 ** merging and deleting segments, and also the root node of the
00187 ** segment's tree.
00188 **
00189 ** The root node is the top node of the segment's tree after encoding
00190 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
00191 ** This could be either a leaf node or an interior node.  If the top
00192 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
00193 ** and a new root interior node is generated (which should always fit
00194 ** within ROOT_MAX because it only needs space for 2 varints, the
00195 ** height and the blockid of the previous root).
00196 **
00197 ** The meta-information in the segment directory is:
00198 **   level               - segment level (see below)
00199 **   idx                 - index within level
00200 **                       - (level,idx uniquely identify a segment)
00201 **   start_block         - first leaf node
00202 **   leaves_end_block    - last leaf node
00203 **   end_block           - last block (including interior nodes)
00204 **   root                - contents of root node
00205 **
00206 ** If the root node is a leaf node, then start_block,
00207 ** leaves_end_block, and end_block are all 0.
00208 **
00209 **
00210 **** Segment merging ****
00211 ** To amortize update costs, segments are groups into levels and
00212 ** merged in matches.  Each increase in level represents exponentially
00213 ** more documents.
00214 **
00215 ** New documents (actually, document updates) are tokenized and
00216 ** written individually (using LeafWriter) to a level 0 segment, with
00217 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
00218 ** level 0 segments are merged into a single level 1 segment.  Level 1
00219 ** is populated like level 0, and eventually MERGE_COUNT level 1
00220 ** segments are merged to a single level 2 segment (representing
00221 ** MERGE_COUNT^2 updates), and so on.
00222 **
00223 ** A segment merge traverses all segments at a given level in
00224 ** parallel, performing a straightforward sorted merge.  Since segment
00225 ** leaf nodes are written in to the %_segments table in order, this
00226 ** merge traverses the underlying sqlite disk structures efficiently.
00227 ** After the merge, all segment blocks from the merged level are
00228 ** deleted.
00229 **
00230 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
00231 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
00232 ** very similar performance numbers to 16 on insertion, though they're
00233 ** a tiny bit slower (perhaps due to more overhead in merge-time
00234 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
00235 ** 16, 2 about 66% slower than 16.
00236 **
00237 ** At query time, high MERGE_COUNT increases the number of segments
00238 ** which need to be scanned and merged.  For instance, with 100k docs
00239 ** inserted:
00240 **
00241 **    MERGE_COUNT   segments
00242 **       16           25
00243 **        8           12
00244 **        4           10
00245 **        2            6
00246 **
00247 ** This appears to have only a moderate impact on queries for very
00248 ** frequent terms (which are somewhat dominated by segment merge
00249 ** costs), and infrequent and non-existent terms still seem to be fast
00250 ** even with many segments.
00251 **
00252 ** TODO(shess) That said, it would be nice to have a better query-side
00253 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
00254 ** optimizations to things like doclist merging will swing the sweet
00255 ** spot around.
00256 **
00257 **
00258 **
00259 **** Handling of deletions and updates ****
00260 ** Since we're using a segmented structure, with no docid-oriented
00261 ** index into the term index, we clearly cannot simply update the term
00262 ** index when a document is deleted or updated.  For deletions, we
00263 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
00264 ** we simply write the new doclist.  Segment merges overwrite older
00265 ** data for a particular docid with newer data, so deletes or updates
00266 ** will eventually overtake the earlier data and knock it out.  The
00267 ** query logic likewise merges doclists so that newer data knocks out
00268 ** older data.
00269 **
00270 ** TODO(shess) Provide a VACUUM type operation to clear out all
00271 ** deletions and duplications.  This would basically be a forced merge
00272 ** into a single segment.
00273 */
00274 
00275 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
00276 
00277 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
00278 # define SQLITE_CORE 1
00279 #endif
00280 
00281 #include <assert.h>
00282 #include <stdlib.h>
00283 #include <stdio.h>
00284 #include <string.h>
00285 #include <ctype.h>
00286 
00287 #include "fts3.h"
00288 #include "fts3_hash.h"
00289 #include "fts3_tokenizer.h"
00290 #ifndef SQLITE_CORE 
00291 # include "sqlite3ext.h"
00292   SQLITE_EXTENSION_INIT1
00293 #endif
00294 
00295 
00296 /* TODO(shess) MAN, this thing needs some refactoring.  At minimum, it
00297 ** would be nice to order the file better, perhaps something along the
00298 ** lines of:
00299 **
00300 **  - utility functions
00301 **  - table setup functions
00302 **  - table update functions
00303 **  - table query functions
00304 **
00305 ** Put the query functions last because they're likely to reference
00306 ** typedefs or functions from the table update section.
00307 */
00308 
00309 #if 0
00310 # define FTSTRACE(A)  printf A; fflush(stdout)
00311 #else
00312 # define FTSTRACE(A)
00313 #endif
00314 
00315 /*
00316 ** Default span for NEAR operators.
00317 */
00318 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
00319 
00320 /* It is not safe to call isspace(), tolower(), or isalnum() on
00321 ** hi-bit-set characters.  This is the same solution used in the
00322 ** tokenizer.
00323 */
00324 /* TODO(shess) The snippet-generation code should be using the
00325 ** tokenizer-generated tokens rather than doing its own local
00326 ** tokenization.
00327 */
00328 /* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
00329 static int safe_isspace(char c){
00330   return (c&0x80)==0 ? isspace(c) : 0;
00331 }
00332 static int safe_tolower(char c){
00333   return (c&0x80)==0 ? tolower(c) : c;
00334 }
00335 static int safe_isalnum(char c){
00336   return (c&0x80)==0 ? isalnum(c) : 0;
00337 }
00338 
00339 typedef enum DocListType {
00340   DL_DOCIDS,              /* docids only */
00341   DL_POSITIONS,           /* docids + positions */
00342   DL_POSITIONS_OFFSETS    /* docids + positions + offsets */
00343 } DocListType;
00344 
00345 /*
00346 ** By default, only positions and not offsets are stored in the doclists.
00347 ** To change this so that offsets are stored too, compile with
00348 **
00349 **          -DDL_DEFAULT=DL_POSITIONS_OFFSETS
00350 **
00351 ** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted
00352 ** into (no deletes or updates).
00353 */
00354 #ifndef DL_DEFAULT
00355 # define DL_DEFAULT DL_POSITIONS
00356 #endif
00357 
00358 enum {
00359   POS_END = 0,        /* end of this position list */
00360   POS_COLUMN,         /* followed by new column number */
00361   POS_BASE
00362 };
00363 
00364 /* MERGE_COUNT controls how often we merge segments (see comment at
00365 ** top of file).
00366 */
00367 #define MERGE_COUNT 16
00368 
00369 /* utility functions */
00370 
00371 /* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single
00372 ** record to prevent errors of the form:
00373 **
00374 ** my_function(SomeType *b){
00375 **   memset(b, '\0', sizeof(b));  // sizeof(b)!=sizeof(*b)
00376 ** }
00377 */
00378 /* TODO(shess) Obvious candidates for a header file. */
00379 #define CLEAR(b) memset(b, '\0', sizeof(*(b)))
00380 
00381 #ifndef NDEBUG
00382 #  define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b)))
00383 #else
00384 #  define SCRAMBLE(b)
00385 #endif
00386 
00387 /* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
00388 #define VARINT_MAX 10
00389 
00390 /* Write a 64-bit variable-length integer to memory starting at p[0].
00391  * The length of data written will be between 1 and VARINT_MAX bytes.
00392  * The number of bytes written is returned. */
00393 static int fts3PutVarint(char *p, sqlite_int64 v){
00394   unsigned char *q = (unsigned char *) p;
00395   sqlite_uint64 vu = v;
00396   do{
00397     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
00398     vu >>= 7;
00399   }while( vu!=0 );
00400   q[-1] &= 0x7f;  /* turn off high bit in final byte */
00401   assert( q - (unsigned char *)p <= VARINT_MAX );
00402   return (int) (q - (unsigned char *)p);
00403 }
00404 
00405 /* Read a 64-bit variable-length integer from memory starting at p[0].
00406  * Return the number of bytes read, or 0 on error.
00407  * The value is stored in *v. */
00408 static int fts3GetVarint(const char *p, sqlite_int64 *v){
00409   const unsigned char *q = (const unsigned char *) p;
00410   sqlite_uint64 x = 0, y = 1;
00411   while( (*q & 0x80) == 0x80 ){
00412     x += y * (*q++ & 0x7f);
00413     y <<= 7;
00414     if( q - (unsigned char *)p >= VARINT_MAX ){  /* bad data */
00415       assert( 0 );
00416       return 0;
00417     }
00418   }
00419   x += y * (*q++);
00420   *v = (sqlite_int64) x;
00421   return (int) (q - (unsigned char *)p);
00422 }
00423 
00424 static int fts3GetVarint32(const char *p, int *pi){
00425  sqlite_int64 i;
00426  int ret = fts3GetVarint(p, &i);
00427  *pi = (int) i;
00428  assert( *pi==i );
00429  return ret;
00430 }
00431 
00432 /*******************************************************************/
00433 /* DataBuffer is used to collect data into a buffer in piecemeal
00434 ** fashion.  It implements the usual distinction between amount of
00435 ** data currently stored (nData) and buffer capacity (nCapacity).
00436 **
00437 ** dataBufferInit - create a buffer with given initial capacity.
00438 ** dataBufferReset - forget buffer's data, retaining capacity.
00439 ** dataBufferDestroy - free buffer's data.
00440 ** dataBufferSwap - swap contents of two buffers.
00441 ** dataBufferExpand - expand capacity without adding data.
00442 ** dataBufferAppend - append data.
00443 ** dataBufferAppend2 - append two pieces of data at once.
00444 ** dataBufferReplace - replace buffer's data.
00445 */
00446 typedef struct DataBuffer {
00447   char *pData;          /* Pointer to malloc'ed buffer. */
00448   int nCapacity;        /* Size of pData buffer. */
00449   int nData;            /* End of data loaded into pData. */
00450 } DataBuffer;
00451 
00452 static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){
00453   assert( nCapacity>=0 );
00454   pBuffer->nData = 0;
00455   pBuffer->nCapacity = nCapacity;
00456   pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity);
00457 }
00458 static void dataBufferReset(DataBuffer *pBuffer){
00459   pBuffer->nData = 0;
00460 }
00461 static void dataBufferDestroy(DataBuffer *pBuffer){
00462   if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData);
00463   SCRAMBLE(pBuffer);
00464 }
00465 static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){
00466   DataBuffer tmp = *pBuffer1;
00467   *pBuffer1 = *pBuffer2;
00468   *pBuffer2 = tmp;
00469 }
00470 static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){
00471   assert( nAddCapacity>0 );
00472   /* TODO(shess) Consider expanding more aggressively.  Note that the
00473   ** underlying malloc implementation may take care of such things for
00474   ** us already.
00475   */
00476   if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){
00477     pBuffer->nCapacity = pBuffer->nData+nAddCapacity;
00478     pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity);
00479   }
00480 }
00481 static void dataBufferAppend(DataBuffer *pBuffer,
00482                              const char *pSource, int nSource){
00483   assert( nSource>0 && pSource!=NULL );
00484   dataBufferExpand(pBuffer, nSource);
00485   memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource);
00486   pBuffer->nData += nSource;
00487 }
00488 static void dataBufferAppend2(DataBuffer *pBuffer,
00489                               const char *pSource1, int nSource1,
00490                               const char *pSource2, int nSource2){
00491   assert( nSource1>0 && pSource1!=NULL );
00492   assert( nSource2>0 && pSource2!=NULL );
00493   dataBufferExpand(pBuffer, nSource1+nSource2);
00494   memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1);
00495   memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2);
00496   pBuffer->nData += nSource1+nSource2;
00497 }
00498 static void dataBufferReplace(DataBuffer *pBuffer,
00499                               const char *pSource, int nSource){
00500   dataBufferReset(pBuffer);
00501   dataBufferAppend(pBuffer, pSource, nSource);
00502 }
00503 
00504 /* StringBuffer is a null-terminated version of DataBuffer. */
00505 typedef struct StringBuffer {
00506   DataBuffer b;            /* Includes null terminator. */
00507 } StringBuffer;
00508 
00509 static void initStringBuffer(StringBuffer *sb){
00510   dataBufferInit(&sb->b, 100);
00511   dataBufferReplace(&sb->b, "", 1);
00512 }
00513 static int stringBufferLength(StringBuffer *sb){
00514   return sb->b.nData-1;
00515 }
00516 static char *stringBufferData(StringBuffer *sb){
00517   return sb->b.pData;
00518 }
00519 static void stringBufferDestroy(StringBuffer *sb){
00520   dataBufferDestroy(&sb->b);
00521 }
00522 
00523 static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
00524   assert( sb->b.nData>0 );
00525   if( nFrom>0 ){
00526     sb->b.nData--;
00527     dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1);
00528   }
00529 }
00530 static void append(StringBuffer *sb, const char *zFrom){
00531   nappend(sb, zFrom, strlen(zFrom));
00532 }
00533 
00534 /* Append a list of strings separated by commas. */
00535 static void appendList(StringBuffer *sb, int nString, char **azString){
00536   int i;
00537   for(i=0; i<nString; ++i){
00538     if( i>0 ) append(sb, ", ");
00539     append(sb, azString[i]);
00540   }
00541 }
00542 
00543 static int endsInWhiteSpace(StringBuffer *p){
00544   return stringBufferLength(p)>0 &&
00545     safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]);
00546 }
00547 
00548 /* If the StringBuffer ends in something other than white space, add a
00549 ** single space character to the end.
00550 */
00551 static void appendWhiteSpace(StringBuffer *p){
00552   if( stringBufferLength(p)==0 ) return;
00553   if( !endsInWhiteSpace(p) ) append(p, " ");
00554 }
00555 
00556 /* Remove white space from the end of the StringBuffer */
00557 static void trimWhiteSpace(StringBuffer *p){
00558   while( endsInWhiteSpace(p) ){
00559     p->b.pData[--p->b.nData-1] = '\0';
00560   }
00561 }
00562 
00563 /*******************************************************************/
00564 /* DLReader is used to read document elements from a doclist.  The
00565 ** current docid is cached, so dlrDocid() is fast.  DLReader does not
00566 ** own the doclist buffer.
00567 **
00568 ** dlrAtEnd - true if there's no more data to read.
00569 ** dlrDocid - docid of current document.
00570 ** dlrDocData - doclist data for current document (including docid).
00571 ** dlrDocDataBytes - length of same.
00572 ** dlrAllDataBytes - length of all remaining data.
00573 ** dlrPosData - position data for current document.
00574 ** dlrPosDataLen - length of pos data for current document (incl POS_END).
00575 ** dlrStep - step to current document.
00576 ** dlrInit - initial for doclist of given type against given data.
00577 ** dlrDestroy - clean up.
00578 **
00579 ** Expected usage is something like:
00580 **
00581 **   DLReader reader;
00582 **   dlrInit(&reader, pData, nData);
00583 **   while( !dlrAtEnd(&reader) ){
00584 **     // calls to dlrDocid() and kin.
00585 **     dlrStep(&reader);
00586 **   }
00587 **   dlrDestroy(&reader);
00588 */
00589 typedef struct DLReader {
00590   DocListType iType;
00591   const char *pData;
00592   int nData;
00593 
00594   sqlite_int64 iDocid;
00595   int nElement;
00596 } DLReader;
00597 
00598 static int dlrAtEnd(DLReader *pReader){
00599   assert( pReader->nData>=0 );
00600   return pReader->nData==0;
00601 }
00602 static sqlite_int64 dlrDocid(DLReader *pReader){
00603   assert( !dlrAtEnd(pReader) );
00604   return pReader->iDocid;
00605 }
00606 static const char *dlrDocData(DLReader *pReader){
00607   assert( !dlrAtEnd(pReader) );
00608   return pReader->pData;
00609 }
00610 static int dlrDocDataBytes(DLReader *pReader){
00611   assert( !dlrAtEnd(pReader) );
00612   return pReader->nElement;
00613 }
00614 static int dlrAllDataBytes(DLReader *pReader){
00615   assert( !dlrAtEnd(pReader) );
00616   return pReader->nData;
00617 }
00618 /* TODO(shess) Consider adding a field to track iDocid varint length
00619 ** to make these two functions faster.  This might matter (a tiny bit)
00620 ** for queries.
00621 */
00622 static const char *dlrPosData(DLReader *pReader){
00623   sqlite_int64 iDummy;
00624   int n = fts3GetVarint(pReader->pData, &iDummy);
00625   assert( !dlrAtEnd(pReader) );
00626   return pReader->pData+n;
00627 }
00628 static int dlrPosDataLen(DLReader *pReader){
00629   sqlite_int64 iDummy;
00630   int n = fts3GetVarint(pReader->pData, &iDummy);
00631   assert( !dlrAtEnd(pReader) );
00632   return pReader->nElement-n;
00633 }
00634 static void dlrStep(DLReader *pReader){
00635   assert( !dlrAtEnd(pReader) );
00636 
00637   /* Skip past current doclist element. */
00638   assert( pReader->nElement<=pReader->nData );
00639   pReader->pData += pReader->nElement;
00640   pReader->nData -= pReader->nElement;
00641 
00642   /* If there is more data, read the next doclist element. */
00643   if( pReader->nData!=0 ){
00644     sqlite_int64 iDocidDelta;
00645     int iDummy, n = fts3GetVarint(pReader->pData, &iDocidDelta);
00646     pReader->iDocid += iDocidDelta;
00647     if( pReader->iType>=DL_POSITIONS ){
00648       assert( n<pReader->nData );
00649       while( 1 ){
00650         n += fts3GetVarint32(pReader->pData+n, &iDummy);
00651         assert( n<=pReader->nData );
00652         if( iDummy==POS_END ) break;
00653         if( iDummy==POS_COLUMN ){
00654           n += fts3GetVarint32(pReader->pData+n, &iDummy);
00655           assert( n<pReader->nData );
00656         }else if( pReader->iType==DL_POSITIONS_OFFSETS ){
00657           n += fts3GetVarint32(pReader->pData+n, &iDummy);
00658           n += fts3GetVarint32(pReader->pData+n, &iDummy);
00659           assert( n<pReader->nData );
00660         }
00661       }
00662     }
00663     pReader->nElement = n;
00664     assert( pReader->nElement<=pReader->nData );
00665   }
00666 }
00667 static void dlrInit(DLReader *pReader, DocListType iType,
00668                     const char *pData, int nData){
00669   assert( pData!=NULL && nData!=0 );
00670   pReader->iType = iType;
00671   pReader->pData = pData;
00672   pReader->nData = nData;
00673   pReader->nElement = 0;
00674   pReader->iDocid = 0;
00675 
00676   /* Load the first element's data.  There must be a first element. */
00677   dlrStep(pReader);
00678 }
00679 static void dlrDestroy(DLReader *pReader){
00680   SCRAMBLE(pReader);
00681 }
00682 
00683 #ifndef NDEBUG
00684 /* Verify that the doclist can be validly decoded.  Also returns the
00685 ** last docid found because it is convenient in other assertions for
00686 ** DLWriter.
00687 */
00688 static void docListValidate(DocListType iType, const char *pData, int nData,
00689                             sqlite_int64 *pLastDocid){
00690   sqlite_int64 iPrevDocid = 0;
00691   assert( nData>0 );
00692   assert( pData!=0 );
00693   assert( pData+nData>pData );
00694   while( nData!=0 ){
00695     sqlite_int64 iDocidDelta;
00696     int n = fts3GetVarint(pData, &iDocidDelta);
00697     iPrevDocid += iDocidDelta;
00698     if( iType>DL_DOCIDS ){
00699       int iDummy;
00700       while( 1 ){
00701         n += fts3GetVarint32(pData+n, &iDummy);
00702         if( iDummy==POS_END ) break;
00703         if( iDummy==POS_COLUMN ){
00704           n += fts3GetVarint32(pData+n, &iDummy);
00705         }else if( iType>DL_POSITIONS ){
00706           n += fts3GetVarint32(pData+n, &iDummy);
00707           n += fts3GetVarint32(pData+n, &iDummy);
00708         }
00709         assert( n<=nData );
00710       }
00711     }
00712     assert( n<=nData );
00713     pData += n;
00714     nData -= n;
00715   }
00716   if( pLastDocid ) *pLastDocid = iPrevDocid;
00717 }
00718 #define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o)
00719 #else
00720 #define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 )
00721 #endif
00722 
00723 /*******************************************************************/
00724 /* DLWriter is used to write doclist data to a DataBuffer.  DLWriter
00725 ** always appends to the buffer and does not own it.
00726 **
00727 ** dlwInit - initialize to write a given type doclistto a buffer.
00728 ** dlwDestroy - clear the writer's memory.  Does not free buffer.
00729 ** dlwAppend - append raw doclist data to buffer.
00730 ** dlwCopy - copy next doclist from reader to writer.
00731 ** dlwAdd - construct doclist element and append to buffer.
00732 **    Only apply dlwAdd() to DL_DOCIDS doclists (else use PLWriter).
00733 */
00734 typedef struct DLWriter {
00735   DocListType iType;
00736   DataBuffer *b;
00737   sqlite_int64 iPrevDocid;
00738 #ifndef NDEBUG
00739   int has_iPrevDocid;
00740 #endif
00741 } DLWriter;
00742 
00743 static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){
00744   pWriter->b = b;
00745   pWriter->iType = iType;
00746   pWriter->iPrevDocid = 0;
00747 #ifndef NDEBUG
00748   pWriter->has_iPrevDocid = 0;
00749 #endif
00750 }
00751 static void dlwDestroy(DLWriter *pWriter){
00752   SCRAMBLE(pWriter);
00753 }
00754 /* iFirstDocid is the first docid in the doclist in pData.  It is
00755 ** needed because pData may point within a larger doclist, in which
00756 ** case the first item would be delta-encoded.
00757 **
00758 ** iLastDocid is the final docid in the doclist in pData.  It is
00759 ** needed to create the new iPrevDocid for future delta-encoding.  The
00760 ** code could decode the passed doclist to recreate iLastDocid, but
00761 ** the only current user (docListMerge) already has decoded this
00762 ** information.
00763 */
00764 /* TODO(shess) This has become just a helper for docListMerge.
00765 ** Consider a refactor to make this cleaner.
00766 */
00767 static void dlwAppend(DLWriter *pWriter,
00768                       const char *pData, int nData,
00769                       sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){
00770   sqlite_int64 iDocid = 0;
00771   char c[VARINT_MAX];
00772   int nFirstOld, nFirstNew;     /* Old and new varint len of first docid. */
00773 #ifndef NDEBUG
00774   sqlite_int64 iLastDocidDelta;
00775 #endif
00776 
00777   /* Recode the initial docid as delta from iPrevDocid. */
00778   nFirstOld = fts3GetVarint(pData, &iDocid);
00779   assert( nFirstOld<nData || (nFirstOld==nData && pWriter->iType==DL_DOCIDS) );
00780   nFirstNew = fts3PutVarint(c, iFirstDocid-pWriter->iPrevDocid);
00781 
00782   /* Verify that the incoming doclist is valid AND that it ends with
00783   ** the expected docid.  This is essential because we'll trust this
00784   ** docid in future delta-encoding.
00785   */
00786   ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta);
00787   assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta );
00788 
00789   /* Append recoded initial docid and everything else.  Rest of docids
00790   ** should have been delta-encoded from previous initial docid.
00791   */
00792   if( nFirstOld<nData ){
00793     dataBufferAppend2(pWriter->b, c, nFirstNew,
00794                       pData+nFirstOld, nData-nFirstOld);
00795   }else{
00796     dataBufferAppend(pWriter->b, c, nFirstNew);
00797   }
00798   pWriter->iPrevDocid = iLastDocid;
00799 }
00800 static void dlwCopy(DLWriter *pWriter, DLReader *pReader){
00801   dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader),
00802             dlrDocid(pReader), dlrDocid(pReader));
00803 }
00804 static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){
00805   char c[VARINT_MAX];
00806   int n = fts3PutVarint(c, iDocid-pWriter->iPrevDocid);
00807 
00808   /* Docids must ascend. */
00809   assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid );
00810   assert( pWriter->iType==DL_DOCIDS );
00811 
00812   dataBufferAppend(pWriter->b, c, n);
00813   pWriter->iPrevDocid = iDocid;
00814 #ifndef NDEBUG
00815   pWriter->has_iPrevDocid = 1;
00816 #endif
00817 }
00818 
00819 /*******************************************************************/
00820 /* PLReader is used to read data from a document's position list.  As
00821 ** the caller steps through the list, data is cached so that varints
00822 ** only need to be decoded once.
00823 **
00824 ** plrInit, plrDestroy - create/destroy a reader.
00825 ** plrColumn, plrPosition, plrStartOffset, plrEndOffset - accessors
00826 ** plrAtEnd - at end of stream, only call plrDestroy once true.
00827 ** plrStep - step to the next element.
00828 */
00829 typedef struct PLReader {
00830   /* These refer to the next position's data.  nData will reach 0 when
00831   ** reading the last position, so plrStep() signals EOF by setting
00832   ** pData to NULL.
00833   */
00834   const char *pData;
00835   int nData;
00836 
00837   DocListType iType;
00838   int iColumn;         /* the last column read */
00839   int iPosition;       /* the last position read */
00840   int iStartOffset;    /* the last start offset read */
00841   int iEndOffset;      /* the last end offset read */
00842 } PLReader;
00843 
00844 static int plrAtEnd(PLReader *pReader){
00845   return pReader->pData==NULL;
00846 }
00847 static int plrColumn(PLReader *pReader){
00848   assert( !plrAtEnd(pReader) );
00849   return pReader->iColumn;
00850 }
00851 static int plrPosition(PLReader *pReader){
00852   assert( !plrAtEnd(pReader) );
00853   return pReader->iPosition;
00854 }
00855 static int plrStartOffset(PLReader *pReader){
00856   assert( !plrAtEnd(pReader) );
00857   return pReader->iStartOffset;
00858 }
00859 static int plrEndOffset(PLReader *pReader){
00860   assert( !plrAtEnd(pReader) );
00861   return pReader->iEndOffset;
00862 }
00863 static void plrStep(PLReader *pReader){
00864   int i, n;
00865 
00866   assert( !plrAtEnd(pReader) );
00867 
00868   if( pReader->nData==0 ){
00869     pReader->pData = NULL;
00870     return;
00871   }
00872 
00873   n = fts3GetVarint32(pReader->pData, &i);
00874   if( i==POS_COLUMN ){
00875     n += fts3GetVarint32(pReader->pData+n, &pReader->iColumn);
00876     pReader->iPosition = 0;
00877     pReader->iStartOffset = 0;
00878     n += fts3GetVarint32(pReader->pData+n, &i);
00879   }
00880   /* Should never see adjacent column changes. */
00881   assert( i!=POS_COLUMN );
00882 
00883   if( i==POS_END ){
00884     pReader->nData = 0;
00885     pReader->pData = NULL;
00886     return;
00887   }
00888 
00889   pReader->iPosition += i-POS_BASE;
00890   if( pReader->iType==DL_POSITIONS_OFFSETS ){
00891     n += fts3GetVarint32(pReader->pData+n, &i);
00892     pReader->iStartOffset += i;
00893     n += fts3GetVarint32(pReader->pData+n, &i);
00894     pReader->iEndOffset = pReader->iStartOffset+i;
00895   }
00896   assert( n<=pReader->nData );
00897   pReader->pData += n;
00898   pReader->nData -= n;
00899 }
00900 
00901 static void plrInit(PLReader *pReader, DLReader *pDLReader){
00902   pReader->pData = dlrPosData(pDLReader);
00903   pReader->nData = dlrPosDataLen(pDLReader);
00904   pReader->iType = pDLReader->iType;
00905   pReader->iColumn = 0;
00906   pReader->iPosition = 0;
00907   pReader->iStartOffset = 0;
00908   pReader->iEndOffset = 0;
00909   plrStep(pReader);
00910 }
00911 static void plrDestroy(PLReader *pReader){
00912   SCRAMBLE(pReader);
00913 }
00914 
00915 /*******************************************************************/
00916 /* PLWriter is used in constructing a document's position list.  As a
00917 ** convenience, if iType is DL_DOCIDS, PLWriter becomes a no-op.
00918 ** PLWriter writes to the associated DLWriter's buffer.
00919 **
00920 ** plwInit - init for writing a document's poslist.
00921 ** plwDestroy - clear a writer.
00922 ** plwAdd - append position and offset information.
00923 ** plwCopy - copy next position's data from reader to writer.
00924 ** plwTerminate - add any necessary doclist terminator.
00925 **
00926 ** Calling plwAdd() after plwTerminate() may result in a corrupt
00927 ** doclist.
00928 */
00929 /* TODO(shess) Until we've written the second item, we can cache the
00930 ** first item's information.  Then we'd have three states:
00931 **
00932 ** - initialized with docid, no positions.
00933 ** - docid and one position.
00934 ** - docid and multiple positions.
00935 **
00936 ** Only the last state needs to actually write to dlw->b, which would
00937 ** be an improvement in the DLCollector case.
00938 */
00939 typedef struct PLWriter {
00940   DLWriter *dlw;
00941 
00942   int iColumn;    /* the last column written */
00943   int iPos;       /* the last position written */
00944   int iOffset;    /* the last start offset written */
00945 } PLWriter;
00946 
00947 /* TODO(shess) In the case where the parent is reading these values
00948 ** from a PLReader, we could optimize to a copy if that PLReader has
00949 ** the same type as pWriter.
00950 */
00951 static void plwAdd(PLWriter *pWriter, int iColumn, int iPos,
00952                    int iStartOffset, int iEndOffset){
00953   /* Worst-case space for POS_COLUMN, iColumn, iPosDelta,
00954   ** iStartOffsetDelta, and iEndOffsetDelta.
00955   */
00956   char c[5*VARINT_MAX];
00957   int n = 0;
00958 
00959   /* Ban plwAdd() after plwTerminate(). */
00960   assert( pWriter->iPos!=-1 );
00961 
00962   if( pWriter->dlw->iType==DL_DOCIDS ) return;
00963 
00964   if( iColumn!=pWriter->iColumn ){
00965     n += fts3PutVarint(c+n, POS_COLUMN);
00966     n += fts3PutVarint(c+n, iColumn);
00967     pWriter->iColumn = iColumn;
00968     pWriter->iPos = 0;
00969     pWriter->iOffset = 0;
00970   }
00971   assert( iPos>=pWriter->iPos );
00972   n += fts3PutVarint(c+n, POS_BASE+(iPos-pWriter->iPos));
00973   pWriter->iPos = iPos;
00974   if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){
00975     assert( iStartOffset>=pWriter->iOffset );
00976     n += fts3PutVarint(c+n, iStartOffset-pWriter->iOffset);
00977     pWriter->iOffset = iStartOffset;
00978     assert( iEndOffset>=iStartOffset );
00979     n += fts3PutVarint(c+n, iEndOffset-iStartOffset);
00980   }
00981   dataBufferAppend(pWriter->dlw->b, c, n);
00982 }
00983 static void plwCopy(PLWriter *pWriter, PLReader *pReader){
00984   plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader),
00985          plrStartOffset(pReader), plrEndOffset(pReader));
00986 }
00987 static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){
00988   char c[VARINT_MAX];
00989   int n;
00990 
00991   pWriter->dlw = dlw;
00992 
00993   /* Docids must ascend. */
00994   assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid );
00995   n = fts3PutVarint(c, iDocid-pWriter->dlw->iPrevDocid);
00996   dataBufferAppend(pWriter->dlw->b, c, n);
00997   pWriter->dlw->iPrevDocid = iDocid;
00998 #ifndef NDEBUG
00999   pWriter->dlw->has_iPrevDocid = 1;
01000 #endif
01001 
01002   pWriter->iColumn = 0;
01003   pWriter->iPos = 0;
01004   pWriter->iOffset = 0;
01005 }
01006 /* TODO(shess) Should plwDestroy() also terminate the doclist?  But
01007 ** then plwDestroy() would no longer be just a destructor, it would
01008 ** also be doing work, which isn't consistent with the overall idiom.
01009 ** Another option would be for plwAdd() to always append any necessary
01010 ** terminator, so that the output is always correct.  But that would
01011 ** add incremental work to the common case with the only benefit being
01012 ** API elegance.  Punt for now.
01013 */
01014 static void plwTerminate(PLWriter *pWriter){
01015   if( pWriter->dlw->iType>DL_DOCIDS ){
01016     char c[VARINT_MAX];
01017     int n = fts3PutVarint(c, POS_END);
01018     dataBufferAppend(pWriter->dlw->b, c, n);
01019   }
01020 #ifndef NDEBUG
01021   /* Mark as terminated for assert in plwAdd(). */
01022   pWriter->iPos = -1;
01023 #endif
01024 }
01025 static void plwDestroy(PLWriter *pWriter){
01026   SCRAMBLE(pWriter);
01027 }
01028 
01029 /*******************************************************************/
01030 /* DLCollector wraps PLWriter and DLWriter to provide a
01031 ** dynamically-allocated doclist area to use during tokenization.
01032 **
01033 ** dlcNew - malloc up and initialize a collector.
01034 ** dlcDelete - destroy a collector and all contained items.
01035 ** dlcAddPos - append position and offset information.
01036 ** dlcAddDoclist - add the collected doclist to the given buffer.
01037 ** dlcNext - terminate the current document and open another.
01038 */
01039 typedef struct DLCollector {
01040   DataBuffer b;
01041   DLWriter dlw;
01042   PLWriter plw;
01043 } DLCollector;
01044 
01045 /* TODO(shess) This could also be done by calling plwTerminate() and
01046 ** dataBufferAppend().  I tried that, expecting nominal performance
01047 ** differences, but it seemed to pretty reliably be worth 1% to code
01048 ** it this way.  I suspect it is the incremental malloc overhead (some
01049 ** percentage of the plwTerminate() calls will cause a realloc), so
01050 ** this might be worth revisiting if the DataBuffer implementation
01051 ** changes.
01052 */
01053 static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){
01054   if( pCollector->dlw.iType>DL_DOCIDS ){
01055     char c[VARINT_MAX];
01056     int n = fts3PutVarint(c, POS_END);
01057     dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n);
01058   }else{
01059     dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData);
01060   }
01061 }
01062 static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){
01063   plwTerminate(&pCollector->plw);
01064   plwDestroy(&pCollector->plw);
01065   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
01066 }
01067 static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos,
01068                       int iStartOffset, int iEndOffset){
01069   plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset);
01070 }
01071 
01072 static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){
01073   DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector));
01074   dataBufferInit(&pCollector->b, 0);
01075   dlwInit(&pCollector->dlw, iType, &pCollector->b);
01076   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
01077   return pCollector;
01078 }
01079 static void dlcDelete(DLCollector *pCollector){
01080   plwDestroy(&pCollector->plw);
01081   dlwDestroy(&pCollector->dlw);
01082   dataBufferDestroy(&pCollector->b);
01083   SCRAMBLE(pCollector);
01084   sqlite3_free(pCollector);
01085 }
01086 
01087 
01088 /* Copy the doclist data of iType in pData/nData into *out, trimming
01089 ** unnecessary data as we go.  Only columns matching iColumn are
01090 ** copied, all columns copied if iColumn is -1.  Elements with no
01091 ** matching columns are dropped.  The output is an iOutType doclist.
01092 */
01093 /* NOTE(shess) This code is only valid after all doclists are merged.
01094 ** If this is run before merges, then doclist items which represent
01095 ** deletion will be trimmed, and will thus not effect a deletion
01096 ** during the merge.
01097 */
01098 static void docListTrim(DocListType iType, const char *pData, int nData,
01099                         int iColumn, DocListType iOutType, DataBuffer *out){
01100   DLReader dlReader;
01101   DLWriter dlWriter;
01102 
01103   assert( iOutType<=iType );
01104 
01105   dlrInit(&dlReader, iType, pData, nData);
01106   dlwInit(&dlWriter, iOutType, out);
01107 
01108   while( !dlrAtEnd(&dlReader) ){
01109     PLReader plReader;
01110     PLWriter plWriter;
01111     int match = 0;
01112 
01113     plrInit(&plReader, &dlReader);
01114 
01115     while( !plrAtEnd(&plReader) ){
01116       if( iColumn==-1 || plrColumn(&plReader)==iColumn ){
01117         if( !match ){
01118           plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader));
01119           match = 1;
01120         }
01121         plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader),
01122                plrStartOffset(&plReader), plrEndOffset(&plReader));
01123       }
01124       plrStep(&plReader);
01125     }
01126     if( match ){
01127       plwTerminate(&plWriter);
01128       plwDestroy(&plWriter);
01129     }
01130 
01131     plrDestroy(&plReader);
01132     dlrStep(&dlReader);
01133   }
01134   dlwDestroy(&dlWriter);
01135   dlrDestroy(&dlReader);
01136 }
01137 
01138 /* Used by docListMerge() to keep doclists in the ascending order by
01139 ** docid, then ascending order by age (so the newest comes first).
01140 */
01141 typedef struct OrderedDLReader {
01142   DLReader *pReader;
01143 
01144   /* TODO(shess) If we assume that docListMerge pReaders is ordered by
01145   ** age (which we do), then we could use pReader comparisons to break
01146   ** ties.
01147   */
01148   int idx;
01149 } OrderedDLReader;
01150 
01151 /* Order eof to end, then by docid asc, idx desc. */
01152 static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){
01153   if( dlrAtEnd(r1->pReader) ){
01154     if( dlrAtEnd(r2->pReader) ) return 0;  /* Both atEnd(). */
01155     return 1;                              /* Only r1 atEnd(). */
01156   }
01157   if( dlrAtEnd(r2->pReader) ) return -1;   /* Only r2 atEnd(). */
01158 
01159   if( dlrDocid(r1->pReader)<dlrDocid(r2->pReader) ) return -1;
01160   if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1;
01161 
01162   /* Descending on idx. */
01163   return r2->idx-r1->idx;
01164 }
01165 
01166 /* Bubble p[0] to appropriate place in p[1..n-1].  Assumes that
01167 ** p[1..n-1] is already sorted.
01168 */
01169 /* TODO(shess) Is this frequent enough to warrant a binary search?
01170 ** Before implementing that, instrument the code to check.  In most
01171 ** current usage, I expect that p[0] will be less than p[1] a very
01172 ** high proportion of the time.
01173 */
01174 static void orderedDLReaderReorder(OrderedDLReader *p, int n){
01175   while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){
01176     OrderedDLReader tmp = p[0];
01177     p[0] = p[1];
01178     p[1] = tmp;
01179     n--;
01180     p++;
01181   }
01182 }
01183 
01184 /* Given an array of doclist readers, merge their doclist elements
01185 ** into out in sorted order (by docid), dropping elements from older
01186 ** readers when there is a duplicate docid.  pReaders is assumed to be
01187 ** ordered by age, oldest first.
01188 */
01189 /* TODO(shess) nReaders must be <= MERGE_COUNT.  This should probably
01190 ** be fixed.
01191 */
01192 static void docListMerge(DataBuffer *out,
01193                          DLReader *pReaders, int nReaders){
01194   OrderedDLReader readers[MERGE_COUNT];
01195   DLWriter writer;
01196   int i, n;
01197   const char *pStart = 0;
01198   int nStart = 0;
01199   sqlite_int64 iFirstDocid = 0, iLastDocid = 0;
01200 
01201   assert( nReaders>0 );
01202   if( nReaders==1 ){
01203     dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders));
01204     return;
01205   }
01206 
01207   assert( nReaders<=MERGE_COUNT );
01208   n = 0;
01209   for(i=0; i<nReaders; i++){
01210     assert( pReaders[i].iType==pReaders[0].iType );
01211     readers[i].pReader = pReaders+i;
01212     readers[i].idx = i;
01213     n += dlrAllDataBytes(&pReaders[i]);
01214   }
01215   /* Conservatively size output to sum of inputs.  Output should end
01216   ** up strictly smaller than input.
01217   */
01218   dataBufferExpand(out, n);
01219 
01220   /* Get the readers into sorted order. */
01221   while( i-->0 ){
01222     orderedDLReaderReorder(readers+i, nReaders-i);
01223   }
01224 
01225   dlwInit(&writer, pReaders[0].iType, out);
01226   while( !dlrAtEnd(readers[0].pReader) ){
01227     sqlite_int64 iDocid = dlrDocid(readers[0].pReader);
01228 
01229     /* If this is a continuation of the current buffer to copy, extend
01230     ** that buffer.  memcpy() seems to be more efficient if it has a
01231     ** lots of data to copy.
01232     */
01233     if( dlrDocData(readers[0].pReader)==pStart+nStart ){
01234       nStart += dlrDocDataBytes(readers[0].pReader);
01235     }else{
01236       if( pStart!=0 ){
01237         dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
01238       }
01239       pStart = dlrDocData(readers[0].pReader);
01240       nStart = dlrDocDataBytes(readers[0].pReader);
01241       iFirstDocid = iDocid;
01242     }
01243     iLastDocid = iDocid;
01244     dlrStep(readers[0].pReader);
01245 
01246     /* Drop all of the older elements with the same docid. */
01247     for(i=1; i<nReaders &&
01248              !dlrAtEnd(readers[i].pReader) &&
01249              dlrDocid(readers[i].pReader)==iDocid; i++){
01250       dlrStep(readers[i].pReader);
01251     }
01252 
01253     /* Get the readers back into order. */
01254     while( i-->0 ){
01255       orderedDLReaderReorder(readers+i, nReaders-i);
01256     }
01257   }
01258 
01259   /* Copy over any remaining elements. */
01260   if( nStart>0 ) dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
01261   dlwDestroy(&writer);
01262 }
01263 
01264 /* Helper function for posListUnion().  Compares the current position
01265 ** between left and right, returning as standard C idiom of <0 if
01266 ** left<right, >0 if left>right, and 0 if left==right.  "End" always
01267 ** compares greater.
01268 */
01269 static int posListCmp(PLReader *pLeft, PLReader *pRight){
01270   assert( pLeft->iType==pRight->iType );
01271   if( pLeft->iType==DL_DOCIDS ) return 0;
01272 
01273   if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1;
01274   if( plrAtEnd(pRight) ) return -1;
01275 
01276   if( plrColumn(pLeft)<plrColumn(pRight) ) return -1;
01277   if( plrColumn(pLeft)>plrColumn(pRight) ) return 1;
01278 
01279   if( plrPosition(pLeft)<plrPosition(pRight) ) return -1;
01280   if( plrPosition(pLeft)>plrPosition(pRight) ) return 1;
01281   if( pLeft->iType==DL_POSITIONS ) return 0;
01282 
01283   if( plrStartOffset(pLeft)<plrStartOffset(pRight) ) return -1;
01284   if( plrStartOffset(pLeft)>plrStartOffset(pRight) ) return 1;
01285 
01286   if( plrEndOffset(pLeft)<plrEndOffset(pRight) ) return -1;
01287   if( plrEndOffset(pLeft)>plrEndOffset(pRight) ) return 1;
01288 
01289   return 0;
01290 }
01291 
01292 /* Write the union of position lists in pLeft and pRight to pOut.
01293 ** "Union" in this case meaning "All unique position tuples".  Should
01294 ** work with any doclist type, though both inputs and the output
01295 ** should be the same type.
01296 */
01297 static void posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){
01298   PLReader left, right;
01299   PLWriter writer;
01300 
01301   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
01302   assert( pLeft->iType==pRight->iType );
01303   assert( pLeft->iType==pOut->iType );
01304 
01305   plrInit(&left, pLeft);
01306   plrInit(&right, pRight);
01307   plwInit(&writer, pOut, dlrDocid(pLeft));
01308 
01309   while( !plrAtEnd(&left) || !plrAtEnd(&right) ){
01310     int c = posListCmp(&left, &right);
01311     if( c<0 ){
01312       plwCopy(&writer, &left);
01313       plrStep(&left);
01314     }else if( c>0 ){
01315       plwCopy(&writer, &right);
01316       plrStep(&right);
01317     }else{
01318       plwCopy(&writer, &left);
01319       plrStep(&left);
01320       plrStep(&right);
01321     }
01322   }
01323 
01324   plwTerminate(&writer);
01325   plwDestroy(&writer);
01326   plrDestroy(&left);
01327   plrDestroy(&right);
01328 }
01329 
01330 /* Write the union of doclists in pLeft and pRight to pOut.  For
01331 ** docids in common between the inputs, the union of the position
01332 ** lists is written.  Inputs and outputs are always type DL_DEFAULT.
01333 */
01334 static void docListUnion(
01335   const char *pLeft, int nLeft,
01336   const char *pRight, int nRight,
01337   DataBuffer *pOut      /* Write the combined doclist here */
01338 ){
01339   DLReader left, right;
01340   DLWriter writer;
01341 
01342   if( nLeft==0 ){
01343     if( nRight!=0) dataBufferAppend(pOut, pRight, nRight);
01344     return;
01345   }
01346   if( nRight==0 ){
01347     dataBufferAppend(pOut, pLeft, nLeft);
01348     return;
01349   }
01350 
01351   dlrInit(&left, DL_DEFAULT, pLeft, nLeft);
01352   dlrInit(&right, DL_DEFAULT, pRight, nRight);
01353   dlwInit(&writer, DL_DEFAULT, pOut);
01354 
01355   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
01356     if( dlrAtEnd(&right) ){
01357       dlwCopy(&writer, &left);
01358       dlrStep(&left);
01359     }else if( dlrAtEnd(&left) ){
01360       dlwCopy(&writer, &right);
01361       dlrStep(&right);
01362     }else if( dlrDocid(&left)<dlrDocid(&right) ){
01363       dlwCopy(&writer, &left);
01364       dlrStep(&left);
01365     }else if( dlrDocid(&left)>dlrDocid(&right) ){
01366       dlwCopy(&writer, &right);
01367       dlrStep(&right);
01368     }else{
01369       posListUnion(&left, &right, &writer);
01370       dlrStep(&left);
01371       dlrStep(&right);
01372     }
01373   }
01374 
01375   dlrDestroy(&left);
01376   dlrDestroy(&right);
01377   dlwDestroy(&writer);
01378 }
01379 
01380 /* 
01381 ** This function is used as part of the implementation of phrase and
01382 ** NEAR matching.
01383 **
01384 ** pLeft and pRight are DLReaders positioned to the same docid in
01385 ** lists of type DL_POSITION. This function writes an entry to the
01386 ** DLWriter pOut for each position in pRight that is less than
01387 ** (nNear+1) greater (but not equal to or smaller) than a position 
01388 ** in pLeft. For example, if nNear is 0, and the positions contained
01389 ** by pLeft and pRight are:
01390 **
01391 **    pLeft:  5 10 15 20
01392 **    pRight: 6  9 17 21
01393 **
01394 ** then the docid is added to pOut. If pOut is of type DL_POSITIONS,
01395 ** then a positionids "6" and "21" are also added to pOut.
01396 **
01397 ** If boolean argument isSaveLeft is true, then positionids are copied
01398 ** from pLeft instead of pRight. In the example above, the positions "5"
01399 ** and "20" would be added instead of "6" and "21".
01400 */
01401 static void posListPhraseMerge(
01402   DLReader *pLeft, 
01403   DLReader *pRight,
01404   int nNear,
01405   int isSaveLeft,
01406   DLWriter *pOut
01407 ){
01408   PLReader left, right;
01409   PLWriter writer;
01410   int match = 0;
01411 
01412   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
01413   assert( pOut->iType!=DL_POSITIONS_OFFSETS );
01414 
01415   plrInit(&left, pLeft);
01416   plrInit(&right, pRight);
01417 
01418   while( !plrAtEnd(&left) && !plrAtEnd(&right) ){
01419     if( plrColumn(&left)<plrColumn(&right) ){
01420       plrStep(&left);
01421     }else if( plrColumn(&left)>plrColumn(&right) ){
01422       plrStep(&right);
01423     }else if( plrPosition(&left)>=plrPosition(&right) ){
01424       plrStep(&right);
01425     }else{
01426       if( (plrPosition(&right)-plrPosition(&left))<=(nNear+1) ){
01427         if( !match ){
01428           plwInit(&writer, pOut, dlrDocid(pLeft));
01429           match = 1;
01430         }
01431         if( !isSaveLeft ){
01432           plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0);
01433         }else{
01434           plwAdd(&writer, plrColumn(&left), plrPosition(&left), 0, 0);
01435         }
01436         plrStep(&right);
01437       }else{
01438         plrStep(&left);
01439       }
01440     }
01441   }
01442 
01443   if( match ){
01444     plwTerminate(&writer);
01445     plwDestroy(&writer);
01446   }
01447 
01448   plrDestroy(&left);
01449   plrDestroy(&right);
01450 }
01451 
01452 /*
01453 ** Compare the values pointed to by the PLReaders passed as arguments. 
01454 ** Return -1 if the value pointed to by pLeft is considered less than
01455 ** the value pointed to by pRight, +1 if it is considered greater
01456 ** than it, or 0 if it is equal. i.e.
01457 **
01458 **     (*pLeft - *pRight)
01459 **
01460 ** A PLReader that is in the EOF condition is considered greater than
01461 ** any other. If neither argument is in EOF state, the return value of
01462 ** plrColumn() is used. If the plrColumn() values are equal, the
01463 ** comparison is on the basis of plrPosition().
01464 */
01465 static int plrCompare(PLReader *pLeft, PLReader *pRight){
01466   assert(!plrAtEnd(pLeft) || !plrAtEnd(pRight));
01467 
01468   if( plrAtEnd(pRight) || plrAtEnd(pLeft) ){
01469     return (plrAtEnd(pRight) ? -1 : 1);
01470   }
01471   if( plrColumn(pLeft)!=plrColumn(pRight) ){
01472     return ((plrColumn(pLeft)<plrColumn(pRight)) ? -1 : 1);
01473   }
01474   if( plrPosition(pLeft)!=plrPosition(pRight) ){
01475     return ((plrPosition(pLeft)<plrPosition(pRight)) ? -1 : 1);
01476   }
01477   return 0;
01478 }
01479 
01480 /* We have two doclists with positions:  pLeft and pRight. Depending
01481 ** on the value of the nNear parameter, perform either a phrase
01482 ** intersection (if nNear==0) or a NEAR intersection (if nNear>0)
01483 ** and write the results into pOut.
01484 **
01485 ** A phrase intersection means that two documents only match
01486 ** if pLeft.iPos+1==pRight.iPos.
01487 **
01488 ** A NEAR intersection means that two documents only match if 
01489 ** (abs(pLeft.iPos-pRight.iPos)<nNear).
01490 **
01491 ** If a NEAR intersection is requested, then the nPhrase argument should
01492 ** be passed the number of tokens in the two operands to the NEAR operator
01493 ** combined. For example:
01494 **
01495 **       Query syntax               nPhrase
01496 **      ------------------------------------
01497 **       "A B C" NEAR "D E"         5
01498 **       A NEAR B                   2
01499 **
01500 ** iType controls the type of data written to pOut.  If iType is
01501 ** DL_POSITIONS, the positions are those from pRight.
01502 */
01503 static void docListPhraseMerge(
01504   const char *pLeft, int nLeft,
01505   const char *pRight, int nRight,
01506   int nNear,            /* 0 for a phrase merge, non-zero for a NEAR merge */
01507   int nPhrase,          /* Number of tokens in left+right operands to NEAR */
01508   DocListType iType,    /* Type of doclist to write to pOut */
01509   DataBuffer *pOut      /* Write the combined doclist here */
01510 ){
01511   DLReader left, right;
01512   DLWriter writer;
01513 
01514   if( nLeft==0 || nRight==0 ) return;
01515 
01516   assert( iType!=DL_POSITIONS_OFFSETS );
01517 
01518   dlrInit(&left, DL_POSITIONS, pLeft, nLeft);
01519   dlrInit(&right, DL_POSITIONS, pRight, nRight);
01520   dlwInit(&writer, iType, pOut);
01521 
01522   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
01523     if( dlrDocid(&left)<dlrDocid(&right) ){
01524       dlrStep(&left);
01525     }else if( dlrDocid(&right)<dlrDocid(&left) ){
01526       dlrStep(&right);
01527     }else{
01528       if( nNear==0 ){
01529         posListPhraseMerge(&left, &right, 0, 0, &writer);
01530       }else{
01531         /* This case occurs when two terms (simple terms or phrases) are
01532          * connected by a NEAR operator, span (nNear+1). i.e.
01533          *
01534          *     '"terrible company" NEAR widget'
01535          */
01536         DataBuffer one = {0, 0, 0};
01537         DataBuffer two = {0, 0, 0};
01538 
01539         DLWriter dlwriter2;
01540         DLReader dr1 = {0, 0, 0, 0, 0}; 
01541         DLReader dr2 = {0, 0, 0, 0, 0};
01542 
01543         dlwInit(&dlwriter2, iType, &one);
01544         posListPhraseMerge(&right, &left, nNear-3+nPhrase, 1, &dlwriter2);
01545         dlwInit(&dlwriter2, iType, &two);
01546         posListPhraseMerge(&left, &right, nNear-1, 0, &dlwriter2);
01547 
01548         if( one.nData) dlrInit(&dr1, iType, one.pData, one.nData);
01549         if( two.nData) dlrInit(&dr2, iType, two.pData, two.nData);
01550 
01551         if( !dlrAtEnd(&dr1) || !dlrAtEnd(&dr2) ){
01552           PLReader pr1 = {0};
01553           PLReader pr2 = {0};
01554 
01555           PLWriter plwriter;
01556           plwInit(&plwriter, &writer, dlrDocid(dlrAtEnd(&dr1)?&dr2:&dr1));
01557 
01558           if( one.nData ) plrInit(&pr1, &dr1);
01559           if( two.nData ) plrInit(&pr2, &dr2);
01560           while( !plrAtEnd(&pr1) || !plrAtEnd(&pr2) ){
01561             int iCompare = plrCompare(&pr1, &pr2);
01562             switch( iCompare ){
01563               case -1:
01564                 plwCopy(&plwriter, &pr1);
01565                 plrStep(&pr1);
01566                 break;
01567               case 1:
01568                 plwCopy(&plwriter, &pr2);
01569                 plrStep(&pr2);
01570                 break;
01571               case 0:
01572                 plwCopy(&plwriter, &pr1);
01573                 plrStep(&pr1);
01574                 plrStep(&pr2);
01575                 break;
01576             }
01577           }
01578           plwTerminate(&plwriter);
01579         }
01580         dataBufferDestroy(&one);
01581         dataBufferDestroy(&two);
01582       }
01583       dlrStep(&left);
01584       dlrStep(&right);
01585     }
01586   }
01587 
01588   dlrDestroy(&left);
01589   dlrDestroy(&right);
01590   dlwDestroy(&writer);
01591 }
01592 
01593 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
01594 ** Write the intersection of these two doclists into pOut as a
01595 ** DL_DOCIDS doclist.
01596 */
01597 static void docListAndMerge(
01598   const char *pLeft, int nLeft,
01599   const char *pRight, int nRight,
01600   DataBuffer *pOut      /* Write the combined doclist here */
01601 ){
01602   DLReader left, right;
01603   DLWriter writer;
01604 
01605   if( nLeft==0 || nRight==0 ) return;
01606 
01607   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
01608   dlrInit(&right, DL_DOCIDS, pRight, nRight);
01609   dlwInit(&writer, DL_DOCIDS, pOut);
01610 
01611   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
01612     if( dlrDocid(&left)<dlrDocid(&right) ){
01613       dlrStep(&left);
01614     }else if( dlrDocid(&right)<dlrDocid(&left) ){
01615       dlrStep(&right);
01616     }else{
01617       dlwAdd(&writer, dlrDocid(&left));
01618       dlrStep(&left);
01619       dlrStep(&right);
01620     }
01621   }
01622 
01623   dlrDestroy(&left);
01624   dlrDestroy(&right);
01625   dlwDestroy(&writer);
01626 }
01627 
01628 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
01629 ** Write the union of these two doclists into pOut as a
01630 ** DL_DOCIDS doclist.
01631 */
01632 static void docListOrMerge(
01633   const char *pLeft, int nLeft,
01634   const char *pRight, int nRight,
01635   DataBuffer *pOut      /* Write the combined doclist here */
01636 ){
01637   DLReader left, right;
01638   DLWriter writer;
01639 
01640   if( nLeft==0 ){
01641     if( nRight!=0 ) dataBufferAppend(pOut, pRight, nRight);
01642     return;
01643   }
01644   if( nRight==0 ){
01645     dataBufferAppend(pOut, pLeft, nLeft);
01646     return;
01647   }
01648 
01649   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
01650   dlrInit(&right, DL_DOCIDS, pRight, nRight);
01651   dlwInit(&writer, DL_DOCIDS, pOut);
01652 
01653   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
01654     if( dlrAtEnd(&right) ){
01655       dlwAdd(&writer, dlrDocid(&left));
01656       dlrStep(&left);
01657     }else if( dlrAtEnd(&left) ){
01658       dlwAdd(&writer, dlrDocid(&right));
01659       dlrStep(&right);
01660     }else if( dlrDocid(&left)<dlrDocid(&right) ){
01661       dlwAdd(&writer, dlrDocid(&left));
01662       dlrStep(&left);
01663     }else if( dlrDocid(&right)<dlrDocid(&left) ){
01664       dlwAdd(&writer, dlrDocid(&right));
01665       dlrStep(&right);
01666     }else{
01667       dlwAdd(&writer, dlrDocid(&left));
01668       dlrStep(&left);
01669       dlrStep(&right);
01670     }
01671   }
01672 
01673   dlrDestroy(&left);
01674   dlrDestroy(&right);
01675   dlwDestroy(&writer);
01676 }
01677 
01678 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
01679 ** Write into pOut as DL_DOCIDS doclist containing all documents that
01680 ** occur in pLeft but not in pRight.
01681 */
01682 static void docListExceptMerge(
01683   const char *pLeft, int nLeft,
01684   const char *pRight, int nRight,
01685   DataBuffer *pOut      /* Write the combined doclist here */
01686 ){
01687   DLReader left, right;
01688   DLWriter writer;
01689 
01690   if( nLeft==0 ) return;
01691   if( nRight==0 ){
01692     dataBufferAppend(pOut, pLeft, nLeft);
01693     return;
01694   }
01695 
01696   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
01697   dlrInit(&right, DL_DOCIDS, pRight, nRight);
01698   dlwInit(&writer, DL_DOCIDS, pOut);
01699 
01700   while( !dlrAtEnd(&left) ){
01701     while( !dlrAtEnd(&right) && dlrDocid(&right)<dlrDocid(&left) ){
01702       dlrStep(&right);
01703     }
01704     if( dlrAtEnd(&right) || dlrDocid(&left)<dlrDocid(&right) ){
01705       dlwAdd(&writer, dlrDocid(&left));
01706     }
01707     dlrStep(&left);
01708   }
01709 
01710   dlrDestroy(&left);
01711   dlrDestroy(&right);
01712   dlwDestroy(&writer);
01713 }
01714 
01715 static char *string_dup_n(const char *s, int n){
01716   char *str = sqlite3_malloc(n + 1);
01717   memcpy(str, s, n);
01718   str[n] = '\0';
01719   return str;
01720 }
01721 
01722 /* Duplicate a string; the caller must free() the returned string.
01723  * (We don't use strdup() since it is not part of the standard C library and
01724  * may not be available everywhere.) */
01725 static char *string_dup(const char *s){
01726   return string_dup_n(s, strlen(s));
01727 }
01728 
01729 /* Format a string, replacing each occurrence of the % character with
01730  * zDb.zName.  This may be more convenient than sqlite_mprintf()
01731  * when one string is used repeatedly in a format string.
01732  * The caller must free() the returned string. */
01733 static char *string_format(const char *zFormat,
01734                            const char *zDb, const char *zName){
01735   const char *p;
01736   size_t len = 0;
01737   size_t nDb = strlen(zDb);
01738   size_t nName = strlen(zName);
01739   size_t nFullTableName = nDb+1+nName;
01740   char *result;
01741   char *r;
01742 
01743   /* first compute length needed */
01744   for(p = zFormat ; *p ; ++p){
01745     len += (*p=='%' ? nFullTableName : 1);
01746   }
01747   len += 1;  /* for null terminator */
01748 
01749   r = result = sqlite3_malloc(len);
01750   for(p = zFormat; *p; ++p){
01751     if( *p=='%' ){
01752       memcpy(r, zDb, nDb);
01753       r += nDb;
01754       *r++ = '.';
01755       memcpy(r, zName, nName);
01756       r += nName;
01757     } else {
01758       *r++ = *p;
01759     }
01760   }
01761   *r++ = '\0';
01762   assert( r == result + len );
01763   return result;
01764 }
01765 
01766 static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
01767                     const char *zFormat){
01768   char *zCommand = string_format(zFormat, zDb, zName);
01769   int rc;
01770   FTSTRACE(("FTS3 sql: %s\n", zCommand));
01771   rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
01772   sqlite3_free(zCommand);
01773   return rc;
01774 }
01775 
01776 static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
01777                        sqlite3_stmt **ppStmt, const char *zFormat){
01778   char *zCommand = string_format(zFormat, zDb, zName);
01779   int rc;
01780   FTSTRACE(("FTS3 prepare: %s\n", zCommand));
01781   rc = sqlite3_prepare_v2(db, zCommand, -1, ppStmt, NULL);
01782   sqlite3_free(zCommand);
01783   return rc;
01784 }
01785 
01786 /* end utility functions */
01787 
01788 /* Forward reference */
01789 typedef struct fulltext_vtab fulltext_vtab;
01790 
01791 /* A single term in a query is represented by an instances of
01792 ** the following structure. Each word which may match against
01793 ** document content is a term. Operators, like NEAR or OR, are
01794 ** not terms. Query terms are organized as a flat list stored
01795 ** in the Query.pTerms array.
01796 **
01797 ** If the QueryTerm.nPhrase variable is non-zero, then the QueryTerm
01798 ** is the first in a contiguous string of terms that are either part
01799 ** of the same phrase, or connected by the NEAR operator.
01800 **
01801 ** If the QueryTerm.nNear variable is non-zero, then the token is followed 
01802 ** by a NEAR operator with span set to (nNear-1). For example, the 
01803 ** following query:
01804 **
01805 ** The QueryTerm.iPhrase variable stores the index of the token within
01806 ** its phrase, indexed starting at 1, or 1 if the token is not part 
01807 ** of any phrase.
01808 **
01809 ** For example, the data structure used to represent the following query:
01810 **
01811 **     ... MATCH 'sqlite NEAR/5 google NEAR/2 "search engine"'
01812 **
01813 ** is:
01814 **
01815 **     {nPhrase=4, iPhrase=1, nNear=6, pTerm="sqlite"},
01816 **     {nPhrase=0, iPhrase=1, nNear=3, pTerm="google"},
01817 **     {nPhrase=0, iPhrase=1, nNear=0, pTerm="search"},
01818 **     {nPhrase=0, iPhrase=2, nNear=0, pTerm="engine"},
01819 **
01820 ** compiling the FTS3 syntax to Query structures is done by the parseQuery()
01821 ** function.
01822 */
01823 typedef struct QueryTerm {
01824   short int nPhrase; /* How many following terms are part of the same phrase */
01825   short int iPhrase; /* This is the i-th term of a phrase. */
01826   short int iColumn; /* Column of the index that must match this term */
01827   short int nNear;   /* term followed by a NEAR operator with span=(nNear-1) */
01828   signed char isOr;  /* this term is preceded by "OR" */
01829   signed char isNot; /* this term is preceded by "-" */
01830   signed char isPrefix; /* this term is followed by "*" */
01831   char *pTerm;       /* text of the term.  '\000' terminated.  malloced */
01832   int nTerm;         /* Number of bytes in pTerm[] */
01833 } QueryTerm;
01834 
01835 
01836 /* A query string is parsed into a Query structure.
01837  *
01838  * We could, in theory, allow query strings to be complicated
01839  * nested expressions with precedence determined by parentheses.
01840  * But none of the major search engines do this.  (Perhaps the
01841  * feeling is that an parenthesized expression is two complex of
01842  * an idea for the average user to grasp.)  Taking our lead from
01843  * the major search engines, we will allow queries to be a list
01844  * of terms (with an implied AND operator) or phrases in double-quotes,
01845  * with a single optional "-" before each non-phrase term to designate
01846  * negation and an optional OR connector.
01847  *
01848  * OR binds more tightly than the implied AND, which is what the
01849  * major search engines seem to do.  So, for example:
01850  * 
01851  *    [one two OR three]     ==>    one AND (two OR three)
01852  *    [one OR two three]     ==>    (one OR two) AND three
01853  *
01854  * A "-" before a term matches all entries that lack that term.
01855  * The "-" must occur immediately before the term with in intervening
01856  * space.  This is how the search engines do it.
01857  *
01858  * A NOT term cannot be the right-hand operand of an OR.  If this
01859  * occurs in the query string, the NOT is ignored:
01860  *
01861  *    [one OR -two]          ==>    one OR two
01862  *
01863  */
01864 typedef struct Query {
01865   fulltext_vtab *pFts;  /* The full text index */
01866   int nTerms;           /* Number of terms in the query */
01867   QueryTerm *pTerms;    /* Array of terms.  Space obtained from malloc() */
01868   int nextIsOr;         /* Set the isOr flag on the next inserted term */
01869   int nextIsNear;       /* Set the isOr flag on the next inserted term */
01870   int nextColumn;       /* Next word parsed must be in this column */
01871   int dfltColumn;       /* The default column */
01872 } Query;
01873 
01874 
01875 /*
01876 ** An instance of the following structure keeps track of generated
01877 ** matching-word offset information and snippets.
01878 */
01879 typedef struct Snippet {
01880   int nMatch;     /* Total number of matches */
01881   int nAlloc;     /* Space allocated for aMatch[] */
01882   struct snippetMatch { /* One entry for each matching term */
01883     char snStatus;       /* Status flag for use while constructing snippets */
01884     short int iCol;      /* The column that contains the match */
01885     short int iTerm;     /* The index in Query.pTerms[] of the matching term */
01886     int iToken;          /* The index of the matching document token */
01887     short int nByte;     /* Number of bytes in the term */
01888     int iStart;          /* The offset to the first character of the term */
01889   } *aMatch;      /* Points to space obtained from malloc */
01890   char *zOffset;  /* Text rendering of aMatch[] */
01891   int nOffset;    /* strlen(zOffset) */
01892   char *zSnippet; /* Snippet text */
01893   int nSnippet;   /* strlen(zSnippet) */
01894 } Snippet;
01895 
01896 
01897 typedef enum QueryType {
01898   QUERY_GENERIC,   /* table scan */
01899   QUERY_DOCID,     /* lookup by docid */
01900   QUERY_FULLTEXT   /* QUERY_FULLTEXT + [i] is a full-text search for column i*/
01901 } QueryType;
01902 
01903 typedef enum fulltext_statement {
01904   CONTENT_INSERT_STMT,
01905   CONTENT_SELECT_STMT,
01906   CONTENT_UPDATE_STMT,
01907   CONTENT_DELETE_STMT,
01908   CONTENT_EXISTS_STMT,
01909 
01910   BLOCK_INSERT_STMT,
01911   BLOCK_SELECT_STMT,
01912   BLOCK_DELETE_STMT,
01913   BLOCK_DELETE_ALL_STMT,
01914 
01915   SEGDIR_MAX_INDEX_STMT,
01916   SEGDIR_SET_STMT,
01917   SEGDIR_SELECT_LEVEL_STMT,
01918   SEGDIR_SPAN_STMT,
01919   SEGDIR_DELETE_STMT,
01920   SEGDIR_SELECT_SEGMENT_STMT,
01921   SEGDIR_SELECT_ALL_STMT,
01922   SEGDIR_DELETE_ALL_STMT,
01923   SEGDIR_COUNT_STMT,
01924 
01925   MAX_STMT                     /* Always at end! */
01926 } fulltext_statement;
01927 
01928 /* These must exactly match the enum above. */
01929 /* TODO(shess): Is there some risk that a statement will be used in two
01930 ** cursors at once, e.g.  if a query joins a virtual table to itself?
01931 ** If so perhaps we should move some of these to the cursor object.
01932 */
01933 static const char *const fulltext_zStatement[MAX_STMT] = {
01934   /* CONTENT_INSERT */ NULL,  /* generated in contentInsertStatement() */
01935   /* CONTENT_SELECT */ NULL,  /* generated in contentSelectStatement() */
01936   /* CONTENT_UPDATE */ NULL,  /* generated in contentUpdateStatement() */
01937   /* CONTENT_DELETE */ "delete from %_content where docid = ?",
01938   /* CONTENT_EXISTS */ "select docid from %_content limit 1",
01939 
01940   /* BLOCK_INSERT */
01941   "insert into %_segments (blockid, block) values (null, ?)",
01942   /* BLOCK_SELECT */ "select block from %_segments where blockid = ?",
01943   /* BLOCK_DELETE */ "delete from %_segments where blockid between ? and ?",
01944   /* BLOCK_DELETE_ALL */ "delete from %_segments",
01945 
01946   /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?",
01947   /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)",
01948   /* SEGDIR_SELECT_LEVEL */
01949   "select start_block, leaves_end_block, root from %_segdir "
01950   " where level = ? order by idx",
01951   /* SEGDIR_SPAN */
01952   "select min(start_block), max(end_block) from %_segdir "
01953   " where level = ? and start_block <> 0",
01954   /* SEGDIR_DELETE */ "delete from %_segdir where level = ?",
01955 
01956   /* NOTE(shess): The first three results of the following two
01957   ** statements must match.
01958   */
01959   /* SEGDIR_SELECT_SEGMENT */
01960   "select start_block, leaves_end_block, root from %_segdir "
01961   " where level = ? and idx = ?",
01962   /* SEGDIR_SELECT_ALL */
01963   "select start_block, leaves_end_block, root from %_segdir "
01964   " order by level desc, idx asc",
01965   /* SEGDIR_DELETE_ALL */ "delete from %_segdir",
01966   /* SEGDIR_COUNT */ "select count(*), ifnull(max(level),0) from %_segdir",
01967 };
01968 
01969 /*
01970 ** A connection to a fulltext index is an instance of the following
01971 ** structure.  The xCreate and xConnect methods create an instance
01972 ** of this structure and xDestroy and xDisconnect free that instance.
01973 ** All other methods receive a pointer to the structure as one of their
01974 ** arguments.
01975 */
01976 struct fulltext_vtab {
01977   sqlite3_vtab base;               /* Base class used by SQLite core */
01978   sqlite3 *db;                     /* The database connection */
01979   const char *zDb;                 /* logical database name */
01980   const char *zName;               /* virtual table name */
01981   int nColumn;                     /* number of columns in virtual table */
01982   char **azColumn;                 /* column names.  malloced */
01983   char **azContentColumn;          /* column names in content table; malloced */
01984   sqlite3_tokenizer *pTokenizer;   /* tokenizer for inserts and queries */
01985 
01986   /* Precompiled statements which we keep as long as the table is
01987   ** open.
01988   */
01989   sqlite3_stmt *pFulltextStatements[MAX_STMT];
01990 
01991   /* Precompiled statements used for segment merges.  We run a
01992   ** separate select across the leaf level of each tree being merged.
01993   */
01994   sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT];
01995   /* The statement used to prepare pLeafSelectStmts. */
01996 #define LEAF_SELECT \
01997   "select block from %_segments where blockid between ? and ? order by blockid"
01998 
01999   /* These buffer pending index updates during transactions.
02000   ** nPendingData estimates the memory size of the pending data.  It
02001   ** doesn't include the hash-bucket overhead, nor any malloc
02002   ** overhead.  When nPendingData exceeds kPendingThreshold, the
02003   ** buffer is flushed even before the transaction closes.
02004   ** pendingTerms stores the data, and is only valid when nPendingData
02005   ** is >=0 (nPendingData<0 means pendingTerms has not been
02006   ** initialized).  iPrevDocid is the last docid written, used to make
02007   ** certain we're inserting in sorted order.
02008   */
02009   int nPendingData;
02010 #define kPendingThreshold (1*1024*1024)
02011   sqlite_int64 iPrevDocid;
02012   fts3Hash pendingTerms;
02013 };
02014 
02015 /*
02016 ** When the core wants to do a query, it create a cursor using a
02017 ** call to xOpen.  This structure is an instance of a cursor.  It
02018 ** is destroyed by xClose.
02019 */
02020 typedef struct fulltext_cursor {
02021   sqlite3_vtab_cursor base;        /* Base class used by SQLite core */
02022   QueryType iCursorType;           /* Copy of sqlite3_index_info.idxNum */
02023   sqlite3_stmt *pStmt;             /* Prepared statement in use by the cursor */
02024   int eof;                         /* True if at End Of Results */
02025   Query q;                         /* Parsed query string */
02026   Snippet snippet;                 /* Cached snippet for the current row */
02027   int iColumn;                     /* Column being searched */
02028   DataBuffer result;               /* Doclist results from fulltextQuery */
02029   DLReader reader;                 /* Result reader if result not empty */
02030 } fulltext_cursor;
02031 
02032 static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){
02033   return (fulltext_vtab *) c->base.pVtab;
02034 }
02035 
02036 static const sqlite3_module fts3Module;   /* forward declaration */
02037 
02038 /* Return a dynamically generated statement of the form
02039  *   insert into %_content (docid, ...) values (?, ...)
02040  */
02041 static const char *contentInsertStatement(fulltext_vtab *v){
02042   StringBuffer sb;
02043   int i;
02044 
02045   initStringBuffer(&sb);
02046   append(&sb, "insert into %_content (docid, ");
02047   appendList(&sb, v->nColumn, v->azContentColumn);
02048   append(&sb, ") values (?");
02049   for(i=0; i<v->nColumn; ++i)
02050     append(&sb, ", ?");
02051   append(&sb, ")");
02052   return stringBufferData(&sb);
02053 }
02054 
02055 /* Return a dynamically generated statement of the form
02056  *   select <content columns> from %_content where docid = ?
02057  */
02058 static const char *contentSelectStatement(fulltext_vtab *v){
02059   StringBuffer sb;
02060   initStringBuffer(&sb);
02061   append(&sb, "SELECT ");
02062   appendList(&sb, v->nColumn, v->azContentColumn);
02063   append(&sb, " FROM %_content WHERE docid = ?");
02064   return stringBufferData(&sb);
02065 }
02066 
02067 /* Return a dynamically generated statement of the form
02068  *   update %_content set [col_0] = ?, [col_1] = ?, ...
02069  *                    where docid = ?
02070  */
02071 static const char *contentUpdateStatement(fulltext_vtab *v){
02072   StringBuffer sb;
02073   int i;
02074 
02075   initStringBuffer(&sb);
02076   append(&sb, "update %_content set ");
02077   for(i=0; i<v->nColumn; ++i) {
02078     if( i>0 ){
02079       append(&sb, ", ");
02080     }
02081     append(&sb, v->azContentColumn[i]);
02082     append(&sb, " = ?");
02083   }
02084   append(&sb, " where docid = ?");
02085   return stringBufferData(&sb);
02086 }
02087 
02088 /* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
02089 ** If the indicated statement has never been prepared, it is prepared
02090 ** and cached, otherwise the cached version is reset.
02091 */
02092 static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
02093                              sqlite3_stmt **ppStmt){
02094   assert( iStmt<MAX_STMT );
02095   if( v->pFulltextStatements[iStmt]==NULL ){
02096     const char *zStmt;
02097     int rc;
02098     switch( iStmt ){
02099       case CONTENT_INSERT_STMT:
02100         zStmt = contentInsertStatement(v); break;
02101       case CONTENT_SELECT_STMT:
02102         zStmt = contentSelectStatement(v); break;
02103       case CONTENT_UPDATE_STMT:
02104         zStmt = contentUpdateStatement(v); break;
02105       default:
02106         zStmt = fulltext_zStatement[iStmt];
02107     }
02108     rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
02109                          zStmt);
02110     if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt);
02111     if( rc!=SQLITE_OK ) return rc;
02112   } else {
02113     int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
02114     if( rc!=SQLITE_OK ) return rc;
02115   }
02116 
02117   *ppStmt = v->pFulltextStatements[iStmt];
02118   return SQLITE_OK;
02119 }
02120 
02121 /* Like sqlite3_step(), but convert SQLITE_DONE to SQLITE_OK and
02122 ** SQLITE_ROW to SQLITE_ERROR.  Useful for statements like UPDATE,
02123 ** where we expect no results.
02124 */
02125 static int sql_single_step(sqlite3_stmt *s){
02126   int rc = sqlite3_step(s);
02127   return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
02128 }
02129 
02130 /* Like sql_get_statement(), but for special replicated LEAF_SELECT
02131 ** statements.  idx -1 is a special case for an uncached version of
02132 ** the statement (used in the optimize implementation).
02133 */
02134 /* TODO(shess) Write version for generic statements and then share
02135 ** that between the cached-statement functions.
02136 */
02137 static int sql_get_leaf_statement(fulltext_vtab *v, int idx,
02138                                   sqlite3_stmt **ppStmt){
02139   assert( idx>=-1 && idx<MERGE_COUNT );
02140   if( idx==-1 ){
02141     return sql_prepare(v->db, v->zDb, v->zName, ppStmt, LEAF_SELECT);
02142   }else if( v->pLeafSelectStmts[idx]==NULL ){
02143     int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx],
02144                          LEAF_SELECT);
02145     if( rc!=SQLITE_OK ) return rc;
02146   }else{
02147     int rc = sqlite3_reset(v->pLeafSelectStmts[idx]);
02148     if( rc!=SQLITE_OK ) return rc;
02149   }
02150 
02151   *ppStmt = v->pLeafSelectStmts[idx];
02152   return SQLITE_OK;
02153 }
02154 
02155 /* insert into %_content (docid, ...) values ([docid], [pValues])
02156 ** If the docid contains SQL NULL, then a unique docid will be
02157 ** generated.
02158 */
02159 static int content_insert(fulltext_vtab *v, sqlite3_value *docid,
02160                           sqlite3_value **pValues){
02161   sqlite3_stmt *s;
02162   int i;
02163   int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
02164   if( rc!=SQLITE_OK ) return rc;
02165 
02166   rc = sqlite3_bind_value(s, 1, docid);
02167   if( rc!=SQLITE_OK ) return rc;
02168 
02169   for(i=0; i<v->nColumn; ++i){
02170     rc = sqlite3_bind_value(s, 2+i, pValues[i]);
02171     if( rc!=SQLITE_OK ) return rc;
02172   }
02173 
02174   return sql_single_step(s);
02175 }
02176 
02177 /* update %_content set col0 = pValues[0], col1 = pValues[1], ...
02178  *                  where docid = [iDocid] */
02179 static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
02180                           sqlite_int64 iDocid){
02181   sqlite3_stmt *s;
02182   int i;
02183   int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
02184   if( rc!=SQLITE_OK ) return rc;
02185 
02186   for(i=0; i<v->nColumn; ++i){
02187     rc = sqlite3_bind_value(s, 1+i, pValues[i]);
02188     if( rc!=SQLITE_OK ) return rc;
02189   }
02190 
02191   rc = sqlite3_bind_int64(s, 1+v->nColumn, iDocid);
02192   if( rc!=SQLITE_OK ) return rc;
02193 
02194   return sql_single_step(s);
02195 }
02196 
02197 static void freeStringArray(int nString, const char **pString){
02198   int i;
02199 
02200   for (i=0 ; i < nString ; ++i) {
02201     if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]);
02202   }
02203   sqlite3_free((void *) pString);
02204 }
02205 
02206 /* select * from %_content where docid = [iDocid]
02207  * The caller must delete the returned array and all strings in it.
02208  * null fields will be NULL in the returned array.
02209  *
02210  * TODO: Perhaps we should return pointer/length strings here for consistency
02211  * with other code which uses pointer/length. */
02212 static int content_select(fulltext_vtab *v, sqlite_int64 iDocid,
02213                           const char ***pValues){
02214   sqlite3_stmt *s;
02215   const char **values;
02216   int i;
02217   int rc;
02218 
02219   *pValues = NULL;
02220 
02221   rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
02222   if( rc!=SQLITE_OK ) return rc;
02223 
02224   rc = sqlite3_bind_int64(s, 1, iDocid);
02225   if( rc!=SQLITE_OK ) return rc;
02226 
02227   rc = sqlite3_step(s);
02228   if( rc!=SQLITE_ROW ) return rc;
02229 
02230   values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *));
02231   for(i=0; i<v->nColumn; ++i){
02232     if( sqlite3_column_type(s, i)==SQLITE_NULL ){
02233       values[i] = NULL;
02234     }else{
02235       values[i] = string_dup((char*)sqlite3_column_text(s, i));
02236     }
02237   }
02238 
02239   /* We expect only one row.  We must execute another sqlite3_step()
02240    * to complete the iteration; otherwise the table will remain locked. */
02241   rc = sqlite3_step(s);
02242   if( rc==SQLITE_DONE ){
02243     *pValues = values;
02244     return SQLITE_OK;
02245   }
02246 
02247   freeStringArray(v->nColumn, values);
02248   return rc;
02249 }
02250 
02251 /* delete from %_content where docid = [iDocid ] */
02252 static int content_delete(fulltext_vtab *v, sqlite_int64 iDocid){
02253   sqlite3_stmt *s;
02254   int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
02255   if( rc!=SQLITE_OK ) return rc;
02256 
02257   rc = sqlite3_bind_int64(s, 1, iDocid);
02258   if( rc!=SQLITE_OK ) return rc;
02259 
02260   return sql_single_step(s);
02261 }
02262 
02263 /* Returns SQLITE_ROW if any rows exist in %_content, SQLITE_DONE if
02264 ** no rows exist, and any error in case of failure.
02265 */
02266 static int content_exists(fulltext_vtab *v){
02267   sqlite3_stmt *s;
02268   int rc = sql_get_statement(v, CONTENT_EXISTS_STMT, &s);
02269   if( rc!=SQLITE_OK ) return rc;
02270 
02271   rc = sqlite3_step(s);
02272   if( rc!=SQLITE_ROW ) return rc;
02273 
02274   /* We expect only one row.  We must execute another sqlite3_step()
02275    * to complete the iteration; otherwise the table will remain locked. */
02276   rc = sqlite3_step(s);
02277   if( rc==SQLITE_DONE ) return SQLITE_ROW;
02278   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
02279   return rc;
02280 }
02281 
02282 /* insert into %_segments values ([pData])
02283 **   returns assigned blockid in *piBlockid
02284 */
02285 static int block_insert(fulltext_vtab *v, const char *pData, int nData,
02286                         sqlite_int64 *piBlockid){
02287   sqlite3_stmt *s;
02288   int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s);
02289   if( rc!=SQLITE_OK ) return rc;
02290 
02291   rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC);
02292   if( rc!=SQLITE_OK ) return rc;
02293 
02294   rc = sqlite3_step(s);
02295   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
02296   if( rc!=SQLITE_DONE ) return rc;
02297 
02298   /* blockid column is an alias for rowid. */
02299   *piBlockid = sqlite3_last_insert_rowid(v->db);
02300   return SQLITE_OK;
02301 }
02302 
02303 /* delete from %_segments
02304 **   where blockid between [iStartBlockid] and [iEndBlockid]
02305 **
02306 ** Deletes the range of blocks, inclusive, used to delete the blocks
02307 ** which form a segment.
02308 */
02309 static int block_delete(fulltext_vtab *v,
02310                         sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){
02311   sqlite3_stmt *s;
02312   int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s);
02313   if( rc!=SQLITE_OK ) return rc;
02314 
02315   rc = sqlite3_bind_int64(s, 1, iStartBlockid);
02316   if( rc!=SQLITE_OK ) return rc;
02317 
02318   rc = sqlite3_bind_int64(s, 2, iEndBlockid);
02319   if( rc!=SQLITE_OK ) return rc;
02320 
02321   return sql_single_step(s);
02322 }
02323 
02324 /* Returns SQLITE_ROW with *pidx set to the maximum segment idx found
02325 ** at iLevel.  Returns SQLITE_DONE if there are no segments at
02326 ** iLevel.  Otherwise returns an error.
02327 */
02328 static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){
02329   sqlite3_stmt *s;
02330   int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s);
02331   if( rc!=SQLITE_OK ) return rc;
02332 
02333   rc = sqlite3_bind_int(s, 1, iLevel);
02334   if( rc!=SQLITE_OK ) return rc;
02335 
02336   rc = sqlite3_step(s);
02337   /* Should always get at least one row due to how max() works. */
02338   if( rc==SQLITE_DONE ) return SQLITE_DONE;
02339   if( rc!=SQLITE_ROW ) return rc;
02340 
02341   /* NULL means that there were no inputs to max(). */
02342   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
02343     rc = sqlite3_step(s);
02344     if( rc==SQLITE_ROW ) return SQLITE_ERROR;
02345     return rc;
02346   }
02347 
02348   *pidx = sqlite3_column_int(s, 0);
02349 
02350   /* We expect only one row.  We must execute another sqlite3_step()
02351    * to complete the iteration; otherwise the table will remain locked. */
02352   rc = sqlite3_step(s);
02353   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
02354   if( rc!=SQLITE_DONE ) return rc;
02355   return SQLITE_ROW;
02356 }
02357 
02358 /* insert into %_segdir values (
02359 **   [iLevel], [idx],
02360 **   [iStartBlockid], [iLeavesEndBlockid], [iEndBlockid],
02361 **   [pRootData]
02362 ** )
02363 */
02364 static int segdir_set(fulltext_vtab *v, int iLevel, int idx,
02365                       sqlite_int64 iStartBlockid,
02366                       sqlite_int64 iLeavesEndBlockid,
02367                       sqlite_int64 iEndBlockid,
02368                       const char *pRootData, int nRootData){
02369   sqlite3_stmt *s;
02370   int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s);
02371   if( rc!=SQLITE_OK ) return rc;
02372 
02373   rc = sqlite3_bind_int(s, 1, iLevel);
02374   if( rc!=SQLITE_OK ) return rc;
02375 
02376   rc = sqlite3_bind_int(s, 2, idx);
02377   if( rc!=SQLITE_OK ) return rc;
02378 
02379   rc = sqlite3_bind_int64(s, 3, iStartBlockid);
02380   if( rc!=SQLITE_OK ) return rc;
02381 
02382   rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid);
02383   if( rc!=SQLITE_OK ) return rc;
02384 
02385   rc = sqlite3_bind_int64(s, 5, iEndBlockid);
02386   if( rc!=SQLITE_OK ) return rc;
02387 
02388   rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC);
02389   if( rc!=SQLITE_OK ) return rc;
02390 
02391   return sql_single_step(s);
02392 }
02393 
02394 /* Queries %_segdir for the block span of the segments in level
02395 ** iLevel.  Returns SQLITE_DONE if there are no blocks for iLevel,
02396 ** SQLITE_ROW if there are blocks, else an error.
02397 */
02398 static int segdir_span(fulltext_vtab *v, int iLevel,
02399                        sqlite_int64 *piStartBlockid,
02400                        sqlite_int64 *piEndBlockid){
02401   sqlite3_stmt *s;
02402   int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s);
02403   if( rc!=SQLITE_OK ) return rc;
02404 
02405   rc = sqlite3_bind_int(s, 1, iLevel);
02406   if( rc!=SQLITE_OK ) return rc;
02407 
02408   rc = sqlite3_step(s);
02409   if( rc==SQLITE_DONE ) return SQLITE_DONE;  /* Should never happen */
02410   if( rc!=SQLITE_ROW ) return rc;
02411 
02412   /* This happens if all segments at this level are entirely inline. */
02413   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
02414     /* We expect only one row.  We must execute another sqlite3_step()
02415      * to complete the iteration; otherwise the table will remain locked. */
02416     int rc2 = sqlite3_step(s);
02417     if( rc2==SQLITE_ROW ) return SQLITE_ERROR;
02418     return rc2;
02419   }
02420 
02421   *piStartBlockid = sqlite3_column_int64(s, 0);
02422   *piEndBlockid = sqlite3_column_int64(s, 1);
02423 
02424   /* We expect only one row.  We must execute another sqlite3_step()
02425    * to complete the iteration; otherwise the table will remain locked. */
02426   rc = sqlite3_step(s);
02427   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
02428   if( rc!=SQLITE_DONE ) return rc;
02429   return SQLITE_ROW;
02430 }
02431 
02432 /* Delete the segment blocks and segment directory records for all
02433 ** segments at iLevel.
02434 */
02435 static int segdir_delete(fulltext_vtab *v, int iLevel){
02436   sqlite3_stmt *s;
02437   sqlite_int64 iStartBlockid, iEndBlockid;
02438   int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid);
02439   if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;
02440 
02441   if( rc==SQLITE_ROW ){
02442     rc = block_delete(v, iStartBlockid, iEndBlockid);
02443     if( rc!=SQLITE_OK ) return rc;
02444   }
02445 
02446   /* Delete the segment directory itself. */
02447   rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s);
02448   if( rc!=SQLITE_OK ) return rc;
02449 
02450   rc = sqlite3_bind_int64(s, 1, iLevel);
02451   if( rc!=SQLITE_OK ) return rc;
02452 
02453   return sql_single_step(s);
02454 }
02455 
02456 /* Delete entire fts index, SQLITE_OK on success, relevant error on
02457 ** failure.
02458 */
02459 static int segdir_delete_all(fulltext_vtab *v){
02460   sqlite3_stmt *s;
02461   int rc = sql_get_statement(v, SEGDIR_DELETE_ALL_STMT, &s);
02462   if( rc!=SQLITE_OK ) return rc;
02463 
02464   rc = sql_single_step(s);
02465   if( rc!=SQLITE_OK ) return rc;
02466 
02467   rc = sql_get_statement(v, BLOCK_DELETE_ALL_STMT, &s);
02468   if( rc!=SQLITE_OK ) return rc;
02469 
02470   return sql_single_step(s);
02471 }
02472 
02473 /* Returns SQLITE_OK with *pnSegments set to the number of entries in
02474 ** %_segdir and *piMaxLevel set to the highest level which has a
02475 ** segment.  Otherwise returns the SQLite error which caused failure.
02476 */
02477 static int segdir_count(fulltext_vtab *v, int *pnSegments, int *piMaxLevel){
02478   sqlite3_stmt *s;
02479   int rc = sql_get_statement(v, SEGDIR_COUNT_STMT, &s);
02480   if( rc!=SQLITE_OK ) return rc;
02481 
02482   rc = sqlite3_step(s);
02483   /* TODO(shess): This case should not be possible?  Should stronger
02484   ** measures be taken if it happens?
02485   */
02486   if( rc==SQLITE_DONE ){
02487     *pnSegments = 0;
02488     *piMaxLevel = 0;
02489     return SQLITE_OK;
02490   }
02491   if( rc!=SQLITE_ROW ) return rc;
02492 
02493   *pnSegments = sqlite3_column_int(s, 0);
02494   *piMaxLevel = sqlite3_column_int(s, 1);
02495 
02496   /* We expect only one row.  We must execute another sqlite3_step()
02497    * to complete the iteration; otherwise the table will remain locked. */
02498   rc = sqlite3_step(s);
02499   if( rc==SQLITE_DONE ) return SQLITE_OK;
02500   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
02501   return rc;
02502 }
02503 
02504 /* TODO(shess) clearPendingTerms() is far down the file because
02505 ** writeZeroSegment() is far down the file because LeafWriter is far
02506 ** down the file.  Consider refactoring the code to move the non-vtab
02507 ** code above the vtab code so that we don't need this forward
02508 ** reference.
02509 */
02510 static int clearPendingTerms(fulltext_vtab *v);
02511 
02512 /*
02513 ** Free the memory used to contain a fulltext_vtab structure.
02514 */
02515 static void fulltext_vtab_destroy(fulltext_vtab *v){
02516   int iStmt, i;
02517 
02518   FTSTRACE(("FTS3 Destroy %p\n", v));
02519   for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
02520     if( v->pFulltextStatements[iStmt]!=NULL ){
02521       sqlite3_finalize(v->pFulltextStatements[iStmt]);
02522       v->pFulltextStatements[iStmt] = NULL;
02523     }
02524   }
02525 
02526   for( i=0; i<MERGE_COUNT; i++ ){
02527     if( v->pLeafSelectStmts[i]!=NULL ){
02528       sqlite3_finalize(v->pLeafSelectStmts[i]);
02529       v->pLeafSelectStmts[i] = NULL;
02530     }
02531   }
02532 
02533   if( v->pTokenizer!=NULL ){
02534     v->pTokenizer->pModule->xDestroy(v->pTokenizer);
02535     v->pTokenizer = NULL;
02536   }
02537 
02538   clearPendingTerms(v);
02539 
02540   sqlite3_free(v->azColumn);
02541   for(i = 0; i < v->nColumn; ++i) {
02542     sqlite3_free(v->azContentColumn[i]);
02543   }
02544   sqlite3_free(v->azContentColumn);
02545   sqlite3_free(v);
02546 }
02547 
02548 /*
02549 ** Token types for parsing the arguments to xConnect or xCreate.
02550 */
02551 #define TOKEN_EOF         0    /* End of file */
02552 #define TOKEN_SPACE       1    /* Any kind of whitespace */
02553 #define TOKEN_ID          2    /* An identifier */
02554 #define TOKEN_STRING      3    /* A string literal */
02555 #define TOKEN_PUNCT       4    /* A single punctuation character */
02556 
02557 /*
02558 ** If X is a character that can be used in an identifier then
02559 ** ftsIdChar(X) will be true.  Otherwise it is false.
02560 **
02561 ** For ASCII, any character with the high-order bit set is
02562 ** allowed in an identifier.  For 7-bit characters, 
02563 ** isFtsIdChar[X] must be 1.
02564 **
02565 ** Ticket #1066.  the SQL standard does not allow '$' in the
02566 ** middle of identfiers.  But many SQL implementations do. 
02567 ** SQLite will allow '$' in identifiers for compatibility.
02568 ** But the feature is undocumented.
02569 */
02570 static const char isFtsIdChar[] = {
02571 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
02572     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
02573     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
02574     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
02575     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
02576     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
02577     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
02578 };
02579 #define ftsIdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && isFtsIdChar[c-0x20]))
02580 
02581 
02582 /*
02583 ** Return the length of the token that begins at z[0]. 
02584 ** Store the token type in *tokenType before returning.
02585 */
02586 static int ftsGetToken(const char *z, int *tokenType){
02587   int i, c;
02588   switch( *z ){
02589     case 0: {
02590       *tokenType = TOKEN_EOF;
02591       return 0;
02592     }
02593     case ' ': case '\t': case '\n': case '\f': case '\r': {
02594       for(i=1; safe_isspace(z[i]); i++){}
02595       *tokenType = TOKEN_SPACE;
02596       return i;
02597     }
02598     case '`':
02599     case '\'':
02600     case '"': {
02601       int delim = z[0];
02602       for(i=1; (c=z[i])!=0; i++){
02603         if( c==delim ){
02604           if( z[i+1]==delim ){
02605             i++;
02606           }else{
02607             break;
02608           }
02609         }
02610       }
02611       *tokenType = TOKEN_STRING;
02612       return i + (c!=0);
02613     }
02614     case '[': {
02615       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
02616       *tokenType = TOKEN_ID;
02617       return i;
02618     }
02619     default: {
02620       if( !ftsIdChar(*z) ){
02621         break;
02622       }
02623       for(i=1; ftsIdChar(z[i]); i++){}
02624       *tokenType = TOKEN_ID;
02625       return i;
02626     }
02627   }
02628   *tokenType = TOKEN_PUNCT;
02629   return 1;
02630 }
02631 
02632 /*
02633 ** A token extracted from a string is an instance of the following
02634 ** structure.
02635 */
02636 typedef struct FtsToken {
02637   const char *z;       /* Pointer to token text.  Not '\000' terminated */
02638   short int n;         /* Length of the token text in bytes. */
02639 } FtsToken;
02640 
02641 /*
02642 ** Given a input string (which is really one of the argv[] parameters
02643 ** passed into xConnect or xCreate) split the string up into tokens.
02644 ** Return an array of pointers to '\000' terminated strings, one string
02645 ** for each non-whitespace token.
02646 **
02647 ** The returned array is terminated by a single NULL pointer.
02648 **
02649 ** Space to hold the returned array is obtained from a single
02650 ** malloc and should be freed by passing the return value to free().
02651 ** The individual strings within the token list are all a part of
02652 ** the single memory allocation and will all be freed at once.
02653 */
02654 static char **tokenizeString(const char *z, int *pnToken){
02655   int nToken = 0;
02656   FtsToken *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) );
02657   int n = 1;
02658   int e, i;
02659   int totalSize = 0;
02660   char **azToken;
02661   char *zCopy;
02662   while( n>0 ){
02663     n = ftsGetToken(z, &e);
02664     if( e!=TOKEN_SPACE ){
02665       aToken[nToken].z = z;
02666       aToken[nToken].n = n;
02667       nToken++;
02668       totalSize += n+1;
02669     }
02670     z += n;
02671   }
02672   azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize );
02673   zCopy = (char*)&azToken[nToken];
02674   nToken--;
02675   for(i=0; i<nToken; i++){
02676     azToken[i] = zCopy;
02677     n = aToken[i].n;
02678     memcpy(zCopy, aToken[i].z, n);
02679     zCopy[n] = 0;
02680     zCopy += n+1;
02681   }
02682   azToken[nToken] = 0;
02683   sqlite3_free(aToken);
02684   *pnToken = nToken;
02685   return azToken;
02686 }
02687 
02688 /*
02689 ** Convert an SQL-style quoted string into a normal string by removing
02690 ** the quote characters.  The conversion is done in-place.  If the
02691 ** input does not begin with a quote character, then this routine
02692 ** is a no-op.
02693 **
02694 ** Examples:
02695 **
02696 **     "abc"   becomes   abc
02697 **     'xyz'   becomes   xyz
02698 **     [pqr]   becomes   pqr
02699 **     `mno`   becomes   mno
02700 */
02701 static void dequoteString(char *z){
02702   int quote;
02703   int i, j;
02704   if( z==0 ) return;
02705   quote = z[0];
02706   switch( quote ){
02707     case '\'':  break;
02708     case '"':   break;
02709     case '`':   break;                /* For MySQL compatibility */
02710     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
02711     default:    return;
02712   }
02713   for(i=1, j=0; z[i]; i++){
02714     if( z[i]==quote ){
02715       if( z[i+1]==quote ){
02716         z[j++] = quote;
02717         i++;
02718       }else{
02719         z[j++] = 0;
02720         break;
02721       }
02722     }else{
02723       z[j++] = z[i];
02724     }
02725   }
02726 }
02727 
02728 /*
02729 ** The input azIn is a NULL-terminated list of tokens.  Remove the first
02730 ** token and all punctuation tokens.  Remove the quotes from
02731 ** around string literal tokens.
02732 **
02733 ** Example:
02734 **
02735 **     input:      tokenize chinese ( 'simplifed' , 'mixed' )
02736 **     output:     chinese simplifed mixed
02737 **
02738 ** Another example:
02739 **
02740 **     input:      delimiters ( '[' , ']' , '...' )
02741 **     output:     [ ] ...
02742 */
02743 static void tokenListToIdList(char **azIn){
02744   int i, j;
02745   if( azIn ){
02746     for(i=0, j=-1; azIn[i]; i++){
02747       if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
02748         dequoteString(azIn[i]);
02749         if( j>=0 ){
02750           azIn[j] = azIn[i];
02751         }
02752         j++;
02753       }
02754     }
02755     azIn[j] = 0;
02756   }
02757 }
02758 
02759 
02760 /*
02761 ** Find the first alphanumeric token in the string zIn.  Null-terminate
02762 ** this token.  Remove any quotation marks.  And return a pointer to
02763 ** the result.
02764 */
02765 static char *firstToken(char *zIn, char **pzTail){
02766   int n, ttype;
02767   while(1){
02768     n = ftsGetToken(zIn, &ttype);
02769     if( ttype==TOKEN_SPACE ){
02770       zIn += n;
02771     }else if( ttype==TOKEN_EOF ){
02772       *pzTail = zIn;
02773       return 0;
02774     }else{
02775       zIn[n] = 0;
02776       *pzTail = &zIn[1];
02777       dequoteString(zIn);
02778       return zIn;
02779     }
02780   }
02781   /*NOTREACHED*/
02782 }
02783 
02784 /* Return true if...
02785 **
02786 **   *  s begins with the string t, ignoring case
02787 **   *  s is longer than t
02788 **   *  The first character of s beyond t is not a alphanumeric
02789 ** 
02790 ** Ignore leading space in *s.
02791 **
02792 ** To put it another way, return true if the first token of
02793 ** s[] is t[].
02794 */
02795 static int startsWith(const char *s, const char *t){
02796   while( safe_isspace(*s) ){ s++; }
02797   while( *t ){
02798     if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
02799   }
02800   return *s!='_' && !safe_isalnum(*s);
02801 }
02802 
02803 /*
02804 ** An instance of this structure defines the "spec" of a
02805 ** full text index.  This structure is populated by parseSpec
02806 ** and use by fulltextConnect and fulltextCreate.
02807 */
02808 typedef struct TableSpec {
02809   const char *zDb;         /* Logical database name */
02810   const char *zName;       /* Name of the full-text index */
02811   int nColumn;             /* Number of columns to be indexed */
02812   char **azColumn;         /* Original names of columns to be indexed */
02813   char **azContentColumn;  /* Column names for %_content */
02814   char **azTokenizer;      /* Name of tokenizer and its arguments */
02815 } TableSpec;
02816 
02817 /*
02818 ** Reclaim all of the memory used by a TableSpec
02819 */
02820 static void clearTableSpec(TableSpec *p) {
02821   sqlite3_free(p->azColumn);
02822   sqlite3_free(p->azContentColumn);
02823   sqlite3_free(p->azTokenizer);
02824 }
02825 
02826 /* Parse a CREATE VIRTUAL TABLE statement, which looks like this:
02827  *
02828  * CREATE VIRTUAL TABLE email
02829  *        USING fts3(subject, body, tokenize mytokenizer(myarg))
02830  *
02831  * We return parsed information in a TableSpec structure.
02832  * 
02833  */
02834 static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
02835                      char**pzErr){
02836   int i, n;
02837   char *z, *zDummy;
02838   char **azArg;
02839   const char *zTokenizer = 0;    /* argv[] entry describing the tokenizer */
02840 
02841   assert( argc>=3 );
02842   /* Current interface:
02843   ** argv[0] - module name
02844   ** argv[1] - database name
02845   ** argv[2] - table name
02846   ** argv[3..] - columns, optionally followed by tokenizer specification
02847   **             and snippet delimiters specification.
02848   */
02849 
02850   /* Make a copy of the complete argv[][] array in a single allocation.
02851   ** The argv[][] array is read-only and transient.  We can write to the
02852   ** copy in order to modify things and the copy is persistent.
02853   */
02854   CLEAR(pSpec);
02855   for(i=n=0; i<argc; i++){
02856     n += strlen(argv[i]) + 1;
02857   }
02858   azArg = sqlite3_malloc( sizeof(char*)*argc + n );
02859   if( azArg==0 ){
02860     return SQLITE_NOMEM;
02861   }
02862   z = (char*)&azArg[argc];
02863   for(i=0; i<argc; i++){
02864     azArg[i] = z;
02865     strcpy(z, argv[i]);
02866     z += strlen(z)+1;
02867   }
02868 
02869   /* Identify the column names and the tokenizer and delimiter arguments
02870   ** in the argv[][] array.
02871   */
02872   pSpec->zDb = azArg[1];
02873   pSpec->zName = azArg[2];
02874   pSpec->nColumn = 0;
02875   pSpec->azColumn = azArg;
02876   zTokenizer = "tokenize simple";
02877   for(i=3; i<argc; ++i){
02878     if( startsWith(azArg[i],"tokenize") ){
02879       zTokenizer = azArg[i];
02880     }else{
02881       z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
02882       pSpec->nColumn++;
02883     }
02884   }
02885   if( pSpec->nColumn==0 ){
02886     azArg[0] = "content";
02887     pSpec->nColumn = 1;
02888   }
02889 
02890   /*
02891   ** Construct the list of content column names.
02892   **
02893   ** Each content column name will be of the form cNNAAAA
02894   ** where NN is the column number and AAAA is the sanitized
02895   ** column name.  "sanitized" means that special characters are
02896   ** converted to "_".  The cNN prefix guarantees that all column
02897   ** names are unique.
02898   **
02899   ** The AAAA suffix is not strictly necessary.  It is included
02900   ** for the convenience of people who might examine the generated
02901   ** %_content table and wonder what the columns are used for.
02902   */
02903   pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) );
02904   if( pSpec->azContentColumn==0 ){
02905     clearTableSpec(pSpec);
02906     return SQLITE_NOMEM;
02907   }
02908   for(i=0; i<pSpec->nColumn; i++){
02909     char *p;
02910     pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
02911     for (p = pSpec->azContentColumn[i]; *p ; ++p) {
02912       if( !safe_isalnum(*p) ) *p = '_';
02913     }
02914   }
02915 
02916   /*
02917   ** Parse the tokenizer specification string.
02918   */
02919   pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
02920   tokenListToIdList(pSpec->azTokenizer);
02921 
02922   return SQLITE_OK;
02923 }
02924 
02925 /*
02926 ** Generate a CREATE TABLE statement that describes the schema of
02927 ** the virtual table.  Return a pointer to this schema string.
02928 **
02929 ** Space is obtained from sqlite3_mprintf() and should be freed
02930 ** using sqlite3_free().
02931 */
02932 static char *fulltextSchema(
02933   int nColumn,                  /* Number of columns */
02934   const char *const* azColumn,  /* List of columns */
02935   const char *zTableName        /* Name of the table */
02936 ){
02937   int i;
02938   char *zSchema, *zNext;
02939   const char *zSep = "(";
02940   zSchema = sqlite3_mprintf("CREATE TABLE x");
02941   for(i=0; i<nColumn; i++){
02942     zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
02943     sqlite3_free(zSchema);
02944     zSchema = zNext;
02945     zSep = ",";
02946   }
02947   zNext = sqlite3_mprintf("%s,%Q HIDDEN", zSchema, zTableName);
02948   sqlite3_free(zSchema);
02949   zSchema = zNext;
02950   zNext = sqlite3_mprintf("%s,docid HIDDEN)", zSchema);
02951   sqlite3_free(zSchema);
02952   return zNext;
02953 }
02954 
02955 /*
02956 ** Build a new sqlite3_vtab structure that will describe the
02957 ** fulltext index defined by spec.
02958 */
02959 static int constructVtab(
02960   sqlite3 *db,              /* The SQLite database connection */
02961   fts3Hash *pHash,          /* Hash table containing tokenizers */
02962   TableSpec *spec,          /* Parsed spec information from parseSpec() */
02963   sqlite3_vtab **ppVTab,    /* Write the resulting vtab structure here */
02964   char **pzErr              /* Write any error message here */
02965 ){
02966   int rc;
02967   int n;
02968   fulltext_vtab *v = 0;
02969   const sqlite3_tokenizer_module *m = NULL;
02970   char *schema;
02971 
02972   char const *zTok;         /* Name of tokenizer to use for this fts table */
02973   int nTok;                 /* Length of zTok, including nul terminator */
02974 
02975   v = (fulltext_vtab *) sqlite3_malloc(sizeof(fulltext_vtab));
02976   if( v==0 ) return SQLITE_NOMEM;
02977   CLEAR(v);
02978   /* sqlite will initialize v->base */
02979   v->db = db;
02980   v->zDb = spec->zDb;       /* Freed when azColumn is freed */
02981   v->zName = spec->zName;   /* Freed when azColumn is freed */
02982   v->nColumn = spec->nColumn;
02983   v->azContentColumn = spec->azContentColumn;
02984   spec->azContentColumn = 0;
02985   v->azColumn = spec->azColumn;
02986   spec->azColumn = 0;
02987 
02988   if( spec->azTokenizer==0 ){
02989     return SQLITE_NOMEM;
02990   }
02991 
02992   zTok = spec->azTokenizer[0]; 
02993   if( !zTok ){
02994     zTok = "simple";
02995   }
02996   nTok = strlen(zTok)+1;
02997 
02998   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zTok, nTok);
02999   if( !m ){
03000     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
03001     rc = SQLITE_ERROR;
03002     goto err;
03003   }
03004 
03005   for(n=0; spec->azTokenizer[n]; n++){}
03006   if( n ){
03007     rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
03008                     &v->pTokenizer);
03009   }else{
03010     rc = m->xCreate(0, 0, &v->pTokenizer);
03011   }
03012   if( rc!=SQLITE_OK ) goto err;
03013   v->pTokenizer->pModule = m;
03014 
03015   /* TODO: verify the existence of backing tables foo_content, foo_term */
03016 
03017   schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
03018                           spec->zName);
03019   rc = sqlite3_declare_vtab(db, schema);
03020   sqlite3_free(schema);
03021   if( rc!=SQLITE_OK ) goto err;
03022 
03023   memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));
03024 
03025   /* Indicate that the buffer is not live. */
03026   v->nPendingData = -1;
03027 
03028   *ppVTab = &v->base;
03029   FTSTRACE(("FTS3 Connect %p\n", v));
03030 
03031   return rc;
03032 
03033 err:
03034   fulltext_vtab_destroy(v);
03035   return rc;
03036 }
03037 
03038 static int fulltextConnect(
03039   sqlite3 *db,
03040   void *pAux,
03041   int argc, const char *const*argv,
03042   sqlite3_vtab **ppVTab,
03043   char **pzErr
03044 ){
03045   TableSpec spec;
03046   int rc = parseSpec(&spec, argc, argv, pzErr);
03047   if( rc!=SQLITE_OK ) return rc;
03048 
03049   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
03050   clearTableSpec(&spec);
03051   return rc;
03052 }
03053 
03054 /* The %_content table holds the text of each document, with
03055 ** the docid column exposed as the SQLite rowid for the table.
03056 */
03057 /* TODO(shess) This comment needs elaboration to match the updated
03058 ** code.  Work it into the top-of-file comment at that time.
03059 */
03060 static int fulltextCreate(sqlite3 *db, void *pAux,
03061                           int argc, const char * const *argv,
03062                           sqlite3_vtab **ppVTab, char **pzErr){
03063   int rc;
03064   TableSpec spec;
03065   StringBuffer schema;
03066   FTSTRACE(("FTS3 Create\n"));
03067 
03068   rc = parseSpec(&spec, argc, argv, pzErr);
03069   if( rc!=SQLITE_OK ) return rc;
03070 
03071   initStringBuffer(&schema);
03072   append(&schema, "CREATE TABLE %_content(");
03073   append(&schema, "  docid INTEGER PRIMARY KEY,");
03074   appendList(&schema, spec.nColumn, spec.azContentColumn);
03075   append(&schema, ")");
03076   rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema));
03077   stringBufferDestroy(&schema);
03078   if( rc!=SQLITE_OK ) goto out;
03079 
03080   rc = sql_exec(db, spec.zDb, spec.zName,
03081                 "create table %_segments("
03082                 "  blockid INTEGER PRIMARY KEY,"
03083                 "  block blob"
03084                 ");"
03085                 );
03086   if( rc!=SQLITE_OK ) goto out;
03087 
03088   rc = sql_exec(db, spec.zDb, spec.zName,
03089                 "create table %_segdir("
03090                 "  level integer,"
03091                 "  idx integer,"
03092                 "  start_block integer,"
03093                 "  leaves_end_block integer,"
03094                 "  end_block integer,"
03095                 "  root blob,"
03096                 "  primary key(level, idx)"
03097                 ");");
03098   if( rc!=SQLITE_OK ) goto out;
03099 
03100   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
03101 
03102 out:
03103   clearTableSpec(&spec);
03104   return rc;
03105 }
03106 
03107 /* Decide how to handle an SQL query. */
03108 static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
03109   fulltext_vtab *v = (fulltext_vtab *)pVTab;
03110   int i;
03111   FTSTRACE(("FTS3 BestIndex\n"));
03112 
03113   for(i=0; i<pInfo->nConstraint; ++i){
03114     const struct sqlite3_index_constraint *pConstraint;
03115     pConstraint = &pInfo->aConstraint[i];
03116     if( pConstraint->usable ) {
03117       if( (pConstraint->iColumn==-1 || pConstraint->iColumn==v->nColumn+1) &&
03118           pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
03119         pInfo->idxNum = QUERY_DOCID;      /* lookup by docid */
03120         FTSTRACE(("FTS3 QUERY_DOCID\n"));
03121       } else if( pConstraint->iColumn>=0 && pConstraint->iColumn<=v->nColumn &&
03122                  pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
03123         /* full-text search */
03124         pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
03125         FTSTRACE(("FTS3 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
03126       } else continue;
03127 
03128       pInfo->aConstraintUsage[i].argvIndex = 1;
03129       pInfo->aConstraintUsage[i].omit = 1;
03130 
03131       /* An arbitrary value for now.
03132        * TODO: Perhaps docid matches should be considered cheaper than
03133        * full-text searches. */
03134       pInfo->estimatedCost = 1.0;   
03135 
03136       return SQLITE_OK;
03137     }
03138   }
03139   pInfo->idxNum = QUERY_GENERIC;
03140   return SQLITE_OK;
03141 }
03142 
03143 static int fulltextDisconnect(sqlite3_vtab *pVTab){
03144   FTSTRACE(("FTS3 Disconnect %p\n", pVTab));
03145   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
03146   return SQLITE_OK;
03147 }
03148 
03149 static int fulltextDestroy(sqlite3_vtab *pVTab){
03150   fulltext_vtab *v = (fulltext_vtab *)pVTab;
03151   int rc;
03152 
03153   FTSTRACE(("FTS3 Destroy %p\n", pVTab));
03154   rc = sql_exec(v->db, v->zDb, v->zName,
03155                 "drop table if exists %_content;"
03156                 "drop table if exists %_segments;"
03157                 "drop table if exists %_segdir;"
03158                 );
03159   if( rc!=SQLITE_OK ) return rc;
03160 
03161   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
03162   return SQLITE_OK;
03163 }
03164 
03165 static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
03166   fulltext_cursor *c;
03167 
03168   c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor));
03169   if( c ){
03170     memset(c, 0, sizeof(fulltext_cursor));
03171     /* sqlite will initialize c->base */
03172     *ppCursor = &c->base;
03173     FTSTRACE(("FTS3 Open %p: %p\n", pVTab, c));
03174     return SQLITE_OK;
03175   }else{
03176     return SQLITE_NOMEM;
03177   }
03178 }
03179 
03180 
03181 /* Free all of the dynamically allocated memory held by *q
03182 */
03183 static void queryClear(Query *q){
03184   int i;
03185   for(i = 0; i < q->nTerms; ++i){
03186     sqlite3_free(q->pTerms[i].pTerm);
03187   }
03188   sqlite3_free(q->pTerms);
03189   CLEAR(q);
03190 }
03191 
03192 /* Free all of the dynamically allocated memory held by the
03193 ** Snippet
03194 */
03195 static void snippetClear(Snippet *p){
03196   sqlite3_free(p->aMatch);
03197   sqlite3_free(p->zOffset);
03198   sqlite3_free(p->zSnippet);
03199   CLEAR(p);
03200 }
03201 /*
03202 ** Append a single entry to the p->aMatch[] log.
03203 */
03204 static void snippetAppendMatch(
03205   Snippet *p,               /* Append the entry to this snippet */
03206   int iCol, int iTerm,      /* The column and query term */
03207   int iToken,               /* Matching token in document */
03208   int iStart, int nByte     /* Offset and size of the match */
03209 ){
03210   int i;
03211   struct snippetMatch *pMatch;
03212   if( p->nMatch+1>=p->nAlloc ){
03213     p->nAlloc = p->nAlloc*2 + 10;
03214     p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
03215     if( p->aMatch==0 ){
03216       p->nMatch = 0;
03217       p->nAlloc = 0;
03218       return;
03219     }
03220   }
03221   i = p->nMatch++;
03222   pMatch = &p->aMatch[i];
03223   pMatch->iCol = iCol;
03224   pMatch->iTerm = iTerm;
03225   pMatch->iToken = iToken;
03226   pMatch->iStart = iStart;
03227   pMatch->nByte = nByte;
03228 }
03229 
03230 /*
03231 ** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
03232 */
03233 #define FTS3_ROTOR_SZ   (32)
03234 #define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
03235 
03236 /*
03237 ** Add entries to pSnippet->aMatch[] for every match that occurs against
03238 ** document zDoc[0..nDoc-1] which is stored in column iColumn.
03239 */
03240 static void snippetOffsetsOfColumn(
03241   Query *pQuery,
03242   Snippet *pSnippet,
03243   int iColumn,
03244   const char *zDoc,
03245   int nDoc
03246 ){
03247   const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
03248   sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
03249   sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
03250   fulltext_vtab *pVtab;                /* The full text index */
03251   int nColumn;                         /* Number of columns in the index */
03252   const QueryTerm *aTerm;              /* Query string terms */
03253   int nTerm;                           /* Number of query string terms */  
03254   int i, j;                            /* Loop counters */
03255   int rc;                              /* Return code */
03256   unsigned int match, prevMatch;       /* Phrase search bitmasks */
03257   const char *zToken;                  /* Next token from the tokenizer */
03258   int nToken;                          /* Size of zToken */
03259   int iBegin, iEnd, iPos;              /* Offsets of beginning and end */
03260 
03261   /* The following variables keep a circular buffer of the last
03262   ** few tokens */
03263   unsigned int iRotor = 0;             /* Index of current token */
03264   int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
03265   int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */
03266 
03267   pVtab = pQuery->pFts;
03268   nColumn = pVtab->nColumn;
03269   pTokenizer = pVtab->pTokenizer;
03270   pTModule = pTokenizer->pModule;
03271   rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
03272   if( rc ) return;
03273   pTCursor->pTokenizer = pTokenizer;
03274   aTerm = pQuery->pTerms;
03275   nTerm = pQuery->nTerms;
03276   if( nTerm>=FTS3_ROTOR_SZ ){
03277     nTerm = FTS3_ROTOR_SZ - 1;
03278   }
03279   prevMatch = 0;
03280   while(1){
03281     rc = pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
03282     if( rc ) break;
03283     iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
03284     iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
03285     match = 0;
03286     for(i=0; i<nTerm; i++){
03287       int iCol;
03288       iCol = aTerm[i].iColumn;
03289       if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
03290       if( aTerm[i].nTerm>nToken ) continue;
03291       if( !aTerm[i].isPrefix && aTerm[i].nTerm<nToken ) continue;
03292       assert( aTerm[i].nTerm<=nToken );
03293       if( memcmp(aTerm[i].pTerm, zToken, aTerm[i].nTerm) ) continue;
03294       if( aTerm[i].iPhrase>1 && (prevMatch & (1<<i))==0 ) continue;
03295       match |= 1<<i;
03296       if( i==nTerm-1 || aTerm[i+1].iPhrase==1 ){
03297         for(j=aTerm[i].iPhrase-1; j>=0; j--){
03298           int k = (iRotor-j) & FTS3_ROTOR_MASK;
03299           snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
03300                 iRotorBegin[k], iRotorLen[k]);
03301         }
03302       }
03303     }
03304     prevMatch = match<<1;
03305     iRotor++;
03306   }
03307   pTModule->xClose(pTCursor);  
03308 }
03309 
03310 /*
03311 ** Remove entries from the pSnippet structure to account for the NEAR
03312 ** operator. When this is called, pSnippet contains the list of token 
03313 ** offsets produced by treating all NEAR operators as AND operators.
03314 ** This function removes any entries that should not be present after
03315 ** accounting for the NEAR restriction. For example, if the queried
03316 ** document is:
03317 **
03318 **     "A B C D E A"
03319 **
03320 ** and the query is:
03321 ** 
03322 **     A NEAR/0 E
03323 **
03324 ** then when this function is called the Snippet contains token offsets
03325 ** 0, 4 and 5. This function removes the "0" entry (because the first A
03326 ** is not near enough to an E).
03327 */
03328 static void trimSnippetOffsetsForNear(Query *pQuery, Snippet *pSnippet){
03329   int ii;
03330   int iDir = 1;
03331 
03332   while(iDir>-2) {
03333     assert( iDir==1 || iDir==-1 );
03334     for(ii=0; ii<pSnippet->nMatch; ii++){
03335       int jj;
03336       int nNear;
03337       struct snippetMatch *pMatch = &pSnippet->aMatch[ii];
03338       QueryTerm *pQueryTerm = &pQuery->pTerms[pMatch->iTerm];
03339 
03340       if( (pMatch->iTerm+iDir)<0 
03341        || (pMatch->iTerm+iDir)>=pQuery->nTerms
03342       ){
03343         continue;
03344       }
03345      
03346       nNear = pQueryTerm->nNear;
03347       if( iDir<0 ){
03348         nNear = pQueryTerm[-1].nNear;
03349       }
03350   
03351       if( pMatch->iTerm>=0 && nNear ){
03352         int isOk = 0;
03353         int iNextTerm = pMatch->iTerm+iDir;
03354         int iPrevTerm = iNextTerm;
03355 
03356         int iEndToken;
03357         int iStartToken;
03358 
03359         if( iDir<0 ){
03360           int nPhrase = 1;
03361           iStartToken = pMatch->iToken;
03362           while( (pMatch->iTerm+nPhrase)<pQuery->nTerms 
03363               && pQuery->pTerms[pMatch->iTerm+nPhrase].iPhrase>1 
03364           ){
03365             nPhrase++;
03366           }
03367           iEndToken = iStartToken + nPhrase - 1;
03368         }else{
03369           iEndToken   = pMatch->iToken;
03370           iStartToken = pMatch->iToken+1-pQueryTerm->iPhrase;
03371         }
03372 
03373         while( pQuery->pTerms[iNextTerm].iPhrase>1 ){
03374           iNextTerm--;
03375         }
03376         while( (iPrevTerm+1)<pQuery->nTerms && 
03377                pQuery->pTerms[iPrevTerm+1].iPhrase>1 
03378         ){
03379           iPrevTerm++;
03380         }
03381   
03382         for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
03383           struct snippetMatch *p = &pSnippet->aMatch[jj];
03384           if( p->iCol==pMatch->iCol && ((
03385                p->iTerm==iNextTerm && 
03386                p->iToken>iEndToken && 
03387                p->iToken<=iEndToken+nNear
03388           ) || (
03389                p->iTerm==iPrevTerm && 
03390                p->iToken<iStartToken && 
03391                p->iToken>=iStartToken-nNear
03392           ))){
03393             isOk = 1;
03394           }
03395         }
03396         if( !isOk ){
03397           for(jj=1-pQueryTerm->iPhrase; jj<=0; jj++){
03398             pMatch[jj].iTerm = -1;
03399           }
03400           ii = -1;
03401           iDir = 1;
03402         }
03403       }
03404     }
03405     iDir -= 2;
03406   }
03407 }
03408 
03409 /*
03410 ** Compute all offsets for the current row of the query.  
03411 ** If the offsets have already been computed, this routine is a no-op.
03412 */
03413 static void snippetAllOffsets(fulltext_cursor *p){
03414   int nColumn;
03415   int iColumn, i;
03416   int iFirst, iLast;
03417   fulltext_vtab *pFts;
03418 
03419   if( p->snippet.nMatch ) return;
03420   if( p->q.nTerms==0 ) return;
03421   pFts = p->q.pFts;
03422   nColumn = pFts->nColumn;
03423   iColumn = (p->iCursorType - QUERY_FULLTEXT);
03424   if( iColumn<0 || iColumn>=nColumn ){
03425     iFirst = 0;
03426     iLast = nColumn-1;
03427   }else{
03428     iFirst = iColumn;
03429     iLast = iColumn;
03430   }
03431   for(i=iFirst; i<=iLast; i++){
03432     const char *zDoc;
03433     int nDoc;
03434     zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
03435     nDoc = sqlite3_column_bytes(p->pStmt, i+1);
03436     snippetOffsetsOfColumn(&p->q, &p->snippet, i, zDoc, nDoc);
03437   }
03438 
03439   trimSnippetOffsetsForNear(&p->q, &p->snippet);
03440 }
03441 
03442 /*
03443 ** Convert the information in the aMatch[] array of the snippet
03444 ** into the string zOffset[0..nOffset-1].
03445 */
03446 static void snippetOffsetText(Snippet *p){
03447   int i;
03448   int cnt = 0;
03449   StringBuffer sb;
03450   char zBuf[200];
03451   if( p->zOffset ) return;
03452   initStringBuffer(&sb);
03453   for(i=0; i<p->nMatch; i++){
03454     struct snippetMatch *pMatch = &p->aMatch[i];
03455     if( pMatch->iTerm>=0 ){
03456       /* If snippetMatch.iTerm is less than 0, then the match was 
03457       ** discarded as part of processing the NEAR operator (see the 
03458       ** trimSnippetOffsetsForNear() function for details). Ignore 
03459       ** it in this case
03460       */
03461       zBuf[0] = ' ';
03462       sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
03463           pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
03464       append(&sb, zBuf);
03465       cnt++;
03466     }
03467   }
03468   p->zOffset = stringBufferData(&sb);
03469   p->nOffset = stringBufferLength(&sb);
03470 }
03471 
03472 /*
03473 ** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
03474 ** of matching words some of which might be in zDoc.  zDoc is column
03475 ** number iCol.
03476 **
03477 ** iBreak is suggested spot in zDoc where we could begin or end an
03478 ** excerpt.  Return a value similar to iBreak but possibly adjusted
03479 ** to be a little left or right so that the break point is better.
03480 */
03481 static int wordBoundary(
03482   int iBreak,                   /* The suggested break point */
03483   const char *zDoc,             /* Document text */
03484   int nDoc,                     /* Number of bytes in zDoc[] */
03485   struct snippetMatch *aMatch,  /* Matching words */
03486   int nMatch,                   /* Number of entries in aMatch[] */
03487   int iCol                      /* The column number for zDoc[] */
03488 ){
03489   int i;
03490   if( iBreak<=10 ){
03491     return 0;
03492   }
03493   if( iBreak>=nDoc-10 ){
03494     return nDoc;
03495   }
03496   for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
03497   while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
03498   if( i<nMatch ){
03499     if( aMatch[i].iStart<iBreak+10 ){
03500       return aMatch[i].iStart;
03501     }
03502     if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
03503       return aMatch[i-1].iStart;
03504     }
03505   }
03506   for(i=1; i<=10; i++){
03507     if( safe_isspace(zDoc[iBreak-i]) ){
03508       return iBreak - i + 1;
03509     }
03510     if( safe_isspace(zDoc[iBreak+i]) ){
03511       return iBreak + i + 1;
03512     }
03513   }
03514   return iBreak;
03515 }
03516 
03517 
03518 
03519 /*
03520 ** Allowed values for Snippet.aMatch[].snStatus
03521 */
03522 #define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
03523 #define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */
03524 
03525 /*
03526 ** Generate the text of a snippet.
03527 */
03528 static void snippetText(
03529   fulltext_cursor *pCursor,   /* The cursor we need the snippet for */
03530   const char *zStartMark,     /* Markup to appear before each match */
03531   const char *zEndMark,       /* Markup to appear after each match */
03532   const char *zEllipsis       /* Ellipsis mark */
03533 ){
03534   int i, j;
03535   struct snippetMatch *aMatch;
03536   int nMatch;
03537   int nDesired;
03538   StringBuffer sb;
03539   int tailCol;
03540   int tailOffset;
03541   int iCol;
03542   int nDoc;
03543   const char *zDoc;
03544   int iStart, iEnd;
03545   int tailEllipsis = 0;
03546   int iMatch;
03547   
03548 
03549   sqlite3_free(pCursor->snippet.zSnippet);
03550   pCursor->snippet.zSnippet = 0;
03551   aMatch = pCursor->snippet.aMatch;
03552   nMatch = pCursor->snippet.nMatch;
03553   initStringBuffer(&sb);
03554 
03555   for(i=0; i<nMatch; i++){
03556     aMatch[i].snStatus = SNIPPET_IGNORE;
03557   }
03558   nDesired = 0;
03559   for(i=0; i<pCursor->q.nTerms; i++){
03560     for(j=0; j<nMatch; j++){
03561       if( aMatch[j].iTerm==i ){
03562         aMatch[j].snStatus = SNIPPET_DESIRED;
03563         nDesired++;
03564         break;
03565       }
03566     }
03567   }
03568 
03569   iMatch = 0;
03570   tailCol = -1;
03571   tailOffset = 0;
03572   for(i=0; i<nMatch && nDesired>0; i++){
03573     if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
03574     nDesired--;
03575     iCol = aMatch[i].iCol;
03576     zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
03577     nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
03578     iStart = aMatch[i].iStart - 40;
03579     iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
03580     if( iStart<=10 ){
03581       iStart = 0;
03582     }
03583     if( iCol==tailCol && iStart<=tailOffset+20 ){
03584       iStart = tailOffset;
03585     }
03586     if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
03587       trimWhiteSpace(&sb);
03588       appendWhiteSpace(&sb);
03589       append(&sb, zEllipsis);
03590       appendWhiteSpace(&sb);
03591     }
03592     iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
03593     iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
03594     if( iEnd>=nDoc-10 ){
03595       iEnd = nDoc;
03596       tailEllipsis = 0;
03597     }else{
03598       tailEllipsis = 1;
03599     }
03600     while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
03601     while( iStart<iEnd ){
03602       while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
03603              && aMatch[iMatch].iCol<=iCol ){
03604         iMatch++;
03605       }
03606       if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
03607              && aMatch[iMatch].iCol==iCol ){
03608         nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
03609         iStart = aMatch[iMatch].iStart;
03610         append(&sb, zStartMark);
03611         nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
03612         append(&sb, zEndMark);
03613         iStart += aMatch[iMatch].nByte;
03614         for(j=iMatch+1; j<nMatch; j++){
03615           if( aMatch[j].iTerm==aMatch[iMatch].iTerm
03616               && aMatch[j].snStatus==SNIPPET_DESIRED ){
03617             nDesired--;
03618             aMatch[j].snStatus = SNIPPET_IGNORE;
03619           }
03620         }
03621       }else{
03622         nappend(&sb, &zDoc[iStart], iEnd - iStart);
03623         iStart = iEnd;
03624       }
03625     }
03626     tailCol = iCol;
03627     tailOffset = iEnd;
03628   }
03629   trimWhiteSpace(&sb);
03630   if( tailEllipsis ){
03631     appendWhiteSpace(&sb);
03632     append(&sb, zEllipsis);
03633   }
03634   pCursor->snippet.zSnippet = stringBufferData(&sb);
03635   pCursor->snippet.nSnippet = stringBufferLength(&sb);
03636 }
03637 
03638 
03639 /*
03640 ** Close the cursor.  For additional information see the documentation
03641 ** on the xClose method of the virtual table interface.
03642 */
03643 static int fulltextClose(sqlite3_vtab_cursor *pCursor){
03644   fulltext_cursor *c = (fulltext_cursor *) pCursor;
03645   FTSTRACE(("FTS3 Close %p\n", c));
03646   sqlite3_finalize(c->pStmt);
03647   queryClear(&c->q);
03648   snippetClear(&c->snippet);
03649   if( c->result.nData!=0 ) dlrDestroy(&c->reader);
03650   dataBufferDestroy(&c->result);
03651   sqlite3_free(c);
03652   return SQLITE_OK;
03653 }
03654 
03655 static int fulltextNext(sqlite3_vtab_cursor *pCursor){
03656   fulltext_cursor *c = (fulltext_cursor *) pCursor;
03657   int rc;
03658 
03659   FTSTRACE(("FTS3 Next %p\n", pCursor));
03660   snippetClear(&c->snippet);
03661   if( c->iCursorType < QUERY_FULLTEXT ){
03662     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
03663     rc = sqlite3_step(c->pStmt);
03664     switch( rc ){
03665       case SQLITE_ROW:
03666         c->eof = 0;
03667         return SQLITE_OK;
03668       case SQLITE_DONE:
03669         c->eof = 1;
03670         return SQLITE_OK;
03671       default:
03672         c->eof = 1;
03673         return rc;
03674     }
03675   } else {  /* full-text query */
03676     rc = sqlite3_reset(c->pStmt);
03677     if( rc!=SQLITE_OK ) return rc;
03678 
03679     if( c->result.nData==0 || dlrAtEnd(&c->reader) ){
03680       c->eof = 1;
03681       return SQLITE_OK;
03682     }
03683     rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader));
03684     dlrStep(&c->reader);
03685     if( rc!=SQLITE_OK ) return rc;
03686     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
03687     rc = sqlite3_step(c->pStmt);
03688     if( rc==SQLITE_ROW ){   /* the case we expect */
03689       c->eof = 0;
03690       return SQLITE_OK;
03691     }
03692     /* an error occurred; abort */
03693     return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
03694   }
03695 }
03696 
03697 
03698 /* TODO(shess) If we pushed LeafReader to the top of the file, or to
03699 ** another file, term_select() could be pushed above
03700 ** docListOfTerm().
03701 */
03702 static int termSelect(fulltext_vtab *v, int iColumn,
03703                       const char *pTerm, int nTerm, int isPrefix,
03704                       DocListType iType, DataBuffer *out);
03705 
03706 /* Return a DocList corresponding to the query term *pTerm.  If *pTerm
03707 ** is the first term of a phrase query, go ahead and evaluate the phrase
03708 ** query and return the doclist for the entire phrase query.
03709 **
03710 ** The resulting DL_DOCIDS doclist is stored in pResult, which is
03711 ** overwritten.
03712 */
03713 static int docListOfTerm(
03714   fulltext_vtab *v,    /* The full text index */
03715   int iColumn,         /* column to restrict to.  No restriction if >=nColumn */
03716   QueryTerm *pQTerm,   /* Term we are looking for, or 1st term of a phrase */
03717   DataBuffer *pResult  /* Write the result here */
03718 ){
03719   DataBuffer left, right, new;
03720   int i, rc;
03721 
03722   /* No phrase search if no position info. */
03723   assert( pQTerm->nPhrase==0 || DL_DEFAULT!=DL_DOCIDS );
03724 
03725   /* This code should never be called with buffered updates. */
03726   assert( v->nPendingData<0 );
03727 
03728   dataBufferInit(&left, 0);
03729   rc = termSelect(v, iColumn, pQTerm->pTerm, pQTerm->nTerm, pQTerm->isPrefix,
03730                   (0<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS), &left);
03731   if( rc ) return rc;
03732   for(i=1; i<=pQTerm->nPhrase && left.nData>0; i++){
03733     /* If this token is connected to the next by a NEAR operator, and
03734     ** the next token is the start of a phrase, then set nPhraseRight
03735     ** to the number of tokens in the phrase. Otherwise leave it at 1.
03736     */
03737     int nPhraseRight = 1;
03738     while( (i+nPhraseRight)<=pQTerm->nPhrase 
03739         && pQTerm[i+nPhraseRight].nNear==0 
03740     ){
03741       nPhraseRight++;
03742     }
03743 
03744     dataBufferInit(&right, 0);
03745     rc = termSelect(v, iColumn, pQTerm[i].pTerm, pQTerm[i].nTerm,
03746                     pQTerm[i].isPrefix, DL_POSITIONS, &right);
03747     if( rc ){
03748       dataBufferDestroy(&left);
03749       return rc;
03750     }
03751     dataBufferInit(&new, 0);
03752     docListPhraseMerge(left.pData, left.nData, right.pData, right.nData,
03753                        pQTerm[i-1].nNear, pQTerm[i-1].iPhrase + nPhraseRight,
03754                        ((i<pQTerm->nPhrase) ? DL_POSITIONS : DL_DOCIDS),
03755                        &new);
03756     dataBufferDestroy(&left);
03757     dataBufferDestroy(&right);
03758     left = new;
03759   }
03760   *pResult = left;
03761   return SQLITE_OK;
03762 }
03763 
03764 /* Add a new term pTerm[0..nTerm-1] to the query *q.
03765 */
03766 static void queryAdd(Query *q, const char *pTerm, int nTerm){
03767   QueryTerm *t;
03768   ++q->nTerms;
03769   q->pTerms = sqlite3_realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0]));
03770   if( q->pTerms==0 ){
03771     q->nTerms = 0;
03772     return;
03773   }
03774   t = &q->pTerms[q->nTerms - 1];
03775   CLEAR(t);
03776   t->pTerm = sqlite3_malloc(nTerm+1);
03777   memcpy(t->pTerm, pTerm, nTerm);
03778   t->pTerm[nTerm] = 0;
03779   t->nTerm = nTerm;
03780   t->isOr = q->nextIsOr;
03781   t->isPrefix = 0;
03782   q->nextIsOr = 0;
03783   t->iColumn = q->nextColumn;
03784   q->nextColumn = q->dfltColumn;
03785 }
03786 
03787 /*
03788 ** Check to see if the string zToken[0...nToken-1] matches any
03789 ** column name in the virtual table.   If it does,
03790 ** return the zero-indexed column number.  If not, return -1.
03791 */
03792 static int checkColumnSpecifier(
03793   fulltext_vtab *pVtab,    /* The virtual table */
03794   const char *zToken,      /* Text of the token */
03795   int nToken               /* Number of characters in the token */
03796 ){
03797   int i;
03798   for(i=0; i<pVtab->nColumn; i++){
03799     if( memcmp(pVtab->azColumn[i], zToken, nToken)==0
03800         && pVtab->azColumn[i][nToken]==0 ){
03801       return i;
03802     }
03803   }
03804   return -1;
03805 }
03806 
03807 /*
03808 ** Parse the text at zSegment[0..nSegment-1].  Add additional terms
03809 ** to the query being assemblied in pQuery.
03810 **
03811 ** inPhrase is true if zSegment[0..nSegement-1] is contained within
03812 ** double-quotes.  If inPhrase is true, then the first term
03813 ** is marked with the number of terms in the phrase less one and
03814 ** OR and "-" syntax is ignored.  If inPhrase is false, then every
03815 ** term found is marked with nPhrase=0 and OR and "-" syntax is significant.
03816 */
03817 static int tokenizeSegment(
03818   sqlite3_tokenizer *pTokenizer,          /* The tokenizer to use */
03819   const char *zSegment, int nSegment,     /* Query expression being parsed */
03820   int inPhrase,                           /* True if within "..." */
03821   Query *pQuery                           /* Append results here */
03822 ){
03823   const sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
03824   sqlite3_tokenizer_cursor *pCursor;
03825   int firstIndex = pQuery->nTerms;
03826   int iCol;
03827   int nTerm = 1;
03828   
03829   int rc = pModule->xOpen(pTokenizer, zSegment, nSegment, &pCursor);
03830   if( rc!=SQLITE_OK ) return rc;
03831   pCursor->pTokenizer = pTokenizer;
03832 
03833   while( 1 ){
03834     const char *zToken;
03835     int nToken, iBegin, iEnd, iPos;
03836 
03837     rc = pModule->xNext(pCursor,
03838                         &zToken, &nToken,
03839                         &iBegin, &iEnd, &iPos);
03840     if( rc!=SQLITE_OK ) break;
03841     if( !inPhrase &&
03842         zSegment[iEnd]==':' &&
03843          (iCol = checkColumnSpecifier(pQuery->pFts, zToken, nToken))>=0 ){
03844       pQuery->nextColumn = iCol;
03845       continue;
03846     }
03847     if( !inPhrase && pQuery->nTerms>0 && nToken==2 
03848      && zSegment[iBegin+0]=='O'
03849      && zSegment[iBegin+1]=='R' 
03850     ){
03851       pQuery->nextIsOr = 1;
03852       continue;
03853     }
03854     if( !inPhrase && pQuery->nTerms>0 && !pQuery->nextIsOr && nToken==4 
03855       && memcmp(&zSegment[iBegin], "NEAR", 4)==0
03856     ){
03857       QueryTerm *pTerm = &pQuery->pTerms[pQuery->nTerms-1];
03858       if( (iBegin+6)<nSegment 
03859        && zSegment[iBegin+4] == '/'
03860        && isdigit(zSegment[iBegin+5])
03861       ){
03862         int k;
03863         pTerm->nNear = 0;
03864         for(k=5; (iBegin+k)<=nSegment && isdigit(zSegment[iBegin+k]); k++){
03865           pTerm->nNear = pTerm->nNear*10 + (zSegment[iBegin+k] - '0');
03866         }
03867         pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
03868       } else {
03869         pTerm->nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
03870       }
03871       pTerm->nNear++;
03872       continue;
03873     }
03874 
03875     queryAdd(pQuery, zToken, nToken);
03876     if( !inPhrase && iBegin>0 && zSegment[iBegin-1]=='-' ){
03877       pQuery->pTerms[pQuery->nTerms-1].isNot = 1;
03878     }
03879     if( iEnd<nSegment && zSegment[iEnd]=='*' ){
03880       pQuery->pTerms[pQuery->nTerms-1].isPrefix = 1;
03881     }
03882     pQuery->pTerms[pQuery->nTerms-1].iPhrase = nTerm;
03883     if( inPhrase ){
03884       nTerm++;
03885     }
03886   }
03887 
03888   if( inPhrase && pQuery->nTerms>firstIndex ){
03889     pQuery->pTerms[firstIndex].nPhrase = pQuery->nTerms - firstIndex - 1;
03890   }
03891 
03892   return pModule->xClose(pCursor);
03893 }
03894 
03895 /* Parse a query string, yielding a Query object pQuery.
03896 **
03897 ** The calling function will need to queryClear() to clean up
03898 ** the dynamically allocated memory held by pQuery.
03899 */
03900 static int parseQuery(
03901   fulltext_vtab *v,        /* The fulltext index */
03902   const char *zInput,      /* Input text of the query string */
03903   int nInput,              /* Size of the input text */
03904   int dfltColumn,          /* Default column of the index to match against */
03905   Query *pQuery            /* Write the parse results here. */
03906 ){
03907   int iInput, inPhrase = 0;
03908   int ii;
03909   QueryTerm *aTerm;
03910 
03911   if( zInput==0 ) nInput = 0;
03912   if( nInput<0 ) nInput = strlen(zInput);
03913   pQuery->nTerms = 0;
03914   pQuery->pTerms = NULL;
03915   pQuery->nextIsOr = 0;
03916   pQuery->nextColumn = dfltColumn;
03917   pQuery->dfltColumn = dfltColumn;
03918   pQuery->pFts = v;
03919 
03920   for(iInput=0; iInput<nInput; ++iInput){
03921     int i;
03922     for(i=iInput; i<nInput && zInput[i]!='"'; ++i){}
03923     if( i>iInput ){
03924       tokenizeSegment(v->pTokenizer, zInput+iInput, i-iInput, inPhrase,
03925                        pQuery);
03926     }
03927     iInput = i;
03928     if( i<nInput ){
03929       assert( zInput[i]=='"' );
03930       inPhrase = !inPhrase;
03931     }
03932   }
03933 
03934   if( inPhrase ){
03935     /* unmatched quote */
03936     queryClear(pQuery);
03937     return SQLITE_ERROR;
03938   }
03939 
03940   /* Modify the values of the QueryTerm.nPhrase variables to account for
03941   ** the NEAR operator. For the purposes of QueryTerm.nPhrase, phrases
03942   ** and tokens connected by the NEAR operator are handled as a single
03943   ** phrase. See comments above the QueryTerm structure for details.
03944   */
03945   aTerm = pQuery->pTerms;
03946   for(ii=0; ii<pQuery->nTerms; ii++){
03947     if( aTerm[ii].nNear || aTerm[ii].nPhrase ){
03948       while (aTerm[ii+aTerm[ii].nPhrase].nNear) {
03949         aTerm[ii].nPhrase += (1 + aTerm[ii+aTerm[ii].nPhrase+1].nPhrase);
03950       }
03951     }
03952   }
03953 
03954   return SQLITE_OK;
03955 }
03956 
03957 /* TODO(shess) Refactor the code to remove this forward decl. */
03958 static int flushPendingTerms(fulltext_vtab *v);
03959 
03960 /* Perform a full-text query using the search expression in
03961 ** zInput[0..nInput-1].  Return a list of matching documents
03962 ** in pResult.
03963 **
03964 ** Queries must match column iColumn.  Or if iColumn>=nColumn
03965 ** they are allowed to match against any column.
03966 */
03967 static int fulltextQuery(
03968   fulltext_vtab *v,      /* The full text index */
03969   int iColumn,           /* Match against this column by default */
03970   const char *zInput,    /* The query string */
03971   int nInput,            /* Number of bytes in zInput[] */
03972   DataBuffer *pResult,   /* Write the result doclist here */
03973   Query *pQuery          /* Put parsed query string here */
03974 ){
03975   int i, iNext, rc;
03976   DataBuffer left, right, or, new;
03977   int nNot = 0;
03978   QueryTerm *aTerm;
03979 
03980   /* TODO(shess) Instead of flushing pendingTerms, we could query for
03981   ** the relevant term and merge the doclist into what we receive from
03982   ** the database.  Wait and see if this is a common issue, first.
03983   **
03984   ** A good reason not to flush is to not generate update-related
03985   ** error codes from here.
03986   */
03987 
03988   /* Flush any buffered updates before executing the query. */
03989   rc = flushPendingTerms(v);
03990   if( rc!=SQLITE_OK ) return rc;
03991 
03992   /* TODO(shess) I think that the queryClear() calls below are not
03993   ** necessary, because fulltextClose() already clears the query.
03994   */
03995   rc = parseQuery(v, zInput, nInput, iColumn, pQuery);
03996   if( rc!=SQLITE_OK ) return rc;
03997 
03998   /* Empty or NULL queries return no results. */
03999   if( pQuery->nTerms==0 ){
04000     dataBufferInit(pResult, 0);
04001     return SQLITE_OK;
04002   }
04003 
04004   /* Merge AND terms. */
04005   /* TODO(shess) I think we can early-exit if( i>nNot && left.nData==0 ). */
04006   aTerm = pQuery->pTerms;
04007   for(i = 0; i<pQuery->nTerms; i=iNext){
04008     if( aTerm[i].isNot ){
04009       /* Handle all NOT terms in a separate pass */
04010       nNot++;
04011       iNext = i + aTerm[i].nPhrase+1;
04012       continue;
04013     }
04014     iNext = i + aTerm[i].nPhrase + 1;
04015     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
04016     if( rc ){
04017       if( i!=nNot ) dataBufferDestroy(&left);
04018       queryClear(pQuery);
04019       return rc;
04020     }
04021     while( iNext<pQuery->nTerms && aTerm[iNext].isOr ){
04022       rc = docListOfTerm(v, aTerm[iNext].iColumn, &aTerm[iNext], &or);
04023       iNext += aTerm[iNext].nPhrase + 1;
04024       if( rc ){
04025         if( i!=nNot ) dataBufferDestroy(&left);
04026         dataBufferDestroy(&right);
04027         queryClear(pQuery);
04028         return rc;
04029       }
04030       dataBufferInit(&new, 0);
04031       docListOrMerge(right.pData, right.nData, or.pData, or.nData, &new);
04032       dataBufferDestroy(&right);
04033       dataBufferDestroy(&or);
04034       right = new;
04035     }
04036     if( i==nNot ){           /* first term processed. */
04037       left = right;
04038     }else{
04039       dataBufferInit(&new, 0);
04040       docListAndMerge(left.pData, left.nData, right.pData, right.nData, &new);
04041       dataBufferDestroy(&right);
04042       dataBufferDestroy(&left);
04043       left = new;
04044     }
04045   }
04046 
04047   if( nNot==pQuery->nTerms ){
04048     /* We do not yet know how to handle a query of only NOT terms */
04049     return SQLITE_ERROR;
04050   }
04051 
04052   /* Do the EXCEPT terms */
04053   for(i=0; i<pQuery->nTerms;  i += aTerm[i].nPhrase + 1){
04054     if( !aTerm[i].isNot ) continue;
04055     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
04056     if( rc ){
04057       queryClear(pQuery);
04058       dataBufferDestroy(&left);
04059       return rc;
04060     }
04061     dataBufferInit(&new, 0);
04062     docListExceptMerge(left.pData, left.nData, right.pData, right.nData, &new);
04063     dataBufferDestroy(&right);
04064     dataBufferDestroy(&left);
04065     left = new;
04066   }
04067 
04068   *pResult = left;
04069   return rc;
04070 }
04071 
04072 /*
04073 ** This is the xFilter interface for the virtual table.  See
04074 ** the virtual table xFilter method documentation for additional
04075 ** information.
04076 **
04077 ** If idxNum==QUERY_GENERIC then do a full table scan against
04078 ** the %_content table.
04079 **
04080 ** If idxNum==QUERY_DOCID then do a docid lookup for a single entry
04081 ** in the %_content table.
04082 **
04083 ** If idxNum>=QUERY_FULLTEXT then use the full text index.  The
04084 ** column on the left-hand side of the MATCH operator is column
04085 ** number idxNum-QUERY_FULLTEXT, 0 indexed.  argv[0] is the right-hand
04086 ** side of the MATCH operator.
04087 */
04088 /* TODO(shess) Upgrade the cursor initialization and destruction to
04089 ** account for fulltextFilter() being called multiple times on the
04090 ** same cursor.  The current solution is very fragile.  Apply fix to
04091 ** fts3 as appropriate.
04092 */
04093 static int fulltextFilter(
04094   sqlite3_vtab_cursor *pCursor,     /* The cursor used for this query */
04095   int idxNum, const char *idxStr,   /* Which indexing scheme to use */
04096   int argc, sqlite3_value **argv    /* Arguments for the indexing scheme */
04097 ){
04098   fulltext_cursor *c = (fulltext_cursor *) pCursor;
04099   fulltext_vtab *v = cursor_vtab(c);
04100   int rc;
04101 
04102   FTSTRACE(("FTS3 Filter %p\n",pCursor));
04103 
04104   /* If the cursor has a statement that was not prepared according to
04105   ** idxNum, clear it.  I believe all calls to fulltextFilter with a
04106   ** given cursor will have the same idxNum , but in this case it's
04107   ** easy to be safe.
04108   */
04109   if( c->pStmt && c->iCursorType!=idxNum ){
04110     sqlite3_finalize(c->pStmt);
04111     c->pStmt = NULL;
04112   }
04113 
04114   /* Get a fresh statement appropriate to idxNum. */
04115   /* TODO(shess): Add a prepared-statement cache in the vt structure.
04116   ** The cache must handle multiple open cursors.  Easier to cache the
04117   ** statement variants at the vt to reduce malloc/realloc/free here.
04118   ** Or we could have a StringBuffer variant which allowed stack
04119   ** construction for small values.
04120   */
04121   if( !c->pStmt ){
04122     StringBuffer sb;
04123     initStringBuffer(&sb);
04124     append(&sb, "SELECT docid, ");
04125     appendList(&sb, v->nColumn, v->azContentColumn);
04126     append(&sb, " FROM %_content");
04127     if( idxNum!=QUERY_GENERIC ) append(&sb, " WHERE docid = ?");
04128     rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt,
04129                      stringBufferData(&sb));
04130     stringBufferDestroy(&sb);
04131     if( rc!=SQLITE_OK ) return rc;
04132     c->iCursorType = idxNum;
04133   }else{
04134     sqlite3_reset(c->pStmt);
04135     assert( c->iCursorType==idxNum );
04136   }
04137 
04138   switch( idxNum ){
04139     case QUERY_GENERIC:
04140       break;
04141 
04142     case QUERY_DOCID:
04143       rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
04144       if( rc!=SQLITE_OK ) return rc;
04145       break;
04146 
04147     default:   /* full-text search */
04148     {
04149       const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
04150       assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
04151       assert( argc==1 );
04152       queryClear(&c->q);
04153       if( c->result.nData!=0 ){
04154         /* This case happens if the same cursor is used repeatedly. */
04155         dlrDestroy(&c->reader);
04156         dataBufferReset(&c->result);
04157       }else{
04158         dataBufferInit(&c->result, 0);
04159       }
04160       rc = fulltextQuery(v, idxNum-QUERY_FULLTEXT, zQuery, -1, &c->result, &c->q);
04161       if( rc!=SQLITE_OK ) return rc;
04162       if( c->result.nData!=0 ){
04163         dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData);
04164       }
04165       break;
04166     }
04167   }
04168 
04169   return fulltextNext(pCursor);
04170 }
04171 
04172 /* This is the xEof method of the virtual table.  The SQLite core
04173 ** calls this routine to find out if it has reached the end of
04174 ** a query's results set.
04175 */
04176 static int fulltextEof(sqlite3_vtab_cursor *pCursor){
04177   fulltext_cursor *c = (fulltext_cursor *) pCursor;
04178   return c->eof;
04179 }
04180 
04181 /* This is the xColumn method of the virtual table.  The SQLite
04182 ** core calls this method during a query when it needs the value
04183 ** of a column from the virtual table.  This method needs to use
04184 ** one of the sqlite3_result_*() routines to store the requested
04185 ** value back in the pContext.
04186 */
04187 static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
04188                           sqlite3_context *pContext, int idxCol){
04189   fulltext_cursor *c = (fulltext_cursor *) pCursor;
04190   fulltext_vtab *v = cursor_vtab(c);
04191 
04192   if( idxCol<v->nColumn ){
04193     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
04194     sqlite3_result_value(pContext, pVal);
04195   }else if( idxCol==v->nColumn ){
04196     /* The extra column whose name is the same as the table.
04197     ** Return a blob which is a pointer to the cursor
04198     */
04199     sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
04200   }else if( idxCol==v->nColumn+1 ){
04201     /* The docid column, which is an alias for rowid. */
04202     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, 0);
04203     sqlite3_result_value(pContext, pVal);
04204   }
04205   return SQLITE_OK;
04206 }
04207 
04208 /* This is the xRowid method.  The SQLite core calls this routine to
04209 ** retrieve the rowid for the current row of the result set.  fts3
04210 ** exposes %_content.docid as the rowid for the virtual table.  The
04211 ** rowid should be written to *pRowid.
04212 */
04213 static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
04214   fulltext_cursor *c = (fulltext_cursor *) pCursor;
04215 
04216   *pRowid = sqlite3_column_int64(c->pStmt, 0);
04217   return SQLITE_OK;
04218 }
04219 
04220 /* Add all terms in [zText] to pendingTerms table.  If [iColumn] > 0,
04221 ** we also store positions and offsets in the hash table using that
04222 ** column number.
04223 */
04224 static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid,
04225                       const char *zText, int iColumn){
04226   sqlite3_tokenizer *pTokenizer = v->pTokenizer;
04227   sqlite3_tokenizer_cursor *pCursor;
04228   const char *pToken;
04229   int nTokenBytes;
04230   int iStartOffset, iEndOffset, iPosition;
04231   int rc;
04232 
04233   rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
04234   if( rc!=SQLITE_OK ) return rc;
04235 
04236   pCursor->pTokenizer = pTokenizer;
04237   while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor,
04238                                                    &pToken, &nTokenBytes,
04239                                                    &iStartOffset, &iEndOffset,
04240                                                    &iPosition)) ){
04241     DLCollector *p;
04242     int nData;                   /* Size of doclist before our update. */
04243 
04244     /* Positions can't be negative; we use -1 as a terminator
04245      * internally.  Token can't be NULL or empty. */
04246     if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){
04247       rc = SQLITE_ERROR;
04248       break;
04249     }
04250 
04251     p = fts3HashFind(&v->pendingTerms, pToken, nTokenBytes);
04252     if( p==NULL ){
04253       nData = 0;
04254       p = dlcNew(iDocid, DL_DEFAULT);
04255       fts3HashInsert(&v->pendingTerms, pToken, nTokenBytes, p);
04256 
04257       /* Overhead for our hash table entry, the key, and the value. */
04258       v->nPendingData += sizeof(struct fts3HashElem)+sizeof(*p)+nTokenBytes;
04259     }else{
04260       nData = p->b.nData;
04261       if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid);
04262     }
04263     if( iColumn>=0 ){
04264       dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset);
04265     }
04266 
04267     /* Accumulate data added by dlcNew or dlcNext, and dlcAddPos. */
04268     v->nPendingData += p->b.nData-nData;
04269   }
04270 
04271   /* TODO(shess) Check return?  Should this be able to cause errors at
04272   ** this point?  Actually, same question about sqlite3_finalize(),
04273   ** though one could argue that failure there means that the data is
04274   ** not durable.  *ponder*
04275   */
04276   pTokenizer->pModule->xClose(pCursor);
04277   if( SQLITE_DONE == rc ) return SQLITE_OK;
04278   return rc;
04279 }
04280 
04281 /* Add doclists for all terms in [pValues] to pendingTerms table. */
04282 static int insertTerms(fulltext_vtab *v, sqlite_int64 iDocid,
04283                        sqlite3_value **pValues){
04284   int i;
04285   for(i = 0; i < v->nColumn ; ++i){
04286     char *zText = (char*)sqlite3_value_text(pValues[i]);
04287     int rc = buildTerms(v, iDocid, zText, i);
04288     if( rc!=SQLITE_OK ) return rc;
04289   }
04290   return SQLITE_OK;
04291 }
04292 
04293 /* Add empty doclists for all terms in the given row's content to
04294 ** pendingTerms.
04295 */
04296 static int deleteTerms(fulltext_vtab *v, sqlite_int64 iDocid){
04297   const char **pValues;
04298   int i, rc;
04299 
04300   /* TODO(shess) Should we allow such tables at all? */
04301   if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR;
04302 
04303   rc = content_select(v, iDocid, &pValues);
04304   if( rc!=SQLITE_OK ) return rc;
04305 
04306   for(i = 0 ; i < v->nColumn; ++i) {
04307     rc = buildTerms(v, iDocid, pValues[i], -1);
04308     if( rc!=SQLITE_OK ) break;
04309   }
04310 
04311   freeStringArray(v->nColumn, pValues);
04312   return SQLITE_OK;
04313 }
04314 
04315 /* TODO(shess) Refactor the code to remove this forward decl. */
04316 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid);
04317 
04318 /* Insert a row into the %_content table; set *piDocid to be the ID of the
04319 ** new row.  Add doclists for terms to pendingTerms.
04320 */
04321 static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestDocid,
04322                         sqlite3_value **pValues, sqlite_int64 *piDocid){
04323   int rc;
04324 
04325   rc = content_insert(v, pRequestDocid, pValues);  /* execute an SQL INSERT */
04326   if( rc!=SQLITE_OK ) return rc;
04327 
04328   /* docid column is an alias for rowid. */
04329   *piDocid = sqlite3_last_insert_rowid(v->db);
04330   rc = initPendingTerms(v, *piDocid);
04331   if( rc!=SQLITE_OK ) return rc;
04332 
04333   return insertTerms(v, *piDocid, pValues);
04334 }
04335 
04336 /* Delete a row from the %_content table; add empty doclists for terms
04337 ** to pendingTerms.
04338 */
04339 static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
04340   int rc = initPendingTerms(v, iRow);
04341   if( rc!=SQLITE_OK ) return rc;
04342 
04343   rc = deleteTerms(v, iRow);
04344   if( rc!=SQLITE_OK ) return rc;
04345 
04346   return content_delete(v, iRow);  /* execute an SQL DELETE */
04347 }
04348 
04349 /* Update a row in the %_content table; add delete doclists to
04350 ** pendingTerms for old terms not in the new data, add insert doclists
04351 ** to pendingTerms for terms in the new data.
04352 */
04353 static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
04354                         sqlite3_value **pValues){
04355   int rc = initPendingTerms(v, iRow);
04356   if( rc!=SQLITE_OK ) return rc;
04357 
04358   /* Generate an empty doclist for each term that previously appeared in this
04359    * row. */
04360   rc = deleteTerms(v, iRow);
04361   if( rc!=SQLITE_OK ) return rc;
04362 
04363   rc = content_update(v, pValues, iRow);  /* execute an SQL UPDATE */
04364   if( rc!=SQLITE_OK ) return rc;
04365 
04366   /* Now add positions for terms which appear in the updated row. */
04367   return insertTerms(v, iRow, pValues);
04368 }
04369 
04370 /*******************************************************************/
04371 /* InteriorWriter is used to collect terms and block references into
04372 ** interior nodes in %_segments.  See commentary at top of file for
04373 ** format.
04374 */
04375 
04376 /* How large interior nodes can grow. */
04377 #define INTERIOR_MAX 2048
04378 
04379 /* Minimum number of terms per interior node (except the root). This
04380 ** prevents large terms from making the tree too skinny - must be >0
04381 ** so that the tree always makes progress.  Note that the min tree
04382 ** fanout will be INTERIOR_MIN_TERMS+1.
04383 */
04384 #define INTERIOR_MIN_TERMS 7
04385 #if INTERIOR_MIN_TERMS<1
04386 # error INTERIOR_MIN_TERMS must be greater than 0.
04387 #endif
04388 
04389 /* ROOT_MAX controls how much data is stored inline in the segment
04390 ** directory.
04391 */
04392 /* TODO(shess) Push ROOT_MAX down to whoever is writing things.  It's
04393 ** only here so that interiorWriterRootInfo() and leafWriterRootInfo()
04394 ** can both see it, but if the caller passed it in, we wouldn't even
04395 ** need a define.
04396 */
04397 #define ROOT_MAX 1024
04398 #if ROOT_MAX<VARINT_MAX*2
04399 # error ROOT_MAX must have enough space for a header.
04400 #endif
04401 
04402 /* InteriorBlock stores a linked-list of interior blocks while a lower
04403 ** layer is being constructed.
04404 */
04405 typedef struct InteriorBlock {
04406   DataBuffer term;           /* Leftmost term in block's subtree. */
04407   DataBuffer data;           /* Accumulated data for the block. */
04408   struct InteriorBlock *next;
04409 } InteriorBlock;
04410 
04411 static InteriorBlock *interiorBlockNew(int iHeight, sqlite_int64 iChildBlock,
04412                                        const char *pTerm, int nTerm){
04413   InteriorBlock *block = sqlite3_malloc(sizeof(InteriorBlock));
04414   char c[VARINT_MAX+VARINT_MAX];
04415   int n;
04416 
04417   if( block ){
04418     memset(block, 0, sizeof(*block));
04419     dataBufferInit(&block->term, 0);
04420     dataBufferReplace(&block->term, pTerm, nTerm);
04421 
04422     n = fts3PutVarint(c, iHeight);
04423     n += fts3PutVarint(c+n, iChildBlock);
04424     dataBufferInit(&block->data, INTERIOR_MAX);
04425     dataBufferReplace(&block->data, c, n);
04426   }
04427   return block;
04428 }
04429 
04430 #ifndef NDEBUG
04431 /* Verify that the data is readable as an interior node. */
04432 static void interiorBlockValidate(InteriorBlock *pBlock){
04433   const char *pData = pBlock->data.pData;
04434   int nData = pBlock->data.nData;
04435   int n, iDummy;
04436   sqlite_int64 iBlockid;
04437 
04438   assert( nData>0 );
04439   assert( pData!=0 );
04440   assert( pData+nData>pData );
04441 
04442   /* Must lead with height of node as a varint(n), n>0 */
04443   n = fts3GetVarint32(pData, &iDummy);
04444   assert( n>0 );
04445   assert( iDummy>0 );
04446   assert( n<nData );
04447   pData += n;
04448   nData -= n;
04449 
04450   /* Must contain iBlockid. */
04451   n = fts3GetVarint(pData, &iBlockid);
04452   assert( n>0 );
04453   assert( n<=nData );
04454   pData += n;
04455   nData -= n;
04456 
04457   /* Zero or more terms of positive length */
04458   if( nData!=0 ){
04459     /* First term is not delta-encoded. */
04460     n = fts3GetVarint32(pData, &iDummy);
04461     assert( n>0 );
04462     assert( iDummy>0 );
04463     assert( n+iDummy>0);
04464     assert( n+iDummy<=nData );
04465     pData += n+iDummy;
04466     nData -= n+iDummy;
04467 
04468     /* Following terms delta-encoded. */
04469     while( nData!=0 ){
04470       /* Length of shared prefix. */
04471       n = fts3GetVarint32(pData, &iDummy);
04472       assert( n>0 );
04473       assert( iDummy>=0 );
04474       assert( n<nData );
04475       pData += n;
04476       nData -= n;
04477 
04478       /* Length and data of distinct suffix. */
04479       n = fts3GetVarint32(pData, &iDummy);
04480       assert( n>0 );
04481       assert( iDummy>0 );
04482       assert( n+iDummy>0);
04483       assert( n+iDummy<=nData );
04484       pData += n+iDummy;
04485       nData -= n+iDummy;
04486     }
04487   }
04488 }
04489 #define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x)
04490 #else
04491 #define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 )
04492 #endif
04493 
04494 typedef struct InteriorWriter {
04495   int iHeight;                   /* from 0 at leaves. */
04496   InteriorBlock *first, *last;
04497   struct InteriorWriter *parentWriter;
04498 
04499   DataBuffer term;               /* Last term written to block "last". */
04500   sqlite_int64 iOpeningChildBlock; /* First child block in block "last". */
04501 #ifndef NDEBUG
04502   sqlite_int64 iLastChildBlock;  /* for consistency checks. */
04503 #endif
04504 } InteriorWriter;
04505 
04506 /* Initialize an interior node where pTerm[nTerm] marks the leftmost
04507 ** term in the tree.  iChildBlock is the leftmost child block at the
04508 ** next level down the tree.
04509 */
04510 static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm,
04511                                sqlite_int64 iChildBlock,
04512                                InteriorWriter *pWriter){
04513   InteriorBlock *block;
04514   assert( iHeight>0 );
04515   CLEAR(pWriter);
04516 
04517   pWriter->iHeight = iHeight;
04518   pWriter->iOpeningChildBlock = iChildBlock;
04519 #ifndef NDEBUG
04520   pWriter->iLastChildBlock = iChildBlock;
04521 #endif
04522   block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm);
04523   pWriter->last = pWriter->first = block;
04524   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
04525   dataBufferInit(&pWriter->term, 0);
04526 }
04527 
04528 /* Append the child node rooted at iChildBlock to the interior node,
04529 ** with pTerm[nTerm] as the leftmost term in iChildBlock's subtree.
04530 */
04531 static void interiorWriterAppend(InteriorWriter *pWriter,
04532                                  const char *pTerm, int nTerm,
04533                                  sqlite_int64 iChildBlock){
04534   char c[VARINT_MAX+VARINT_MAX];
04535   int n, nPrefix = 0;
04536 
04537   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
04538 
04539   /* The first term written into an interior node is actually
04540   ** associated with the second child added (the first child was added
04541   ** in interiorWriterInit, or in the if clause at the bottom of this
04542   ** function).  That term gets encoded straight up, with nPrefix left
04543   ** at 0.
04544   */
04545   if( pWriter->term.nData==0 ){
04546     n = fts3PutVarint(c, nTerm);
04547   }else{
04548     while( nPrefix<pWriter->term.nData &&
04549            pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
04550       nPrefix++;
04551     }
04552 
04553     n = fts3PutVarint(c, nPrefix);
04554     n += fts3PutVarint(c+n, nTerm-nPrefix);
04555   }
04556 
04557 #ifndef NDEBUG
04558   pWriter->iLastChildBlock++;
04559 #endif
04560   assert( pWriter->iLastChildBlock==iChildBlock );
04561 
04562   /* Overflow to a new block if the new term makes the current block
04563   ** too big, and the current block already has enough terms.
04564   */
04565   if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX &&
04566       iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){
04567     pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock,
04568                                            pTerm, nTerm);
04569     pWriter->last = pWriter->last->next;
04570     pWriter->iOpeningChildBlock = iChildBlock;
04571     dataBufferReset(&pWriter->term);
04572   }else{
04573     dataBufferAppend2(&pWriter->last->data, c, n,
04574                       pTerm+nPrefix, nTerm-nPrefix);
04575     dataBufferReplace(&pWriter->term, pTerm, nTerm);
04576   }
04577   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
04578 }
04579 
04580 /* Free the space used by pWriter, including the linked-list of
04581 ** InteriorBlocks, and parentWriter, if present.
04582 */
04583 static int interiorWriterDestroy(InteriorWriter *pWriter){
04584   InteriorBlock *block = pWriter->first;
04585 
04586   while( block!=NULL ){
04587     InteriorBlock *b = block;
04588     block = block->next;
04589     dataBufferDestroy(&b->term);
04590     dataBufferDestroy(&b->data);
04591     sqlite3_free(b);
04592   }
04593   if( pWriter->parentWriter!=NULL ){
04594     interiorWriterDestroy(pWriter->parentWriter);
04595     sqlite3_free(pWriter->parentWriter);
04596   }
04597   dataBufferDestroy(&pWriter->term);
04598   SCRAMBLE(pWriter);
04599   return SQLITE_OK;
04600 }
04601 
04602 /* If pWriter can fit entirely in ROOT_MAX, return it as the root info
04603 ** directly, leaving *piEndBlockid unchanged.  Otherwise, flush
04604 ** pWriter to %_segments, building a new layer of interior nodes, and
04605 ** recursively ask for their root into.
04606 */
04607 static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter,
04608                                   char **ppRootInfo, int *pnRootInfo,
04609                                   sqlite_int64 *piEndBlockid){
04610   InteriorBlock *block = pWriter->first;
04611   sqlite_int64 iBlockid = 0;
04612   int rc;
04613 
04614   /* If we can fit the segment inline */
04615   if( block==pWriter->last && block->data.nData<ROOT_MAX ){
04616     *ppRootInfo = block->data.pData;
04617     *pnRootInfo = block->data.nData;
04618     return SQLITE_OK;
04619   }
04620 
04621   /* Flush the first block to %_segments, and create a new level of
04622   ** interior node.
04623   */
04624   ASSERT_VALID_INTERIOR_BLOCK(block);
04625   rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
04626   if( rc!=SQLITE_OK ) return rc;
04627   *piEndBlockid = iBlockid;
04628 
04629   pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter));
04630   interiorWriterInit(pWriter->iHeight+1,
04631                      block->term.pData, block->term.nData,
04632                      iBlockid, pWriter->parentWriter);
04633 
04634   /* Flush additional blocks and append to the higher interior
04635   ** node.
04636   */
04637   for(block=block->next; block!=NULL; block=block->next){
04638     ASSERT_VALID_INTERIOR_BLOCK(block);
04639     rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
04640     if( rc!=SQLITE_OK ) return rc;
04641     *piEndBlockid = iBlockid;
04642 
04643     interiorWriterAppend(pWriter->parentWriter,
04644                          block->term.pData, block->term.nData, iBlockid);
04645   }
04646 
04647   /* Parent node gets the chance to be the root. */
04648   return interiorWriterRootInfo(v, pWriter->parentWriter,
04649                                 ppRootInfo, pnRootInfo, piEndBlockid);
04650 }
04651 
04652 /****************************************************************/
04653 /* InteriorReader is used to read off the data from an interior node
04654 ** (see comment at top of file for the format).
04655 */
04656 typedef struct InteriorReader {
04657   const char *pData;
04658   int nData;
04659 
04660   DataBuffer term;          /* previous term, for decoding term delta. */
04661 
04662   sqlite_int64 iBlockid;
04663 } InteriorReader;
04664 
04665 static void interiorReaderDestroy(InteriorReader *pReader){
04666   dataBufferDestroy(&pReader->term);
04667   SCRAMBLE(pReader);
04668 }
04669 
04670 /* TODO(shess) The assertions are great, but what if we're in NDEBUG
04671 ** and the blob is empty or otherwise contains suspect data?
04672 */
04673 static void interiorReaderInit(const char *pData, int nData,
04674                                InteriorReader *pReader){
04675   int n, nTerm;
04676 
04677   /* Require at least the leading flag byte */
04678   assert( nData>0 );
04679   assert( pData[0]!='\0' );
04680 
04681   CLEAR(pReader);
04682 
04683   /* Decode the base blockid, and set the cursor to the first term. */
04684   n = fts3GetVarint(pData+1, &pReader->iBlockid);
04685   assert( 1+n<=nData );
04686   pReader->pData = pData+1+n;
04687   pReader->nData = nData-(1+n);
04688 
04689   /* A single-child interior node (such as when a leaf node was too
04690   ** large for the segment directory) won't have any terms.
04691   ** Otherwise, decode the first term.
04692   */
04693   if( pReader->nData==0 ){
04694     dataBufferInit(&pReader->term, 0);
04695   }else{
04696     n = fts3GetVarint32(pReader->pData, &nTerm);
04697     dataBufferInit(&pReader->term, nTerm);
04698     dataBufferReplace(&pReader->term, pReader->pData+n, nTerm);
04699     assert( n+nTerm<=pReader->nData );
04700     pReader->pData += n+nTerm;
04701     pReader->nData -= n+nTerm;
04702   }
04703 }
04704 
04705 static int interiorReaderAtEnd(InteriorReader *pReader){
04706   return pReader->term.nData==0;
04707 }
04708 
04709 static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){
04710   return pReader->iBlockid;
04711 }
04712 
04713 static int interiorReaderTermBytes(InteriorReader *pReader){
04714   assert( !interiorReaderAtEnd(pReader) );
04715   return pReader->term.nData;
04716 }
04717 static const char *interiorReaderTerm(InteriorReader *pReader){
04718   assert( !interiorReaderAtEnd(pReader) );
04719   return pReader->term.pData;
04720 }
04721 
04722 /* Step forward to the next term in the node. */
04723 static void interiorReaderStep(InteriorReader *pReader){
04724   assert( !interiorReaderAtEnd(pReader) );
04725 
04726   /* If the last term has been read, signal eof, else construct the
04727   ** next term.
04728   */
04729   if( pReader->nData==0 ){
04730     dataBufferReset(&pReader->term);
04731   }else{
04732     int n, nPrefix, nSuffix;
04733 
04734     n = fts3GetVarint32(pReader->pData, &nPrefix);
04735     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
04736 
04737     /* Truncate the current term and append suffix data. */
04738     pReader->term.nData = nPrefix;
04739     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
04740 
04741     assert( n+nSuffix<=pReader->nData );
04742     pReader->pData += n+nSuffix;
04743     pReader->nData -= n+nSuffix;
04744   }
04745   pReader->iBlockid++;
04746 }
04747 
04748 /* Compare the current term to pTerm[nTerm], returning strcmp-style
04749 ** results.  If isPrefix, equality means equal through nTerm bytes.
04750 */
04751 static int interiorReaderTermCmp(InteriorReader *pReader,
04752                                  const char *pTerm, int nTerm, int isPrefix){
04753   const char *pReaderTerm = interiorReaderTerm(pReader);
04754   int nReaderTerm = interiorReaderTermBytes(pReader);
04755   int c, n = nReaderTerm<nTerm ? nReaderTerm : nTerm;
04756 
04757   if( n==0 ){
04758     if( nReaderTerm>0 ) return -1;
04759     if( nTerm>0 ) return 1;
04760     return 0;
04761   }
04762 
04763   c = memcmp(pReaderTerm, pTerm, n);
04764   if( c!=0 ) return c;
04765   if( isPrefix && n==nTerm ) return 0;
04766   return nReaderTerm - nTerm;
04767 }
04768 
04769 /****************************************************************/
04770 /* LeafWriter is used to collect terms and associated doclist data
04771 ** into leaf blocks in %_segments (see top of file for format info).
04772 ** Expected usage is:
04773 **
04774 ** LeafWriter writer;
04775 ** leafWriterInit(0, 0, &writer);
04776 ** while( sorted_terms_left_to_process ){
04777 **   // data is doclist data for that term.
04778 **   rc = leafWriterStep(v, &writer, pTerm, nTerm, pData, nData);
04779 **   if( rc!=SQLITE_OK ) goto err;
04780 ** }
04781 ** rc = leafWriterFinalize(v, &writer);
04782 **err:
04783 ** leafWriterDestroy(&writer);
04784 ** return rc;
04785 **
04786 ** leafWriterStep() may write a collected leaf out to %_segments.
04787 ** leafWriterFinalize() finishes writing any buffered data and stores
04788 ** a root node in %_segdir.  leafWriterDestroy() frees all buffers and
04789 ** InteriorWriters allocated as part of writing this segment.
04790 **
04791 ** TODO(shess) Document leafWriterStepMerge().
04792 */
04793 
04794 /* Put terms with data this big in their own block. */
04795 #define STANDALONE_MIN 1024
04796 
04797 /* Keep leaf blocks below this size. */
04798 #define LEAF_MAX 2048
04799 
04800 typedef struct LeafWriter {
04801   int iLevel;
04802   int idx;
04803   sqlite_int64 iStartBlockid;     /* needed to create the root info */
04804   sqlite_int64 iEndBlockid;       /* when we're done writing. */
04805 
04806   DataBuffer term;                /* previous encoded term */
04807   DataBuffer data;                /* encoding buffer */
04808 
04809   /* bytes of first term in the current node which distinguishes that
04810   ** term from the last term of the previous node.
04811   */
04812   int nTermDistinct;
04813 
04814   InteriorWriter parentWriter;    /* if we overflow */
04815   int has_parent;
04816 } LeafWriter;
04817 
04818 static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){
04819   CLEAR(pWriter);
04820   pWriter->iLevel = iLevel;
04821   pWriter->idx = idx;
04822 
04823   dataBufferInit(&pWriter->term, 32);
04824 
04825   /* Start out with a reasonably sized block, though it can grow. */
04826   dataBufferInit(&pWriter->data, LEAF_MAX);
04827 }
04828 
04829 #ifndef NDEBUG
04830 /* Verify that the data is readable as a leaf node. */
04831 static void leafNodeValidate(const char *pData, int nData){
04832   int n, iDummy;
04833 
04834   if( nData==0 ) return;
04835   assert( nData>0 );
04836   assert( pData!=0 );
04837   assert( pData+nData>pData );
04838 
04839   /* Must lead with a varint(0) */
04840   n = fts3GetVarint32(pData, &iDummy);
04841   assert( iDummy==0 );
04842   assert( n>0 );
04843   assert( n<nData );
04844   pData += n;
04845   nData -= n;
04846 
04847   /* Leading term length and data must fit in buffer. */
04848   n = fts3GetVarint32(pData, &iDummy);
04849   assert( n>0 );
04850   assert( iDummy>0 );
04851   assert( n+iDummy>0 );
04852   assert( n+iDummy<nData );
04853   pData += n+iDummy;
04854   nData -= n+iDummy;
04855 
04856   /* Leading term's doclist length and data must fit. */
04857   n = fts3GetVarint32(pData, &iDummy);
04858   assert( n>0 );
04859   assert( iDummy>0 );
04860   assert( n+iDummy>0 );
04861   assert( n+iDummy<=nData );
04862   ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
04863   pData += n+iDummy;
04864   nData -= n+iDummy;
04865 
04866   /* Verify that trailing terms and doclists also are readable. */
04867   while( nData!=0 ){
04868     n = fts3GetVarint32(pData, &iDummy);
04869     assert( n>0 );
04870     assert( iDummy>=0 );
04871     assert( n<nData );
04872     pData += n;
04873     nData -= n;
04874     n = fts3GetVarint32(pData, &iDummy);
04875     assert( n>0 );
04876     assert( iDummy>0 );
04877     assert( n+iDummy>0 );
04878     assert( n+iDummy<nData );
04879     pData += n+iDummy;
04880     nData -= n+iDummy;
04881 
04882     n = fts3GetVarint32(pData, &iDummy);
04883     assert( n>0 );
04884     assert( iDummy>0 );
04885     assert( n+iDummy>0 );
04886     assert( n+iDummy<=nData );
04887     ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
04888     pData += n+iDummy;
04889     nData -= n+iDummy;
04890   }
04891 }
04892 #define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n)
04893 #else
04894 #define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 )
04895 #endif
04896 
04897 /* Flush the current leaf node to %_segments, and adding the resulting
04898 ** blockid and the starting term to the interior node which will
04899 ** contain it.
04900 */
04901 static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter,
04902                                    int iData, int nData){
04903   sqlite_int64 iBlockid = 0;
04904   const char *pStartingTerm;
04905   int nStartingTerm, rc, n;
04906 
04907   /* Must have the leading varint(0) flag, plus at least some
04908   ** valid-looking data.
04909   */
04910   assert( nData>2 );
04911   assert( iData>=0 );
04912   assert( iData+nData<=pWriter->data.nData );
04913   ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData);
04914 
04915   rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid);
04916   if( rc!=SQLITE_OK ) return rc;
04917   assert( iBlockid!=0 );
04918 
04919   /* Reconstruct the first term in the leaf for purposes of building
04920   ** the interior node.
04921   */
04922   n = fts3GetVarint32(pWriter->data.pData+iData+1, &nStartingTerm);
04923   pStartingTerm = pWriter->data.pData+iData+1+n;
04924   assert( pWriter->data.nData>iData+1+n+nStartingTerm );
04925   assert( pWriter->nTermDistinct>0 );
04926   assert( pWriter->nTermDistinct<=nStartingTerm );
04927   nStartingTerm = pWriter->nTermDistinct;
04928 
04929   if( pWriter->has_parent ){
04930     interiorWriterAppend(&pWriter->parentWriter,
04931                          pStartingTerm, nStartingTerm, iBlockid);
04932   }else{
04933     interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid,
04934                        &pWriter->parentWriter);
04935     pWriter->has_parent = 1;
04936   }
04937 
04938   /* Track the span of this segment's leaf nodes. */
04939   if( pWriter->iEndBlockid==0 ){
04940     pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid;
04941   }else{
04942     pWriter->iEndBlockid++;
04943     assert( iBlockid==pWriter->iEndBlockid );
04944   }
04945 
04946   return SQLITE_OK;
04947 }
04948 static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){
04949   int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData);
04950   if( rc!=SQLITE_OK ) return rc;
04951 
04952   /* Re-initialize the output buffer. */
04953   dataBufferReset(&pWriter->data);
04954 
04955   return SQLITE_OK;
04956 }
04957 
04958 /* Fetch the root info for the segment.  If the entire leaf fits
04959 ** within ROOT_MAX, then it will be returned directly, otherwise it
04960 ** will be flushed and the root info will be returned from the
04961 ** interior node.  *piEndBlockid is set to the blockid of the last
04962 ** interior or leaf node written to disk (0 if none are written at
04963 ** all).
04964 */
04965 static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter,
04966                               char **ppRootInfo, int *pnRootInfo,
04967                               sqlite_int64 *piEndBlockid){
04968   /* we can fit the segment entirely inline */
04969   if( !pWriter->has_parent && pWriter->data.nData<ROOT_MAX ){
04970     *ppRootInfo = pWriter->data.pData;
04971     *pnRootInfo = pWriter->data.nData;
04972     *piEndBlockid = 0;
04973     return SQLITE_OK;
04974   }
04975 
04976   /* Flush remaining leaf data. */
04977   if( pWriter->data.nData>0 ){
04978     int rc = leafWriterFlush(v, pWriter);
04979     if( rc!=SQLITE_OK ) return rc;
04980   }
04981 
04982   /* We must have flushed a leaf at some point. */
04983   assert( pWriter->has_parent );
04984 
04985   /* Tenatively set the end leaf blockid as the end blockid.  If the
04986   ** interior node can be returned inline, this will be the final
04987   ** blockid, otherwise it will be overwritten by
04988   ** interiorWriterRootInfo().
04989   */
04990   *piEndBlockid = pWriter->iEndBlockid;
04991 
04992   return interiorWriterRootInfo(v, &pWriter->parentWriter,
04993                                 ppRootInfo, pnRootInfo, piEndBlockid);
04994 }
04995 
04996 /* Collect the rootInfo data and store it into the segment directory.
04997 ** This has the effect of flushing the segment's leaf data to
04998 ** %_segments, and also flushing any interior nodes to %_segments.
04999 */
05000 static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){
05001   sqlite_int64 iEndBlockid;
05002   char *pRootInfo;
05003   int rc, nRootInfo;
05004 
05005   rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid);
05006   if( rc!=SQLITE_OK ) return rc;
05007 
05008   /* Don't bother storing an entirely empty segment. */
05009   if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK;
05010 
05011   return segdir_set(v, pWriter->iLevel, pWriter->idx,
05012                     pWriter->iStartBlockid, pWriter->iEndBlockid,
05013                     iEndBlockid, pRootInfo, nRootInfo);
05014 }
05015 
05016 static void leafWriterDestroy(LeafWriter *pWriter){
05017   if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter);
05018   dataBufferDestroy(&pWriter->term);
05019   dataBufferDestroy(&pWriter->data);
05020 }
05021 
05022 /* Encode a term into the leafWriter, delta-encoding as appropriate.
05023 ** Returns the length of the new term which distinguishes it from the
05024 ** previous term, which can be used to set nTermDistinct when a node
05025 ** boundary is crossed.
05026 */
05027 static int leafWriterEncodeTerm(LeafWriter *pWriter,
05028                                 const char *pTerm, int nTerm){
05029   char c[VARINT_MAX+VARINT_MAX];
05030   int n, nPrefix = 0;
05031 
05032   assert( nTerm>0 );
05033   while( nPrefix<pWriter->term.nData &&
05034          pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
05035     nPrefix++;
05036     /* Failing this implies that the terms weren't in order. */
05037     assert( nPrefix<nTerm );
05038   }
05039 
05040   if( pWriter->data.nData==0 ){
05041     /* Encode the node header and leading term as:
05042     **  varint(0)
05043     **  varint(nTerm)
05044     **  char pTerm[nTerm]
05045     */
05046     n = fts3PutVarint(c, '\0');
05047     n += fts3PutVarint(c+n, nTerm);
05048     dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm);
05049   }else{
05050     /* Delta-encode the term as:
05051     **  varint(nPrefix)
05052     **  varint(nSuffix)
05053     **  char pTermSuffix[nSuffix]
05054     */
05055     n = fts3PutVarint(c, nPrefix);
05056     n += fts3PutVarint(c+n, nTerm-nPrefix);
05057     dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix);
05058   }
05059   dataBufferReplace(&pWriter->term, pTerm, nTerm);
05060 
05061   return nPrefix+1;
05062 }
05063 
05064 /* Used to avoid a memmove when a large amount of doclist data is in
05065 ** the buffer.  This constructs a node and term header before
05066 ** iDoclistData and flushes the resulting complete node using
05067 ** leafWriterInternalFlush().
05068 */
05069 static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter,
05070                                  const char *pTerm, int nTerm,
05071                                  int iDoclistData){
05072   char c[VARINT_MAX+VARINT_MAX];
05073   int iData, n = fts3PutVarint(c, 0);
05074   n += fts3PutVarint(c+n, nTerm);
05075 
05076   /* There should always be room for the header.  Even if pTerm shared
05077   ** a substantial prefix with the previous term, the entire prefix
05078   ** could be constructed from earlier data in the doclist, so there
05079   ** should be room.
05080   */
05081   assert( iDoclistData>=n+nTerm );
05082 
05083   iData = iDoclistData-(n+nTerm);
05084   memcpy(pWriter->data.pData+iData, c, n);
05085   memcpy(pWriter->data.pData+iData+n, pTerm, nTerm);
05086 
05087   return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData);
05088 }
05089 
05090 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
05091 ** %_segments.
05092 */
05093 static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter,
05094                                const char *pTerm, int nTerm,
05095                                DLReader *pReaders, int nReaders){
05096   char c[VARINT_MAX+VARINT_MAX];
05097   int iTermData = pWriter->data.nData, iDoclistData;
05098   int i, nData, n, nActualData, nActual, rc, nTermDistinct;
05099 
05100   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
05101   nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm);
05102 
05103   /* Remember nTermDistinct if opening a new node. */
05104   if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct;
05105 
05106   iDoclistData = pWriter->data.nData;
05107 
05108   /* Estimate the length of the merged doclist so we can leave space
05109   ** to encode it.
05110   */
05111   for(i=0, nData=0; i<nReaders; i++){
05112     nData += dlrAllDataBytes(&pReaders[i]);
05113   }
05114   n = fts3PutVarint(c, nData);
05115   dataBufferAppend(&pWriter->data, c, n);
05116 
05117   docListMerge(&pWriter->data, pReaders, nReaders);
05118   ASSERT_VALID_DOCLIST(DL_DEFAULT,
05119                        pWriter->data.pData+iDoclistData+n,
05120                        pWriter->data.nData-iDoclistData-n, NULL);
05121 
05122   /* The actual amount of doclist data at this point could be smaller
05123   ** than the length we encoded.  Additionally, the space required to
05124   ** encode this length could be smaller.  For small doclists, this is
05125   ** not a big deal, we can just use memmove() to adjust things.
05126   */
05127   nActualData = pWriter->data.nData-(iDoclistData+n);
05128   nActual = fts3PutVarint(c, nActualData);
05129   assert( nActualData<=nData );
05130   assert( nActual<=n );
05131 
05132   /* If the new doclist is big enough for force a standalone leaf
05133   ** node, we can immediately flush it inline without doing the
05134   ** memmove().
05135   */
05136   /* TODO(shess) This test matches leafWriterStep(), which does this
05137   ** test before it knows the cost to varint-encode the term and
05138   ** doclist lengths.  At some point, change to
05139   ** pWriter->data.nData-iTermData>STANDALONE_MIN.
05140   */
05141   if( nTerm+nActualData>STANDALONE_MIN ){
05142     /* Push leaf node from before this term. */
05143     if( iTermData>0 ){
05144       rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
05145       if( rc!=SQLITE_OK ) return rc;
05146 
05147       pWriter->nTermDistinct = nTermDistinct;
05148     }
05149 
05150     /* Fix the encoded doclist length. */
05151     iDoclistData += n - nActual;
05152     memcpy(pWriter->data.pData+iDoclistData, c, nActual);
05153 
05154     /* Push the standalone leaf node. */
05155     rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData);
05156     if( rc!=SQLITE_OK ) return rc;
05157 
05158     /* Leave the node empty. */
05159     dataBufferReset(&pWriter->data);
05160 
05161     return rc;
05162   }
05163 
05164   /* At this point, we know that the doclist was small, so do the
05165   ** memmove if indicated.
05166   */
05167   if( nActual<n ){
05168     memmove(pWriter->data.pData+iDoclistData+nActual,
05169             pWriter->data.pData+iDoclistData+n,
05170             pWriter->data.nData-(iDoclistData+n));
05171     pWriter->data.nData -= n-nActual;
05172   }
05173 
05174   /* Replace written length with actual length. */
05175   memcpy(pWriter->data.pData+iDoclistData, c, nActual);
05176 
05177   /* If the node is too large, break things up. */
05178   /* TODO(shess) This test matches leafWriterStep(), which does this
05179   ** test before it knows the cost to varint-encode the term and
05180   ** doclist lengths.  At some point, change to
05181   ** pWriter->data.nData>LEAF_MAX.
05182   */
05183   if( iTermData+nTerm+nActualData>LEAF_MAX ){
05184     /* Flush out the leading data as a node */
05185     rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
05186     if( rc!=SQLITE_OK ) return rc;
05187 
05188     pWriter->nTermDistinct = nTermDistinct;
05189 
05190     /* Rebuild header using the current term */
05191     n = fts3PutVarint(pWriter->data.pData, 0);
05192     n += fts3PutVarint(pWriter->data.pData+n, nTerm);
05193     memcpy(pWriter->data.pData+n, pTerm, nTerm);
05194     n += nTerm;
05195 
05196     /* There should always be room, because the previous encoding
05197     ** included all data necessary to construct the term.
05198     */
05199     assert( n<iDoclistData );
05200     /* So long as STANDALONE_MIN is half or less of LEAF_MAX, the
05201     ** following memcpy() is safe (as opposed to needing a memmove).
05202     */
05203     assert( 2*STANDALONE_MIN<=LEAF_MAX );
05204     assert( n+pWriter->data.nData-iDoclistData<iDoclistData );
05205     memcpy(pWriter->data.pData+n,
05206            pWriter->data.pData+iDoclistData,
05207            pWriter->data.nData-iDoclistData);
05208     pWriter->data.nData -= iDoclistData-n;
05209   }
05210   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
05211 
05212   return SQLITE_OK;
05213 }
05214 
05215 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
05216 ** %_segments.
05217 */
05218 /* TODO(shess) Revise writeZeroSegment() so that doclists are
05219 ** constructed directly in pWriter->data.
05220 */
05221 static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter,
05222                           const char *pTerm, int nTerm,
05223                           const char *pData, int nData){
05224   int rc;
05225   DLReader reader;
05226 
05227   dlrInit(&reader, DL_DEFAULT, pData, nData);
05228   rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1);
05229   dlrDestroy(&reader);
05230 
05231   return rc;
05232 }
05233 
05234 
05235 /****************************************************************/
05236 /* LeafReader is used to iterate over an individual leaf node. */
05237 typedef struct LeafReader {
05238   DataBuffer term;          /* copy of current term. */
05239 
05240   const char *pData;        /* data for current term. */
05241   int nData;
05242 } LeafReader;
05243 
05244 static void leafReaderDestroy(LeafReader *pReader){
05245   dataBufferDestroy(&pReader->term);
05246   SCRAMBLE(pReader);
05247 }
05248 
05249 static int leafReaderAtEnd(LeafReader *pReader){
05250   return pReader->nData<=0;
05251 }
05252 
05253 /* Access the current term. */
05254 static int leafReaderTermBytes(LeafReader *pReader){
05255   return pReader->term.nData;
05256 }
05257 static const char *leafReaderTerm(LeafReader *pReader){
05258   assert( pReader->term.nData>0 );
05259   return pReader->term.pData;
05260 }
05261 
05262 /* Access the doclist data for the current term. */
05263 static int leafReaderDataBytes(LeafReader *pReader){
05264   int nData;
05265   assert( pReader->term.nData>0 );
05266   fts3GetVarint32(pReader->pData, &nData);
05267   return nData;
05268 }
05269 static const char *leafReaderData(LeafReader *pReader){
05270   int n, nData;
05271   assert( pReader->term.nData>0 );
05272   n = fts3GetVarint32(pReader->pData, &nData);
05273   return pReader->pData+n;
05274 }
05275 
05276 static void leafReaderInit(const char *pData, int nData,
05277                            LeafReader *pReader){
05278   int nTerm, n;
05279 
05280   assert( nData>0 );
05281   assert( pData[0]=='\0' );
05282 
05283   CLEAR(pReader);
05284 
05285   /* Read the first term, skipping the header byte. */
05286   n = fts3GetVarint32(pData+1, &nTerm);
05287   dataBufferInit(&pReader->term, nTerm);
05288   dataBufferReplace(&pReader->term, pData+1+n, nTerm);
05289 
05290   /* Position after the first term. */
05291   assert( 1+n+nTerm<nData );
05292   pReader->pData = pData+1+n+nTerm;
05293   pReader->nData = nData-1-n-nTerm;
05294 }
05295 
05296 /* Step the reader forward to the next term. */
05297 static void leafReaderStep(LeafReader *pReader){
05298   int n, nData, nPrefix, nSuffix;
05299   assert( !leafReaderAtEnd(pReader) );
05300 
05301   /* Skip previous entry's data block. */
05302   n = fts3GetVarint32(pReader->pData, &nData);
05303   assert( n+nData<=pReader->nData );
05304   pReader->pData += n+nData;
05305   pReader->nData -= n+nData;
05306 
05307   if( !leafReaderAtEnd(pReader) ){
05308     /* Construct the new term using a prefix from the old term plus a
05309     ** suffix from the leaf data.
05310     */
05311     n = fts3GetVarint32(pReader->pData, &nPrefix);
05312     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
05313     assert( n+nSuffix<pReader->nData );
05314     pReader->term.nData = nPrefix;
05315     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
05316 
05317     pReader->pData += n+nSuffix;
05318     pReader->nData -= n+nSuffix;
05319   }
05320 }
05321 
05322 /* strcmp-style comparison of pReader's current term against pTerm.
05323 ** If isPrefix, equality means equal through nTerm bytes.
05324 */
05325 static int leafReaderTermCmp(LeafReader *pReader,
05326                              const char *pTerm, int nTerm, int isPrefix){
05327   int c, n = pReader->term.nData<nTerm ? pReader->term.nData : nTerm;
05328   if( n==0 ){
05329     if( pReader->term.nData>0 ) return -1;
05330     if(nTerm>0 ) return 1;
05331     return 0;
05332   }
05333 
05334   c = memcmp(pReader->term.pData, pTerm, n);
05335   if( c!=0 ) return c;
05336   if( isPrefix && n==nTerm ) return 0;
05337   return pReader->term.nData - nTerm;
05338 }
05339 
05340 
05341 /****************************************************************/
05342 /* LeavesReader wraps LeafReader to allow iterating over the entire
05343 ** leaf layer of the tree.
05344 */
05345 typedef struct LeavesReader {
05346   int idx;                  /* Index within the segment. */
05347 
05348   sqlite3_stmt *pStmt;      /* Statement we're streaming leaves from. */
05349   int eof;                  /* we've seen SQLITE_DONE from pStmt. */
05350 
05351   LeafReader leafReader;    /* reader for the current leaf. */
05352   DataBuffer rootData;      /* root data for inline. */
05353 } LeavesReader;
05354 
05355 /* Access the current term. */
05356 static int leavesReaderTermBytes(LeavesReader *pReader){
05357   assert( !pReader->eof );
05358   return leafReaderTermBytes(&pReader->leafReader);
05359 }
05360 static const char *leavesReaderTerm(LeavesReader *pReader){
05361   assert( !pReader->eof );
05362   return leafReaderTerm(&pReader->leafReader);
05363 }
05364 
05365 /* Access the doclist data for the current term. */
05366 static int leavesReaderDataBytes(LeavesReader *pReader){
05367   assert( !pReader->eof );
05368   return leafReaderDataBytes(&pReader->leafReader);
05369 }
05370 static const char *leavesReaderData(LeavesReader *pReader){
05371   assert( !pReader->eof );
05372   return leafReaderData(&pReader->leafReader);
05373 }
05374 
05375 static int leavesReaderAtEnd(LeavesReader *pReader){
05376   return pReader->eof;
05377 }
05378 
05379 /* loadSegmentLeaves() may not read all the way to SQLITE_DONE, thus
05380 ** leaving the statement handle open, which locks the table.
05381 */
05382 /* TODO(shess) This "solution" is not satisfactory.  Really, there
05383 ** should be check-in function for all statement handles which
05384 ** arranges to call sqlite3_reset().  This most likely will require
05385 ** modification to control flow all over the place, though, so for now
05386 ** just punt.
05387 **
05388 ** Note the the current system assumes that segment merges will run to
05389 ** completion, which is why this particular probably hasn't arisen in
05390 ** this case.  Probably a brittle assumption.
05391 */
05392 static int leavesReaderReset(LeavesReader *pReader){
05393   return sqlite3_reset(pReader->pStmt);
05394 }
05395 
05396 static void leavesReaderDestroy(LeavesReader *pReader){
05397   /* If idx is -1, that means we're using a non-cached statement
05398   ** handle in the optimize() case, so we need to release it.
05399   */
05400   if( pReader->pStmt!=NULL && pReader->idx==-1 ){
05401     sqlite3_finalize(pReader->pStmt);
05402   }
05403   leafReaderDestroy(&pReader->leafReader);
05404   dataBufferDestroy(&pReader->rootData);
05405   SCRAMBLE(pReader);
05406 }
05407 
05408 /* Initialize pReader with the given root data (if iStartBlockid==0
05409 ** the leaf data was entirely contained in the root), or from the
05410 ** stream of blocks between iStartBlockid and iEndBlockid, inclusive.
05411 */
05412 static int leavesReaderInit(fulltext_vtab *v,
05413                             int idx,
05414                             sqlite_int64 iStartBlockid,
05415                             sqlite_int64 iEndBlockid,
05416                             const char *pRootData, int nRootData,
05417                             LeavesReader *pReader){
05418   CLEAR(pReader);
05419   pReader->idx = idx;
05420 
05421   dataBufferInit(&pReader->rootData, 0);
05422   if( iStartBlockid==0 ){
05423     /* Entire leaf level fit in root data. */
05424     dataBufferReplace(&pReader->rootData, pRootData, nRootData);
05425     leafReaderInit(pReader->rootData.pData, pReader->rootData.nData,
05426                    &pReader->leafReader);
05427   }else{
05428     sqlite3_stmt *s;
05429     int rc = sql_get_leaf_statement(v, idx, &s);
05430     if( rc!=SQLITE_OK ) return rc;
05431 
05432     rc = sqlite3_bind_int64(s, 1, iStartBlockid);
05433     if( rc!=SQLITE_OK ) return rc;
05434 
05435     rc = sqlite3_bind_int64(s, 2, iEndBlockid);
05436     if( rc!=SQLITE_OK ) return rc;
05437 
05438     rc = sqlite3_step(s);
05439     if( rc==SQLITE_DONE ){
05440       pReader->eof = 1;
05441       return SQLITE_OK;
05442     }
05443     if( rc!=SQLITE_ROW ) return rc;
05444 
05445     pReader->pStmt = s;
05446     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
05447                    sqlite3_column_bytes(pReader->pStmt, 0),
05448                    &pReader->leafReader);
05449   }
05450   return SQLITE_OK;
05451 }
05452 
05453 /* Step the current leaf forward to the next term.  If we reach the
05454 ** end of the current leaf, step forward to the next leaf block.
05455 */
05456 static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){
05457   assert( !leavesReaderAtEnd(pReader) );
05458   leafReaderStep(&pReader->leafReader);
05459 
05460   if( leafReaderAtEnd(&pReader->leafReader) ){
05461     int rc;
05462     if( pReader->rootData.pData ){
05463       pReader->eof = 1;
05464       return SQLITE_OK;
05465     }
05466     rc = sqlite3_step(pReader->pStmt);
05467     if( rc!=SQLITE_ROW ){
05468       pReader->eof = 1;
05469       return rc==SQLITE_DONE ? SQLITE_OK : rc;
05470     }
05471     leafReaderDestroy(&pReader->leafReader);
05472     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
05473                    sqlite3_column_bytes(pReader->pStmt, 0),
05474                    &pReader->leafReader);
05475   }
05476   return SQLITE_OK;
05477 }
05478 
05479 /* Order LeavesReaders by their term, ignoring idx.  Readers at eof
05480 ** always sort to the end.
05481 */
05482 static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){
05483   if( leavesReaderAtEnd(lr1) ){
05484     if( leavesReaderAtEnd(lr2) ) return 0;
05485     return 1;
05486   }
05487   if( leavesReaderAtEnd(lr2) ) return -1;
05488 
05489   return leafReaderTermCmp(&lr1->leafReader,
05490                            leavesReaderTerm(lr2), leavesReaderTermBytes(lr2),
05491                            0);
05492 }
05493 
05494 /* Similar to leavesReaderTermCmp(), with additional ordering by idx
05495 ** so that older segments sort before newer segments.
05496 */
05497 static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){
05498   int c = leavesReaderTermCmp(lr1, lr2);
05499   if( c!=0 ) return c;
05500   return lr1->idx-lr2->idx;
05501 }
05502 
05503 /* Assume that pLr[1]..pLr[nLr] are sorted.  Bubble pLr[0] into its
05504 ** sorted position.
05505 */
05506 static void leavesReaderReorder(LeavesReader *pLr, int nLr){
05507   while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){
05508     LeavesReader tmp = pLr[0];
05509     pLr[0] = pLr[1];
05510     pLr[1] = tmp;
05511     nLr--;
05512     pLr++;
05513   }
05514 }
05515 
05516 /* Initializes pReaders with the segments from level iLevel, returning
05517 ** the number of segments in *piReaders.  Leaves pReaders in sorted
05518 ** order.
05519 */
05520 static int leavesReadersInit(fulltext_vtab *v, int iLevel,
05521                              LeavesReader *pReaders, int *piReaders){
05522   sqlite3_stmt *s;
05523   int i, rc = sql_get_statement(v, SEGDIR_SELECT_LEVEL_STMT, &s);
05524   if( rc!=SQLITE_OK ) return rc;
05525 
05526   rc = sqlite3_bind_int(s, 1, iLevel);
05527   if( rc!=SQLITE_OK ) return rc;
05528 
05529   i = 0;
05530   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
05531     sqlite_int64 iStart = sqlite3_column_int64(s, 0);
05532     sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
05533     const char *pRootData = sqlite3_column_blob(s, 2);
05534     int nRootData = sqlite3_column_bytes(s, 2);
05535 
05536     assert( i<MERGE_COUNT );
05537     rc = leavesReaderInit(v, i, iStart, iEnd, pRootData, nRootData,
05538                           &pReaders[i]);
05539     if( rc!=SQLITE_OK ) break;
05540 
05541     i++;
05542   }
05543   if( rc!=SQLITE_DONE ){
05544     while( i-->0 ){
05545       leavesReaderDestroy(&pReaders[i]);
05546     }
05547     return rc;
05548   }
05549 
05550   *piReaders = i;
05551 
05552   /* Leave our results sorted by term, then age. */
05553   while( i-- ){
05554     leavesReaderReorder(pReaders+i, *piReaders-i);
05555   }
05556   return SQLITE_OK;
05557 }
05558 
05559 /* Merge doclists from pReaders[nReaders] into a single doclist, which
05560 ** is written to pWriter.  Assumes pReaders is ordered oldest to
05561 ** newest.
05562 */
05563 /* TODO(shess) Consider putting this inline in segmentMerge(). */
05564 static int leavesReadersMerge(fulltext_vtab *v,
05565                               LeavesReader *pReaders, int nReaders,
05566                               LeafWriter *pWriter){
05567   DLReader dlReaders[MERGE_COUNT];
05568   const char *pTerm = leavesReaderTerm(pReaders);
05569   int i, nTerm = leavesReaderTermBytes(pReaders);
05570 
05571   assert( nReaders<=MERGE_COUNT );
05572 
05573   for(i=0; i<nReaders; i++){
05574     dlrInit(&dlReaders[i], DL_DEFAULT,
05575             leavesReaderData(pReaders+i),
05576             leavesReaderDataBytes(pReaders+i));
05577   }
05578 
05579   return leafWriterStepMerge(v, pWriter, pTerm, nTerm, dlReaders, nReaders);
05580 }
05581 
05582 /* Forward ref due to mutual recursion with segdirNextIndex(). */
05583 static int segmentMerge(fulltext_vtab *v, int iLevel);
05584 
05585 /* Put the next available index at iLevel into *pidx.  If iLevel
05586 ** already has MERGE_COUNT segments, they are merged to a higher
05587 ** level to make room.
05588 */
05589 static int segdirNextIndex(fulltext_vtab *v, int iLevel, int *pidx){
05590   int rc = segdir_max_index(v, iLevel, pidx);
05591   if( rc==SQLITE_DONE ){              /* No segments at iLevel. */
05592     *pidx = 0;
05593   }else if( rc==SQLITE_ROW ){
05594     if( *pidx==(MERGE_COUNT-1) ){
05595       rc = segmentMerge(v, iLevel);
05596       if( rc!=SQLITE_OK ) return rc;
05597       *pidx = 0;
05598     }else{
05599       (*pidx)++;
05600     }
05601   }else{
05602     return rc;
05603   }
05604   return SQLITE_OK;
05605 }
05606 
05607 /* Merge MERGE_COUNT segments at iLevel into a new segment at
05608 ** iLevel+1.  If iLevel+1 is already full of segments, those will be
05609 ** merged to make room.
05610 */
05611 static int segmentMerge(fulltext_vtab *v, int iLevel){
05612   LeafWriter writer;
05613   LeavesReader lrs[MERGE_COUNT];
05614   int i, rc, idx = 0;
05615 
05616   /* Determine the next available segment index at the next level,
05617   ** merging as necessary.
05618   */
05619   rc = segdirNextIndex(v, iLevel+1, &idx);
05620   if( rc!=SQLITE_OK ) return rc;
05621 
05622   /* TODO(shess) This assumes that we'll always see exactly
05623   ** MERGE_COUNT segments to merge at a given level.  That will be
05624   ** broken if we allow the developer to request preemptive or
05625   ** deferred merging.
05626   */
05627   memset(&lrs, '\0', sizeof(lrs));
05628   rc = leavesReadersInit(v, iLevel, lrs, &i);
05629   if( rc!=SQLITE_OK ) return rc;
05630   assert( i==MERGE_COUNT );
05631 
05632   leafWriterInit(iLevel+1, idx, &writer);
05633 
05634   /* Since leavesReaderReorder() pushes readers at eof to the end,
05635   ** when the first reader is empty, all will be empty.
05636   */
05637   while( !leavesReaderAtEnd(lrs) ){
05638     /* Figure out how many readers share their next term. */
05639     for(i=1; i<MERGE_COUNT && !leavesReaderAtEnd(lrs+i); i++){
05640       if( 0!=leavesReaderTermCmp(lrs, lrs+i) ) break;
05641     }
05642 
05643     rc = leavesReadersMerge(v, lrs, i, &writer);
05644     if( rc!=SQLITE_OK ) goto err;
05645 
05646     /* Step forward those that were merged. */
05647     while( i-->0 ){
05648       rc = leavesReaderStep(v, lrs+i);
05649       if( rc!=SQLITE_OK ) goto err;
05650 
05651       /* Reorder by term, then by age. */
05652       leavesReaderReorder(lrs+i, MERGE_COUNT-i);
05653     }
05654   }
05655 
05656   for(i=0; i<MERGE_COUNT; i++){
05657     leavesReaderDestroy(&lrs[i]);
05658   }
05659 
05660   rc = leafWriterFinalize(v, &writer);
05661   leafWriterDestroy(&writer);
05662   if( rc!=SQLITE_OK ) return rc;
05663 
05664   /* Delete the merged segment data. */
05665   return segdir_delete(v, iLevel);
05666 
05667  err:
05668   for(i=0; i<MERGE_COUNT; i++){
05669     leavesReaderDestroy(&lrs[i]);
05670   }
05671   leafWriterDestroy(&writer);
05672   return rc;
05673 }
05674 
05675 /* Accumulate the union of *acc and *pData into *acc. */
05676 static void docListAccumulateUnion(DataBuffer *acc,
05677                                    const char *pData, int nData) {
05678   DataBuffer tmp = *acc;
05679   dataBufferInit(acc, tmp.nData+nData);
05680   docListUnion(tmp.pData, tmp.nData, pData, nData, acc);
05681   dataBufferDestroy(&tmp);
05682 }
05683 
05684 /* TODO(shess) It might be interesting to explore different merge
05685 ** strategies, here.  For instance, since this is a sorted merge, we
05686 ** could easily merge many doclists in parallel.  With some
05687 ** comprehension of the storage format, we could merge all of the
05688 ** doclists within a leaf node directly from the leaf node's storage.
05689 ** It may be worthwhile to merge smaller doclists before larger
05690 ** doclists, since they can be traversed more quickly - but the
05691 ** results may have less overlap, making them more expensive in a
05692 ** different way.
05693 */
05694 
05695 /* Scan pReader for pTerm/nTerm, and merge the term's doclist over
05696 ** *out (any doclists with duplicate docids overwrite those in *out).
05697 ** Internal function for loadSegmentLeaf().
05698 */
05699 static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader,
05700                                 const char *pTerm, int nTerm, int isPrefix,
05701                                 DataBuffer *out){
05702   /* doclist data is accumulated into pBuffers similar to how one does
05703   ** increment in binary arithmetic.  If index 0 is empty, the data is
05704   ** stored there.  If there is data there, it is merged and the
05705   ** results carried into position 1, with further merge-and-carry
05706   ** until an empty position is found.
05707   */
05708   DataBuffer *pBuffers = NULL;
05709   int nBuffers = 0, nMaxBuffers = 0, rc;
05710 
05711   assert( nTerm>0 );
05712 
05713   for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader);
05714       rc=leavesReaderStep(v, pReader)){
05715     /* TODO(shess) Really want leavesReaderTermCmp(), but that name is
05716     ** already taken to compare the terms of two LeavesReaders.  Think
05717     ** on a better name.  [Meanwhile, break encapsulation rather than
05718     ** use a confusing name.]
05719     */
05720     int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix);
05721     if( c>0 ) break;      /* Past any possible matches. */
05722     if( c==0 ){
05723       const char *pData = leavesReaderData(pReader);
05724       int iBuffer, nData = leavesReaderDataBytes(pReader);
05725 
05726       /* Find the first empty buffer. */
05727       for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
05728         if( 0==pBuffers[iBuffer].nData ) break;
05729       }
05730 
05731       /* Out of buffers, add an empty one. */
05732       if( iBuffer==nBuffers ){
05733         if( nBuffers==nMaxBuffers ){
05734           DataBuffer *p;
05735           nMaxBuffers += 20;
05736 
05737           /* Manual realloc so we can handle NULL appropriately. */
05738           p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers));
05739           if( p==NULL ){
05740             rc = SQLITE_NOMEM;
05741             break;
05742           }
05743 
05744           if( nBuffers>0 ){
05745             assert(pBuffers!=NULL);
05746             memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers));
05747             sqlite3_free(pBuffers);
05748           }
05749           pBuffers = p;
05750         }
05751         dataBufferInit(&(pBuffers[nBuffers]), 0);
05752         nBuffers++;
05753       }
05754 
05755       /* At this point, must have an empty at iBuffer. */
05756       assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0);
05757 
05758       /* If empty was first buffer, no need for merge logic. */
05759       if( iBuffer==0 ){
05760         dataBufferReplace(&(pBuffers[0]), pData, nData);
05761       }else{
05762         /* pAcc is the empty buffer the merged data will end up in. */
05763         DataBuffer *pAcc = &(pBuffers[iBuffer]);
05764         DataBuffer *p = &(pBuffers[0]);
05765 
05766         /* Handle position 0 specially to avoid need to prime pAcc
05767         ** with pData/nData.
05768         */
05769         dataBufferSwap(p, pAcc);
05770         docListAccumulateUnion(pAcc, pData, nData);
05771 
05772         /* Accumulate remaining doclists into pAcc. */
05773         for(++p; p<pAcc; ++p){
05774           docListAccumulateUnion(pAcc, p->pData, p->nData);
05775 
05776           /* dataBufferReset() could allow a large doclist to blow up
05777           ** our memory requirements.
05778           */
05779           if( p->nCapacity<1024 ){
05780             dataBufferReset(p);
05781           }else{
05782             dataBufferDestroy(p);
05783             dataBufferInit(p, 0);
05784           }
05785         }
05786       }
05787     }
05788   }
05789 
05790   /* Union all the doclists together into *out. */
05791   /* TODO(shess) What if *out is big?  Sigh. */
05792   if( rc==SQLITE_OK && nBuffers>0 ){
05793     int iBuffer;
05794     for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
05795       if( pBuffers[iBuffer].nData>0 ){
05796         if( out->nData==0 ){
05797           dataBufferSwap(out, &(pBuffers[iBuffer]));
05798         }else{
05799           docListAccumulateUnion(out, pBuffers[iBuffer].pData,
05800                                  pBuffers[iBuffer].nData);
05801         }
05802       }
05803     }
05804   }
05805 
05806   while( nBuffers-- ){
05807     dataBufferDestroy(&(pBuffers[nBuffers]));
05808   }
05809   if( pBuffers!=NULL ) sqlite3_free(pBuffers);
05810 
05811   return rc;
05812 }
05813 
05814 /* Call loadSegmentLeavesInt() with pData/nData as input. */
05815 static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData,
05816                            const char *pTerm, int nTerm, int isPrefix,
05817                            DataBuffer *out){
05818   LeavesReader reader;
05819   int rc;
05820 
05821   assert( nData>1 );
05822   assert( *pData=='\0' );
05823   rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader);
05824   if( rc!=SQLITE_OK ) return rc;
05825 
05826   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
05827   leavesReaderReset(&reader);
05828   leavesReaderDestroy(&reader);
05829   return rc;
05830 }
05831 
05832 /* Call loadSegmentLeavesInt() with the leaf nodes from iStartLeaf to
05833 ** iEndLeaf (inclusive) as input, and merge the resulting doclist into
05834 ** out.
05835 */
05836 static int loadSegmentLeaves(fulltext_vtab *v,
05837                              sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf,
05838                              const char *pTerm, int nTerm, int isPrefix,
05839                              DataBuffer *out){
05840   int rc;
05841   LeavesReader reader;
05842 
05843   assert( iStartLeaf<=iEndLeaf );
05844   rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader);
05845   if( rc!=SQLITE_OK ) return rc;
05846 
05847   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
05848   leavesReaderReset(&reader);
05849   leavesReaderDestroy(&reader);
05850   return rc;
05851 }
05852 
05853 /* Taking pData/nData as an interior node, find the sequence of child
05854 ** nodes which could include pTerm/nTerm/isPrefix.  Note that the
05855 ** interior node terms logically come between the blocks, so there is
05856 ** one more blockid than there are terms (that block contains terms >=
05857 ** the last interior-node term).
05858 */
05859 /* TODO(shess) The calling code may already know that the end child is
05860 ** not worth calculating, because the end may be in a later sibling
05861 ** node.  Consider whether breaking symmetry is worthwhile.  I suspect
05862 ** it is not worthwhile.
05863 */
05864 static void getChildrenContaining(const char *pData, int nData,
05865                                   const char *pTerm, int nTerm, int isPrefix,
05866                                   sqlite_int64 *piStartChild,
05867                                   sqlite_int64 *piEndChild){
05868   InteriorReader reader;
05869 
05870   assert( nData>1 );
05871   assert( *pData!='\0' );
05872   interiorReaderInit(pData, nData, &reader);
05873 
05874   /* Scan for the first child which could contain pTerm/nTerm. */
05875   while( !interiorReaderAtEnd(&reader) ){
05876     if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break;
05877     interiorReaderStep(&reader);
05878   }
05879   *piStartChild = interiorReaderCurrentBlockid(&reader);
05880 
05881   /* Keep scanning to find a term greater than our term, using prefix
05882   ** comparison if indicated.  If isPrefix is false, this will be the
05883   ** same blockid as the starting block.
05884   */
05885   while( !interiorReaderAtEnd(&reader) ){
05886     if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break;
05887     interiorReaderStep(&reader);
05888   }
05889   *piEndChild = interiorReaderCurrentBlockid(&reader);
05890 
05891   interiorReaderDestroy(&reader);
05892 
05893   /* Children must ascend, and if !prefix, both must be the same. */
05894   assert( *piEndChild>=*piStartChild );
05895   assert( isPrefix || *piStartChild==*piEndChild );
05896 }
05897 
05898 /* Read block at iBlockid and pass it with other params to
05899 ** getChildrenContaining().
05900 */
05901 static int loadAndGetChildrenContaining(
05902   fulltext_vtab *v,
05903   sqlite_int64 iBlockid,
05904   const char *pTerm, int nTerm, int isPrefix,
05905   sqlite_int64 *piStartChild, sqlite_int64 *piEndChild
05906 ){
05907   sqlite3_stmt *s = NULL;
05908   int rc;
05909 
05910   assert( iBlockid!=0 );
05911   assert( pTerm!=NULL );
05912   assert( nTerm!=0 );        /* TODO(shess) Why not allow this? */
05913   assert( piStartChild!=NULL );
05914   assert( piEndChild!=NULL );
05915 
05916   rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s);
05917   if( rc!=SQLITE_OK ) return rc;
05918 
05919   rc = sqlite3_bind_int64(s, 1, iBlockid);
05920   if( rc!=SQLITE_OK ) return rc;
05921 
05922   rc = sqlite3_step(s);
05923   if( rc==SQLITE_DONE ) return SQLITE_ERROR;
05924   if( rc!=SQLITE_ROW ) return rc;
05925 
05926   getChildrenContaining(sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0),
05927                         pTerm, nTerm, isPrefix, piStartChild, piEndChild);
05928 
05929   /* We expect only one row.  We must execute another sqlite3_step()
05930    * to complete the iteration; otherwise the table will remain
05931    * locked. */
05932   rc = sqlite3_step(s);
05933   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
05934   if( rc!=SQLITE_DONE ) return rc;
05935 
05936   return SQLITE_OK;
05937 }
05938 
05939 /* Traverse the tree represented by pData[nData] looking for
05940 ** pTerm[nTerm], placing its doclist into *out.  This is internal to
05941 ** loadSegment() to make error-handling cleaner.
05942 */
05943 static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData,
05944                           sqlite_int64 iLeavesEnd,
05945                           const char *pTerm, int nTerm, int isPrefix,
05946                           DataBuffer *out){
05947   /* Special case where root is a leaf. */
05948   if( *pData=='\0' ){
05949     return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out);
05950   }else{
05951     int rc;
05952     sqlite_int64 iStartChild, iEndChild;
05953 
05954     /* Process pData as an interior node, then loop down the tree
05955     ** until we find the set of leaf nodes to scan for the term.
05956     */
05957     getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix,
05958                           &iStartChild, &iEndChild);
05959     while( iStartChild>iLeavesEnd ){
05960       sqlite_int64 iNextStart, iNextEnd;
05961       rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix,
05962                                         &iNextStart, &iNextEnd);
05963       if( rc!=SQLITE_OK ) return rc;
05964 
05965       /* If we've branched, follow the end branch, too. */
05966       if( iStartChild!=iEndChild ){
05967         sqlite_int64 iDummy;
05968         rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix,
05969                                           &iDummy, &iNextEnd);
05970         if( rc!=SQLITE_OK ) return rc;
05971       }
05972 
05973       assert( iNextStart<=iNextEnd );
05974       iStartChild = iNextStart;
05975       iEndChild = iNextEnd;
05976     }
05977     assert( iStartChild<=iLeavesEnd );
05978     assert( iEndChild<=iLeavesEnd );
05979 
05980     /* Scan through the leaf segments for doclists. */
05981     return loadSegmentLeaves(v, iStartChild, iEndChild,
05982                              pTerm, nTerm, isPrefix, out);
05983   }
05984 }
05985 
05986 /* Call loadSegmentInt() to collect the doclist for pTerm/nTerm, then
05987 ** merge its doclist over *out (any duplicate doclists read from the
05988 ** segment rooted at pData will overwrite those in *out).
05989 */
05990 /* TODO(shess) Consider changing this to determine the depth of the
05991 ** leaves using either the first characters of interior nodes (when
05992 ** ==1, we're one level above the leaves), or the first character of
05993 ** the root (which will describe the height of the tree directly).
05994 ** Either feels somewhat tricky to me.
05995 */
05996 /* TODO(shess) The current merge is likely to be slow for large
05997 ** doclists (though it should process from newest/smallest to
05998 ** oldest/largest, so it may not be that bad).  It might be useful to
05999 ** modify things to allow for N-way merging.  This could either be
06000 ** within a segment, with pairwise merges across segments, or across
06001 ** all segments at once.
06002 */
06003 static int loadSegment(fulltext_vtab *v, const char *pData, int nData,
06004                        sqlite_int64 iLeavesEnd,
06005                        const char *pTerm, int nTerm, int isPrefix,
06006                        DataBuffer *out){
06007   DataBuffer result;
06008   int rc;
06009 
06010   assert( nData>1 );
06011 
06012   /* This code should never be called with buffered updates. */
06013   assert( v->nPendingData<0 );
06014 
06015   dataBufferInit(&result, 0);
06016   rc = loadSegmentInt(v, pData, nData, iLeavesEnd,
06017                       pTerm, nTerm, isPrefix, &result);
06018   if( rc==SQLITE_OK && result.nData>0 ){
06019     if( out->nData==0 ){
06020       DataBuffer tmp = *out;
06021       *out = result;
06022       result = tmp;
06023     }else{
06024       DataBuffer merged;
06025       DLReader readers[2];
06026 
06027       dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData);
06028       dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData);
06029       dataBufferInit(&merged, out->nData+result.nData);
06030       docListMerge(&merged, readers, 2);
06031       dataBufferDestroy(out);
06032       *out = merged;
06033       dlrDestroy(&readers[0]);
06034       dlrDestroy(&readers[1]);
06035     }
06036   }
06037   dataBufferDestroy(&result);
06038   return rc;
06039 }
06040 
06041 /* Scan the database and merge together the posting lists for the term
06042 ** into *out.
06043 */
06044 static int termSelect(fulltext_vtab *v, int iColumn,
06045                       const char *pTerm, int nTerm, int isPrefix,
06046                       DocListType iType, DataBuffer *out){
06047   DataBuffer doclist;
06048   sqlite3_stmt *s;
06049   int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
06050   if( rc!=SQLITE_OK ) return rc;
06051 
06052   /* This code should never be called with buffered updates. */
06053   assert( v->nPendingData<0 );
06054 
06055   dataBufferInit(&doclist, 0);
06056 
06057   /* Traverse the segments from oldest to newest so that newer doclist
06058   ** elements for given docids overwrite older elements.
06059   */
06060   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
06061     const char *pData = sqlite3_column_blob(s, 2);
06062     const int nData = sqlite3_column_bytes(s, 2);
06063     const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
06064     rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix,
06065                      &doclist);
06066     if( rc!=SQLITE_OK ) goto err;
06067   }
06068   if( rc==SQLITE_DONE ){
06069     if( doclist.nData!=0 ){
06070       /* TODO(shess) The old term_select_all() code applied the column
06071       ** restrict as we merged segments, leading to smaller buffers.
06072       ** This is probably worthwhile to bring back, once the new storage
06073       ** system is checked in.
06074       */
06075       if( iColumn==v->nColumn) iColumn = -1;
06076       docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
06077                   iColumn, iType, out);
06078     }
06079     rc = SQLITE_OK;
06080   }
06081 
06082  err:
06083   dataBufferDestroy(&doclist);
06084   return rc;
06085 }
06086 
06087 /****************************************************************/
06088 /* Used to hold hashtable data for sorting. */
06089 typedef struct TermData {
06090   const char *pTerm;
06091   int nTerm;
06092   DLCollector *pCollector;
06093 } TermData;
06094 
06095 /* Orders TermData elements in strcmp fashion ( <0 for less-than, 0
06096 ** for equal, >0 for greater-than).
06097 */
06098 static int termDataCmp(const void *av, const void *bv){
06099   const TermData *a = (const TermData *)av;
06100   const TermData *b = (const TermData *)bv;
06101   int n = a->nTerm<b->nTerm ? a->nTerm : b->nTerm;
06102   int c = memcmp(a->pTerm, b->pTerm, n);
06103   if( c!=0 ) return c;
06104   return a->nTerm-b->nTerm;
06105 }
06106 
06107 /* Order pTerms data by term, then write a new level 0 segment using
06108 ** LeafWriter.
06109 */
06110 static int writeZeroSegment(fulltext_vtab *v, fts3Hash *pTerms){
06111   fts3HashElem *e;
06112   int idx, rc, i, n;
06113   TermData *pData;
06114   LeafWriter writer;
06115   DataBuffer dl;
06116 
06117   /* Determine the next index at level 0, merging as necessary. */
06118   rc = segdirNextIndex(v, 0, &idx);
06119   if( rc!=SQLITE_OK ) return rc;
06120 
06121   n = fts3HashCount(pTerms);
06122   pData = sqlite3_malloc(n*sizeof(TermData));
06123 
06124   for(i = 0, e = fts3HashFirst(pTerms); e; i++, e = fts3HashNext(e)){
06125     assert( i<n );
06126     pData[i].pTerm = fts3HashKey(e);
06127     pData[i].nTerm = fts3HashKeysize(e);
06128     pData[i].pCollector = fts3HashData(e);
06129   }
06130   assert( i==n );
06131 
06132   /* TODO(shess) Should we allow user-defined collation sequences,
06133   ** here?  I think we only need that once we support prefix searches.
06134   */
06135   if( n>1 ) qsort(pData, n, sizeof(*pData), termDataCmp);
06136 
06137   /* TODO(shess) Refactor so that we can write directly to the segment
06138   ** DataBuffer, as happens for segment merges.
06139   */
06140   leafWriterInit(0, idx, &writer);
06141   dataBufferInit(&dl, 0);
06142   for(i=0; i<n; i++){
06143     dataBufferReset(&dl);
06144     dlcAddDoclist(pData[i].pCollector, &dl);
06145     rc = leafWriterStep(v, &writer,
06146                         pData[i].pTerm, pData[i].nTerm, dl.pData, dl.nData);
06147     if( rc!=SQLITE_OK ) goto err;
06148   }
06149   rc = leafWriterFinalize(v, &writer);
06150 
06151  err:
06152   dataBufferDestroy(&dl);
06153   sqlite3_free(pData);
06154   leafWriterDestroy(&writer);
06155   return rc;
06156 }
06157 
06158 /* If pendingTerms has data, free it. */
06159 static int clearPendingTerms(fulltext_vtab *v){
06160   if( v->nPendingData>=0 ){
06161     fts3HashElem *e;
06162     for(e=fts3HashFirst(&v->pendingTerms); e; e=fts3HashNext(e)){
06163       dlcDelete(fts3HashData(e));
06164     }
06165     fts3HashClear(&v->pendingTerms);
06166     v->nPendingData = -1;
06167   }
06168   return SQLITE_OK;
06169 }
06170 
06171 /* If pendingTerms has data, flush it to a level-zero segment, and
06172 ** free it.
06173 */
06174 static int flushPendingTerms(fulltext_vtab *v){
06175   if( v->nPendingData>=0 ){
06176     int rc = writeZeroSegment(v, &v->pendingTerms);
06177     if( rc==SQLITE_OK ) clearPendingTerms(v);
06178     return rc;
06179   }
06180   return SQLITE_OK;
06181 }
06182 
06183 /* If pendingTerms is "too big", or docid is out of order, flush it.
06184 ** Regardless, be certain that pendingTerms is initialized for use.
06185 */
06186 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){
06187   /* TODO(shess) Explore whether partially flushing the buffer on
06188   ** forced-flush would provide better performance.  I suspect that if
06189   ** we ordered the doclists by size and flushed the largest until the
06190   ** buffer was half empty, that would let the less frequent terms
06191   ** generate longer doclists.
06192   */
06193   if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){
06194     int rc = flushPendingTerms(v);
06195     if( rc!=SQLITE_OK ) return rc;
06196   }
06197   if( v->nPendingData<0 ){
06198     fts3HashInit(&v->pendingTerms, FTS3_HASH_STRING, 1);
06199     v->nPendingData = 0;
06200   }
06201   v->iPrevDocid = iDocid;
06202   return SQLITE_OK;
06203 }
06204 
06205 /* This function implements the xUpdate callback; it is the top-level entry
06206  * point for inserting, deleting or updating a row in a full-text table. */
06207 static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
06208                           sqlite_int64 *pRowid){
06209   fulltext_vtab *v = (fulltext_vtab *) pVtab;
06210   int rc;
06211 
06212   FTSTRACE(("FTS3 Update %p\n", pVtab));
06213 
06214   if( nArg<2 ){
06215     rc = index_delete(v, sqlite3_value_int64(ppArg[0]));
06216     if( rc==SQLITE_OK ){
06217       /* If we just deleted the last row in the table, clear out the
06218       ** index data.
06219       */
06220       rc = content_exists(v);
06221       if( rc==SQLITE_ROW ){
06222         rc = SQLITE_OK;
06223       }else if( rc==SQLITE_DONE ){
06224         /* Clear the pending terms so we don't flush a useless level-0
06225         ** segment when the transaction closes.
06226         */
06227         rc = clearPendingTerms(v);
06228         if( rc==SQLITE_OK ){
06229           rc = segdir_delete_all(v);
06230         }
06231       }
06232     }
06233   } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
06234     /* An update:
06235      * ppArg[0] = old rowid
06236      * ppArg[1] = new rowid
06237      * ppArg[2..2+v->nColumn-1] = values
06238      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
06239      * ppArg[2+v->nColumn+1] = value for docid
06240      */
06241     sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
06242     if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
06243         sqlite3_value_int64(ppArg[1]) != rowid ){
06244       rc = SQLITE_ERROR;  /* we don't allow changing the rowid */
06245     }else if( sqlite3_value_type(ppArg[2+v->nColumn+1]) != SQLITE_INTEGER ||
06246               sqlite3_value_int64(ppArg[2+v->nColumn+1]) != rowid ){
06247       rc = SQLITE_ERROR;  /* we don't allow changing the docid */
06248     }else{
06249       assert( nArg==2+v->nColumn+2);
06250       rc = index_update(v, rowid, &ppArg[2]);
06251     }
06252   } else {
06253     /* An insert:
06254      * ppArg[1] = requested rowid
06255      * ppArg[2..2+v->nColumn-1] = values
06256      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
06257      * ppArg[2+v->nColumn+1] = value for docid
06258      */
06259     sqlite3_value *pRequestDocid = ppArg[2+v->nColumn+1];
06260     assert( nArg==2+v->nColumn+2);
06261     if( SQLITE_NULL != sqlite3_value_type(pRequestDocid) &&
06262         SQLITE_NULL != sqlite3_value_type(ppArg[1]) ){
06263       /* TODO(shess) Consider allowing this to work if the values are
06264       ** identical.  I'm inclined to discourage that usage, though,
06265       ** given that both rowid and docid are special columns.  Better
06266       ** would be to define one or the other as the default winner,
06267       ** but should it be fts3-centric (docid) or SQLite-centric
06268       ** (rowid)?
06269       */
06270       rc = SQLITE_ERROR;
06271     }else{
06272       if( SQLITE_NULL == sqlite3_value_type(pRequestDocid) ){
06273         pRequestDocid = ppArg[1];
06274       }
06275       rc = index_insert(v, pRequestDocid, &ppArg[2], pRowid);
06276     }
06277   }
06278 
06279   return rc;
06280 }
06281 
06282 static int fulltextSync(sqlite3_vtab *pVtab){
06283   FTSTRACE(("FTS3 xSync()\n"));
06284   return flushPendingTerms((fulltext_vtab *)pVtab);
06285 }
06286 
06287 static int fulltextBegin(sqlite3_vtab *pVtab){
06288   fulltext_vtab *v = (fulltext_vtab *) pVtab;
06289   FTSTRACE(("FTS3 xBegin()\n"));
06290 
06291   /* Any buffered updates should have been cleared by the previous
06292   ** transaction.
06293   */
06294   assert( v->nPendingData<0 );
06295   return clearPendingTerms(v);
06296 }
06297 
06298 static int fulltextCommit(sqlite3_vtab *pVtab){
06299   fulltext_vtab *v = (fulltext_vtab *) pVtab;
06300   FTSTRACE(("FTS3 xCommit()\n"));
06301 
06302   /* Buffered updates should have been cleared by fulltextSync(). */
06303   assert( v->nPendingData<0 );
06304   return clearPendingTerms(v);
06305 }
06306 
06307 static int fulltextRollback(sqlite3_vtab *pVtab){
06308   FTSTRACE(("FTS3 xRollback()\n"));
06309   return clearPendingTerms((fulltext_vtab *)pVtab);
06310 }
06311 
06312 /*
06313 ** Implementation of the snippet() function for FTS3
06314 */
06315 static void snippetFunc(
06316   sqlite3_context *pContext,
06317   int argc,
06318   sqlite3_value **argv
06319 ){
06320   fulltext_cursor *pCursor;
06321   if( argc<1 ) return;
06322   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
06323       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
06324     sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
06325   }else{
06326     const char *zStart = "<b>";
06327     const char *zEnd = "</b>";
06328     const char *zEllipsis = "<b>...</b>";
06329     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
06330     if( argc>=2 ){
06331       zStart = (const char*)sqlite3_value_text(argv[1]);
06332       if( argc>=3 ){
06333         zEnd = (const char*)sqlite3_value_text(argv[2]);
06334         if( argc>=4 ){
06335           zEllipsis = (const char*)sqlite3_value_text(argv[3]);
06336         }
06337       }
06338     }
06339     snippetAllOffsets(pCursor);
06340     snippetText(pCursor, zStart, zEnd, zEllipsis);
06341     sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
06342                         pCursor->snippet.nSnippet, SQLITE_STATIC);
06343   }
06344 }
06345 
06346 /*
06347 ** Implementation of the offsets() function for FTS3
06348 */
06349 static void snippetOffsetsFunc(
06350   sqlite3_context *pContext,
06351   int argc,
06352   sqlite3_value **argv
06353 ){
06354   fulltext_cursor *pCursor;
06355   if( argc<1 ) return;
06356   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
06357       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
06358     sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
06359   }else{
06360     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
06361     snippetAllOffsets(pCursor);
06362     snippetOffsetText(&pCursor->snippet);
06363     sqlite3_result_text(pContext,
06364                         pCursor->snippet.zOffset, pCursor->snippet.nOffset,
06365                         SQLITE_STATIC);
06366   }
06367 }
06368 
06369 /* OptLeavesReader is nearly identical to LeavesReader, except that
06370 ** where LeavesReader is geared towards the merging of complete
06371 ** segment levels (with exactly MERGE_COUNT segments), OptLeavesReader
06372 ** is geared towards implementation of the optimize() function, and
06373 ** can merge all segments simultaneously.  This version may be
06374 ** somewhat less efficient than LeavesReader because it merges into an
06375 ** accumulator rather than doing an N-way merge, but since segment
06376 ** size grows exponentially (so segment count logrithmically) this is
06377 ** probably not an immediate problem.
06378 */
06379 /* TODO(shess): Prove that assertion, or extend the merge code to
06380 ** merge tree fashion (like the prefix-searching code does).
06381 */
06382 /* TODO(shess): OptLeavesReader and LeavesReader could probably be
06383 ** merged with little or no loss of performance for LeavesReader.  The
06384 ** merged code would need to handle >MERGE_COUNT segments, and would
06385 ** also need to be able to optionally optimize away deletes.
06386 */
06387 typedef struct OptLeavesReader {
06388   /* Segment number, to order readers by age. */
06389   int segment;
06390   LeavesReader reader;
06391 } OptLeavesReader;
06392 
06393 static int optLeavesReaderAtEnd(OptLeavesReader *pReader){
06394   return leavesReaderAtEnd(&pReader->reader);
06395 }
06396 static int optLeavesReaderTermBytes(OptLeavesReader *pReader){
06397   return leavesReaderTermBytes(&pReader->reader);
06398 }
06399 static const char *optLeavesReaderData(OptLeavesReader *pReader){
06400   return leavesReaderData(&pReader->reader);
06401 }
06402 static int optLeavesReaderDataBytes(OptLeavesReader *pReader){
06403   return leavesReaderDataBytes(&pReader->reader);
06404 }
06405 static const char *optLeavesReaderTerm(OptLeavesReader *pReader){
06406   return leavesReaderTerm(&pReader->reader);
06407 }
06408 static int optLeavesReaderStep(fulltext_vtab *v, OptLeavesReader *pReader){
06409   return leavesReaderStep(v, &pReader->reader);
06410 }
06411 static int optLeavesReaderTermCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
06412   return leavesReaderTermCmp(&lr1->reader, &lr2->reader);
06413 }
06414 /* Order by term ascending, segment ascending (oldest to newest), with
06415 ** exhausted readers to the end.
06416 */
06417 static int optLeavesReaderCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
06418   int c = optLeavesReaderTermCmp(lr1, lr2);
06419   if( c!=0 ) return c;
06420   return lr1->segment-lr2->segment;
06421 }
06422 /* Bubble pLr[0] to appropriate place in pLr[1..nLr-1].  Assumes that
06423 ** pLr[1..nLr-1] is already sorted.
06424 */
06425 static void optLeavesReaderReorder(OptLeavesReader *pLr, int nLr){
06426   while( nLr>1 && optLeavesReaderCmp(pLr, pLr+1)>0 ){
06427     OptLeavesReader tmp = pLr[0];
06428     pLr[0] = pLr[1];
06429     pLr[1] = tmp;
06430     nLr--;
06431     pLr++;
06432   }
06433 }
06434 
06435 /* optimize() helper function.  Put the readers in order and iterate
06436 ** through them, merging doclists for matching terms into pWriter.
06437 ** Returns SQLITE_OK on success, or the SQLite error code which
06438 ** prevented success.
06439 */
06440 static int optimizeInternal(fulltext_vtab *v,
06441                             OptLeavesReader *readers, int nReaders,
06442                             LeafWriter *pWriter){
06443   int i, rc = SQLITE_OK;
06444   DataBuffer doclist, merged, tmp;
06445 
06446   /* Order the readers. */
06447   i = nReaders;
06448   while( i-- > 0 ){
06449     optLeavesReaderReorder(&readers[i], nReaders-i);
06450   }
06451 
06452   dataBufferInit(&doclist, LEAF_MAX);
06453   dataBufferInit(&merged, LEAF_MAX);
06454 
06455   /* Exhausted readers bubble to the end, so when the first reader is
06456   ** at eof, all are at eof.
06457   */
06458   while( !optLeavesReaderAtEnd(&readers[0]) ){
06459 
06460     /* Figure out how many readers share the next term. */
06461     for(i=1; i<nReaders && !optLeavesReaderAtEnd(&readers[i]); i++){
06462       if( 0!=optLeavesReaderTermCmp(&readers[0], &readers[i]) ) break;
06463     }
06464 
06465     /* Special-case for no merge. */
06466     if( i==1 ){
06467       /* Trim deletions from the doclist. */
06468       dataBufferReset(&merged);
06469       docListTrim(DL_DEFAULT,
06470                   optLeavesReaderData(&readers[0]),
06471                   optLeavesReaderDataBytes(&readers[0]),
06472                   -1, DL_DEFAULT, &merged);
06473     }else{
06474       DLReader dlReaders[MERGE_COUNT];
06475       int iReader, nReaders;
06476 
06477       /* Prime the pipeline with the first reader's doclist.  After
06478       ** one pass index 0 will reference the accumulated doclist.
06479       */
06480       dlrInit(&dlReaders[0], DL_DEFAULT,
06481               optLeavesReaderData(&readers[0]),
06482               optLeavesReaderDataBytes(&readers[0]));
06483       iReader = 1;
06484 
06485       assert( iReader<i );  /* Must execute the loop at least once. */
06486       while( iReader<i ){
06487         /* Merge 16 inputs per pass. */
06488         for( nReaders=1; iReader<i && nReaders<MERGE_COUNT;
06489              iReader++, nReaders++ ){
06490           dlrInit(&dlReaders[nReaders], DL_DEFAULT,
06491                   optLeavesReaderData(&readers[iReader]),
06492                   optLeavesReaderDataBytes(&readers[iReader]));
06493         }
06494 
06495         /* Merge doclists and swap result into accumulator. */
06496         dataBufferReset(&merged);
06497         docListMerge(&merged, dlReaders, nReaders);
06498         tmp = merged;
06499         merged = doclist;
06500         doclist = tmp;
06501 
06502         while( nReaders-- > 0 ){
06503           dlrDestroy(&dlReaders[nReaders]);
06504         }
06505 
06506         /* Accumulated doclist to reader 0 for next pass. */
06507         dlrInit(&dlReaders[0], DL_DEFAULT, doclist.pData, doclist.nData);
06508       }
06509 
06510       /* Destroy reader that was left in the pipeline. */
06511       dlrDestroy(&dlReaders[0]);
06512 
06513       /* Trim deletions from the doclist. */
06514       dataBufferReset(&merged);
06515       docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
06516                   -1, DL_DEFAULT, &merged);
06517     }
06518 
06519     /* Only pass doclists with hits (skip if all hits deleted). */
06520     if( merged.nData>0 ){
06521       rc = leafWriterStep(v, pWriter,
06522                           optLeavesReaderTerm(&readers[0]),
06523                           optLeavesReaderTermBytes(&readers[0]),
06524                           merged.pData, merged.nData);
06525       if( rc!=SQLITE_OK ) goto err;
06526     }
06527 
06528     /* Step merged readers to next term and reorder. */
06529     while( i-- > 0 ){
06530       rc = optLeavesReaderStep(v, &readers[i]);
06531       if( rc!=SQLITE_OK ) goto err;
06532 
06533       optLeavesReaderReorder(&readers[i], nReaders-i);
06534     }
06535   }
06536 
06537  err:
06538   dataBufferDestroy(&doclist);
06539   dataBufferDestroy(&merged);
06540   return rc;
06541 }
06542 
06543 /* Implement optimize() function for FTS3.  optimize(t) merges all
06544 ** segments in the fts index into a single segment.  't' is the magic
06545 ** table-named column.
06546 */
06547 static void optimizeFunc(sqlite3_context *pContext,
06548                          int argc, sqlite3_value **argv){
06549   fulltext_cursor *pCursor;
06550   if( argc>1 ){
06551     sqlite3_result_error(pContext, "excess arguments to optimize()",-1);
06552   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
06553             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
06554     sqlite3_result_error(pContext, "illegal first argument to optimize",-1);
06555   }else{
06556     fulltext_vtab *v;
06557     int i, rc, iMaxLevel;
06558     OptLeavesReader *readers;
06559     int nReaders;
06560     LeafWriter writer;
06561     sqlite3_stmt *s;
06562 
06563     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
06564     v = cursor_vtab(pCursor);
06565 
06566     /* Flush any buffered updates before optimizing. */
06567     rc = flushPendingTerms(v);
06568     if( rc!=SQLITE_OK ) goto err;
06569 
06570     rc = segdir_count(v, &nReaders, &iMaxLevel);
06571     if( rc!=SQLITE_OK ) goto err;
06572     if( nReaders==0 || nReaders==1 ){
06573       sqlite3_result_text(pContext, "Index already optimal", -1,
06574                           SQLITE_STATIC);
06575       return;
06576     }
06577 
06578     rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
06579     if( rc!=SQLITE_OK ) goto err;
06580 
06581     readers = sqlite3_malloc(nReaders*sizeof(readers[0]));
06582     if( readers==NULL ) goto err;
06583 
06584     /* Note that there will already be a segment at this position
06585     ** until we call segdir_delete() on iMaxLevel.
06586     */
06587     leafWriterInit(iMaxLevel, 0, &writer);
06588 
06589     i = 0;
06590     while( (rc = sqlite3_step(s))==SQLITE_ROW ){
06591       sqlite_int64 iStart = sqlite3_column_int64(s, 0);
06592       sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
06593       const char *pRootData = sqlite3_column_blob(s, 2);
06594       int nRootData = sqlite3_column_bytes(s, 2);
06595 
06596       assert( i<nReaders );
06597       rc = leavesReaderInit(v, -1, iStart, iEnd, pRootData, nRootData,
06598                             &readers[i].reader);
06599       if( rc!=SQLITE_OK ) break;
06600 
06601       readers[i].segment = i;
06602       i++;
06603     }
06604 
06605     /* If we managed to succesfully read them all, optimize them. */
06606     if( rc==SQLITE_DONE ){
06607       assert( i==nReaders );
06608       rc = optimizeInternal(v, readers, nReaders, &writer);
06609     }
06610 
06611     while( i-- > 0 ){
06612       leavesReaderDestroy(&readers[i].reader);
06613     }
06614     sqlite3_free(readers);
06615 
06616     /* If we've successfully gotten to here, delete the old segments
06617     ** and flush the interior structure of the new segment.
06618     */
06619     if( rc==SQLITE_OK ){
06620       for( i=0; i<=iMaxLevel; i++ ){
06621         rc = segdir_delete(v, i);
06622         if( rc!=SQLITE_OK ) break;
06623       }
06624 
06625       if( rc==SQLITE_OK ) rc = leafWriterFinalize(v, &writer);
06626     }
06627 
06628     leafWriterDestroy(&writer);
06629 
06630     if( rc!=SQLITE_OK ) goto err;
06631 
06632     sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
06633     return;
06634 
06635     /* TODO(shess): Error-handling needs to be improved along the
06636     ** lines of the dump_ functions.
06637     */
06638  err:
06639     {
06640       char buf[512];
06641       sqlite3_snprintf(sizeof(buf), buf, "Error in optimize: %s",
06642                        sqlite3_errmsg(sqlite3_context_db_handle(pContext)));
06643       sqlite3_result_error(pContext, buf, -1);
06644     }
06645   }
06646 }
06647 
06648 #ifdef SQLITE_TEST
06649 /* Generate an error of the form "<prefix>: <msg>".  If msg is NULL,
06650 ** pull the error from the context's db handle.
06651 */
06652 static void generateError(sqlite3_context *pContext,
06653                           const char *prefix, const char *msg){
06654   char buf[512];
06655   if( msg==NULL ) msg = sqlite3_errmsg(sqlite3_context_db_handle(pContext));
06656   sqlite3_snprintf(sizeof(buf), buf, "%s: %s", prefix, msg);
06657   sqlite3_result_error(pContext, buf, -1);
06658 }
06659 
06660 /* Helper function to collect the set of terms in the segment into
06661 ** pTerms.  The segment is defined by the leaf nodes between
06662 ** iStartBlockid and iEndBlockid, inclusive, or by the contents of
06663 ** pRootData if iStartBlockid is 0 (in which case the entire segment
06664 ** fit in a leaf).
06665 */
06666 static int collectSegmentTerms(fulltext_vtab *v, sqlite3_stmt *s,
06667                                fts3Hash *pTerms){
06668   const sqlite_int64 iStartBlockid = sqlite3_column_int64(s, 0);
06669   const sqlite_int64 iEndBlockid = sqlite3_column_int64(s, 1);
06670   const char *pRootData = sqlite3_column_blob(s, 2);
06671   const int nRootData = sqlite3_column_bytes(s, 2);
06672   LeavesReader reader;
06673   int rc = leavesReaderInit(v, 0, iStartBlockid, iEndBlockid,
06674                             pRootData, nRootData, &reader);
06675   if( rc!=SQLITE_OK ) return rc;
06676 
06677   while( rc==SQLITE_OK && !leavesReaderAtEnd(&reader) ){
06678     const char *pTerm = leavesReaderTerm(&reader);
06679     const int nTerm = leavesReaderTermBytes(&reader);
06680     void *oldValue = sqlite3Fts3HashFind(pTerms, pTerm, nTerm);
06681     void *newValue = (void *)((char *)oldValue+1);
06682 
06683     /* From the comment before sqlite3Fts3HashInsert in fts3_hash.c,
06684     ** the data value passed is returned in case of malloc failure.
06685     */
06686     if( newValue==sqlite3Fts3HashInsert(pTerms, pTerm, nTerm, newValue) ){
06687       rc = SQLITE_NOMEM;
06688     }else{
06689       rc = leavesReaderStep(v, &reader);
06690     }
06691   }
06692 
06693   leavesReaderDestroy(&reader);
06694   return rc;
06695 }
06696 
06697 /* Helper function to build the result string for dump_terms(). */
06698 static int generateTermsResult(sqlite3_context *pContext, fts3Hash *pTerms){
06699   int iTerm, nTerms, nResultBytes, iByte;
06700   char *result;
06701   TermData *pData;
06702   fts3HashElem *e;
06703 
06704   /* Iterate pTerms to generate an array of terms in pData for
06705   ** sorting.
06706   */
06707   nTerms = fts3HashCount(pTerms);
06708   assert( nTerms>0 );
06709   pData = sqlite3_malloc(nTerms*sizeof(TermData));
06710   if( pData==NULL ) return SQLITE_NOMEM;
06711 
06712   nResultBytes = 0;
06713   for(iTerm = 0, e = fts3HashFirst(pTerms); e; iTerm++, e = fts3HashNext(e)){
06714     nResultBytes += fts3HashKeysize(e)+1;   /* Term plus trailing space */
06715     assert( iTerm<nTerms );
06716     pData[iTerm].pTerm = fts3HashKey(e);
06717     pData[iTerm].nTerm = fts3HashKeysize(e);
06718     pData[iTerm].pCollector = fts3HashData(e);  /* unused */
06719   }
06720   assert( iTerm==nTerms );
06721 
06722   assert( nResultBytes>0 );   /* nTerms>0, nResultsBytes must be, too. */
06723   result = sqlite3_malloc(nResultBytes);
06724   if( result==NULL ){
06725     sqlite3_free(pData);
06726     return SQLITE_NOMEM;
06727   }
06728 
06729   if( nTerms>1 ) qsort(pData, nTerms, sizeof(*pData), termDataCmp);
06730 
06731   /* Read the terms in order to build the result. */
06732   iByte = 0;
06733   for(iTerm=0; iTerm<nTerms; ++iTerm){
06734     memcpy(result+iByte, pData[iTerm].pTerm, pData[iTerm].nTerm);
06735     iByte += pData[iTerm].nTerm;
06736     result[iByte++] = ' ';
06737   }
06738   assert( iByte==nResultBytes );
06739   assert( result[nResultBytes-1]==' ' );
06740   result[nResultBytes-1] = '\0';
06741 
06742   /* Passes away ownership of result. */
06743   sqlite3_result_text(pContext, result, nResultBytes-1, sqlite3_free);
06744   sqlite3_free(pData);
06745   return SQLITE_OK;
06746 }
06747 
06748 /* Implements dump_terms() for use in inspecting the fts3 index from
06749 ** tests.  TEXT result containing the ordered list of terms joined by
06750 ** spaces.  dump_terms(t, level, idx) dumps the terms for the segment
06751 ** specified by level, idx (in %_segdir), while dump_terms(t) dumps
06752 ** all terms in the index.  In both cases t is the fts table's magic
06753 ** table-named column.
06754 */
06755 static void dumpTermsFunc(
06756   sqlite3_context *pContext,
06757   int argc, sqlite3_value **argv
06758 ){
06759   fulltext_cursor *pCursor;
06760   if( argc!=3 && argc!=1 ){
06761     generateError(pContext, "dump_terms", "incorrect arguments");
06762   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
06763             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
06764     generateError(pContext, "dump_terms", "illegal first argument");
06765   }else{
06766     fulltext_vtab *v;
06767     fts3Hash terms;
06768     sqlite3_stmt *s = NULL;
06769     int rc;
06770 
06771     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
06772     v = cursor_vtab(pCursor);
06773 
06774     /* If passed only the cursor column, get all segments.  Otherwise
06775     ** get the segment described by the following two arguments.
06776     */
06777     if( argc==1 ){
06778       rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
06779     }else{
06780       rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
06781       if( rc==SQLITE_OK ){
06782         rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[1]));
06783         if( rc==SQLITE_OK ){
06784           rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[2]));
06785         }
06786       }
06787     }
06788 
06789     if( rc!=SQLITE_OK ){
06790       generateError(pContext, "dump_terms", NULL);
06791       return;
06792     }
06793 
06794     /* Collect the terms for each segment. */
06795     sqlite3Fts3HashInit(&terms, FTS3_HASH_STRING, 1);
06796     while( (rc = sqlite3_step(s))==SQLITE_ROW ){
06797       rc = collectSegmentTerms(v, s, &terms);
06798       if( rc!=SQLITE_OK ) break;
06799     }
06800 
06801     if( rc!=SQLITE_DONE ){
06802       sqlite3_reset(s);
06803       generateError(pContext, "dump_terms", NULL);
06804     }else{
06805       const int nTerms = fts3HashCount(&terms);
06806       if( nTerms>0 ){
06807         rc = generateTermsResult(pContext, &terms);
06808         if( rc==SQLITE_NOMEM ){
06809           generateError(pContext, "dump_terms", "out of memory");
06810         }else{
06811           assert( rc==SQLITE_OK );
06812         }
06813       }else if( argc==3 ){
06814         /* The specific segment asked for could not be found. */
06815         generateError(pContext, "dump_terms", "segment not found");
06816       }else{
06817         /* No segments found. */
06818         /* TODO(shess): It should be impossible to reach this.  This
06819         ** case can only happen for an empty table, in which case
06820         ** SQLite has no rows to call this function on.
06821         */
06822         sqlite3_result_null(pContext);
06823       }
06824     }
06825     sqlite3Fts3HashClear(&terms);
06826   }
06827 }
06828 
06829 /* Expand the DL_DEFAULT doclist in pData into a text result in
06830 ** pContext.
06831 */
06832 static void createDoclistResult(sqlite3_context *pContext,
06833                                 const char *pData, int nData){
06834   DataBuffer dump;
06835   DLReader dlReader;
06836 
06837   assert( pData!=NULL && nData>0 );
06838 
06839   dataBufferInit(&dump, 0);
06840   dlrInit(&dlReader, DL_DEFAULT, pData, nData);
06841   for( ; !dlrAtEnd(&dlReader); dlrStep(&dlReader) ){
06842     char buf[256];
06843     PLReader plReader;
06844 
06845     plrInit(&plReader, &dlReader);
06846     if( DL_DEFAULT==DL_DOCIDS || plrAtEnd(&plReader) ){
06847       sqlite3_snprintf(sizeof(buf), buf, "[%lld] ", dlrDocid(&dlReader));
06848       dataBufferAppend(&dump, buf, strlen(buf));
06849     }else{
06850       int iColumn = plrColumn(&plReader);
06851 
06852       sqlite3_snprintf(sizeof(buf), buf, "[%lld %d[",
06853                        dlrDocid(&dlReader), iColumn);
06854       dataBufferAppend(&dump, buf, strlen(buf));
06855 
06856       for( ; !plrAtEnd(&plReader); plrStep(&plReader) ){
06857         if( plrColumn(&plReader)!=iColumn ){
06858           iColumn = plrColumn(&plReader);
06859           sqlite3_snprintf(sizeof(buf), buf, "] %d[", iColumn);
06860           assert( dump.nData>0 );
06861           dump.nData--;                     /* Overwrite trailing space. */
06862           assert( dump.pData[dump.nData]==' ');
06863           dataBufferAppend(&dump, buf, strlen(buf));
06864         }
06865         if( DL_DEFAULT==DL_POSITIONS_OFFSETS ){
06866           sqlite3_snprintf(sizeof(buf), buf, "%d,%d,%d ",
06867                            plrPosition(&plReader),
06868                            plrStartOffset(&plReader), plrEndOffset(&plReader));
06869         }else if( DL_DEFAULT==DL_POSITIONS ){
06870           sqlite3_snprintf(sizeof(buf), buf, "%d ", plrPosition(&plReader));
06871         }else{
06872           assert( NULL=="Unhandled DL_DEFAULT value");
06873         }
06874         dataBufferAppend(&dump, buf, strlen(buf));
06875       }
06876       plrDestroy(&plReader);
06877 
06878       assert( dump.nData>0 );
06879       dump.nData--;                     /* Overwrite trailing space. */
06880       assert( dump.pData[dump.nData]==' ');
06881       dataBufferAppend(&dump, "]] ", 3);
06882     }
06883   }
06884   dlrDestroy(&dlReader);
06885 
06886   assert( dump.nData>0 );
06887   dump.nData--;                     /* Overwrite trailing space. */
06888   assert( dump.pData[dump.nData]==' ');
06889   dump.pData[dump.nData] = '\0';
06890   assert( dump.nData>0 );
06891 
06892   /* Passes ownership of dump's buffer to pContext. */
06893   sqlite3_result_text(pContext, dump.pData, dump.nData, sqlite3_free);
06894   dump.pData = NULL;
06895   dump.nData = dump.nCapacity = 0;
06896 }
06897 
06898 /* Implements dump_doclist() for use in inspecting the fts3 index from
06899 ** tests.  TEXT result containing a string representation of the
06900 ** doclist for the indicated term.  dump_doclist(t, term, level, idx)
06901 ** dumps the doclist for term from the segment specified by level, idx
06902 ** (in %_segdir), while dump_doclist(t, term) dumps the logical
06903 ** doclist for the term across all segments.  The per-segment doclist
06904 ** can contain deletions, while the full-index doclist will not
06905 ** (deletions are omitted).
06906 **
06907 ** Result formats differ with the setting of DL_DEFAULTS.  Examples:
06908 **
06909 ** DL_DOCIDS: [1] [3] [7]
06910 ** DL_POSITIONS: [1 0[0 4] 1[17]] [3 1[5]]
06911 ** DL_POSITIONS_OFFSETS: [1 0[0,0,3 4,23,26] 1[17,102,105]] [3 1[5,20,23]]
06912 **
06913 ** In each case the number after the outer '[' is the docid.  In the
06914 ** latter two cases, the number before the inner '[' is the column
06915 ** associated with the values within.  For DL_POSITIONS the numbers
06916 ** within are the positions, for DL_POSITIONS_OFFSETS they are the
06917 ** position, the start offset, and the end offset.
06918 */
06919 static void dumpDoclistFunc(
06920   sqlite3_context *pContext,
06921   int argc, sqlite3_value **argv
06922 ){
06923   fulltext_cursor *pCursor;
06924   if( argc!=2 && argc!=4 ){
06925     generateError(pContext, "dump_doclist", "incorrect arguments");
06926   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
06927             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
06928     generateError(pContext, "dump_doclist", "illegal first argument");
06929   }else if( sqlite3_value_text(argv[1])==NULL ||
06930             sqlite3_value_text(argv[1])[0]=='\0' ){
06931     generateError(pContext, "dump_doclist", "empty second argument");
06932   }else{
06933     const char *pTerm = (const char *)sqlite3_value_text(argv[1]);
06934     const int nTerm = strlen(pTerm);
06935     fulltext_vtab *v;
06936     int rc;
06937     DataBuffer doclist;
06938 
06939     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
06940     v = cursor_vtab(pCursor);
06941 
06942     dataBufferInit(&doclist, 0);
06943 
06944     /* termSelect() yields the same logical doclist that queries are
06945     ** run against.
06946     */
06947     if( argc==2 ){
06948       rc = termSelect(v, v->nColumn, pTerm, nTerm, 0, DL_DEFAULT, &doclist);
06949     }else{
06950       sqlite3_stmt *s = NULL;
06951 
06952       /* Get our specific segment's information. */
06953       rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
06954       if( rc==SQLITE_OK ){
06955         rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[2]));
06956         if( rc==SQLITE_OK ){
06957           rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[3]));
06958         }
06959       }
06960 
06961       if( rc==SQLITE_OK ){
06962         rc = sqlite3_step(s);
06963 
06964         if( rc==SQLITE_DONE ){
06965           dataBufferDestroy(&doclist);
06966           generateError(pContext, "dump_doclist", "segment not found");
06967           return;
06968         }
06969 
06970         /* Found a segment, load it into doclist. */
06971         if( rc==SQLITE_ROW ){
06972           const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
06973           const char *pData = sqlite3_column_blob(s, 2);
06974           const int nData = sqlite3_column_bytes(s, 2);
06975 
06976           /* loadSegment() is used by termSelect() to load each
06977           ** segment's data.
06978           */
06979           rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, 0,
06980                            &doclist);
06981           if( rc==SQLITE_OK ){
06982             rc = sqlite3_step(s);
06983 
06984             /* Should not have more than one matching segment. */
06985             if( rc!=SQLITE_DONE ){
06986               sqlite3_reset(s);
06987               dataBufferDestroy(&doclist);
06988               generateError(pContext, "dump_doclist", "invalid segdir");
06989               return;
06990             }
06991             rc = SQLITE_OK;
06992           }
06993         }
06994       }
06995 
06996       sqlite3_reset(s);
06997     }
06998 
06999     if( rc==SQLITE_OK ){
07000       if( doclist.nData>0 ){
07001         createDoclistResult(pContext, doclist.pData, doclist.nData);
07002       }else{
07003         /* TODO(shess): This can happen if the term is not present, or
07004         ** if all instances of the term have been deleted and this is
07005         ** an all-index dump.  It may be interesting to distinguish
07006         ** these cases.
07007         */
07008         sqlite3_result_text(pContext, "", 0, SQLITE_STATIC);
07009       }
07010     }else if( rc==SQLITE_NOMEM ){
07011       /* Handle out-of-memory cases specially because if they are
07012       ** generated in fts3 code they may not be reflected in the db
07013       ** handle.
07014       */
07015       /* TODO(shess): Handle this more comprehensively.
07016       ** sqlite3ErrStr() has what I need, but is internal.
07017       */
07018       generateError(pContext, "dump_doclist", "out of memory");
07019     }else{
07020       generateError(pContext, "dump_doclist", NULL);
07021     }
07022 
07023     dataBufferDestroy(&doclist);
07024   }
07025 }
07026 #endif
07027 
07028 /*
07029 ** This routine implements the xFindFunction method for the FTS3
07030 ** virtual table.
07031 */
07032 static int fulltextFindFunction(
07033   sqlite3_vtab *pVtab,
07034   int nArg,
07035   const char *zName,
07036   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
07037   void **ppArg
07038 ){
07039   if( strcmp(zName,"snippet")==0 ){
07040     *pxFunc = snippetFunc;
07041     return 1;
07042   }else if( strcmp(zName,"offsets")==0 ){
07043     *pxFunc = snippetOffsetsFunc;
07044     return 1;
07045   }else if( strcmp(zName,"optimize")==0 ){
07046     *pxFunc = optimizeFunc;
07047     return 1;
07048 #ifdef SQLITE_TEST
07049     /* NOTE(shess): These functions are present only for testing
07050     ** purposes.  No particular effort is made to optimize their
07051     ** execution or how they build their results.
07052     */
07053   }else if( strcmp(zName,"dump_terms")==0 ){
07054     /* fprintf(stderr, "Found dump_terms\n"); */
07055     *pxFunc = dumpTermsFunc;
07056     return 1;
07057   }else if( strcmp(zName,"dump_doclist")==0 ){
07058     /* fprintf(stderr, "Found dump_doclist\n"); */
07059     *pxFunc = dumpDoclistFunc;
07060     return 1;
07061 #endif
07062   }
07063   return 0;
07064 }
07065 
07066 /*
07067 ** Rename an fts3 table.
07068 */
07069 static int fulltextRename(
07070   sqlite3_vtab *pVtab,
07071   const char *zName
07072 ){
07073   fulltext_vtab *p = (fulltext_vtab *)pVtab;
07074   int rc = SQLITE_NOMEM;
07075   char *zSql = sqlite3_mprintf(
07076     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
07077     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
07078     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
07079     , p->zDb, p->zName, zName 
07080     , p->zDb, p->zName, zName 
07081     , p->zDb, p->zName, zName
07082   );
07083   if( zSql ){
07084     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
07085     sqlite3_free(zSql);
07086   }
07087   return rc;
07088 }
07089 
07090 static const sqlite3_module fts3Module = {
07091   /* iVersion      */ 0,
07092   /* xCreate       */ fulltextCreate,
07093   /* xConnect      */ fulltextConnect,
07094   /* xBestIndex    */ fulltextBestIndex,
07095   /* xDisconnect   */ fulltextDisconnect,
07096   /* xDestroy      */ fulltextDestroy,
07097   /* xOpen         */ fulltextOpen,
07098   /* xClose        */ fulltextClose,
07099   /* xFilter       */ fulltextFilter,
07100   /* xNext         */ fulltextNext,
07101   /* xEof          */ fulltextEof,
07102   /* xColumn       */ fulltextColumn,
07103   /* xRowid        */ fulltextRowid,
07104   /* xUpdate       */ fulltextUpdate,
07105   /* xBegin        */ fulltextBegin,
07106   /* xSync         */ fulltextSync,
07107   /* xCommit       */ fulltextCommit,
07108   /* xRollback     */ fulltextRollback,
07109   /* xFindFunction */ fulltextFindFunction,
07110   /* xRename */       fulltextRename,
07111 };
07112 
07113 static void hashDestroy(void *p){
07114   fts3Hash *pHash = (fts3Hash *)p;
07115   sqlite3Fts3HashClear(pHash);
07116   sqlite3_free(pHash);
07117 }
07118 
07119 /*
07120 ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
07121 ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
07122 ** two forward declarations are for functions declared in these files
07123 ** used to retrieve the respective implementations.
07124 **
07125 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
07126 ** to by the argument to point a the "simple" tokenizer implementation.
07127 ** Function ...PorterTokenizerModule() sets *pModule to point to the
07128 ** porter tokenizer/stemmer implementation.
07129 */
07130 void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
07131 void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
07132 void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
07133 
07134 int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *);
07135 
07136 /*
07137 ** Initialise the fts3 extension. If this extension is built as part
07138 ** of the sqlite library, then this function is called directly by
07139 ** SQLite. If fts3 is built as a dynamically loadable extension, this
07140 ** function is called by the sqlite3_extension_init() entry point.
07141 */
07142 int sqlite3Fts3Init(sqlite3 *db){
07143   int rc = SQLITE_OK;
07144   fts3Hash *pHash = 0;
07145   const sqlite3_tokenizer_module *pSimple = 0;
07146   const sqlite3_tokenizer_module *pPorter = 0;
07147   const sqlite3_tokenizer_module *pIcu = 0;
07148 
07149   sqlite3Fts3SimpleTokenizerModule(&pSimple);
07150   sqlite3Fts3PorterTokenizerModule(&pPorter);
07151 #ifdef SQLITE_ENABLE_ICU
07152   sqlite3Fts3IcuTokenizerModule(&pIcu);
07153 #endif
07154 
07155   /* Allocate and initialise the hash-table used to store tokenizers. */
07156   pHash = sqlite3_malloc(sizeof(fts3Hash));
07157   if( !pHash ){
07158     rc = SQLITE_NOMEM;
07159   }else{
07160     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
07161   }
07162 
07163   /* Load the built-in tokenizers into the hash table */
07164   if( rc==SQLITE_OK ){
07165     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
07166      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
07167      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
07168     ){
07169       rc = SQLITE_NOMEM;
07170     }
07171   }
07172 
07173   /* Create the virtual table wrapper around the hash-table and overload 
07174   ** the two scalar functions. If this is successful, register the
07175   ** module with sqlite.
07176   */
07177   if( SQLITE_OK==rc 
07178    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
07179    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
07180    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
07181    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", -1))
07182 #ifdef SQLITE_TEST
07183    && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_terms", -1))
07184    && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_doclist", -1))
07185 #endif
07186   ){
07187     return sqlite3_create_module_v2(
07188         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
07189     );
07190   }
07191 
07192   /* An error has occured. Delete the hash table and return the error code. */
07193   assert( rc!=SQLITE_OK );
07194   if( pHash ){
07195     sqlite3Fts3HashClear(pHash);
07196     sqlite3_free(pHash);
07197   }
07198   return rc;
07199 }
07200 
07201 #if !SQLITE_CORE
07202 int sqlite3_extension_init(
07203   sqlite3 *db, 
07204   char **pzErrMsg,
07205   const sqlite3_api_routines *pApi
07206 ){
07207   SQLITE_EXTENSION_INIT2(pApi)
07208   return sqlite3Fts3Init(db);
07209 }
07210 #endif
07211 
07212 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:53 2011 by Doxygen 1.6.1