Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/ext/fts3/fts3.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / ext / fts3 / fts3.c` 6263 lines ยท 211675 bytes Raw Blame History 1 /* 2 ** 2006 Oct 10 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ****************************************************************************** 12 ** 13 ** This is an SQLite module implementing full-text search. 14 */ 15 16 /* 17 ** The code in this file is only compiled if: 18 ** 19 ** * The FTS3 module is being built as an extension 20 ** (in which case SQLITE_CORE is not defined), or 21 ** 22 ** * The FTS3 module is being built into the core of 23 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). 24 */ 25 26 /* The full-text index is stored in a series of b+tree (-like) 27 ** structures called segments which map terms to doclists. The 28 ** structures are like b+trees in layout, but are constructed from the 29 ** bottom up in optimal fashion and are not updatable. Since trees 30 ** are built from the bottom up, things will be described from the 31 ** bottom up. 32 ** 33 ** 34 **** Varints **** 35 ** The basic unit of encoding is a variable-length integer called a 36 ** varint. We encode variable-length integers in little-endian order 37 ** using seven bits * per byte as follows: 38 ** 39 ** KEY: 40 ** A = 0xxxxxxx 7 bits of data and one flag bit 41 ** B = 1xxxxxxx 7 bits of data and one flag bit 42 ** 43 ** 7 bits - A 44 ** 14 bits - BA 45 ** 21 bits - BBA 46 ** and so on. 47 ** 48 ** This is similar in concept to how sqlite encodes "varints" but 49 ** the encoding is not the same. SQLite varints are big-endian 50 ** are are limited to 9 bytes in length whereas FTS3 varints are 51 ** little-endian and can be up to 10 bytes in length (in theory). 52 ** 53 ** Example encodings: 54 ** 55 ** 1: 0x01 56 ** 127: 0x7f 57 ** 128: 0x81 0x00 58 ** 59 ** 60 **** Document lists **** 61 ** A doclist (document list) holds a docid-sorted list of hits for a 62 ** given term. Doclists hold docids and associated token positions. 63 ** A docid is the unique integer identifier for a single document. 64 ** A position is the index of a word within the document. The first 65 ** word of the document has a position of 0. 66 ** 67 ** FTS3 used to optionally store character offsets using a compile-time 68 ** option. But that functionality is no longer supported. 69 ** 70 ** A doclist is stored like this: 71 ** 72 ** array { 73 ** varint docid; (delta from previous doclist) 74 ** array { (position list for column 0) 75 ** varint position; (2 more than the delta from previous position) 76 ** } 77 ** array { 78 ** varint POS_COLUMN; (marks start of position list for new column) 79 ** varint column; (index of new column) 80 ** array { 81 ** varint position; (2 more than the delta from previous position) 82 ** } 83 ** } 84 ** varint POS_END; (marks end of positions for this document. 85 ** } 86 ** 87 ** Here, array { X } means zero or more occurrences of X, adjacent in 88 ** memory. A "position" is an index of a token in the token stream 89 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 90 ** in the same logical place as the position element, and act as sentinels 91 ** ending a position list array. POS_END is 0. POS_COLUMN is 1. 92 ** The positions numbers are not stored literally but rather as two more 93 ** than the difference from the prior position, or the just the position plus 94 ** 2 for the first position. Example: 95 ** 96 ** label: A B C D E F G H I J K 97 ** value: 123 5 9 1 1 14 35 0 234 72 0 98 ** 99 ** The 123 value is the first docid. For column zero in this document 100 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1 101 ** at D signals the start of a new column; the 1 at E indicates that the 102 ** new column is column number 1. There are two positions at 12 and 45 103 ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The 104 ** 234 at I is the delta to next docid (357). It has one position 70 105 ** (72-2) and then terminates with the 0 at K. 106 ** 107 ** A "position-list" is the list of positions for multiple columns for 108 ** a single docid. A "column-list" is the set of positions for a single 109 ** column. Hence, a position-list consists of one or more column-lists, 110 ** a document record consists of a docid followed by a position-list and 111 ** a doclist consists of one or more document records. 112 ** 113 ** A bare doclist omits the position information, becoming an 114 ** array of varint-encoded docids. 115 ** 116 **** Segment leaf nodes **** 117 ** Segment leaf nodes store terms and doclists, ordered by term. Leaf 118 ** nodes are written using LeafWriter, and read using LeafReader (to 119 ** iterate through a single leaf node's data) and LeavesReader (to 120 ** iterate through a segment's entire leaf layer). Leaf nodes have 121 ** the format: 122 ** 123 ** varint iHeight; (height from leaf level, always 0) 124 ** varint nTerm; (length of first term) 125 ** char pTerm[nTerm]; (content of first term) 126 ** varint nDoclist; (length of term's associated doclist) 127 ** char pDoclist[nDoclist]; (content of doclist) 128 ** array { 129 ** (further terms are delta-encoded) 130 ** varint nPrefix; (length of prefix shared with previous term) 131 ** varint nSuffix; (length of unshared suffix) 132 ** char pTermSuffix[nSuffix];(unshared suffix of next term) 133 ** varint nDoclist; (length of term's associated doclist) 134 ** char pDoclist[nDoclist]; (content of doclist) 135 ** } 136 ** 137 ** Here, array { X } means zero or more occurrences of X, adjacent in 138 ** memory. 139 ** 140 ** Leaf nodes are broken into blocks which are stored contiguously in 141 ** the %_segments table in sorted order. This means that when the end 142 ** of a node is reached, the next term is in the node with the next 143 ** greater node id. 144 ** 145 ** New data is spilled to a new leaf node when the current node 146 ** exceeds LEAF_MAX bytes (default 2048). New data which itself is 147 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone 148 ** node (a leaf node with a single term and doclist). The goal of 149 ** these settings is to pack together groups of small doclists while 150 ** making it efficient to directly access large doclists. The 151 ** assumption is that large doclists represent terms which are more 152 ** likely to be query targets. 153 ** 154 ** TODO(shess) It may be useful for blocking decisions to be more 155 ** dynamic. For instance, it may make more sense to have a 2.5k leaf 156 ** node rather than splitting into 2k and .5k nodes. My intuition is 157 ** that this might extend through 2x or 4x the pagesize. 158 ** 159 ** 160 **** Segment interior nodes **** 161 ** Segment interior nodes store blockids for subtree nodes and terms 162 ** to describe what data is stored by the each subtree. Interior 163 ** nodes are written using InteriorWriter, and read using 164 ** InteriorReader. InteriorWriters are created as needed when 165 ** SegmentWriter creates new leaf nodes, or when an interior node 166 ** itself grows too big and must be split. The format of interior 167 ** nodes: 168 ** 169 ** varint iHeight; (height from leaf level, always >0) 170 ** varint iBlockid; (block id of node's leftmost subtree) 171 ** optional { 172 ** varint nTerm; (length of first term) 173 ** char pTerm[nTerm]; (content of first term) 174 ** array { 175 ** (further terms are delta-encoded) 176 ** varint nPrefix; (length of shared prefix with previous term) 177 ** varint nSuffix; (length of unshared suffix) 178 ** char pTermSuffix[nSuffix]; (unshared suffix of next term) 179 ** } 180 ** } 181 ** 182 ** Here, optional { X } means an optional element, while array { X } 183 ** means zero or more occurrences of X, adjacent in memory. 184 ** 185 ** An interior node encodes n terms separating n+1 subtrees. The 186 ** subtree blocks are contiguous, so only the first subtree's blockid 187 ** is encoded. The subtree at iBlockid will contain all terms less 188 ** than the first term encoded (or all terms if no term is encoded). 189 ** Otherwise, for terms greater than or equal to pTerm[i] but less 190 ** than pTerm[i+1], the subtree for that term will be rooted at 191 ** iBlockid+i. Interior nodes only store enough term data to 192 ** distinguish adjacent children (if the rightmost term of the left 193 ** child is "something", and the leftmost term of the right child is 194 ** "wicked", only "w" is stored). 195 ** 196 ** New data is spilled to a new interior node at the same height when 197 ** the current node exceeds INTERIOR_MAX bytes (default 2048). 198 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing 199 ** interior nodes and making the tree too skinny. The interior nodes 200 ** at a given height are naturally tracked by interior nodes at 201 ** height+1, and so on. 202 ** 203 ** 204 **** Segment directory **** 205 ** The segment directory in table %_segdir stores meta-information for 206 ** merging and deleting segments, and also the root node of the 207 ** segment's tree. 208 ** 209 ** The root node is the top node of the segment's tree after encoding 210 ** the entire segment, restricted to ROOT_MAX bytes (default 1024). 211 ** This could be either a leaf node or an interior node. If the top 212 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments 213 ** and a new root interior node is generated (which should always fit 214 ** within ROOT_MAX because it only needs space for 2 varints, the 215 ** height and the blockid of the previous root). 216 ** 217 ** The meta-information in the segment directory is: 218 ** level - segment level (see below) 219 ** idx - index within level 220 ** - (level,idx uniquely identify a segment) 221 ** start_block - first leaf node 222 ** leaves_end_block - last leaf node 223 ** end_block - last block (including interior nodes) 224 ** root - contents of root node 225 ** 226 ** If the root node is a leaf node, then start_block, 227 ** leaves_end_block, and end_block are all 0. 228 ** 229 ** 230 **** Segment merging **** 231 ** To amortize update costs, segments are grouped into levels and 232 ** merged in batches. Each increase in level represents exponentially 233 ** more documents. 234 ** 235 ** New documents (actually, document updates) are tokenized and 236 ** written individually (using LeafWriter) to a level 0 segment, with 237 ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all 238 ** level 0 segments are merged into a single level 1 segment. Level 1 239 ** is populated like level 0, and eventually MERGE_COUNT level 1 240 ** segments are merged to a single level 2 segment (representing 241 ** MERGE_COUNT^2 updates), and so on. 242 ** 243 ** A segment merge traverses all segments at a given level in 244 ** parallel, performing a straightforward sorted merge. Since segment 245 ** leaf nodes are written in to the %_segments table in order, this 246 ** merge traverses the underlying sqlite disk structures efficiently. 247 ** After the merge, all segment blocks from the merged level are 248 ** deleted. 249 ** 250 ** MERGE_COUNT controls how often we merge segments. 16 seems to be 251 ** somewhat of a sweet spot for insertion performance. 32 and 64 show 252 ** very similar performance numbers to 16 on insertion, though they're 253 ** a tiny bit slower (perhaps due to more overhead in merge-time 254 ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than 255 ** 16, 2 about 66% slower than 16. 256 ** 257 ** At query time, high MERGE_COUNT increases the number of segments 258 ** which need to be scanned and merged. For instance, with 100k docs 259 ** inserted: 260 ** 261 ** MERGE_COUNT segments 262 ** 16 25 263 ** 8 12 264 ** 4 10 265 ** 2 6 266 ** 267 ** This appears to have only a moderate impact on queries for very 268 ** frequent terms (which are somewhat dominated by segment merge 269 ** costs), and infrequent and non-existent terms still seem to be fast 270 ** even with many segments. 271 ** 272 ** TODO(shess) That said, it would be nice to have a better query-side 273 ** argument for MERGE_COUNT of 16. Also, it is possible/likely that 274 ** optimizations to things like doclist merging will swing the sweet 275 ** spot around. 276 ** 277 ** 278 ** 279 **** Handling of deletions and updates **** 280 ** Since we're using a segmented structure, with no docid-oriented 281 ** index into the term index, we clearly cannot simply update the term 282 ** index when a document is deleted or updated. For deletions, we 283 ** write an empty doclist (varint(docid) varint(POS_END)), for updates 284 ** we simply write the new doclist. Segment merges overwrite older 285 ** data for a particular docid with newer data, so deletes or updates 286 ** will eventually overtake the earlier data and knock it out. The 287 ** query logic likewise merges doclists so that newer data knocks out 288 ** older data. 289 */ 290 291 #include "fts3Int.h" 292 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) 293 294 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE) 295 # define SQLITE_CORE 1 296 #endif 297 298 299 #include "fts3.h" 300 #ifndef SQLITE_CORE 301 # include "sqlite3ext.h" 302 SQLITE_EXTENSION_INIT1 303 #endif 304 305 306 /* 307 ** Assume any b-tree layer with more levels than this is corrupt. 308 */ 309 #define FTS3_MAX_BTREE_HEIGHT 48 310 311 typedef struct Fts3HashWrapper Fts3HashWrapper; 312 struct Fts3HashWrapper { 313 Fts3Hash hash; /* Hash table */ 314 int nRef; /* Number of pointers to this object */ 315 }; 316 317 static int fts3EvalNext(Fts3Cursor *pCsr); 318 static int fts3EvalStart(Fts3Cursor *pCsr); 319 static int fts3TermSegReaderCursor( 320 Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **); 321 322 /* 323 ** This variable is set to false when running tests for which the on disk 324 ** structures should not be corrupt. Otherwise, true. If it is false, extra 325 ** assert() conditions in the fts3 code are activated - conditions that are 326 ** only true if it is guaranteed that the fts3 database is not corrupt. 327 */ 328 #ifdef SQLITE_DEBUG 329 int sqlite3_fts3_may_be_corrupt = 1; 330 #endif 331 332 /* 333 ** Write a 64-bit variable-length integer to memory starting at p[0]. 334 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes. 335 ** The number of bytes written is returned. 336 */ 337 int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){ 338 unsigned char *q = (unsigned char *) p; 339 sqlite_uint64 vu = v; 340 do{ 341 *q++ = (unsigned char) ((vu & 0x7f) | 0x80); 342 vu >>= 7; 343 }while( vu!=0 ); 344 q[-1] &= 0x7f; /* turn off high bit in final byte */ 345 assert( q - (unsigned char *)p <= FTS3_VARINT_MAX ); 346 return (int) (q - (unsigned char *)p); 347 } 348 349 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \ 350 v = (v & mask1) | ( (*(const unsigned char*)(ptr++)) << shift ); \ 351 if( (v & mask2)==0 ){ var = v; return ret; } 352 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \ 353 v = (*ptr++); \ 354 if( (v & mask2)==0 ){ var = v; return ret; } 355 356 int sqlite3Fts3GetVarintU(const char *pBuf, sqlite_uint64 *v){ 357 const unsigned char *p = (const unsigned char*)pBuf; 358 const unsigned char *pStart = p; 359 u32 a; 360 u64 b; 361 int shift; 362 363 GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1); 364 GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2); 365 GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3); 366 GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4); 367 b = (a & 0x0FFFFFFF ); 368 369 for(shift=28; shift<=63; shift+=7){ 370 u64 c = *p++; 371 b += (c&0x7F) << shift; 372 if( (c & 0x80)==0 ) break; 373 } 374 *v = b; 375 return (int)(p - pStart); 376 } 377 378 /* 379 ** Read a 64-bit variable-length integer from memory starting at p[0]. 380 ** Return the number of bytes read, or 0 on error. 381 ** The value is stored in *v. 382 */ 383 int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){ 384 return sqlite3Fts3GetVarintU(pBuf, (sqlite3_uint64*)v); 385 } 386 387 /* 388 ** Read a 64-bit variable-length integer from memory starting at p[0] and 389 ** not extending past pEnd[-1]. 390 ** Return the number of bytes read, or 0 on error. 391 ** The value is stored in *v. 392 */ 393 int sqlite3Fts3GetVarintBounded( 394 const char *pBuf, 395 const char *pEnd, 396 sqlite_int64 *v 397 ){ 398 const unsigned char *p = (const unsigned char*)pBuf; 399 const unsigned char *pStart = p; 400 const unsigned char *pX = (const unsigned char*)pEnd; 401 u64 b = 0; 402 int shift; 403 for(shift=0; shift<=63; shift+=7){ 404 u64 c = p=0 ); 435 return 5; 436 } 437 438 /* 439 ** Return the number of bytes required to encode v as a varint 440 */ 441 int sqlite3Fts3VarintLen(sqlite3_uint64 v){ 442 int i = 0; 443 do{ 444 i++; 445 v >>= 7; 446 }while( v!=0 ); 447 return i; 448 } 449 450 /* 451 ** Convert an SQL-style quoted string into a normal string by removing 452 ** the quote characters. The conversion is done in-place. If the 453 ** input does not begin with a quote character, then this routine 454 ** is a no-op. 455 ** 456 ** Examples: 457 ** 458 ** "abc" becomes abc 459 ** 'xyz' becomes xyz 460 ** [pqr] becomes pqr 461 ** `mno` becomes mno 462 ** 463 */ 464 void sqlite3Fts3Dequote(char *z){ 465 char quote; /* Quote character (if any ) */ 466 467 quote = z[0]; 468 if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){ 469 int iIn = 1; /* Index of next byte to read from input */ 470 int iOut = 0; /* Index of next byte to write to output */ 471 472 /* If the first byte was a '[', then the close-quote character is a ']' */ 473 if( quote=='[' ) quote = ']'; 474 475 while( z[iIn] ){ 476 if( z[iIn]==quote ){ 477 if( z[iIn+1]!=quote ) break; 478 z[iOut++] = quote; 479 iIn += 2; 480 }else{ 481 z[iOut++] = z[iIn++]; 482 } 483 } 484 z[iOut] = '\0'; 485 } 486 } 487 488 /* 489 ** Read a single varint from the doclist at *pp and advance *pp to point 490 ** to the first byte past the end of the varint. Add the value of the varint 491 ** to *pVal. 492 */ 493 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){ 494 sqlite3_int64 iVal; 495 *pp += sqlite3Fts3GetVarint(*pp, &iVal); 496 *pVal += iVal; 497 } 498 499 /* 500 ** When this function is called, *pp points to the first byte following a 501 ** varint that is part of a doclist (or position-list, or any other list 502 ** of varints). This function moves *pp to point to the start of that varint, 503 ** and sets *pVal by the varint value. 504 ** 505 ** Argument pStart points to the first byte of the doclist that the 506 ** varint is part of. 507 */ 508 static void fts3GetReverseVarint( 509 char **pp, 510 char *pStart, 511 sqlite3_int64 *pVal 512 ){ 513 sqlite3_int64 iVal; 514 char *p; 515 516 /* Pointer p now points at the first byte past the varint we are 517 ** interested in. So, unless the doclist is corrupt, the 0x80 bit is 518 ** clear on character p[-1]. */ 519 for(p = (*pp)-2; p>=pStart && *p&0x80; p--); 520 p++; 521 *pp = p; 522 523 sqlite3Fts3GetVarint(p, &iVal); 524 *pVal = iVal; 525 } 526 527 /* 528 ** The xDisconnect() virtual table method. 529 */ 530 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){ 531 Fts3Table *p = (Fts3Table *)pVtab; 532 int i; 533 534 assert( p->nPendingData==0 ); 535 assert( p->pSegments==0 ); 536 537 /* Free any prepared statements held */ 538 sqlite3_finalize(p->pSeekStmt); 539 for(i=0; iaStmt); i++){ 540 sqlite3_finalize(p->aStmt[i]); 541 } 542 sqlite3_free(p->zSegmentsTbl); 543 sqlite3_free(p->zReadExprlist); 544 sqlite3_free(p->zWriteExprlist); 545 sqlite3_free(p->zContentTbl); 546 sqlite3_free(p->zLanguageid); 547 548 /* Invoke the tokenizer destructor to free the tokenizer. */ 549 p->pTokenizer->pModule->xDestroy(p->pTokenizer); 550 551 sqlite3_free(p); 552 return SQLITE_OK; 553 } 554 555 /* 556 ** Write an error message into *pzErr 557 */ 558 void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){ 559 va_list ap; 560 sqlite3_free(*pzErr); 561 va_start(ap, zFormat); 562 *pzErr = sqlite3_vmprintf(zFormat, ap); 563 va_end(ap); 564 } 565 566 /* 567 ** Construct one or more SQL statements from the format string given 568 ** and then evaluate those statements. The success code is written 569 ** into *pRc. 570 ** 571 ** If *pRc is initially non-zero then this routine is a no-op. 572 */ 573 static void fts3DbExec( 574 int *pRc, /* Success code */ 575 sqlite3 *db, /* Database in which to run SQL */ 576 const char *zFormat, /* Format string for SQL */ 577 ... /* Arguments to the format string */ 578 ){ 579 va_list ap; 580 char *zSql; 581 if( *pRc ) return; 582 va_start(ap, zFormat); 583 zSql = sqlite3_vmprintf(zFormat, ap); 584 va_end(ap); 585 if( zSql==0 ){ 586 *pRc = SQLITE_NOMEM; 587 }else{ 588 *pRc = sqlite3_exec(db, zSql, 0, 0, 0); 589 sqlite3_free(zSql); 590 } 591 } 592 593 /* 594 ** The xDestroy() virtual table method. 595 */ 596 static int fts3DestroyMethod(sqlite3_vtab *pVtab){ 597 Fts3Table *p = (Fts3Table *)pVtab; 598 int rc = SQLITE_OK; /* Return code */ 599 const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */ 600 sqlite3 *db = p->db; /* Database handle */ 601 602 /* Drop the shadow tables */ 603 fts3DbExec(&rc, db, 604 "DROP TABLE IF EXISTS %Q.'%q_segments';" 605 "DROP TABLE IF EXISTS %Q.'%q_segdir';" 606 "DROP TABLE IF EXISTS %Q.'%q_docsize';" 607 "DROP TABLE IF EXISTS %Q.'%q_stat';" 608 "%s DROP TABLE IF EXISTS %Q.'%q_content';", 609 zDb, p->zName, 610 zDb, p->zName, 611 zDb, p->zName, 612 zDb, p->zName, 613 (p->zContentTbl ? "--" : ""), zDb,p->zName 614 ); 615 616 /* If everything has worked, invoke fts3DisconnectMethod() to free the 617 ** memory associated with the Fts3Table structure and return SQLITE_OK. 618 ** Otherwise, return an SQLite error code. 619 */ 620 return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc); 621 } 622 623 624 /* 625 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table 626 ** passed as the first argument. This is done as part of the xConnect() 627 ** and xCreate() methods. 628 ** 629 ** If *pRc is non-zero when this function is called, it is a no-op. 630 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc 631 ** before returning. 632 */ 633 static void fts3DeclareVtab(int *pRc, Fts3Table *p){ 634 if( *pRc==SQLITE_OK ){ 635 int i; /* Iterator variable */ 636 int rc; /* Return code */ 637 char *zSql; /* SQL statement passed to declare_vtab() */ 638 char *zCols; /* List of user defined columns */ 639 const char *zLanguageid; 640 641 zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid"); 642 sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); 643 sqlite3_vtab_config(p->db, SQLITE_VTAB_INNOCUOUS); 644 645 /* Create a list of user columns for the virtual table */ 646 zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]); 647 for(i=1; zCols && inColumn; i++){ 648 zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]); 649 } 650 651 /* Create the whole "CREATE TABLE" statement to pass to SQLite */ 652 zSql = sqlite3_mprintf( 653 "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", 654 zCols, p->zName, zLanguageid 655 ); 656 if( !zCols || !zSql ){ 657 rc = SQLITE_NOMEM; 658 }else{ 659 rc = sqlite3_declare_vtab(p->db, zSql); 660 } 661 662 sqlite3_free(zSql); 663 sqlite3_free(zCols); 664 *pRc = rc; 665 } 666 } 667 668 /* 669 ** Create the %_stat table if it does not already exist. 670 */ 671 void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){ 672 fts3DbExec(pRc, p->db, 673 "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'" 674 "(id INTEGER PRIMARY KEY, value BLOB);", 675 p->zDb, p->zName 676 ); 677 if( (*pRc)==SQLITE_OK ) p->bHasStat = 1; 678 } 679 680 /* 681 ** Create the backing store tables (%_content, %_segments and %_segdir) 682 ** required by the FTS3 table passed as the only argument. This is done 683 ** as part of the vtab xCreate() method. 684 ** 685 ** If the p->bHasDocsize boolean is true (indicating that this is an 686 ** FTS4 table, not an FTS3 table) then also create the %_docsize and 687 ** %_stat tables required by FTS4. 688 */ 689 static int fts3CreateTables(Fts3Table *p){ 690 int rc = SQLITE_OK; /* Return code */ 691 int i; /* Iterator variable */ 692 sqlite3 *db = p->db; /* The database connection */ 693 694 if( p->zContentTbl==0 ){ 695 const char *zLanguageid = p->zLanguageid; 696 char *zContentCols; /* Columns of %_content table */ 697 698 /* Create a list of user columns for the content table */ 699 zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY"); 700 for(i=0; zContentCols && inColumn; i++){ 701 char *z = p->azColumn[i]; 702 zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z); 703 } 704 if( zLanguageid && zContentCols ){ 705 zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid); 706 } 707 if( zContentCols==0 ) rc = SQLITE_NOMEM; 708 709 /* Create the content table */ 710 fts3DbExec(&rc, db, 711 "CREATE TABLE %Q.'%q_content'(%s)", 712 p->zDb, p->zName, zContentCols 713 ); 714 sqlite3_free(zContentCols); 715 } 716 717 /* Create other tables */ 718 fts3DbExec(&rc, db, 719 "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);", 720 p->zDb, p->zName 721 ); 722 fts3DbExec(&rc, db, 723 "CREATE TABLE %Q.'%q_segdir'(" 724 "level INTEGER," 725 "idx INTEGER," 726 "start_block INTEGER," 727 "leaves_end_block INTEGER," 728 "end_block INTEGER," 729 "root BLOB," 730 "PRIMARY KEY(level, idx)" 731 ");", 732 p->zDb, p->zName 733 ); 734 if( p->bHasDocsize ){ 735 fts3DbExec(&rc, db, 736 "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);", 737 p->zDb, p->zName 738 ); 739 } 740 assert( p->bHasStat==p->bFts4 ); 741 if( p->bHasStat ){ 742 sqlite3Fts3CreateStatTable(&rc, p); 743 } 744 return rc; 745 } 746 747 /* 748 ** Store the current database page-size in bytes in p->nPgsz. 749 ** 750 ** If *pRc is non-zero when this function is called, it is a no-op. 751 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc 752 ** before returning. 753 */ 754 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){ 755 if( *pRc==SQLITE_OK ){ 756 int rc; /* Return code */ 757 char *zSql; /* SQL text "PRAGMA %Q.page_size" */ 758 sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */ 759 760 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb); 761 if( !zSql ){ 762 rc = SQLITE_NOMEM; 763 }else{ 764 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); 765 if( rc==SQLITE_OK ){ 766 sqlite3_step(pStmt); 767 p->nPgsz = sqlite3_column_int(pStmt, 0); 768 rc = sqlite3_finalize(pStmt); 769 }else if( rc==SQLITE_AUTH ){ 770 p->nPgsz = 1024; 771 rc = SQLITE_OK; 772 } 773 } 774 assert( p->nPgsz>0 || rc!=SQLITE_OK ); 775 sqlite3_free(zSql); 776 *pRc = rc; 777 } 778 } 779 780 /* 781 ** "Special" FTS4 arguments are column specifications of the following form: 782 ** 783 ** = 784 ** 785 ** There may not be whitespace surrounding the "=" character. The 786 ** term may be quoted, but the may not. 787 */ 788 static int fts3IsSpecialColumn( 789 const char *z, 790 int *pnKey, 791 char **pzValue 792 ){ 793 char *zValue; 794 const char *zCsr = z; 795 796 while( *zCsr!='=' ){ 797 if( *zCsr=='\0' ) return 0; 798 zCsr++; 799 } 800 801 *pnKey = (int)(zCsr-z); 802 zValue = sqlite3_mprintf("%s", &zCsr[1]); 803 if( zValue ){ 804 sqlite3Fts3Dequote(zValue); 805 } 806 *pzValue = zValue; 807 return 1; 808 } 809 810 /* 811 ** Append the output of a printf() style formatting to an existing string. 812 */ 813 static void fts3Appendf( 814 int *pRc, /* IN/OUT: Error code */ 815 char **pz, /* IN/OUT: Pointer to string buffer */ 816 const char *zFormat, /* Printf format string to append */ 817 ... /* Arguments for printf format string */ 818 ){ 819 if( *pRc==SQLITE_OK ){ 820 va_list ap; 821 char *z; 822 va_start(ap, zFormat); 823 z = sqlite3_vmprintf(zFormat, ap); 824 va_end(ap); 825 if( z && *pz ){ 826 char *z2 = sqlite3_mprintf("%s%s", *pz, z); 827 sqlite3_free(z); 828 z = z2; 829 } 830 if( z==0 ) *pRc = SQLITE_NOMEM; 831 sqlite3_free(*pz); 832 *pz = z; 833 } 834 } 835 836 /* 837 ** Return a copy of input string zInput enclosed in double-quotes (") and 838 ** with all double quote characters escaped. For example: 839 ** 840 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\"" 841 ** 842 ** The pointer returned points to memory obtained from sqlite3_malloc(). It 843 ** is the callers responsibility to call sqlite3_free() to release this 844 ** memory. 845 */ 846 static char *fts3QuoteId(char const *zInput){ 847 sqlite3_int64 nRet; 848 char *zRet; 849 nRet = 2 + (int)strlen(zInput)*2 + 1; 850 zRet = sqlite3_malloc64(nRet); 851 if( zRet ){ 852 int i; 853 char *z = zRet; 854 *(z++) = '"'; 855 for(i=0; zInput[i]; i++){ 856 if( zInput[i]=='"' ) *(z++) = '"'; 857 *(z++) = zInput[i]; 858 } 859 *(z++) = '"'; 860 *(z++) = '\0'; 861 } 862 return zRet; 863 } 864 865 /* 866 ** Return a list of comma separated SQL expressions and a FROM clause that 867 ** could be used in a SELECT statement such as the following: 868 ** 869 ** SELECT FROM %_content AS x ... 870 ** 871 ** to return the docid, followed by each column of text data in order 872 ** from left to write. If parameter zFunc is not NULL, then instead of 873 ** being returned directly each column of text data is passed to an SQL 874 ** function named zFunc first. For example, if zFunc is "unzip" and the 875 ** table has the three user-defined columns "a", "b", and "c", the following 876 ** string is returned: 877 ** 878 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x" 879 ** 880 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It 881 ** is the responsibility of the caller to eventually free it. 882 ** 883 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and 884 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered 885 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If 886 ** no error occurs, *pRc is left unmodified. 887 */ 888 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){ 889 char *zRet = 0; 890 char *zFree = 0; 891 char *zFunction; 892 int i; 893 894 if( p->zContentTbl==0 ){ 895 if( !zFunc ){ 896 zFunction = ""; 897 }else{ 898 zFree = zFunction = fts3QuoteId(zFunc); 899 if( zFunction==0 ) *pRc = SQLITE_NOMEM; 900 } 901 fts3Appendf(pRc, &zRet, "docid"); 902 for(i=0; inColumn; i++){ 903 fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]); 904 } 905 if( p->zLanguageid ){ 906 fts3Appendf(pRc, &zRet, ", x.%Q", "langid"); 907 } 908 sqlite3_free(zFree); 909 }else{ 910 fts3Appendf(pRc, &zRet, "rowid"); 911 for(i=0; inColumn; i++){ 912 fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]); 913 } 914 if( p->zLanguageid ){ 915 fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid); 916 } 917 } 918 fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", 919 p->zDb, 920 (p->zContentTbl ? p->zContentTbl : p->zName), 921 (p->zContentTbl ? "" : "_content") 922 ); 923 return zRet; 924 } 925 926 /* 927 ** Return a list of N comma separated question marks, where N is the number 928 ** of columns in the %_content table (one for the docid plus one for each 929 ** user-defined text column). 930 ** 931 ** If argument zFunc is not NULL, then all but the first question mark 932 ** is preceded by zFunc and an open bracket, and followed by a closed 933 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three 934 ** user-defined text columns, the following string is returned: 935 ** 936 ** "?, zip(?), zip(?), zip(?)" 937 ** 938 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It 939 ** is the responsibility of the caller to eventually free it. 940 ** 941 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and 942 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered 943 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If 944 ** no error occurs, *pRc is left unmodified. 945 */ 946 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){ 947 char *zRet = 0; 948 char *zFree = 0; 949 char *zFunction; 950 int i; 951 952 if( !zFunc ){ 953 zFunction = ""; 954 }else{ 955 zFree = zFunction = fts3QuoteId(zFunc); 956 if( zFunction==0 ) *pRc = SQLITE_NOMEM; 957 } 958 fts3Appendf(pRc, &zRet, "?"); 959 for(i=0; inColumn; i++){ 960 fts3Appendf(pRc, &zRet, ",%s(?)", zFunction); 961 } 962 if( p->zLanguageid ){ 963 fts3Appendf(pRc, &zRet, ", ?"); 964 } 965 sqlite3_free(zFree); 966 return zRet; 967 } 968 969 /* 970 ** Buffer z contains a positive integer value encoded as utf-8 text. 971 ** Decode this value and store it in *pnOut, returning the number of bytes 972 ** consumed. If an overflow error occurs return a negative value. 973 */ 974 int sqlite3Fts3ReadInt(const char *z, int *pnOut){ 975 u64 iVal = 0; 976 int i; 977 for(i=0; z[i]>='0' && z[i]<='9'; i++){ 978 iVal = iVal*10 + (z[i] - '0'); 979 if( iVal>0x7FFFFFFF ) return -1; 980 } 981 *pnOut = (int)iVal; 982 return i; 983 } 984 985 /* 986 ** This function interprets the string at (*pp) as a non-negative integer 987 ** value. It reads the integer and sets *pnOut to the value read, then 988 ** sets *pp to point to the byte immediately following the last byte of 989 ** the integer value. 990 ** 991 ** Only decimal digits ('0'..'9') may be part of an integer value. 992 ** 993 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and 994 ** the output value undefined. Otherwise SQLITE_OK is returned. 995 ** 996 ** This function is used when parsing the "prefix=" FTS4 parameter. 997 */ 998 static int fts3GobbleInt(const char **pp, int *pnOut){ 999 const int MAX_NPREFIX = `10000000`; 1000 int nInt = 0; /* Output value */ 1001 int nByte; 1002 nByte = sqlite3Fts3ReadInt(*pp, &nInt); 1003 if( nInt>MAX_NPREFIX ){ 1004 nInt = 0; 1005 } 1006 if( nByte==0 ){ 1007 return SQLITE_ERROR; 1008 } 1009 *pnOut = nInt; 1010 *pp += nByte; 1011 return SQLITE_OK; 1012 } 1013 1014 /* 1015 ** This function is called to allocate an array of Fts3Index structures 1016 ** representing the indexes maintained by the current FTS table. FTS tables 1017 ** always maintain the main "terms" index, but may also maintain one or 1018 ** more "prefix" indexes, depending on the value of the "prefix=" parameter 1019 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement. 1020 ** 1021 ** Argument zParam is passed the value of the "prefix=" option if one was 1022 ** specified, or NULL otherwise. 1023 ** 1024 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to 1025 ** the allocated array. *pnIndex is set to the number of elements in the 1026 ** array. If an error does occur, an SQLite error code is returned. 1027 ** 1028 ** Regardless of whether or not an error is returned, it is the responsibility 1029 ** of the caller to call sqlite3_free() on the output array to free it. 1030 */ 1031 static int fts3PrefixParameter( 1032 const char *zParam, /* ABC in prefix=ABC parameter to parse */ 1033 int *pnIndex, /* OUT: size of *apIndex[] array */ 1034 struct Fts3Index **apIndex /* OUT: Array of indexes for this table */ 1035 ){ 1036 struct Fts3Index *aIndex; /* Allocated array */ 1037 int nIndex = 1; /* Number of entries in array */ 1038 1039 if( zParam && zParam[0] ){ 1040 const char *p; 1041 nIndex++; 1042 for(p=zParam; *p; p++){ 1043 if( *p==',' ) nIndex++; 1044 } 1045 } 1046 1047 aIndex = sqlite3_malloc64(sizeof(struct Fts3Index) * nIndex); 1048 *apIndex = aIndex; 1049 if( !aIndex ){ 1050 return SQLITE_NOMEM; 1051 } 1052 1053 memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex); 1054 if( zParam ){ 1055 const char *p = zParam; 1056 int i; 1057 for(i=1; i=0 ); 1061 if( nPrefix==0 ){ 1062 nIndex--; 1063 i--; 1064 }else{ 1065 aIndex[i].nPrefix = nPrefix; 1066 } 1067 p++; 1068 } 1069 } 1070 1071 *pnIndex = nIndex; 1072 return SQLITE_OK; 1073 } 1074 1075 /* 1076 ** This function is called when initializing an FTS4 table that uses the 1077 ** content=xxx option. It determines the number of and names of the columns 1078 ** of the new FTS4 table. 1079 ** 1080 ** The third argument passed to this function is the value passed to the 1081 ** config=xxx option (i.e. "xxx"). This function queries the database for 1082 ** a table of that name. If found, the output variables are populated 1083 ** as follows: 1084 ** 1085 ** *pnCol: Set to the number of columns table xxx has, 1086 ** 1087 ** *pnStr: Set to the total amount of space required to store a copy 1088 ** of each columns name, including the nul-terminator. 1089 ** 1090 ** *pazCol: Set to point to an array of *pnCol strings. Each string is 1091 ** the name of the corresponding column in table xxx. The array 1092 ** and its contents are allocated using a single allocation. It 1093 ** is the responsibility of the caller to free this allocation 1094 ** by eventually passing the *pazCol value to sqlite3_free(). 1095 ** 1096 ** If the table cannot be found, an error code is returned and the output 1097 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is 1098 ** returned (and the output variables are undefined). 1099 */ 1100 static int fts3ContentColumns( 1101 sqlite3 *db, /* Database handle */ 1102 const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */ 1103 const char *zTbl, /* Name of content table */ 1104 const char ***pazCol, /* OUT: Malloc'd array of column names */ 1105 int *pnCol, /* OUT: Size of array *pazCol */ 1106 int *pnStr, /* OUT: Bytes of string content */ 1107 char **pzErr /* OUT: error message */ 1108 ){ 1109 int rc = SQLITE_OK; /* Return code */ 1110 char *zSql; /* "SELECT *" statement on zTbl */ 1111 sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */ 1112 1113 zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl); 1114 if( !zSql ){ 1115 rc = SQLITE_NOMEM; 1116 }else{ 1117 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); 1118 if( rc!=SQLITE_OK ){ 1119 sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db)); 1120 } 1121 } 1122 sqlite3_free(zSql); 1123 1124 if( rc==SQLITE_OK ){ 1125 const char **azCol; /* Output array */ 1126 sqlite3_int64 nStr = 0; /* Size of all column names (incl. 0x00) */ 1127 int nCol; /* Number of table columns */ 1128 int i; /* Used to iterate through columns */ 1129 1130 /* Loop through the returned columns. Set nStr to the number of bytes of 1131 ** space required to store a copy of each column name, including the 1132 ** nul-terminator byte. */ 1133 nCol = sqlite3_column_count(pStmt); 1134 for(i=0; i module name ("fts3" or "fts4") 1175 ** argv[1] -> database name 1176 ** argv[2] -> table name 1177 ** argv[...] -> "column name" and other module argument fields. 1178 */ 1179 static int fts3InitVtab( 1180 int isCreate, /* True for xCreate, false for xConnect */ 1181 sqlite3 *db, /* The SQLite database connection */ 1182 void *pAux, /* Hash table containing tokenizers */ 1183 int argc, /* Number of elements in argv array */ 1184 const char * const *argv, /* xCreate/xConnect argument array */ 1185 sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ 1186 char **pzErr /* Write any error message here */ 1187 ){ 1188 Fts3Hash *pHash = &((Fts3HashWrapper*)pAux)->hash; 1189 Fts3Table *p = 0; /* Pointer to allocated vtab */ 1190 int rc = SQLITE_OK; /* Return code */ 1191 int i; /* Iterator variable */ 1192 sqlite3_int64 nByte; /* Size of allocation used for *p */ 1193 int iCol; /* Column index */ 1194 int nString = 0; /* Bytes required to hold all column names */ 1195 int nCol = 0; /* Number of columns in the FTS table */ 1196 char *zCsr; /* Space for holding column names */ 1197 int nDb; /* Bytes required to hold database name */ 1198 int nName; /* Bytes required to hold table name */ 1199 int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */ 1200 const char **aCol; /* Array of column names */ 1201 sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */ 1202 1203 int nIndex = 0; /* Size of aIndex[] array */ 1204 struct Fts3Index *aIndex = 0; /* Array of indexes for this table */ 1205 1206 /* The results of parsing supported FTS4 key=value options: */ 1207 int bNoDocsize = 0; /* True to omit %_docsize table */ 1208 int bDescIdx = 0; /* True to store descending indexes */ 1209 char *zPrefix = 0; /* Prefix parameter value (or NULL) */ 1210 char *zCompress = 0; /* compress=? parameter (or NULL) */ 1211 char *zUncompress = 0; /* uncompress=? parameter (or NULL) */ 1212 char *zContent = 0; /* content=? parameter (or NULL) */ 1213 char *zLanguageid = 0; /* languageid=? parameter (or NULL) */ 1214 char **azNotindexed = 0; /* The set of notindexed= columns */ 1215 int nNotindexed = 0; /* Size of azNotindexed[] array */ 1216 1217 assert( strlen(argv[0])==4 ); 1218 assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4) 1219 || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4) 1220 ); 1221 1222 nDb = (int)strlen(argv[1]) + 1; 1223 nName = (int)strlen(argv[2]) + 1; 1224 1225 nByte = sizeof(const char *) * (argc-2); 1226 aCol = (const char **)sqlite3_malloc64(nByte); 1227 if( aCol ){ 1228 memset((void*)aCol, 0, nByte); 1229 azNotindexed = (char **)sqlite3_malloc64(nByte); 1230 } 1231 if( azNotindexed ){ 1232 memset(azNotindexed, 0, nByte); 1233 } 1234 if( !aCol || !azNotindexed ){ 1235 rc = SQLITE_NOMEM; 1236 goto fts3_init_out; 1237 } 1238 1239 /* Loop through all of the arguments passed by the user to the FTS3/4 1240 ** module (i.e. all the column names and special arguments). This loop 1241 ** does the following: 1242 ** 1243 ** + Figures out the number of columns the FTSX table will have, and 1244 ** the number of bytes of space that must be allocated to store copies 1245 ** of the column names. 1246 ** 1247 ** + If there is a tokenizer specification included in the arguments, 1248 ** initializes the tokenizer pTokenizer. 1249 */ 1250 for(i=3; rc==SQLITE_OK && i8 1258 && 0==sqlite3_strnicmp(z, "tokenize", 8) 1259 && 0==sqlite3Fts3IsIdChar(z[8]) 1260 ){ 1261 rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr); 1262 } 1263 1264 /* Check if it is an FTS4 special argument. */ 1265 else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){ 1266 struct Fts4Option { 1267 const char *zOpt; 1268 int nOpt; 1269 } aFts4Opt[] = { 1270 { "matchinfo", 9 }, /* 0 -> MATCHINFO */ 1271 { "prefix", 6 }, /* 1 -> PREFIX */ 1272 { "compress", 8 }, /* 2 -> COMPRESS */ 1273 { "uncompress", 10 }, /* 3 -> UNCOMPRESS */ 1274 { "order", 5 }, /* 4 -> ORDER */ 1275 { "content", 7 }, /* 5 -> CONTENT */ 1276 { "languageid", 10 }, /* 6 -> LANGUAGEID */ 1277 { "notindexed", 10 } /* 7 -> NOTINDEXED */ 1278 }; 1279 1280 int iOpt; 1281 if( !zVal ){ 1282 rc = SQLITE_NOMEM; 1283 }else{ 1284 for(iOpt=0; iOptnOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){ 1287 break; 1288 } 1289 } 1290 switch( iOpt ){ 1291 case 0: /* MATCHINFO */ 1292 if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){ 1293 sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal); 1294 rc = SQLITE_ERROR; 1295 } 1296 bNoDocsize = 1; 1297 break; 1298 1299 case 1: /* PREFIX */ 1300 sqlite3_free(zPrefix); 1301 zPrefix = zVal; 1302 zVal = 0; 1303 break; 1304 1305 case 2: /* COMPRESS */ 1306 sqlite3_free(zCompress); 1307 zCompress = zVal; 1308 zVal = 0; 1309 break; 1310 1311 case 3: /* UNCOMPRESS */ 1312 sqlite3_free(zUncompress); 1313 zUncompress = zVal; 1314 zVal = 0; 1315 break; 1316 1317 case 4: /* ORDER */ 1318 if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) 1319 && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) 1320 ){ 1321 sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal); 1322 rc = SQLITE_ERROR; 1323 } 1324 bDescIdx = (zVal[0]=='d' || zVal[0]=='D'); 1325 break; 1326 1327 case 5: /* CONTENT */ 1328 sqlite3_free(zContent); 1329 zContent = zVal; 1330 zVal = 0; 1331 break; 1332 1333 case 6: /* LANGUAGEID */ 1334 assert( iOpt==6 ); 1335 sqlite3_free(zLanguageid); 1336 zLanguageid = zVal; 1337 zVal = 0; 1338 break; 1339 1340 case 7: /* NOTINDEXED */ 1341 azNotindexed[nNotindexed++] = zVal; 1342 zVal = 0; 1343 break; 1344 1345 default: 1346 assert( iOpt==SizeofArray(aFts4Opt) ); 1347 sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z); 1348 rc = SQLITE_ERROR; 1349 break; 1350 } 1351 sqlite3_free(zVal); 1352 } 1353 } 1354 1355 /* Otherwise, the argument is a column name. */ 1356 else { 1357 nString += (int)(strlen(z) + 1); 1358 aCol[nCol++] = z; 1359 } 1360 } 1361 1362 /* If a content=xxx option was specified, the following: 1363 ** 1364 ** 1. Ignore any compress= and uncompress= options. 1365 ** 1366 ** 2. If no column names were specified as part of the CREATE VIRTUAL 1367 ** TABLE statement, use all columns from the content table. 1368 */ 1369 if( rc==SQLITE_OK && zContent ){ 1370 sqlite3_free(zCompress); 1371 sqlite3_free(zUncompress); 1372 zCompress = 0; 1373 zUncompress = 0; 1374 if( nCol==0 ){ 1375 sqlite3_free((void*)aCol); 1376 aCol = 0; 1377 rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr); 1378 1379 /* If a languageid= option was specified, remove the language id 1380 ** column from the aCol[] array. */ 1381 if( rc==SQLITE_OK && zLanguageid ){ 1382 int j; 1383 for(j=0; jdb = db; 1431 p->nColumn = nCol; 1432 p->nPendingData = 0; 1433 p->azColumn = (char **)&p[1]; 1434 p->pTokenizer = pTokenizer; 1435 p->nMaxPendingData = FTS3_MAX_PENDING_DATA; 1436 p->bHasDocsize = (isFts4 && bNoDocsize==0); 1437 p->bHasStat = (u8)isFts4; 1438 p->bFts4 = (u8)isFts4; 1439 p->bDescIdx = (u8)bDescIdx; 1440 p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */ 1441 p->zContentTbl = zContent; 1442 p->zLanguageid = zLanguageid; 1443 zContent = 0; 1444 zLanguageid = 0; 1445 TESTONLY( p->inTransaction = -1 ); 1446 TESTONLY( p->mxSavepoint = -1 ); 1447 1448 p->aIndex = (struct Fts3Index *)&p->azColumn[nCol]; 1449 memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex); 1450 p->nIndex = nIndex; 1451 for(i=0; iaIndex[i].hPending, FTS3_HASH_STRING, 1); 1453 } 1454 p->abNotindexed = (u8 *)&p->aIndex[nIndex]; 1455 1456 /* Fill in the zName and zDb fields of the vtab structure. */ 1457 zCsr = (char *)&p->abNotindexed[nCol]; 1458 p->zName = zCsr; 1459 memcpy(zCsr, argv[2], nName); 1460 zCsr += nName; 1461 p->zDb = zCsr; 1462 memcpy(zCsr, argv[1], nDb); 1463 zCsr += nDb; 1464 1465 /* Fill in the azColumn array */ 1466 for(iCol=0; iCol0 ){ 1471 memcpy(zCsr, z, n); 1472 } 1473 zCsr[n] = '\0'; 1474 sqlite3Fts3Dequote(zCsr); 1475 p->azColumn[iCol] = zCsr; 1476 zCsr += n+1; 1477 assert( zCsr <= &((char *)p)[nByte] ); 1478 } 1479 1480 /* Fill in the abNotindexed array */ 1481 for(iCol=0; iColazColumn[iCol]); 1483 for(i=0; iazColumn[iCol], zNot, n) 1487 ){ 1488 p->abNotindexed[iCol] = 1; 1489 sqlite3_free(zNot); 1490 azNotindexed[i] = 0; 1491 } 1492 } 1493 } 1494 for(i=0; izReadExprlist = fts3ReadExprList(p, zUncompress, &rc); 1507 p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc); 1508 if( rc!=SQLITE_OK ) goto fts3_init_out; 1509 1510 /* If this is an xCreate call, create the underlying tables in the 1511 ** database. TODO: For xConnect(), it could verify that said tables exist. 1512 */ 1513 if( isCreate ){ 1514 rc = fts3CreateTables(p); 1515 } 1516 1517 /* Check to see if a legacy fts3 table has been "upgraded" by the 1518 ** addition of a %_stat table so that it can use incremental merge. 1519 */ 1520 if( !isFts4 && !isCreate ){ 1521 p->bHasStat = 2; 1522 } 1523 1524 /* Figure out the page-size for the database. This is required in order to 1525 ** estimate the cost of loading large doclists from the database. */ 1526 fts3DatabasePageSize(&rc, p); 1527 p->nNodeSize = p->nPgsz-35; 1528 1529 #if defined(SQLITE_DEBUG)||defined(SQLITE_TEST) 1530 p->nMergeCount = FTS3_MERGE_COUNT; 1531 #endif 1532 1533 /* Declare the table schema to SQLite. */ 1534 fts3DeclareVtab(&rc, p); 1535 1536 fts3_init_out: 1537 sqlite3_free(zPrefix); 1538 sqlite3_free(aIndex); 1539 sqlite3_free(zCompress); 1540 sqlite3_free(zUncompress); 1541 sqlite3_free(zContent); 1542 sqlite3_free(zLanguageid); 1543 for(i=0; ipModule->xDestroy(pTokenizer); 1551 } 1552 }else{ 1553 assert( p->pSegments==0 ); 1554 *ppVTab = &p->base; 1555 } 1556 return rc; 1557 } 1558 1559 /* 1560 ** The xConnect() and xCreate() methods for the virtual table. All the 1561 ** work is done in function fts3InitVtab(). 1562 */ 1563 static int fts3ConnectMethod( 1564 sqlite3 *db, /* Database connection */ 1565 void *pAux, /* Pointer to tokenizer hash table */ 1566 int argc, /* Number of elements in argv array */ 1567 const char * const *argv, /* xCreate/xConnect argument array */ 1568 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ 1569 char **pzErr /* OUT: sqlite3_malloc'd error message */ 1570 ){ 1571 return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr); 1572 } 1573 static int fts3CreateMethod( 1574 sqlite3 *db, /* Database connection */ 1575 void *pAux, /* Pointer to tokenizer hash table */ 1576 int argc, /* Number of elements in argv array */ 1577 const char * const *argv, /* xCreate/xConnect argument array */ 1578 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ 1579 char **pzErr /* OUT: sqlite3_malloc'd error message */ 1580 ){ 1581 return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr); 1582 } 1583 1584 /* 1585 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this 1586 ** extension is currently being used by a version of SQLite too old to 1587 ** support estimatedRows. In that case this function is a no-op. 1588 */ 1589 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){ 1590 #if SQLITE_VERSION_NUMBER>=`3008002` 1591 if( sqlite3_libversion_number()>=`3008002` ){ 1592 pIdxInfo->estimatedRows = nRow; 1593 } 1594 #endif 1595 } 1596 1597 /* 1598 ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this 1599 ** extension is currently being used by a version of SQLite too old to 1600 ** support index-info flags. In that case this function is a no-op. 1601 */ 1602 static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){ 1603 #if SQLITE_VERSION_NUMBER>=`3008012` 1604 if( sqlite3_libversion_number()>=`3008012` ){ 1605 pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE; 1606 } 1607 #endif 1608 } 1609 1610 /* 1611 ** Implementation of the xBestIndex method for FTS3 tables. There 1612 ** are three possible strategies, in order of preference: 1613 ** 1614 ** 1. Direct lookup by rowid or docid. 1615 ** 2. Full-text search using a MATCH operator on a non-docid column. 1616 ** 3. Linear scan of %_content table. 1617 */ 1618 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ 1619 Fts3Table *p = (Fts3Table *)pVTab; 1620 int i; /* Iterator variable */ 1621 int iCons = -1; /* Index of constraint to use */ 1622 1623 int iLangidCons = -1; /* Index of langid=x constraint, if present */ 1624 int iDocidGe = -1; /* Index of docid>=x constraint, if present */ 1625 int iDocidLe = -1; /* Index of docid<=x constraint, if present */ 1626 int iIdx; 1627 1628 if( p->bLock ){ 1629 return SQLITE_ERROR; 1630 } 1631 1632 /* By default use a full table scan. This is an expensive option, 1633 ** so search through the constraints to see if a more efficient 1634 ** strategy is possible. 1635 */ 1636 pInfo->idxNum = FTS3_FULLSCAN_SEARCH; 1637 pInfo->estimatedCost = `5000000`; 1638 for(i=0; inConstraint; i++){ 1639 int bDocid; /* True if this constraint is on docid */ 1640 struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i]; 1641 if( pCons->usable==0 ){ 1642 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){ 1643 /* There exists an unusable MATCH constraint. This means that if 1644 ** the planner does elect to use the results of this call as part 1645 ** of the overall query plan the user will see an "unable to use 1646 ** function MATCH in the requested context" error. To discourage 1647 ** this, return a very high cost here. */ 1648 pInfo->idxNum = FTS3_FULLSCAN_SEARCH; 1649 pInfo->estimatedCost = 1e50; 1650 fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50); 1651 return SQLITE_OK; 1652 } 1653 continue; 1654 } 1655 1656 bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1); 1657 1658 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */ 1659 if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){ 1660 pInfo->idxNum = FTS3_DOCID_SEARCH; 1661 pInfo->estimatedCost = 1.0; 1662 iCons = i; 1663 } 1664 1665 /* A MATCH constraint. Use a full-text search. 1666 ** 1667 ** If there is more than one MATCH constraint available, use the first 1668 ** one encountered. If there is both a MATCH constraint and a direct 1669 ** rowid/docid lookup, prefer the MATCH strategy. This is done even 1670 ** though the rowid/docid lookup is faster than a MATCH query, selecting 1671 ** it would lead to an "unable to use function MATCH in the requested 1672 ** context" error. 1673 */ 1674 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 1675 && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn 1676 ){ 1677 pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn; 1678 pInfo->estimatedCost = 2.0; 1679 iCons = i; 1680 } 1681 1682 /* Equality constraint on the langid column */ 1683 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 1684 && pCons->iColumn==p->nColumn + 2 1685 ){ 1686 iLangidCons = i; 1687 } 1688 1689 if( bDocid ){ 1690 switch( pCons->op ){ 1691 case SQLITE_INDEX_CONSTRAINT_GE: 1692 case SQLITE_INDEX_CONSTRAINT_GT: 1693 iDocidGe = i; 1694 break; 1695 1696 case SQLITE_INDEX_CONSTRAINT_LE: 1697 case SQLITE_INDEX_CONSTRAINT_LT: 1698 iDocidLe = i; 1699 break; 1700 } 1701 } 1702 } 1703 1704 /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */ 1705 if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo); 1706 1707 iIdx = 1; 1708 if( iCons>=0 ){ 1709 pInfo->aConstraintUsage[iCons].argvIndex = iIdx++; 1710 pInfo->aConstraintUsage[iCons].omit = 1; 1711 } 1712 if( iLangidCons>=0 ){ 1713 pInfo->idxNum |= FTS3_HAVE_LANGID; 1714 pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++; 1715 } 1716 if( iDocidGe>=0 ){ 1717 pInfo->idxNum |= FTS3_HAVE_DOCID_GE; 1718 pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++; 1719 } 1720 if( iDocidLe>=0 ){ 1721 pInfo->idxNum |= FTS3_HAVE_DOCID_LE; 1722 pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++; 1723 } 1724 1725 /* Regardless of the strategy selected, FTS can deliver rows in rowid (or 1726 ** docid) order. Both ascending and descending are possible. 1727 */ 1728 if( pInfo->nOrderBy==1 ){ 1729 struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0]; 1730 if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){ 1731 if( pOrder->desc ){ 1732 pInfo->idxStr = "DESC"; 1733 }else{ 1734 pInfo->idxStr = "ASC"; 1735 } 1736 pInfo->orderByConsumed = 1; 1737 } 1738 } 1739 1740 assert( p->pSegments==0 ); 1741 return SQLITE_OK; 1742 } 1743 1744 /* 1745 ** Implementation of xOpen method. 1746 */ 1747 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ 1748 sqlite3_vtab_cursor *pCsr; /* Allocated cursor */ 1749 1750 UNUSED_PARAMETER(pVTab); 1751 1752 /* Allocate a buffer large enough for an Fts3Cursor structure. If the 1753 ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 1754 ** if the allocation fails, return SQLITE_NOMEM. 1755 */ 1756 *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor)); 1757 if( !pCsr ){ 1758 return SQLITE_NOMEM; 1759 } 1760 memset(pCsr, 0, sizeof(Fts3Cursor)); 1761 return SQLITE_OK; 1762 } 1763 1764 /* 1765 ** Finalize the statement handle at pCsr->pStmt. 1766 ** 1767 ** Or, if that statement handle is one created by fts3CursorSeekStmt(), 1768 ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement 1769 ** pointer there instead of finalizing it. 1770 */ 1771 static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){ 1772 if( pCsr->bSeekStmt ){ 1773 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; 1774 if( p->pSeekStmt==0 ){ 1775 p->pSeekStmt = pCsr->pStmt; 1776 sqlite3_reset(pCsr->pStmt); 1777 pCsr->pStmt = 0; 1778 } 1779 pCsr->bSeekStmt = 0; 1780 } 1781 sqlite3_finalize(pCsr->pStmt); 1782 } 1783 1784 /* 1785 ** Free all resources currently held by the cursor passed as the only 1786 ** argument. 1787 */ 1788 static void fts3ClearCursor(Fts3Cursor *pCsr){ 1789 fts3CursorFinalizeStmt(pCsr); 1790 sqlite3Fts3FreeDeferredTokens(pCsr); 1791 sqlite3_free(pCsr->aDoclist); 1792 sqlite3Fts3MIBufferFree(pCsr->pMIBuffer); 1793 sqlite3Fts3ExprFree(pCsr->pExpr); 1794 memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor)); 1795 } 1796 1797 /* 1798 ** Close the cursor. For additional information see the documentation 1799 ** on the xClose method of the virtual table interface. 1800 */ 1801 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){ 1802 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; 1803 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); 1804 fts3ClearCursor(pCsr); 1805 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); 1806 sqlite3_free(pCsr); 1807 return SQLITE_OK; 1808 } 1809 1810 /* 1811 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then 1812 ** compose and prepare an SQL statement of the form: 1813 ** 1814 ** "SELECT FROM %_content WHERE rowid = ?" 1815 ** 1816 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to 1817 ** it. If an error occurs, return an SQLite error code. 1818 */ 1819 static int fts3CursorSeekStmt(Fts3Cursor *pCsr){ 1820 int rc = SQLITE_OK; 1821 if( pCsr->pStmt==0 ){ 1822 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; 1823 char *zSql; 1824 if( p->pSeekStmt ){ 1825 pCsr->pStmt = p->pSeekStmt; 1826 p->pSeekStmt = 0; 1827 }else{ 1828 zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist); 1829 if( !zSql ) return SQLITE_NOMEM; 1830 p->bLock++; 1831 rc = sqlite3Fts3PrepareStmt(p, zSql, 1, 1, &pCsr->pStmt); 1832 p->bLock--; 1833 sqlite3_free(zSql); 1834 } 1835 if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1; 1836 } 1837 return rc; 1838 } 1839 1840 /* 1841 ** Position the pCsr->pStmt statement so that it is on the row 1842 ** of the %_content table that contains the last match. Return 1843 ** SQLITE_OK on success. 1844 */ 1845 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){ 1846 int rc = SQLITE_OK; 1847 if( pCsr->isRequireSeek ){ 1848 rc = fts3CursorSeekStmt(pCsr); 1849 if( rc==SQLITE_OK ){ 1850 Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab; 1851 pTab->bLock++; 1852 sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId); 1853 pCsr->isRequireSeek = 0; 1854 if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){ 1855 pTab->bLock--; 1856 return SQLITE_OK; 1857 }else{ 1858 pTab->bLock--; 1859 rc = sqlite3_reset(pCsr->pStmt); 1860 if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){ 1861 /* If no row was found and no error has occurred, then the %_content 1862 ** table is missing a row that is present in the full-text index. 1863 ** The data structures are corrupt. */ 1864 rc = FTS_CORRUPT_VTAB; 1865 pCsr->isEof = 1; 1866 } 1867 } 1868 } 1869 } 1870 1871 if( rc!=SQLITE_OK && pContext ){ 1872 sqlite3_result_error_code(pContext, rc); 1873 } 1874 return rc; 1875 } 1876 1877 /* 1878 ** This function is used to process a single interior node when searching 1879 ** a b-tree for a term or term prefix. The node data is passed to this 1880 ** function via the zNode/nNode parameters. The term to search for is 1881 ** passed in zTerm/nTerm. 1882 ** 1883 ** If piFirst is not NULL, then this function sets *piFirst to the blockid 1884 ** of the child node that heads the sub-tree that may contain the term. 1885 ** 1886 ** If piLast is not NULL, then *piLast is set to the right-most child node 1887 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is 1888 ** a prefix. 1889 ** 1890 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK. 1891 */ 1892 static int fts3ScanInteriorNode( 1893 const char *zTerm, /* Term to select leaves for */ 1894 int nTerm, /* Size of term zTerm in bytes */ 1895 const char *zNode, /* Buffer containing segment interior node */ 1896 int nNode, /* Size of buffer at zNode */ 1897 sqlite3_int64 *piFirst, /* OUT: Selected child node */ 1898 sqlite3_int64 *piLast /* OUT: Selected child node */ 1899 ){ 1900 int rc = SQLITE_OK; /* Return code */ 1901 const char *zCsr = zNode; /* Cursor to iterate through node */ 1902 const char *zEnd = &zCsr[nNode];/* End of interior node buffer */ 1903 char *zBuffer = 0; /* Buffer to load terms into */ 1904 i64 nAlloc = 0; /* Size of allocated buffer */ 1905 int isFirstTerm = 1; /* True when processing first term on page */ 1906 u64 iChild; /* Block id of child node to descend to */ 1907 int nBuffer = 0; /* Total term size */ 1908 1909 /* Skip over the 'height' varint that occurs at the start of every 1910 ** interior node. Then load the blockid of the left-child of the b-tree 1911 ** node into variable iChild. 1912 ** 1913 ** Even if the data structure on disk is corrupted, this (reading two 1914 ** varints from the buffer) does not risk an overread. If zNode is a 1915 ** root node, then the buffer comes from a SELECT statement. SQLite does 1916 ** not make this guarantee explicitly, but in practice there are always 1917 ** either more than 20 bytes of allocated space following the nNode bytes of 1918 ** contents, or two zero bytes. Or, if the node is read from the %_segments 1919 ** table, then there are always 20 bytes of zeroed padding following the 1920 ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details). 1921 */ 1922 zCsr += sqlite3Fts3GetVarintU(zCsr, &iChild); 1923 zCsr += sqlite3Fts3GetVarintU(zCsr, &iChild); 1924 if( zCsr>zEnd ){ 1925 return FTS_CORRUPT_VTAB; 1926 } 1927 1928 while( zCsrnBuffer ){ 1938 rc = FTS_CORRUPT_VTAB; 1939 goto finish_scan; 1940 } 1941 } 1942 isFirstTerm = 0; 1943 zCsr += fts3GetVarint32(zCsr, &nSuffix); 1944 1945 assert( nPrefix>=0 && nSuffix>=0 ); 1946 if( nPrefix>zCsr-zNode || nSuffix>zEnd-zCsr || nSuffix==0 ){ 1947 rc = FTS_CORRUPT_VTAB; 1948 goto finish_scan; 1949 } 1950 if( (i64)nPrefix+nSuffix>nAlloc ){ 1951 char *zNew; 1952 nAlloc = ((i64)nPrefix+nSuffix) * 2; 1953 zNew = (char *)sqlite3_realloc64(zBuffer, nAlloc); 1954 if( !zNew ){ 1955 rc = SQLITE_NOMEM; 1956 goto finish_scan; 1957 } 1958 zBuffer = zNew; 1959 } 1960 assert( zBuffer ); 1961 memcpy(&zBuffer[nPrefix], zCsr, nSuffix); 1962 nBuffer = nPrefix + nSuffix; 1963 zCsr += nSuffix; 1964 1965 /* Compare the term we are searching for with the term just loaded from 1966 ** the interior node. If the specified term is greater than or equal 1967 ** to the term from the interior node, then all terms on the sub-tree 1968 ** headed by node iChild are smaller than zTerm. No need to search 1969 ** iChild. 1970 ** 1971 ** If the interior node term is larger than the specified term, then 1972 ** the tree headed by iChild may contain the specified term. 1973 */ 1974 cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer)); 1975 if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){ 1976 *piFirst = (i64)iChild; 1977 piFirst = 0; 1978 } 1979 1980 if( piLast && cmp<0 ){ 1981 *piLast = (i64)iChild; 1982 piLast = 0; 1983 } 1984 1985 iChild++; 1986 }; 1987 1988 if( piFirst ) *piFirst = (i64)iChild; 1989 if( piLast ) *piLast = (i64)iChild; 1990 1991 finish_scan: 1992 sqlite3_free(zBuffer); 1993 return rc; 1994 } 1995 1996 1997 /* 1998 ** The buffer pointed to by argument zNode (size nNode bytes) contains an 1999 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes) 2000 ** contains a term. This function searches the sub-tree headed by the zNode 2001 ** node for the range of leaf nodes that may contain the specified term 2002 ** or terms for which the specified term is a prefix. 2003 ** 2004 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 2005 ** left-most leaf node in the tree that may contain the specified term. 2006 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the 2007 ** right-most leaf node that may contain a term for which the specified 2008 ** term is a prefix. 2009 ** 2010 ** It is possible that the range of returned leaf nodes does not contain 2011 ** the specified term or any terms for which it is a prefix. However, if the 2012 ** segment does contain any such terms, they are stored within the identified 2013 ** range. Because this function only inspects interior segment nodes (and 2014 ** never loads leaf nodes into memory), it is not possible to be sure. 2015 ** 2016 ** If an error occurs, an error code other than SQLITE_OK is returned. 2017 */ 2018 static int fts3SelectLeaf( 2019 Fts3Table *p, /* Virtual table handle */ 2020 const char *zTerm, /* Term to select leaves for */ 2021 int nTerm, /* Size of term zTerm in bytes */ 2022 const char *zNode, /* Buffer containing segment interior node */ 2023 int nNode, /* Size of buffer at zNode */ 2024 sqlite3_int64 *piLeaf, /* Selected leaf node */ 2025 sqlite3_int64 *piLeaf2 /* Selected leaf node */ 2026 ){ 2027 int rc = SQLITE_OK; /* Return code */ 2028 int iHeight; /* Height of this node in tree */ 2029 2030 assert( piLeaf || piLeaf2 ); 2031 2032 fts3GetVarint32(zNode, &iHeight); 2033 if( iHeight>FTS3_MAX_BTREE_HEIGHT ){ 2034 rc = FTS_CORRUPT_VTAB; 2035 }else{ 2036 rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2); 2037 } 2038 assert_fts3_nc( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) ); 2039 2040 if( rc==SQLITE_OK && iHeight>1 ){ 2041 char *zBlob = 0; /* Blob read from %_segments table */ 2042 int nBlob = 0; /* Size of zBlob in bytes */ 2043 2044 if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){ 2045 rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0); 2046 if( rc==SQLITE_OK ){ 2047 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0); 2048 } 2049 sqlite3_free(zBlob); 2050 piLeaf = 0; 2051 zBlob = 0; 2052 } 2053 2054 if( rc==SQLITE_OK ){ 2055 rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0); 2056 } 2057 if( rc==SQLITE_OK ){ 2058 int iNewHeight = 0; 2059 fts3GetVarint32(zBlob, &iNewHeight); 2060 if( iNewHeight>=iHeight ){ 2061 rc = FTS_CORRUPT_VTAB; 2062 }else{ 2063 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2); 2064 } 2065 } 2066 sqlite3_free(zBlob); 2067 } 2068 2069 return rc; 2070 } 2071 2072 /* 2073 ** This function is used to create delta-encoded serialized lists of FTS3 2074 ** varints. Each call to this function appends a single varint to a list. 2075 */ 2076 static void fts3PutDeltaVarint( 2077 char **pp, /* IN/OUT: Output pointer */ 2078 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ 2079 sqlite3_int64 iVal /* Write this value to the list */ 2080 ){ 2081 assert_fts3_nc( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) ); 2082 if( iVal-(*piPrev)>=0 ){ 2083 /* Refuse to write a negative delta integer. This only happens with a 2084 ** corrupt db (see the assert above) and can cause buffer overwrites 2085 ** in some cases. */ 2086 *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev); 2087 *piPrev = iVal; 2088 } 2089 } 2090 2091 /* 2092 ** When this function is called, *ppPoslist is assumed to point to the 2093 ** start of a position-list. After it returns, *ppPoslist points to the 2094 ** first byte after the position-list. 2095 ** 2096 ** A position list is list of positions (delta encoded) and columns for 2097 ** a single document record of a doclist. So, in other words, this 2098 ** routine advances *ppPoslist so that it points to the next docid in 2099 ** the doclist, or to the first byte past the end of the doclist. 2100 ** 2101 ** If pp is not NULL, then the contents of the position list are copied 2102 ** to *pp. *pp is set to point to the first byte past the last byte copied 2103 ** before this function returns. 2104 */ 2105 static void fts3PoslistCopy(char **pp, char **ppPoslist){ 2106 char *pEnd = *ppPoslist; 2107 char c = 0; 2108 2109 /* The end of a position list is marked by a zero encoded as an FTS3 2110 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by 2111 ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail 2112 ** of some other, multi-byte, value. 2113 ** 2114 ** The following while-loop moves pEnd to point to the first byte that is not 2115 ** immediately preceded by a byte with the 0x80 bit set. Then increments 2116 ** pEnd once more so that it points to the byte immediately following the 2117 ** last byte in the position-list. 2118 */ 2119 while( *pEnd | c ){ 2120 c = *pEnd++ & 0x80; 2121 testcase( c!=0 && (*pEnd)==0 ); 2122 } 2123 pEnd++; /* Advance past the POS_END terminator byte */ 2124 2125 if( pp ){ 2126 int n = (int)(pEnd - *ppPoslist); 2127 char *p = *pp; 2128 memcpy(p, *ppPoslist, n); 2129 p += n; 2130 *pp = p; 2131 } 2132 *ppPoslist = pEnd; 2133 } 2134 2135 /* 2136 ** When this function is called, *ppPoslist is assumed to point to the 2137 ** start of a column-list. After it returns, *ppPoslist points to the 2138 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list. 2139 ** 2140 ** A column-list is list of delta-encoded positions for a single column 2141 ** within a single document within a doclist. 2142 ** 2143 ** The column-list is terminated either by a POS_COLUMN varint (1) or 2144 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to 2145 ** the POS_COLUMN or POS_END that terminates the column-list. 2146 ** 2147 ** If pp is not NULL, then the contents of the column-list are copied 2148 ** to *pp. *pp is set to point to the first byte past the last byte copied 2149 ** before this function returns. The POS_COLUMN or POS_END terminator 2150 ** is not copied into *pp. 2151 */ 2152 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){ 2153 char *pEnd = *ppPoslist; 2154 char c = 0; 2155 2156 /* A column-list is terminated by either a 0x01 or 0x00 byte that is 2157 ** not part of a multi-byte varint. 2158 */ 2159 while( 0xFE & (*pEnd | c) ){ 2160 c = *pEnd++ & 0x80; 2161 testcase( c!=0 && ((*pEnd)&0xfe)==0 ); 2162 } 2163 if( pp ){ 2164 int n = (int)(pEnd - *ppPoslist); 2165 char *p = *pp; 2166 memcpy(p, *ppPoslist, n); 2167 p += n; 2168 *pp = p; 2169 } 2170 *ppPoslist = pEnd; 2171 } 2172 2173 /* 2174 ** Value used to signify the end of an position-list. This must be 2175 ** as large or larger than any value that might appear on the 2176 ** position-list, even a position list that has been corrupted. 2177 */ 2178 #define POSITION_LIST_END LARGEST_INT64 2179 2180 /* 2181 ** This function is used to help parse position-lists. When this function is 2182 ** called, *pp may point to the start of the next varint in the position-list 2183 ** being parsed, or it may point to 1 byte past the end of the position-list 2184 ** (in which case **pp will be a terminator bytes POS_END (0) or 2185 ** (1)). 2186 ** 2187 ** If *pp points past the end of the current position-list, set *pi to 2188 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp, 2189 ** increment the current value of *pi by the value read, and set *pp to 2190 ** point to the next value before returning. 2191 ** 2192 ** Before calling this routine *pi must be initialized to the value of 2193 ** the previous position, or zero if we are reading the first position 2194 ** in the position-list. Because positions are delta-encoded, the value 2195 ** of the previous position is needed in order to compute the value of 2196 ** the next position. 2197 */ 2198 static void fts3ReadNextPos( 2199 char **pp, /* IN/OUT: Pointer into position-list buffer */ 2200 sqlite3_int64 *pi /* IN/OUT: Value read from position-list */ 2201 ){ 2202 if( (**pp)&0xFE ){ 2203 int iVal; 2204 *pp += fts3GetVarint32((*pp), &iVal); 2205 *pi += iVal; 2206 *pi -= 2; 2207 }else{ 2208 *pi = POSITION_LIST_END; 2209 } 2210 } 2211 2212 /* 2213 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by 2214 ** the value of iCol encoded as a varint to *pp. This will start a new 2215 ** column list. 2216 ** 2217 ** Set *pp to point to the byte just after the last byte written before 2218 ** returning (do not modify it if iCol==0). Return the total number of bytes 2219 ** written (0 if iCol==0). 2220 */ 2221 static int fts3PutColNumber(char **pp, int iCol){ 2222 int n = 0; /* Number of bytes written */ 2223 if( iCol ){ 2224 char *p = *pp; /* Output pointer */ 2225 n = 1 + sqlite3Fts3PutVarint(&p[1], iCol); 2226 *p = 0x01; 2227 *pp = &p[n]; 2228 } 2229 return n; 2230 } 2231 2232 /* 2233 ** Compute the union of two position lists. The output written 2234 ** into *pp contains all positions of both *pp1 and *pp2 in sorted 2235 ** order and with any duplicates removed. All pointers are 2236 ** updated appropriately. The caller is responsible for insuring 2237 ** that there is enough space in *pp to hold the complete output. 2238 */ 2239 static int fts3PoslistMerge( 2240 char **pp, /* Output buffer */ 2241 char **pp1, /* Left input list */ 2242 char **pp2 /* Right input list */ 2243 ){ 2244 char *p = *pp; 2245 char *p1 = *pp1; 2246 char *p2 = *pp2; 2247 2248 while( *p1 || *p2 ){ 2249 int iCol1; /* The current column index in pp1 */ 2250 int iCol2; /* The current column index in pp2 */ 2251 2252 if( *p1==POS_COLUMN ){ 2253 fts3GetVarint32(&p1[1], &iCol1); 2254 if( iCol1==0 ) return FTS_CORRUPT_VTAB; 2255 } 2256 else if( *p1==POS_END ) iCol1 = 0x7fffffff; 2257 else iCol1 = 0; 2258 2259 if( *p2==POS_COLUMN ){ 2260 fts3GetVarint32(&p2[1], &iCol2); 2261 if( iCol2==0 ) return FTS_CORRUPT_VTAB; 2262 } 2263 else if( *p2==POS_END ) iCol2 = 0x7fffffff; 2264 else iCol2 = 0; 2265 2266 if( iCol1==iCol2 ){ 2267 sqlite3_int64 i1 = 0; /* Last position from pp1 */ 2268 sqlite3_int64 i2 = 0; /* Last position from pp2 */ 2269 sqlite3_int64 iPrev = 0; 2270 int n = fts3PutColNumber(&p, iCol1); 2271 p1 += n; 2272 p2 += n; 2273 2274 /* At this point, both p1 and p2 point to the start of column-lists 2275 ** for the same column (the column with index iCol1 and iCol2). 2276 ** A column-list is a list of non-negative delta-encoded varints, each 2277 ** incremented by 2 before being stored. Each list is terminated by a 2278 ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists 2279 ** and writes the results to buffer p. p is left pointing to the byte 2280 ** after the list written. No terminator (POS_END or POS_COLUMN) is 2281 ** written to the output. 2282 */ 2283 fts3GetDeltaVarint(&p1, &i1); 2284 fts3GetDeltaVarint(&p2, &i2); 2285 if( i1<2 || i2<2 ){ 2286 break; 2287 } 2288 do { 2289 fts3PutDeltaVarint(&p, &iPrev, (i1pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e. 2334 ** when the *pp1 token appears before the *pp2 token, but not more than nToken 2335 ** slots before it. 2336 ** 2337 ** e.g. nToken==1 searches for adjacent positions. 2338 */ 2339 static int fts3PoslistPhraseMerge( 2340 char **pp, /* IN/OUT: Preallocated output buffer */ 2341 int nToken, /* Maximum difference in token positions */ 2342 int isSaveLeft, /* Save the left position */ 2343 int isExact, /* If *pp1 is exactly nTokens before *pp2 */ 2344 char **pp1, /* IN/OUT: Left input list */ 2345 char **pp2 /* IN/OUT: Right input list */ 2346 ){ 2347 char *p = *pp; 2348 char *p1 = *pp1; 2349 char *p2 = *pp2; 2350 int iCol1 = 0; 2351 int iCol2 = 0; 2352 2353 /* Never set both isSaveLeft and isExact for the same invocation. */ 2354 assert( isSaveLeft==0 || isExact==0 ); 2355 2356 assert_fts3_nc( p!=0 && *p1!=0 && *p2!=0 ); 2357 if( *p1==POS_COLUMN ){ 2358 p1++; 2359 p1 += fts3GetVarint32(p1, &iCol1); 2360 /* iCol1==0 indicates corruption. Column 0 does not have a POS_COLUMN 2361 ** entry, so this is actually end-of-doclist. */ 2362 if( iCol1==0 ) return 0; 2363 } 2364 if( *p2==POS_COLUMN ){ 2365 p2++; 2366 p2 += fts3GetVarint32(p2, &iCol2); 2367 /* As above, iCol2==0 indicates corruption. */ 2368 if( iCol2==0 ) return 0; 2369 } 2370 2371 while( 1 ){ 2372 if( iCol1==iCol2 ){ 2373 char *pSave = p; 2374 sqlite3_int64 iPrev = 0; 2375 sqlite3_int64 iPos1 = 0; 2376 sqlite3_int64 iPos2 = 0; 2377 2378 if( iCol1 ){ 2379 *p++ = POS_COLUMN; 2380 p += sqlite3Fts3PutVarint(p, iCol1); 2381 } 2382 2383 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; 2384 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; 2385 if( iPos1<0 || iPos2<0 ) break; 2386 2387 while( 1 ){ 2388 if( iPos2==iPos1+nToken 2389 || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 2390 ){ 2391 sqlite3_int64 iSave; 2392 iSave = isSaveLeft ? iPos1 : iPos2; 2393 fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2; 2394 pSave = 0; 2395 assert( p ); 2396 } 2397 if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){ 2398 if( (*p2&0xFE)==0 ) break; 2399 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; 2400 }else{ 2401 if( (*p1&0xFE)==0 ) break; 2402 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; 2403 } 2404 } 2405 2406 if( pSave ){ 2407 assert( pp && p ); 2408 p = pSave; 2409 } 2410 2411 fts3ColumnlistCopy(0, &p1); 2412 fts3ColumnlistCopy(0, &p2); 2413 assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 ); 2414 if( 0==*p1 || 0==*p2 ) break; 2415 2416 p1++; 2417 p1 += fts3GetVarint32(p1, &iCol1); 2418 p2++; 2419 p2 += fts3GetVarint32(p2, &iCol2); 2420 } 2421 2422 /* Advance pointer p1 or p2 (whichever corresponds to the smaller of 2423 ** iCol1 and iCol2) so that it points to either the 0x00 that marks the 2424 ** end of the position list, or the 0x01 that precedes the next 2425 ** column-number in the position list. 2426 */ 2427 else if( iCol1=pEnd ){ 2532 *pp = 0; 2533 }else{ 2534 u64 iVal; 2535 *pp += sqlite3Fts3GetVarintU(*pp, &iVal); 2536 if( bDescIdx ){ 2537 *pVal = (i64)((u64)*pVal - iVal); 2538 }else{ 2539 *pVal = (i64)((u64)*pVal + iVal); 2540 } 2541 } 2542 } 2543 2544 /* 2545 ** This function is used to write a single varint to a buffer. The varint 2546 ** is written to *pp. Before returning, *pp is set to point 1 byte past the 2547 ** end of the value written. 2548 ** 2549 ** If *pbFirst is zero when this function is called, the value written to 2550 ** the buffer is that of parameter iVal. 2551 ** 2552 ** If *pbFirst is non-zero when this function is called, then the value 2553 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal) 2554 ** (if bDescIdx is non-zero). 2555 ** 2556 ** Before returning, this function always sets *pbFirst to 1 and *piPrev 2557 ** to the value of parameter iVal. 2558 */ 2559 static void fts3PutDeltaVarint3( 2560 char **pp, /* IN/OUT: Output pointer */ 2561 int bDescIdx, /* True for descending docids */ 2562 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ 2563 int *pbFirst, /* IN/OUT: True after first int written */ 2564 sqlite3_int64 iVal /* Write this value to the list */ 2565 ){ 2566 sqlite3_uint64 iWrite; 2567 if( bDescIdx==0 || *pbFirst==0 ){ 2568 assert_fts3_nc( *pbFirst==0 || iVal>=*piPrev ); 2569 iWrite = (u64)iVal - (u64)*piPrev; 2570 }else{ 2571 assert_fts3_nc( *piPrev>=iVal ); 2572 iWrite = (u64)*piPrev - (u64)iVal; 2573 } 2574 assert( *pbFirst || *piPrev==0 ); 2575 assert_fts3_nc( *pbFirst==0 || iWrite>0 ); 2576 *pp += sqlite3Fts3PutVarint(*pp, iWrite); 2577 *piPrev = iVal; 2578 *pbFirst = 1; 2579 } 2580 2581 2582 /* 2583 ** This macro is used by various functions that merge doclists. The two 2584 ** arguments are 64-bit docid values. If the value of the stack variable 2585 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). 2586 ** Otherwise, (i2-i1). 2587 ** 2588 ** Using this makes it easier to write code that can merge doclists that are 2589 ** sorted in either ascending or descending order. 2590 */ 2591 /* #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i64)((u64)i1-i2)) */ 2592 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1>i2?1:((i1==i2)?0:-1))) 2593 2594 /* 2595 ** This function does an "OR" merge of two doclists (output contains all 2596 ** positions contained in either argument doclist). If the docids in the 2597 ** input doclists are sorted in ascending order, parameter bDescDoclist 2598 ** should be false. If they are sorted in ascending order, it should be 2599 ** passed a non-zero value. 2600 ** 2601 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer 2602 ** containing the output doclist and SQLITE_OK is returned. In this case 2603 ** *pnOut is set to the number of bytes in the output doclist. 2604 ** 2605 ** If an error occurs, an SQLite error code is returned. The output values 2606 ** are undefined in this case. 2607 */ 2608 static int fts3DoclistOrMerge( 2609 int bDescDoclist, /* True if arguments are desc */ 2610 char *a1, int n1, /* First doclist */ 2611 char *a2, int n2, /* Second doclist */ 2612 char **paOut, int *pnOut /* OUT: Malloc'd doclist */ 2613 ){ 2614 int rc = SQLITE_OK; 2615 sqlite3_int64 i1 = 0; 2616 sqlite3_int64 i2 = 0; 2617 sqlite3_int64 iPrev = 0; 2618 char *pEnd1 = &a1[n1]; 2619 char *pEnd2 = &a2[n2]; 2620 char *p1 = a1; 2621 char *p2 = a2; 2622 char *p; 2623 char *aOut; 2624 int bFirstOut = 0; 2625 2626 *paOut = 0; 2627 *pnOut = 0; 2628 2629 /* Allocate space for the output. Both the input and output doclists 2630 ** are delta encoded. If they are in ascending order (bDescDoclist==0), 2631 ** then the first docid in each list is simply encoded as a varint. For 2632 ** each subsequent docid, the varint stored is the difference between the 2633 ** current and previous docid (a positive number - since the list is in 2634 ** ascending order). 2635 ** 2636 ** The first docid written to the output is therefore encoded using the 2637 ** same number of bytes as it is in whichever of the input lists it is 2638 ** read from. And each subsequent docid read from the same input list 2639 ** consumes either the same or less bytes as it did in the input (since 2640 ** the difference between it and the previous value in the output must 2641 ** be a positive value less than or equal to the delta value read from 2642 ** the input list). The same argument applies to all but the first docid 2643 ** read from the 'other' list. And to the contents of all position lists 2644 ** that will be copied and merged from the input to the output. 2645 ** 2646 ** However, if the first docid copied to the output is a negative number, 2647 ** then the encoding of the first docid from the 'other' input list may 2648 ** be larger in the output than it was in the input (since the delta value 2649 ** may be a larger positive integer than the actual docid). 2650 ** 2651 ** The space required to store the output is therefore the sum of the 2652 ** sizes of the two inputs, plus enough space for exactly one of the input 2653 ** docids to grow. 2654 ** 2655 ** A symmetric argument may be made if the doclists are in descending 2656 ** order. 2657 */ 2658 aOut = sqlite3_malloc64((i64)n1+n2+FTS3_VARINT_MAX-1+FTS3_BUFFER_PADDING); 2659 if( !aOut ) return SQLITE_NOMEM; 2660 2661 p = aOut; 2662 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1); 2663 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2); 2664 while( p1 || p2 ){ 2665 sqlite3_int64 iDiff = DOCID_CMP(i1, i2); 2666 2667 if( p2 && p1 && iDiff==0 ){ 2668 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); 2669 rc = fts3PoslistMerge(&p, &p1, &p2); 2670 if( rc ) break; 2671 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); 2672 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); 2673 }else if( !p2 || (p1 && iDiff<0) ){ 2674 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); 2675 fts3PoslistCopy(&p, &p1); 2676 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); 2677 }else{ 2678 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2); 2679 fts3PoslistCopy(&p, &p2); 2680 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); 2681 } 2682 2683 assert( (p-aOut)<=((p1?(p1-a1):n1)+(p2?(p2-a2):n2)+FTS3_VARINT_MAX-1) ); 2684 } 2685 2686 if( rc!=SQLITE_OK ){ 2687 sqlite3_free(aOut); 2688 p = aOut = 0; 2689 }else{ 2690 assert( (p-aOut)<=n1+n2+FTS3_VARINT_MAX-1 ); 2691 memset(&aOut[(p-aOut)], 0, FTS3_BUFFER_PADDING); 2692 } 2693 *paOut = aOut; 2694 *pnOut = (int)(p-aOut); 2695 return rc; 2696 } 2697 2698 /* 2699 ** This function does a "phrase" merge of two doclists. In a phrase merge, 2700 ** the output contains a copy of each position from the right-hand input 2701 ** doclist for which there is a position in the left-hand input doclist 2702 ** exactly nDist tokens before it. 2703 ** 2704 ** If the docids in the input doclists are sorted in ascending order, 2705 ** parameter bDescDoclist should be false. If they are sorted in ascending 2706 ** order, it should be passed a non-zero value. 2707 ** 2708 ** The right-hand input doclist is overwritten by this function. 2709 */ 2710 static int fts3DoclistPhraseMerge( 2711 int bDescDoclist, /* True if arguments are desc */ 2712 int nDist, /* Distance from left to right (1=adjacent) */ 2713 char *aLeft, int nLeft, /* Left doclist */ 2714 char **paRight, int *pnRight /* IN/OUT: Right/output doclist */ 2715 ){ 2716 sqlite3_int64 i1 = 0; 2717 sqlite3_int64 i2 = 0; 2718 sqlite3_int64 iPrev = 0; 2719 char *aRight = *paRight; 2720 char *pEnd1 = &aLeft[nLeft]; 2721 char *pEnd2 = &aRight[*pnRight]; 2722 char *p1 = aLeft; 2723 char *p2 = aRight; 2724 char *p; 2725 int bFirstOut = 0; 2726 char *aOut; 2727 2728 assert( nDist>0 ); 2729 if( bDescDoclist ){ 2730 aOut = sqlite3_malloc64((sqlite3_int64)*pnRight + FTS3_VARINT_MAX); 2731 if( aOut==0 ) return SQLITE_NOMEM; 2732 }else{ 2733 aOut = aRight; 2734 } 2735 p = aOut; 2736 2737 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1); 2738 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2); 2739 2740 while( p1 && p2 ){ 2741 sqlite3_int64 iDiff = DOCID_CMP(i1, i2); 2742 if( iDiff==0 ){ 2743 char *pSave = p; 2744 sqlite3_int64 iPrevSave = iPrev; 2745 int bFirstOutSave = bFirstOut; 2746 2747 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); 2748 if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){ 2749 p = pSave; 2750 iPrev = iPrevSave; 2751 bFirstOut = bFirstOutSave; 2752 } 2753 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); 2754 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); 2755 }else if( iDiff<0 ){ 2756 fts3PoslistCopy(0, &p1); 2757 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); 2758 }else{ 2759 fts3PoslistCopy(0, &p2); 2760 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); 2761 } 2762 } 2763 2764 *pnRight = (int)(p - aOut); 2765 if( bDescDoclist ){ 2766 sqlite3_free(aRight); 2767 *paRight = aOut; 2768 } 2769 2770 return SQLITE_OK; 2771 } 2772 2773 /* 2774 ** Argument pList points to a position list nList bytes in size. This 2775 ** function checks to see if the position list contains any entries for 2776 ** a token in position 0 (of any column). If so, it writes argument iDelta 2777 ** to the output buffer pOut, followed by a position list consisting only 2778 ** of the entries from pList at position 0, and terminated by an 0x00 byte. 2779 ** The value returned is the number of bytes written to pOut (if any). 2780 */ 2781 int sqlite3Fts3FirstFilter( 2782 sqlite3_int64 iDelta, /* Varint that may be written to pOut */ 2783 char *pList, /* Position list (no 0x00 term) */ 2784 int nList, /* Size of pList in bytes */ 2785 char *pOut /* Write output here */ 2786 ){ 2787 int nOut = 0; 2788 int bWritten = 0; /* True once iDelta has been written */ 2789 char *p = pList; 2790 char *pEnd = &pList[nList]; 2791 2792 if( *p!=0x01 ){ 2793 if( *p==0x02 ){ 2794 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta); 2795 pOut[nOut++] = 0x02; 2796 bWritten = 1; 2797 } 2798 fts3ColumnlistCopy(0, &p); 2799 } 2800 2801 while( paaOutput); i++){ 2842 if( pTS->aaOutput[i] ){ 2843 if( !aOut ){ 2844 aOut = pTS->aaOutput[i]; 2845 nOut = pTS->anOutput[i]; 2846 pTS->aaOutput[i] = 0; 2847 }else{ 2848 int nNew; 2849 char *aNew; 2850 2851 int rc = fts3DoclistOrMerge(p->bDescIdx, 2852 pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew 2853 ); 2854 if( rc!=SQLITE_OK ){ 2855 sqlite3_free(aOut); 2856 return rc; 2857 } 2858 2859 sqlite3_free(pTS->aaOutput[i]); 2860 sqlite3_free(aOut); 2861 pTS->aaOutput[i] = 0; 2862 aOut = aNew; 2863 nOut = nNew; 2864 } 2865 } 2866 } 2867 2868 pTS->aaOutput[0] = aOut; 2869 pTS->anOutput[0] = nOut; 2870 return SQLITE_OK; 2871 } 2872 2873 /* 2874 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed 2875 ** as the first argument. The merge is an "OR" merge (see function 2876 ** fts3DoclistOrMerge() for details). 2877 ** 2878 ** This function is called with the doclist for each term that matches 2879 ** a queried prefix. It merges all these doclists into one, the doclist 2880 ** for the specified prefix. Since there can be a very large number of 2881 ** doclists to merge, the merging is done pair-wise using the TermSelect 2882 ** object. 2883 ** 2884 ** This function returns SQLITE_OK if the merge is successful, or an 2885 ** SQLite error code (SQLITE_NOMEM) if an error occurs. 2886 */ 2887 static int fts3TermSelectMerge( 2888 Fts3Table *p, /* FTS table handle */ 2889 TermSelect *pTS, /* TermSelect object to merge into */ 2890 char *aDoclist, /* Pointer to doclist */ 2891 int nDoclist /* Size of aDoclist in bytes */ 2892 ){ 2893 if( pTS->aaOutput[0]==0 ){ 2894 /* If this is the first term selected, copy the doclist to the output 2895 ** buffer using memcpy(). 2896 ** 2897 ** Add FTS3_VARINT_MAX bytes of unused space to the end of the 2898 ** allocation. This is so as to ensure that the buffer is big enough 2899 ** to hold the current doclist AND'd with any other doclist. If the 2900 ** doclists are stored in order=ASC order, this padding would not be 2901 ** required (since the size of [doclistA AND doclistB] is always less 2902 ** than or equal to the size of [doclistA] in that case). But this is 2903 ** not true for order=DESC. For example, a doclist containing (1, -1) 2904 ** may be smaller than (-1), as in the first example the -1 may be stored 2905 ** as a single-byte delta, whereas in the second it must be stored as a 2906 ** FTS3_VARINT_MAX byte varint. 2907 ** 2908 ** Similar padding is added in the fts3DoclistOrMerge() function. 2909 */ 2910 pTS->aaOutput[0] = sqlite3_malloc64((i64)nDoclist + FTS3_VARINT_MAX + 1); 2911 pTS->anOutput[0] = nDoclist; 2912 if( pTS->aaOutput[0] ){ 2913 memcpy(pTS->aaOutput[0], aDoclist, nDoclist); 2914 memset(&pTS->aaOutput[0][nDoclist], 0, FTS3_VARINT_MAX); 2915 }else{ 2916 return SQLITE_NOMEM; 2917 } 2918 }else{ 2919 char *aMerge = aDoclist; 2920 int nMerge = nDoclist; 2921 int iOut; 2922 2923 for(iOut=0; iOutaaOutput); iOut++){ 2924 if( pTS->aaOutput[iOut]==0 ){ 2925 assert( iOut>0 ); 2926 pTS->aaOutput[iOut] = aMerge; 2927 pTS->anOutput[iOut] = nMerge; 2928 break; 2929 }else{ 2930 char *aNew; 2931 int nNew; 2932 2933 int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, 2934 pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew 2935 ); 2936 if( rc!=SQLITE_OK ){ 2937 if( aMerge!=aDoclist ) sqlite3_free(aMerge); 2938 return rc; 2939 } 2940 2941 if( aMerge!=aDoclist ) sqlite3_free(aMerge); 2942 sqlite3_free(pTS->aaOutput[iOut]); 2943 pTS->aaOutput[iOut] = 0; 2944 2945 aMerge = aNew; 2946 nMerge = nNew; 2947 if( (iOut+1)==SizeofArray(pTS->aaOutput) ){ 2948 pTS->aaOutput[iOut] = aMerge; 2949 pTS->anOutput[iOut] = nMerge; 2950 } 2951 } 2952 } 2953 } 2954 return SQLITE_OK; 2955 } 2956 2957 /* 2958 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array. 2959 */ 2960 static int fts3SegReaderCursorAppend( 2961 Fts3MultiSegReader *pCsr, 2962 Fts3SegReader *pNew 2963 ){ 2964 if( (pCsr->nSegment%16)==0 ){ 2965 Fts3SegReader **apNew; 2966 sqlite3_int64 nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*); 2967 apNew = (Fts3SegReader **)sqlite3_realloc64(pCsr->apSegment, nByte); 2968 if( !apNew ){ 2969 sqlite3Fts3SegReaderFree(pNew); 2970 return SQLITE_NOMEM; 2971 } 2972 pCsr->apSegment = apNew; 2973 } 2974 pCsr->apSegment[pCsr->nSegment++] = pNew; 2975 return SQLITE_OK; 2976 } 2977 2978 /* 2979 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the 2980 ** 8th argument. 2981 ** 2982 ** This function returns SQLITE_OK if successful, or an SQLite error code 2983 ** otherwise. 2984 */ 2985 static int fts3SegReaderCursor( 2986 Fts3Table *p, /* FTS3 table handle */ 2987 int iLangid, /* Language id */ 2988 int iIndex, /* Index to search (from 0 to p->nIndex-1) */ 2989 int iLevel, /* Level of segments to scan */ 2990 const char *zTerm, /* Term to query for */ 2991 int nTerm, /* Size of zTerm in bytes */ 2992 int isPrefix, /* True for a prefix search */ 2993 int isScan, /* True to scan from zTerm to EOF */ 2994 Fts3MultiSegReader *pCsr /* Cursor object to populate */ 2995 ){ 2996 int rc = SQLITE_OK; /* Error code */ 2997 sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */ 2998 int rc2; /* Result of sqlite3_reset() */ 2999 3000 /* If iLevel is less than 0 and this is not a scan, include a seg-reader 3001 ** for the pending-terms. If this is a scan, then this call must be being 3002 ** made by an fts4aux module, not an FTS table. In this case calling 3003 ** Fts3SegReaderPending might segfault, as the data structures used by 3004 ** fts4aux are not completely populated. So it's easiest to filter these 3005 ** calls out here. */ 3006 if( iLevel<0 && p->aIndex && p->iPrevLangid==iLangid ){ 3007 Fts3SegReader *pSeg = 0; 3008 rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg); 3009 if( rc==SQLITE_OK && pSeg ){ 3010 rc = fts3SegReaderCursorAppend(pCsr, pSeg); 3011 } 3012 } 3013 3014 if( iLevel!=FTS3_SEGCURSOR_PENDING ){ 3015 if( rc==SQLITE_OK ){ 3016 rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt); 3017 } 3018 3019 while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){ 3020 Fts3SegReader *pSeg = 0; 3021 3022 /* Read the values returned by the SELECT into local variables. */ 3023 sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1); 3024 sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2); 3025 sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3); 3026 int nRoot = sqlite3_column_bytes(pStmt, 4); 3027 char const *zRoot = sqlite3_column_blob(pStmt, 4); 3028 3029 /* If zTerm is not NULL, and this segment is not stored entirely on its 3030 ** root node, the range of leaves scanned can be reduced. Do this. */ 3031 if( iStartBlock && zTerm && zRoot ){ 3032 sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0); 3033 rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi); 3034 if( rc!=SQLITE_OK ) goto finished; 3035 if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock; 3036 } 3037 3038 rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, 3039 (isPrefix==0 && isScan==0), 3040 iStartBlock, iLeavesEndBlock, 3041 iEndBlock, zRoot, nRoot, &pSeg 3042 ); 3043 if( rc!=SQLITE_OK ) goto finished; 3044 rc = fts3SegReaderCursorAppend(pCsr, pSeg); 3045 } 3046 } 3047 3048 finished: 3049 rc2 = sqlite3_reset(pStmt); 3050 if( rc==SQLITE_DONE ) rc = rc2; 3051 3052 return rc; 3053 } 3054 3055 /* 3056 ** Set up a cursor object for iterating through a full-text index or a 3057 ** single level therein. 3058 */ 3059 int sqlite3Fts3SegReaderCursor( 3060 Fts3Table *p, /* FTS3 table handle */ 3061 int iLangid, /* Language-id to search */ 3062 int iIndex, /* Index to search (from 0 to p->nIndex-1) */ 3063 int iLevel, /* Level of segments to scan */ 3064 const char *zTerm, /* Term to query for */ 3065 int nTerm, /* Size of zTerm in bytes */ 3066 int isPrefix, /* True for a prefix search */ 3067 int isScan, /* True to scan from zTerm to EOF */ 3068 Fts3MultiSegReader *pCsr /* Cursor object to populate */ 3069 ){ 3070 assert( iIndex>=0 && iIndexnIndex ); 3071 assert( iLevel==FTS3_SEGCURSOR_ALL 3072 || iLevel==FTS3_SEGCURSOR_PENDING 3073 || iLevel>=0 3074 ); 3075 assert( iLevelbase.pVtab; 3131 3132 if( isPrefix ){ 3133 for(i=1; bFound==0 && inIndex; i++){ 3134 if( p->aIndex[i].nPrefix==nTerm ){ 3135 bFound = 1; 3136 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 3137 i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr 3138 ); 3139 pSegcsr->bLookup = 1; 3140 } 3141 } 3142 3143 for(i=1; bFound==0 && inIndex; i++){ 3144 if( p->aIndex[i].nPrefix==nTerm+1 ){ 3145 bFound = 1; 3146 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 3147 i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr 3148 ); 3149 if( rc==SQLITE_OK ){ 3150 rc = fts3SegReaderCursorAddZero( 3151 p, pCsr->iLangid, zTerm, nTerm, pSegcsr 3152 ); 3153 } 3154 } 3155 } 3156 } 3157 3158 if( bFound==0 ){ 3159 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 3160 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr 3161 ); 3162 pSegcsr->bLookup = !isPrefix; 3163 } 3164 } 3165 3166 *ppSegcsr = pSegcsr; 3167 return rc; 3168 } 3169 3170 /* 3171 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor(). 3172 */ 3173 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){ 3174 sqlite3Fts3SegReaderFinish(pSegcsr); 3175 sqlite3_free(pSegcsr); 3176 } 3177 3178 /* 3179 ** This function retrieves the doclist for the specified term (or term 3180 ** prefix) from the database. 3181 */ 3182 static int fts3TermSelect( 3183 Fts3Table *p, /* Virtual table handle */ 3184 Fts3PhraseToken *pTok, /* Token to query for */ 3185 int iColumn, /* Column to query (or -ve for all columns) */ 3186 int *pnOut, /* OUT: Size of buffer at *ppOut */ 3187 char **ppOut /* OUT: Malloced result buffer */ 3188 ){ 3189 int rc; /* Return code */ 3190 Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */ 3191 TermSelect tsc; /* Object for pair-wise doclist merging */ 3192 Fts3SegFilter filter; /* Segment term filter configuration */ 3193 3194 pSegcsr = pTok->pSegcsr; 3195 memset(&tsc, 0, sizeof(TermSelect)); 3196 3197 filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS 3198 | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0) 3199 | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0) 3200 | (iColumnnColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0); 3201 filter.iCol = iColumn; 3202 filter.zTerm = pTok->z; 3203 filter.nTerm = pTok->n; 3204 3205 rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter); 3206 while( SQLITE_OK==rc 3207 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) 3208 ){ 3209 rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist); 3210 } 3211 3212 if( rc==SQLITE_OK ){ 3213 rc = fts3TermSelectFinishMerge(p, &tsc); 3214 } 3215 if( rc==SQLITE_OK ){ 3216 *ppOut = tsc.aaOutput[0]; 3217 *pnOut = tsc.anOutput[0]; 3218 }else{ 3219 int i; 3220 for(i=0; ipSegcsr = 0; 3227 return rc; 3228 } 3229 3230 /* 3231 ** This function counts the total number of docids in the doclist stored 3232 ** in buffer aList[], size nList bytes. 3233 ** 3234 ** If the isPoslist argument is true, then it is assumed that the doclist 3235 ** contains a position-list following each docid. Otherwise, it is assumed 3236 ** that the doclist is simply a list of docids stored as delta encoded 3237 ** varints. 3238 */ 3239 static int fts3DoclistCountDocids(char *aList, int nList){ 3240 int nDoc = 0; /* Return value */ 3241 if( aList ){ 3242 char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */ 3243 char *p = aList; /* Cursor */ 3244 while( peSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){ 3269 Fts3Table *pTab = (Fts3Table*)pCursor->pVtab; 3270 pTab->bLock++; 3271 if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){ 3272 pCsr->isEof = 1; 3273 rc = sqlite3_reset(pCsr->pStmt); 3274 }else{ 3275 pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0); 3276 rc = SQLITE_OK; 3277 } 3278 pTab->bLock--; 3279 }else{ 3280 rc = fts3EvalNext((Fts3Cursor *)pCursor); 3281 } 3282 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); 3283 return rc; 3284 } 3285 3286 /* 3287 ** If the numeric type of argument pVal is "integer", then return it 3288 ** converted to a 64-bit signed integer. Otherwise, return a copy of 3289 ** the second parameter, iDefault. 3290 */ 3291 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){ 3292 if( pVal ){ 3293 int eType = sqlite3_value_numeric_type(pVal); 3294 if( eType==SQLITE_INTEGER ){ 3295 return sqlite3_value_int64(pVal); 3296 } 3297 } 3298 return iDefault; 3299 } 3300 3301 /* 3302 ** This is the xFilter interface for the virtual table. See 3303 ** the virtual table xFilter method documentation for additional 3304 ** information. 3305 ** 3306 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against 3307 ** the %_content table. 3308 ** 3309 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry 3310 ** in the %_content table. 3311 ** 3312 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The 3313 ** column on the left-hand side of the MATCH operator is column 3314 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand 3315 ** side of the MATCH operator. 3316 */ 3317 static int fts3FilterMethod( 3318 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ 3319 int idxNum, /* Strategy index */ 3320 const char *idxStr, /* Unused */ 3321 int nVal, /* Number of elements in apVal */ 3322 sqlite3_value **apVal /* Arguments for the indexing scheme */ 3323 ){ 3324 int rc = SQLITE_OK; 3325 char *zSql; /* SQL statement used to access %_content */ 3326 int eSearch; 3327 Fts3Table *p = (Fts3Table *)pCursor->pVtab; 3328 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; 3329 3330 sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */ 3331 sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */ 3332 sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */ 3333 sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */ 3334 int iIdx; 3335 3336 UNUSED_PARAMETER(idxStr); 3337 UNUSED_PARAMETER(nVal); 3338 3339 if( p->bLock ){ 3340 return SQLITE_ERROR; 3341 } 3342 3343 eSearch = (idxNum & 0x0000FFFF); 3344 assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) ); 3345 assert( p->pSegments==0 ); 3346 3347 /* Collect arguments into local variables */ 3348 iIdx = 0; 3349 if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++]; 3350 if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++]; 3351 if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++]; 3352 if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++]; 3353 assert( iIdx==nVal ); 3354 3355 /* In case the cursor has been used before, clear it now. */ 3356 fts3ClearCursor(pCsr); 3357 3358 /* Set the lower and upper bounds on docids to return */ 3359 pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64); 3360 pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64); 3361 3362 if( idxStr ){ 3363 pCsr->bDesc = (idxStr[0]=='D'); 3364 }else{ 3365 pCsr->bDesc = p->bDescIdx; 3366 } 3367 pCsr->eSearch = (i16)eSearch; 3368 3369 if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){ 3370 int iCol = eSearch-FTS3_FULLTEXT_SEARCH; 3371 const char *zQuery = (const char *)sqlite3_value_text(pCons); 3372 3373 if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){ 3374 return SQLITE_NOMEM; 3375 } 3376 3377 pCsr->iLangid = 0; 3378 if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid); 3379 3380 assert( p->base.zErrMsg==0 ); 3381 rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid, 3382 p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, 3383 &p->base.zErrMsg 3384 ); 3385 if( rc!=SQLITE_OK ){ 3386 return rc; 3387 } 3388 3389 rc = fts3EvalStart(pCsr); 3390 sqlite3Fts3SegmentsClose(p); 3391 if( rc!=SQLITE_OK ) return rc; 3392 pCsr->pNextId = pCsr->aDoclist; 3393 pCsr->iPrevId = 0; 3394 } 3395 3396 /* Compile a SELECT statement for this cursor. For a full-table-scan, the 3397 ** statement loops through all rows of the %_content table. For a 3398 ** full-text query or docid lookup, the statement retrieves a single 3399 ** row by docid. 3400 */ 3401 if( eSearch==FTS3_FULLSCAN_SEARCH ){ 3402 if( pDocidGe || pDocidLe ){ 3403 zSql = sqlite3_mprintf( 3404 "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s", 3405 p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid, 3406 (pCsr->bDesc ? "DESC" : "ASC") 3407 ); 3408 }else{ 3409 zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s", 3410 p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC") 3411 ); 3412 } 3413 if( zSql ){ 3414 p->bLock++; 3415 rc = sqlite3Fts3PrepareStmt(p, zSql, 1, 1, &pCsr->pStmt); 3416 p->bLock--; 3417 sqlite3_free(zSql); 3418 }else{ 3419 rc = SQLITE_NOMEM; 3420 } 3421 }else if( eSearch==FTS3_DOCID_SEARCH ){ 3422 rc = fts3CursorSeekStmt(pCsr); 3423 if( rc==SQLITE_OK ){ 3424 rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons); 3425 } 3426 } 3427 if( rc!=SQLITE_OK ) return rc; 3428 3429 return fts3NextMethod(pCursor); 3430 } 3431 3432 /* 3433 ** This is the xEof method of the virtual table. SQLite calls this 3434 ** routine to find out if it has reached the end of a result set. 3435 */ 3436 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){ 3437 Fts3Cursor *pCsr = (Fts3Cursor*)pCursor; 3438 if( pCsr->isEof ){ 3439 fts3ClearCursor(pCsr); 3440 pCsr->isEof = 1; 3441 } 3442 return pCsr->isEof; 3443 } 3444 3445 /* 3446 ** This is the xRowid method. The SQLite core calls this routine to 3447 ** retrieve the rowid for the current row of the result set. fts3 3448 ** exposes %_content.docid as the rowid for the virtual table. The 3449 ** rowid should be written to *pRowid. 3450 */ 3451 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ 3452 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor; 3453 *pRowid = pCsr->iPrevId; 3454 return SQLITE_OK; 3455 } 3456 3457 /* 3458 ** This is the xColumn method, called by SQLite to request a value from 3459 ** the row that the supplied cursor currently points to. 3460 ** 3461 ** If: 3462 ** 3463 ** (iCol < p->nColumn) -> The value of the iCol'th user column. 3464 ** (iCol == p->nColumn) -> Magic column with the same name as the table. 3465 ** (iCol == p->nColumn+1) -> Docid column 3466 ** (iCol == p->nColumn+2) -> Langid column 3467 */ 3468 static int fts3ColumnMethod( 3469 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ 3470 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ 3471 int iCol /* Index of column to read value from */ 3472 ){ 3473 int rc = SQLITE_OK; /* Return Code */ 3474 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor; 3475 Fts3Table *p = (Fts3Table *)pCursor->pVtab; 3476 3477 /* The column value supplied by SQLite must be in range. */ 3478 assert( iCol>=0 && iCol<=p->nColumn+2 ); 3479 3480 switch( iCol-p->nColumn ){ 3481 case 0: 3482 /* The special 'table-name' column */ 3483 sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0); 3484 break; 3485 3486 case 1: 3487 /* The docid column */ 3488 sqlite3_result_int64(pCtx, pCsr->iPrevId); 3489 break; 3490 3491 case 2: 3492 if( pCsr->pExpr ){ 3493 sqlite3_result_int64(pCtx, pCsr->iLangid); 3494 break; 3495 }else if( p->zLanguageid==0 ){ 3496 sqlite3_result_int(pCtx, 0); 3497 break; 3498 }else{ 3499 iCol = p->nColumn; 3500 /* no break */ deliberate_fall_through 3501 } 3502 3503 default: 3504 /* A user column. Or, if this is a full-table scan, possibly the 3505 ** language-id column. Seek the cursor. */ 3506 rc = fts3CursorSeek(0, pCsr); 3507 if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){ 3508 sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1)); 3509 } 3510 break; 3511 } 3512 3513 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); 3514 return rc; 3515 } 3516 3517 /* 3518 ** This function is the implementation of the xUpdate callback used by 3519 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be 3520 ** inserted, updated or deleted. 3521 */ 3522 static int fts3UpdateMethod( 3523 sqlite3_vtab *pVtab, /* Virtual table handle */ 3524 int nArg, /* Size of argument array */ 3525 sqlite3_value **apVal, /* Array of arguments */ 3526 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ 3527 ){ 3528 return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid); 3529 } 3530 3531 /* 3532 ** Implementation of xSync() method. Flush the contents of the pending-terms 3533 ** hash-table to the database. 3534 */ 3535 static int fts3SyncMethod(sqlite3_vtab *pVtab){ 3536 3537 /* Following an incremental-merge operation, assuming that the input 3538 ** segments are not completely consumed (the usual case), they are updated 3539 ** in place to remove the entries that have already been merged. This 3540 ** involves updating the leaf block that contains the smallest unmerged 3541 ** entry and each block (if any) between the leaf and the root node. So 3542 ** if the height of the input segment b-trees is N, and input segments 3543 ** are merged eight at a time, updating the input segments at the end 3544 ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually 3545 ** small - often between 0 and 2. So the overhead of the incremental 3546 ** merge is somewhere between 8 and 24 blocks. To avoid this overhead 3547 ** dwarfing the actual productive work accomplished, the incremental merge 3548 ** is only attempted if it will write at least 64 leaf blocks. Hence 3549 ** nMinMerge. 3550 ** 3551 ** Of course, updating the input segments also involves deleting a bunch 3552 ** of blocks from the segments table. But this is not considered overhead 3553 ** as it would also be required by a crisis-merge that used the same input 3554 ** segments. 3555 */ 3556 const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */ 3557 3558 Fts3Table *p = (Fts3Table*)pVtab; 3559 int rc; 3560 i64 iLastRowid = sqlite3_last_insert_rowid(p->db); 3561 3562 rc = sqlite3Fts3PendingTermsFlush(p); 3563 if( rc==SQLITE_OK 3564 && p->nLeafAdd>(nMinMerge/16) 3565 && p->nAutoincrmerge && p->nAutoincrmerge!=0xff 3566 ){ 3567 int mxLevel = 0; /* Maximum relative level value in db */ 3568 int A; /* Incr-merge parameter A */ 3569 3570 rc = sqlite3Fts3MaxLevel(p, &mxLevel); 3571 assert( rc==SQLITE_OK || mxLevel==0 ); 3572 A = p->nLeafAdd * mxLevel; 3573 A += (A/2); 3574 if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge); 3575 } 3576 sqlite3Fts3SegmentsClose(p); 3577 sqlite3_set_last_insert_rowid(p->db, iLastRowid); 3578 return rc; 3579 } 3580 3581 /* 3582 ** If it is currently unknown whether or not the FTS table has an %_stat 3583 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat 3584 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code 3585 ** if an error occurs. 3586 */ 3587 static int fts3SetHasStat(Fts3Table *p){ 3588 int rc = SQLITE_OK; 3589 if( p->bHasStat==2 ){ 3590 char *zTbl = sqlite3_mprintf("%s_stat", p->zName); 3591 if( zTbl ){ 3592 int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0); 3593 sqlite3_free(zTbl); 3594 p->bHasStat = (res==SQLITE_OK); 3595 }else{ 3596 rc = SQLITE_NOMEM; 3597 } 3598 } 3599 return rc; 3600 } 3601 3602 /* 3603 ** Implementation of xBegin() method. 3604 */ 3605 static int fts3BeginMethod(sqlite3_vtab *pVtab){ 3606 Fts3Table *p = (Fts3Table*)pVtab; 3607 int rc; 3608 UNUSED_PARAMETER(pVtab); 3609 assert( p->pSegments==0 ); 3610 assert( p->nPendingData==0 ); 3611 assert( p->inTransaction!=1 ); 3612 p->nLeafAdd = 0; 3613 rc = fts3SetHasStat(p); 3614 #ifdef SQLITE_DEBUG 3615 if( rc==SQLITE_OK ){ 3616 p->inTransaction = 1; 3617 p->mxSavepoint = -1; 3618 } 3619 #endif 3620 return rc; 3621 } 3622 3623 /* 3624 ** Implementation of xCommit() method. This is a no-op. The contents of 3625 ** the pending-terms hash-table have already been flushed into the database 3626 ** by fts3SyncMethod(). 3627 */ 3628 static int fts3CommitMethod(sqlite3_vtab *pVtab){ 3629 TESTONLY( Fts3Table *p = (Fts3Table*)pVtab ); 3630 UNUSED_PARAMETER(pVtab); 3631 assert( p->nPendingData==0 ); 3632 assert( p->inTransaction!=0 ); 3633 assert( p->pSegments==0 ); 3634 TESTONLY( p->inTransaction = 0 ); 3635 TESTONLY( p->mxSavepoint = -1; ); 3636 return SQLITE_OK; 3637 } 3638 3639 /* 3640 ** Implementation of xRollback(). Discard the contents of the pending-terms 3641 ** hash-table. Any changes made to the database are reverted by SQLite. 3642 */ 3643 static int fts3RollbackMethod(sqlite3_vtab *pVtab){ 3644 Fts3Table *p = (Fts3Table*)pVtab; 3645 sqlite3Fts3PendingTermsClear(p); 3646 assert( p->inTransaction!=0 ); 3647 TESTONLY( p->inTransaction = 0 ); 3648 TESTONLY( p->mxSavepoint = -1; ); 3649 return SQLITE_OK; 3650 } 3651 3652 /* 3653 ** When called, *ppPoslist must point to the byte immediately following the 3654 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function 3655 ** moves *ppPoslist so that it instead points to the first byte of the 3656 ** same position list. 3657 */ 3658 static void fts3ReversePoslist(char *pStart, char **ppPoslist){ 3659 char *p = &(*ppPoslist)[-2]; 3660 char c = 0; 3661 3662 /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */ 3663 while( p>pStart && (c=*p--)==0 ); 3664 3665 /* Search backwards for a varint with value zero (the end of the previous 3666 ** poslist). This is an 0x00 byte preceded by some byte that does not 3667 ** have the 0x80 bit set. */ 3668 while( p>pStart && (*p & 0x80) | c ){ 3669 c = *p--; 3670 } 3671 assert( p==pStart || c==0 ); 3672 3673 /* At this point p points to that preceding byte without the 0x80 bit 3674 ** set. So to find the start of the poslist, skip forward 2 bytes then 3675 ** over a varint. 3676 ** 3677 ** Normally. The other case is that p==pStart and the poslist to return 3678 ** is the first in the doclist. In this case do not skip forward 2 bytes. 3679 ** The second part of the if condition (c==0 && *ppPoslist>&p[2]) 3680 ** is required for cases where the first byte of a doclist and the 3681 ** doclist is empty. For example, if the first docid is 10, a doclist 3682 ** that begins with: 3683 ** 3684 ** 0x0A 0x00 3685 */ 3686 if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; } 3687 while( *p++&0x80 ); 3688 *ppPoslist = p; 3689 } 3690 3691 /* 3692 ** Helper function used by the implementation of the overloaded snippet(), 3693 ** offsets() and optimize() SQL functions. 3694 ** 3695 ** If the value passed as the third argument is a blob of size 3696 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 3697 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error 3698 ** message is written to context pContext and SQLITE_ERROR returned. The 3699 ** string passed via zFunc is used as part of the error message. 3700 */ 3701 static int fts3FunctionArg( 3702 sqlite3_context *pContext, /* SQL function call context */ 3703 const char *zFunc, /* Function name */ 3704 sqlite3_value *pVal, /* argv[0] passed to function */ 3705 Fts3Cursor **ppCsr /* OUT: Store cursor handle here */ 3706 ){ 3707 int rc; 3708 *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor"); 3709 if( (*ppCsr)!=0 ){ 3710 rc = SQLITE_OK; 3711 }else{ 3712 char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc); 3713 sqlite3_result_error(pContext, zErr, -1); 3714 sqlite3_free(zErr); 3715 rc = SQLITE_ERROR; 3716 } 3717 return rc; 3718 } 3719 3720 /* 3721 ** Implementation of the snippet() function for FTS3 3722 */ 3723 static void fts3SnippetFunc( 3724 sqlite3_context *pContext, /* SQLite function call context */ 3725 int nVal, /* Size of apVal[] array */ 3726 sqlite3_value **apVal /* Array of arguments */ 3727 ){ 3728 Fts3Table *pTab = 0; 3729 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ 3730 const char *zStart = ""; 3731 const char *zEnd = ""; 3732 const char *zEllipsis = "..."; 3733 i64 iCol = -1; 3734 i64 nToken = 15; /* Default number of tokens in snippet */ 3735 3736 /* There must be at least one argument passed to this function (otherwise 3737 ** the non-overloaded version would have been called instead of this one). 3738 */ 3739 assert( nVal>=1 ); 3740 3741 if( nVal>6 ){ 3742 sqlite3_result_error(pContext, 3743 "wrong number of arguments to function snippet()", -1); 3744 return; 3745 } 3746 if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return; 3747 pTab = (Fts3Table *)pCsr->base.pVtab; 3748 3749 switch( nVal ){ 3750 case 6: nToken = sqlite3_value_int64(apVal[5]); 3751 /* no break */ deliberate_fall_through 3752 case 5: iCol = sqlite3_value_int64(apVal[4]); 3753 /* no break */ deliberate_fall_through 3754 case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]); 3755 /* no break */ deliberate_fall_through 3756 case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]); 3757 /* no break */ deliberate_fall_through 3758 case 2: zStart = (const char*)sqlite3_value_text(apVal[1]); 3759 } 3760 if( !zEllipsis || !zEnd || !zStart ){ 3761 sqlite3_result_error_nomem(pContext); 3762 }else if( nToken==0 || iCol>=pTab->nColumn ){ 3763 sqlite3_result_text(pContext, "", -1, SQLITE_STATIC); 3764 }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ 3765 if( iCol<0 ) iCol = -1; 3766 if( nToken<-64 ) nToken = -64; 3767 if( nToken>64 ) nToken = 64; 3768 sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken); 3769 } 3770 } 3771 3772 /* 3773 ** Implementation of the offsets() function for FTS3 3774 */ 3775 static void fts3OffsetsFunc( 3776 sqlite3_context *pContext, /* SQLite function call context */ 3777 int nVal, /* Size of argument array */ 3778 sqlite3_value **apVal /* Array of arguments */ 3779 ){ 3780 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ 3781 3782 UNUSED_PARAMETER(nVal); 3783 3784 assert( nVal==1 ); 3785 if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return; 3786 assert( pCsr ); 3787 if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ 3788 sqlite3Fts3Offsets(pContext, pCsr); 3789 } 3790 } 3791 3792 /* 3793 ** Implementation of the special optimize() function for FTS3. This 3794 ** function merges all segments in the database to a single segment. 3795 ** Example usage is: 3796 ** 3797 ** SELECT optimize(t) FROM t LIMIT 1; 3798 ** 3799 ** where 't' is the name of an FTS3 table. 3800 */ 3801 static void fts3OptimizeFunc( 3802 sqlite3_context *pContext, /* SQLite function call context */ 3803 int nVal, /* Size of argument array */ 3804 sqlite3_value **apVal /* Array of arguments */ 3805 ){ 3806 int rc; /* Return code */ 3807 Fts3Table *p; /* Virtual table handle */ 3808 Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */ 3809 3810 UNUSED_PARAMETER(nVal); 3811 3812 assert( nVal==1 ); 3813 if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return; 3814 p = (Fts3Table *)pCursor->base.pVtab; 3815 assert( p ); 3816 3817 rc = sqlite3Fts3Optimize(p); 3818 3819 switch( rc ){ 3820 case SQLITE_OK: 3821 sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC); 3822 break; 3823 case SQLITE_DONE: 3824 sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC); 3825 break; 3826 default: 3827 sqlite3_result_error_code(pContext, rc); 3828 break; 3829 } 3830 } 3831 3832 /* 3833 ** Implementation of the matchinfo() function for FTS3 3834 */ 3835 static void fts3MatchinfoFunc( 3836 sqlite3_context *pContext, /* SQLite function call context */ 3837 int nVal, /* Size of argument array */ 3838 sqlite3_value **apVal /* Array of arguments */ 3839 ){ 3840 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ 3841 assert( nVal==1 || nVal==2 ); 3842 if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){ 3843 const char *zArg = 0; 3844 if( nVal>1 ){ 3845 zArg = (const char *)sqlite3_value_text(apVal[1]); 3846 } 3847 sqlite3Fts3Matchinfo(pContext, pCsr, zArg); 3848 } 3849 } 3850 3851 /* 3852 ** This routine implements the xFindFunction method for the FTS3 3853 ** virtual table. 3854 */ 3855 static int fts3FindFunctionMethod( 3856 sqlite3_vtab *pVtab, /* Virtual table handle */ 3857 int nArg, /* Number of SQL function arguments */ 3858 const char *zName, /* Name of SQL function */ 3859 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ 3860 void **ppArg /* Unused */ 3861 ){ 3862 struct Overloaded { 3863 const char *zName; 3864 void (*xFunc)(sqlite3_context*,int,sqlite3_value**); 3865 } aOverload[] = { 3866 { "snippet", fts3SnippetFunc }, 3867 { "offsets", fts3OffsetsFunc }, 3868 { "optimize", fts3OptimizeFunc }, 3869 { "matchinfo", fts3MatchinfoFunc }, 3870 }; 3871 int i; /* Iterator variable */ 3872 3873 UNUSED_PARAMETER(pVtab); 3874 UNUSED_PARAMETER(nArg); 3875 UNUSED_PARAMETER(ppArg); 3876 3877 for(i=0; idb; /* Database connection */ 3897 int rc; /* Return Code */ 3898 3899 /* At this point it must be known if the %_stat table exists or not. 3900 ** So bHasStat may not be 2. */ 3901 rc = fts3SetHasStat(p); 3902 3903 /* As it happens, the pending terms table is always empty here. This is 3904 ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction 3905 ** always opens a savepoint transaction. And the xSavepoint() method 3906 ** flushes the pending terms table. But leave the (no-op) call to 3907 ** PendingTermsFlush() in in case that changes. 3908 */ 3909 assert( p->nPendingData==0 ); 3910 if( rc==SQLITE_OK ){ 3911 rc = sqlite3Fts3PendingTermsFlush(p); 3912 } 3913 3914 p->bIgnoreSavepoint = 1; 3915 3916 if( p->zContentTbl==0 ){ 3917 fts3DbExec(&rc, db, 3918 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';", 3919 p->zDb, p->zName, zName 3920 ); 3921 } 3922 3923 if( p->bHasDocsize ){ 3924 fts3DbExec(&rc, db, 3925 "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';", 3926 p->zDb, p->zName, zName 3927 ); 3928 } 3929 if( p->bHasStat ){ 3930 fts3DbExec(&rc, db, 3931 "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';", 3932 p->zDb, p->zName, zName 3933 ); 3934 } 3935 fts3DbExec(&rc, db, 3936 "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';", 3937 p->zDb, p->zName, zName 3938 ); 3939 fts3DbExec(&rc, db, 3940 "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';", 3941 p->zDb, p->zName, zName 3942 ); 3943 3944 p->bIgnoreSavepoint = 0; 3945 return rc; 3946 } 3947 3948 /* 3949 ** The xSavepoint() method. 3950 ** 3951 ** Flush the contents of the pending-terms table to disk. 3952 */ 3953 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){ 3954 int rc = SQLITE_OK; 3955 Fts3Table *pTab = (Fts3Table*)pVtab; 3956 assert( pTab->inTransaction ); 3957 assert( pTab->mxSavepoint<=iSavepoint ); 3958 TESTONLY( pTab->mxSavepoint = iSavepoint ); 3959 3960 if( pTab->bIgnoreSavepoint==0 ){ 3961 if( fts3HashCount(&pTab->aIndex[0].hPending)>0 ){ 3962 char *zSql = sqlite3_mprintf("INSERT INTO %Q.%Q(%Q) VALUES('flush')", 3963 pTab->zDb, pTab->zName, pTab->zName 3964 ); 3965 if( zSql ){ 3966 pTab->bIgnoreSavepoint = 1; 3967 rc = sqlite3_exec(pTab->db, zSql, 0, 0, 0); 3968 pTab->bIgnoreSavepoint = 0; 3969 sqlite3_free(zSql); 3970 }else{ 3971 rc = SQLITE_NOMEM; 3972 } 3973 } 3974 if( rc==SQLITE_OK ){ 3975 pTab->iSavepoint = iSavepoint+1; 3976 } 3977 } 3978 return rc; 3979 } 3980 3981 /* 3982 ** The xRelease() method. 3983 ** 3984 ** This is a no-op. 3985 */ 3986 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){ 3987 Fts3Table *pTab = (Fts3Table*)pVtab; 3988 assert( pTab->inTransaction ); 3989 assert( pTab->mxSavepoint >= iSavepoint ); 3990 TESTONLY( pTab->mxSavepoint = iSavepoint-1 ); 3991 pTab->iSavepoint = iSavepoint; 3992 return SQLITE_OK; 3993 } 3994 3995 /* 3996 ** The xRollbackTo() method. 3997 ** 3998 ** Discard the contents of the pending terms table. 3999 */ 4000 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){ 4001 Fts3Table *pTab = (Fts3Table*)pVtab; 4002 UNUSED_PARAMETER(iSavepoint); 4003 assert( pTab->inTransaction ); 4004 TESTONLY( pTab->mxSavepoint = iSavepoint ); 4005 if( (iSavepoint+1)<=pTab->iSavepoint ){ 4006 sqlite3Fts3PendingTermsClear(pTab); 4007 } 4008 return SQLITE_OK; 4009 } 4010 4011 /* 4012 ** Return true if zName is the extension on one of the shadow tables used 4013 ** by this module. 4014 */ 4015 static int fts3ShadowName(const char *zName){ 4016 static const char *azName[] = { 4017 "content", "docsize", "segdir", "segments", "stat", 4018 }; 4019 unsigned int i; 4020 for(i=0; izErrMsg==0 || rc!=SQLITE_OK ); 4044 assert( rc!=SQLITE_CORRUPT_VTAB ); 4045 if( rc==SQLITE_ERROR || (rc&0xFF)==SQLITE_CORRUPT ){ 4046 *pzErr = sqlite3_mprintf("unable to validate the inverted index for" 4047 " FTS%d table %s.%s: %s", 4048 p->bFts4 ? 4 : 3, zSchema, zTabname, sqlite3_errstr(rc)); 4049 if( *pzErr ) rc = SQLITE_OK; 4050 }else if( rc==SQLITE_OK && bOk==0 ){ 4051 *pzErr = sqlite3_mprintf("malformed inverted index for FTS%d table %s.%s", 4052 p->bFts4 ? 4 : 3, zSchema, zTabname); 4053 if( *pzErr==0 ) rc = SQLITE_NOMEM; 4054 } 4055 sqlite3Fts3SegmentsClose(p); 4056 return rc; 4057 } 4058 4059 4060 4061 static const sqlite3_module fts3Module = { 4062 /* iVersion */ 4, 4063 /* xCreate */ fts3CreateMethod, 4064 /* xConnect */ fts3ConnectMethod, 4065 /* xBestIndex */ fts3BestIndexMethod, 4066 /* xDisconnect */ fts3DisconnectMethod, 4067 /* xDestroy */ fts3DestroyMethod, 4068 /* xOpen */ fts3OpenMethod, 4069 /* xClose */ fts3CloseMethod, 4070 /* xFilter */ fts3FilterMethod, 4071 /* xNext */ fts3NextMethod, 4072 /* xEof */ fts3EofMethod, 4073 /* xColumn */ fts3ColumnMethod, 4074 /* xRowid */ fts3RowidMethod, 4075 /* xUpdate */ fts3UpdateMethod, 4076 /* xBegin */ fts3BeginMethod, 4077 /* xSync */ fts3SyncMethod, 4078 /* xCommit */ fts3CommitMethod, 4079 /* xRollback */ fts3RollbackMethod, 4080 /* xFindFunction */ fts3FindFunctionMethod, 4081 /* xRename */ fts3RenameMethod, 4082 /* xSavepoint */ fts3SavepointMethod, 4083 /* xRelease */ fts3ReleaseMethod, 4084 /* xRollbackTo */ fts3RollbackToMethod, 4085 /* xShadowName */ fts3ShadowName, 4086 /* xIntegrity */ fts3IntegrityMethod, 4087 }; 4088 4089 /* 4090 ** This function is registered as the module destructor (called when an 4091 ** FTS3 enabled database connection is closed). It frees the memory 4092 ** allocated for the tokenizer hash table. 4093 */ 4094 static void hashDestroy(void *p){ 4095 Fts3HashWrapper *pHash = (Fts3HashWrapper *)p; 4096 pHash->nRef--; 4097 if( pHash->nRef<=0 ){ 4098 sqlite3Fts3HashClear(&pHash->hash); 4099 sqlite3_free(pHash); 4100 } 4101 } 4102 4103 /* 4104 ** Register an SQL function that uses the tokenizer hash table pHash as its 4105 ** user-data pointer. The new function holds a reference to the hash table, 4106 ** which is released by hashDestroy() when the function is deleted or if 4107 ** this call fails. 4108 ** 4109 ** The Fts3Hash object passed as the fifth argument must be the "hash" member 4110 ** of an Fts3HashWrapper object. Since it is the first member of that 4111 ** structure, the pointer may be cast to (Fts3HashWrapper*). 4112 */ 4113 int sqlite3Fts3CreateHashFunction( 4114 sqlite3 *db, /* Database connection */ 4115 const char *zName, /* Name of SQL function */ 4116 int nArg, /* Number of arguments */ 4117 int eTextRep, /* Text encoding and function flags */ 4118 Fts3Hash *pHash, /* Tokenizer hash table */ 4119 void (*xFunc)(sqlite3_context*,int,sqlite3_value**) /* Implementation */ 4120 ){ 4121 Fts3HashWrapper *pWrapper = (Fts3HashWrapper*)pHash; 4122 pWrapper->nRef++; 4123 return sqlite3_create_function_v2( 4124 db, zName, nArg, eTextRep, (void*)pWrapper, xFunc, 0, 0, hashDestroy 4125 ); 4126 } 4127 4128 /* 4129 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 4130 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c 4131 ** respectively. The following three forward declarations are for functions 4132 ** declared in these files used to retrieve the respective implementations. 4133 ** 4134 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed 4135 ** to by the argument to point to the "simple" tokenizer implementation. 4136 ** And so on. 4137 */ 4138 void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); 4139 void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule); 4140 #ifndef SQLITE_DISABLE_FTS3_UNICODE 4141 void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule); 4142 #endif 4143 #ifdef SQLITE_ENABLE_ICU 4144 void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule); 4145 #endif 4146 4147 /* 4148 ** Initialize the fts3 extension. If this extension is built as part 4149 ** of the sqlite library, then this function is called directly by 4150 ** SQLite. If fts3 is built as a dynamically loadable extension, this 4151 ** function is called by the sqlite3_extension_init() entry point. 4152 */ 4153 int sqlite3Fts3Init(sqlite3 *db){ 4154 int rc = SQLITE_OK; 4155 Fts3HashWrapper *pHash = 0; 4156 const sqlite3_tokenizer_module *pSimple = 0; 4157 const sqlite3_tokenizer_module *pPorter = 0; 4158 #ifndef SQLITE_DISABLE_FTS3_UNICODE 4159 const sqlite3_tokenizer_module *pUnicode = 0; 4160 #endif 4161 4162 #ifdef SQLITE_ENABLE_ICU 4163 const sqlite3_tokenizer_module *pIcu = 0; 4164 sqlite3Fts3IcuTokenizerModule(&pIcu); 4165 #endif 4166 4167 #ifndef SQLITE_DISABLE_FTS3_UNICODE 4168 sqlite3Fts3UnicodeTokenizer(&pUnicode); 4169 #endif 4170 4171 #ifdef SQLITE_TEST 4172 rc = sqlite3Fts3InitTerm(db); 4173 if( rc!=SQLITE_OK ) return rc; 4174 #endif 4175 4176 rc = sqlite3Fts3InitAux(db); 4177 if( rc!=SQLITE_OK ) return rc; 4178 4179 sqlite3Fts3SimpleTokenizerModule(&pSimple); 4180 sqlite3Fts3PorterTokenizerModule(&pPorter); 4181 4182 /* Allocate and initialize the hash-table used to store tokenizers. The 4183 ** reference held by this function is released before it returns. */ 4184 pHash = sqlite3_malloc(sizeof(Fts3HashWrapper)); 4185 if( !pHash ){ 4186 rc = SQLITE_NOMEM; 4187 }else{ 4188 sqlite3Fts3HashInit(&pHash->hash, FTS3_HASH_STRING, 1); 4189 pHash->nRef = 1; 4190 } 4191 4192 /* Load the built-in tokenizers into the hash table */ 4193 if( rc==SQLITE_OK ){ 4194 if( sqlite3Fts3HashInsert(&pHash->hash, "simple", 7, (void *)pSimple) 4195 || sqlite3Fts3HashInsert(&pHash->hash, "porter", 7, (void *)pPorter) 4196 4197 #ifndef SQLITE_DISABLE_FTS3_UNICODE 4198 || sqlite3Fts3HashInsert(&pHash->hash, "unicode61", 10, (void *)pUnicode) 4199 #endif 4200 #ifdef SQLITE_ENABLE_ICU 4201 || (pIcu && sqlite3Fts3HashInsert(&pHash->hash, "icu", 4, (void *)pIcu)) 4202 #endif 4203 ){ 4204 rc = SQLITE_NOMEM; 4205 } 4206 } 4207 4208 #ifdef SQLITE_TEST 4209 if( rc==SQLITE_OK ){ 4210 rc = sqlite3Fts3ExprInitTestInterface(db, &pHash->hash); 4211 } 4212 #endif 4213 4214 /* Create the virtual table wrapper around the hash-table and overload 4215 ** the four scalar functions. If this is successful, register the 4216 ** module with sqlite. 4217 */ 4218 if( SQLITE_OK==rc 4219 && SQLITE_OK==(rc=sqlite3Fts3InitHashTable(db,&pHash->hash,"fts3_tokenizer")) 4220 && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1)) 4221 && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1)) 4222 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1)) 4223 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2)) 4224 && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1)) 4225 ){ 4226 pHash->nRef++; 4227 rc = sqlite3_create_module_v2( 4228 db, "fts3", &fts3Module, (void *)pHash, hashDestroy 4229 ); 4230 if( rc==SQLITE_OK ){ 4231 pHash->nRef++; 4232 rc = sqlite3_create_module_v2( 4233 db, "fts4", &fts3Module, (void *)pHash, hashDestroy 4234 ); 4235 } 4236 if( rc==SQLITE_OK ){ 4237 pHash->nRef++; 4238 rc = sqlite3Fts3InitTok(db, (void *)pHash, hashDestroy); 4239 } 4240 } 4241 4242 /* If an error has occurred, remove any modules and functions registered 4243 ** above. If this is a loadable extension, the shared library may be unloaded 4244 ** as soon as this function returns, so they must not be left in place. */ 4245 if( rc!=SQLITE_OK ){ 4246 sqlite3_create_module(db, "fts3", 0, 0); 4247 sqlite3_create_module(db, "fts4", 0, 0); 4248 sqlite3_create_module(db, "fts3tokenize", 0, 0); 4249 sqlite3_create_module(db, "fts4aux", 0, 0); 4250 sqlite3_create_function(db, "fts3_tokenizer", 1, SQLITE_UTF8, 0, 0, 0, 0); 4251 sqlite3_create_function(db, "fts3_tokenizer", 2, SQLITE_UTF8, 0, 0, 0, 0); 4252 } 4253 4254 /* Release the reference held by this function. If nothing else still holds 4255 ** a reference, this deletes the hash table. */ 4256 if( pHash ) hashDestroy(pHash); 4257 return rc; 4258 } 4259 4260 /* 4261 ** Allocate an Fts3MultiSegReader for each token in the expression headed 4262 ** by pExpr. 4263 ** 4264 ** An Fts3SegReader object is a cursor that can seek or scan a range of 4265 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple 4266 ** Fts3SegReader objects internally to provide an interface to seek or scan 4267 ** within the union of all segments of a b-tree. Hence the name. 4268 ** 4269 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a 4270 ** segment b-tree (if the term is not a prefix or it is a prefix for which 4271 ** there exists prefix b-tree of the right length) then it may be traversed 4272 ** and merged incrementally. Otherwise, it has to be merged into an in-memory 4273 ** doclist and then traversed. 4274 */ 4275 static void fts3EvalAllocateReaders( 4276 Fts3Cursor *pCsr, /* FTS cursor handle */ 4277 Fts3Expr *pExpr, /* Allocate readers for this expression */ 4278 int *pnToken, /* OUT: Total number of tokens in phrase. */ 4279 int *pnOr, /* OUT: Total number of OR nodes in expr. */ 4280 int *pRc /* IN/OUT: Error code */ 4281 ){ 4282 if( pExpr && SQLITE_OK==*pRc ){ 4283 if( pExpr->eType==FTSQUERY_PHRASE ){ 4284 int i; 4285 int nToken = pExpr->pPhrase->nToken; 4286 *pnToken += nToken; 4287 for(i=0; ipPhrase->aToken[i]; 4289 int rc = fts3TermSegReaderCursor(pCsr, 4290 pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr 4291 ); 4292 if( rc!=SQLITE_OK ){ 4293 *pRc = rc; 4294 return; 4295 } 4296 } 4297 assert( pExpr->pPhrase->iDoclistToken==0 ); 4298 pExpr->pPhrase->iDoclistToken = -1; 4299 }else{ 4300 *pnOr += (pExpr->eType==FTSQUERY_OR); 4301 fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc); 4302 fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc); 4303 } 4304 } 4305 } 4306 4307 /* 4308 ** Arguments pList/nList contain the doclist for token iToken of phrase p. 4309 ** It is merged into the main doclist stored in p->doclist.aAll/nAll. 4310 ** 4311 ** This function assumes that pList points to a buffer allocated using 4312 ** sqlite3_malloc(). This function takes responsibility for eventually 4313 ** freeing the buffer. 4314 ** 4315 ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs. 4316 */ 4317 static int fts3EvalPhraseMergeToken( 4318 Fts3Table *pTab, /* FTS Table pointer */ 4319 Fts3Phrase *p, /* Phrase to merge pList/nList into */ 4320 int iToken, /* Token pList/nList corresponds to */ 4321 char *pList, /* Pointer to doclist */ 4322 int nList /* Number of bytes in pList */ 4323 ){ 4324 int rc = SQLITE_OK; 4325 assert( iToken!=p->iDoclistToken ); 4326 4327 if( pList==0 ){ 4328 sqlite3_free(p->doclist.aAll); 4329 p->doclist.aAll = 0; 4330 p->doclist.nAll = 0; 4331 } 4332 4333 else if( p->iDoclistToken<0 ){ 4334 p->doclist.aAll = pList; 4335 p->doclist.nAll = nList; 4336 } 4337 4338 else if( p->doclist.aAll==0 ){ 4339 sqlite3_free(pList); 4340 } 4341 4342 else { 4343 char *pLeft; 4344 char *pRight; 4345 int nLeft; 4346 int nRight; 4347 int nDiff; 4348 4349 if( p->iDoclistTokendoclist.aAll; 4351 nLeft = p->doclist.nAll; 4352 pRight = pList; 4353 nRight = nList; 4354 nDiff = iToken - p->iDoclistToken; 4355 }else{ 4356 pRight = p->doclist.aAll; 4357 nRight = p->doclist.nAll; 4358 pLeft = pList; 4359 nLeft = nList; 4360 nDiff = p->iDoclistToken - iToken; 4361 } 4362 4363 rc = fts3DoclistPhraseMerge( 4364 pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight 4365 ); 4366 sqlite3_free(pLeft); 4367 p->doclist.aAll = pRight; 4368 p->doclist.nAll = nRight; 4369 } 4370 4371 if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken; 4372 return rc; 4373 } 4374 4375 /* 4376 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist 4377 ** does not take deferred tokens into account. 4378 ** 4379 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. 4380 */ 4381 static int fts3EvalPhraseLoad( 4382 Fts3Cursor *pCsr, /* FTS Cursor handle */ 4383 Fts3Phrase *p /* Phrase object */ 4384 ){ 4385 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; 4386 int iToken; 4387 int rc = SQLITE_OK; 4388 4389 for(iToken=0; rc==SQLITE_OK && iTokennToken; iToken++){ 4390 Fts3PhraseToken *pToken = &p->aToken[iToken]; 4391 assert( pToken->pDeferred==0 || pToken->pSegcsr==0 ); 4392 4393 if( pToken->pSegcsr ){ 4394 int nThis = 0; 4395 char *pThis = 0; 4396 rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis); 4397 if( rc==SQLITE_OK ){ 4398 rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis); 4399 } 4400 } 4401 assert( pToken->pSegcsr==0 ); 4402 } 4403 4404 return rc; 4405 } 4406 4407 #ifndef SQLITE_DISABLE_FTS4_DEFERRED 4408 /* 4409 ** This function is called on each phrase after the position lists for 4410 ** any deferred tokens have been loaded into memory. It updates the phrases 4411 ** current position list to include only those positions that are really 4412 ** instances of the phrase (after considering deferred tokens). If this 4413 ** means that the phrase does not appear in the current row, doclist.pList 4414 ** and doclist.nList are both zeroed. 4415 ** 4416 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. 4417 */ 4418 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){ 4419 int iToken; /* Used to iterate through phrase tokens */ 4420 char *aPoslist = 0; /* Position list for deferred tokens */ 4421 int nPoslist = 0; /* Number of bytes in aPoslist */ 4422 int iPrev = -1; /* Token number of previous deferred token */ 4423 char *aFree = (pPhrase->doclist.bFreeList ? pPhrase->doclist.pList : 0); 4424 4425 for(iToken=0; iTokennToken; iToken++){ 4426 Fts3PhraseToken *pToken = &pPhrase->aToken[iToken]; 4427 Fts3DeferredToken *pDeferred = pToken->pDeferred; 4428 4429 if( pDeferred ){ 4430 char *pList; 4431 int nList; 4432 int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList); 4433 if( rc!=SQLITE_OK ) return rc; 4434 4435 if( pList==0 ){ 4436 sqlite3_free(aPoslist); 4437 sqlite3_free(aFree); 4438 pPhrase->doclist.pList = 0; 4439 pPhrase->doclist.nList = 0; 4440 return SQLITE_OK; 4441 4442 }else if( aPoslist==0 ){ 4443 aPoslist = pList; 4444 nPoslist = nList; 4445 4446 }else{ 4447 char *aOut = pList; 4448 char *p1 = aPoslist; 4449 char *p2 = aOut; 4450 4451 assert( iPrev>=0 ); 4452 fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2); 4453 sqlite3_free(aPoslist); 4454 aPoslist = pList; 4455 nPoslist = (int)(aOut - aPoslist); 4456 if( nPoslist==0 ){ 4457 sqlite3_free(aPoslist); 4458 sqlite3_free(aFree); 4459 pPhrase->doclist.pList = 0; 4460 pPhrase->doclist.nList = 0; 4461 return SQLITE_OK; 4462 } 4463 } 4464 iPrev = iToken; 4465 } 4466 } 4467 4468 if( iPrev>=0 ){ 4469 int nMaxUndeferred = pPhrase->iDoclistToken; 4470 if( nMaxUndeferred<0 ){ 4471 pPhrase->doclist.pList = aPoslist; 4472 pPhrase->doclist.nList = nPoslist; 4473 pPhrase->doclist.iDocid = pCsr->iPrevId; 4474 pPhrase->doclist.bFreeList = 1; 4475 }else{ 4476 int nDistance; 4477 char *p1; 4478 char *p2; 4479 char *aOut; 4480 i64 nAlloc = (i64)nPoslist*2 + FTS3_BUFFER_PADDING; 4481 4482 if( nMaxUndeferred>iPrev ){ 4483 p1 = aPoslist; 4484 p2 = pPhrase->doclist.pList; 4485 nDistance = nMaxUndeferred - iPrev; 4486 }else{ 4487 p1 = pPhrase->doclist.pList; 4488 p2 = aPoslist; 4489 nDistance = iPrev - nMaxUndeferred; 4490 } 4491 4492 aOut = (char *)sqlite3Fts3MallocZero(nAlloc); 4493 if( !aOut ){ 4494 sqlite3_free(aPoslist); 4495 return SQLITE_NOMEM; 4496 } 4497 4498 pPhrase->doclist.pList = aOut; 4499 assert( p1 && p2 ); 4500 if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){ 4501 pPhrase->doclist.bFreeList = 1; 4502 pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList); 4503 }else{ 4504 sqlite3_free(aOut); 4505 pPhrase->doclist.pList = 0; 4506 pPhrase->doclist.nList = 0; 4507 } 4508 sqlite3_free(aPoslist); 4509 } 4510 } 4511 4512 if( pPhrase->doclist.pList!=aFree ) sqlite3_free(aFree); 4513 return SQLITE_OK; 4514 } 4515 #endif /* SQLITE_DISABLE_FTS4_DEFERRED */ 4516 4517 /* 4518 ** Maximum number of tokens a phrase may have to be considered for the 4519 ** incremental doclists strategy. 4520 */ 4521 #define MAX_INCR_PHRASE_TOKENS 4 4522 4523 /* 4524 ** This function is called for each Fts3Phrase in a full-text query 4525 ** expression to initialize the mechanism for returning rows. Once this 4526 ** function has been called successfully on an Fts3Phrase, it may be 4527 ** used with fts3EvalPhraseNext() to iterate through the matching docids. 4528 ** 4529 ** If parameter bOptOk is true, then the phrase may (or may not) use the 4530 ** incremental loading strategy. Otherwise, the entire doclist is loaded into 4531 ** memory within this call. 4532 ** 4533 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. 4534 */ 4535 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){ 4536 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; 4537 int rc = SQLITE_OK; /* Error code */ 4538 int i; 4539 4540 /* Determine if doclists may be loaded from disk incrementally. This is 4541 ** possible if the bOptOk argument is true, the FTS doclists will be 4542 ** scanned in forward order, and the phrase consists of 4543 ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first" 4544 ** tokens or prefix tokens that cannot use a prefix-index. */ 4545 int bHaveIncr = 0; 4546 int bIncrOk = (bOptOk 4547 && pCsr->bDesc==pTab->bDescIdx 4548 && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0 4549 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) 4550 && pTab->bNoIncrDoclist==0 4551 #endif 4552 ); 4553 for(i=0; bIncrOk==1 && inToken; i++){ 4554 Fts3PhraseToken *pToken = &p->aToken[i]; 4555 if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){ 4556 bIncrOk = 0; 4557 } 4558 if( pToken->pSegcsr ) bHaveIncr = 1; 4559 } 4560 4561 if( bIncrOk && bHaveIncr ){ 4562 /* Use the incremental approach. */ 4563 int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn); 4564 for(i=0; rc==SQLITE_OK && inToken; i++){ 4565 Fts3PhraseToken *pToken = &p->aToken[i]; 4566 Fts3MultiSegReader *pSegcsr = pToken->pSegcsr; 4567 if( pSegcsr ){ 4568 rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n); 4569 } 4570 } 4571 p->bIncr = 1; 4572 }else{ 4573 /* Load the full doclist for the phrase into memory. */ 4574 rc = fts3EvalPhraseLoad(pCsr, p); 4575 p->bIncr = 0; 4576 } 4577 4578 assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr ); 4579 return rc; 4580 } 4581 4582 /* 4583 ** This function is used to iterate backwards (from the end to start) 4584 ** through doclists. It is used by this module to iterate through phrase 4585 ** doclists in reverse and by the fts3_write.c module to iterate through 4586 ** pending-terms lists when writing to databases with "order=desc". 4587 ** 4588 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or 4589 ** descending (parameter bDescIdx==1) order of docid. Regardless, this 4590 ** function iterates from the end of the doclist to the beginning. 4591 */ 4592 void sqlite3Fts3DoclistPrev( 4593 int bDescIdx, /* True if the doclist is desc */ 4594 char *aDoclist, /* Pointer to entire doclist */ 4595 int nDoclist, /* Length of aDoclist in bytes */ 4596 char **ppIter, /* IN/OUT: Iterator pointer */ 4597 sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */ 4598 int *pnList, /* OUT: List length pointer */ 4599 u8 *pbEof /* OUT: End-of-file flag */ 4600 ){ 4601 char *p = *ppIter; 4602 4603 assert( nDoclist>0 ); 4604 assert( *pbEof==0 ); 4605 assert_fts3_nc( p || *piDocid==0 ); 4606 assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) ); 4607 4608 if( p==0 ){ 4609 sqlite3_int64 iDocid = 0; 4610 char *pNext = 0; 4611 char *pDocid = aDoclist; 4612 char *pEnd = &aDoclist[nDoclist]; 4613 int iMul = 1; 4614 4615 while( pDocid0 ); 4659 assert( *pbEof==0 ); 4660 assert_fts3_nc( p || *piDocid==0 ); 4661 assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) ); 4662 4663 if( p==0 ){ 4664 p = aDoclist; 4665 p += sqlite3Fts3GetVarint(p, piDocid); 4666 }else{ 4667 fts3PoslistCopy(0, &p); 4668 while( p<&aDoclist[nDoclist] && *p==0 ) p++; 4669 if( p>=&aDoclist[nDoclist] ){ 4670 *pbEof = 1; 4671 }else{ 4672 sqlite3_int64 iVar; 4673 p += sqlite3Fts3GetVarint(p, &iVar); 4674 *piDocid += ((bDescIdx ? -1 : 1) * iVar); 4675 } 4676 } 4677 4678 *ppIter = p; 4679 } 4680 4681 /* 4682 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof 4683 ** to true if EOF is reached. 4684 */ 4685 static void fts3EvalDlPhraseNext( 4686 Fts3Table *pTab, 4687 Fts3Doclist *pDL, 4688 u8 *pbEof 4689 ){ 4690 char *pIter; /* Used to iterate through aAll */ 4691 char *pEnd; /* 1 byte past end of aAll */ 4692 4693 if( pDL->pNextDocid ){ 4694 pIter = pDL->pNextDocid; 4695 assert( pDL->aAll!=0 || pIter==0 ); 4696 }else{ 4697 pIter = pDL->aAll; 4698 } 4699 4700 if( pIter==0 || pIter>=(pEnd = pDL->aAll + pDL->nAll) ){ 4701 /* We have already reached the end of this doclist. EOF. */ 4702 *pbEof = 1; 4703 }else{ 4704 sqlite3_int64 iDelta; 4705 pIter += sqlite3Fts3GetVarint(pIter, &iDelta); 4706 if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){ 4707 pDL->iDocid += iDelta; 4708 }else{ 4709 pDL->iDocid -= iDelta; 4710 } 4711 pDL->pList = pIter; 4712 fts3PoslistCopy(0, &pIter); 4713 pDL->nList = (int)(pIter - pDL->pList); 4714 4715 /* pIter now points just past the 0x00 that terminates the position- 4716 ** list for document pDL->iDocid. However, if this position-list was 4717 ** edited in place by fts3EvalNearTrim(), then pIter may not actually 4718 ** point to the start of the next docid value. The following line deals 4719 ** with this case by advancing pIter past the zero-padding added by 4720 ** fts3EvalNearTrim(). */ 4721 while( pIterpNextDocid = pIter; 4724 assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter ); 4725 *pbEof = 0; 4726 } 4727 } 4728 4729 /* 4730 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext(). 4731 */ 4732 typedef struct TokenDoclist TokenDoclist; 4733 struct TokenDoclist { 4734 int bIgnore; 4735 sqlite3_int64 iDocid; 4736 char *pList; 4737 int nList; 4738 }; 4739 4740 /* 4741 ** Token pToken is an incrementally loaded token that is part of a 4742 ** multi-token phrase. Advance it to the next matching document in the 4743 ** database and populate output variable *p with the details of the new 4744 ** entry. Or, if the iterator has reached EOF, set *pbEof to true. 4745 ** 4746 ** If an error occurs, return an SQLite error code. Otherwise, return 4747 ** SQLITE_OK. 4748 */ 4749 static int incrPhraseTokenNext( 4750 Fts3Table *pTab, /* Virtual table handle */ 4751 Fts3Phrase *pPhrase, /* Phrase to advance token of */ 4752 int iToken, /* Specific token to advance */ 4753 TokenDoclist *p, /* OUT: Docid and doclist for new entry */ 4754 u8 *pbEof /* OUT: True if iterator is at EOF */ 4755 ){ 4756 int rc = SQLITE_OK; 4757 4758 if( pPhrase->iDoclistToken==iToken ){ 4759 assert( p->bIgnore==0 ); 4760 assert( pPhrase->aToken[iToken].pSegcsr==0 ); 4761 fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof); 4762 p->pList = pPhrase->doclist.pList; 4763 p->nList = pPhrase->doclist.nList; 4764 p->iDocid = pPhrase->doclist.iDocid; 4765 }else{ 4766 Fts3PhraseToken *pToken = &pPhrase->aToken[iToken]; 4767 assert( pToken->pDeferred==0 ); 4768 assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 ); 4769 if( pToken->pSegcsr ){ 4770 assert( p->bIgnore==0 ); 4771 rc = sqlite3Fts3MsrIncrNext( 4772 pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList 4773 ); 4774 if( p->pList==0 ) *pbEof = 1; 4775 }else{ 4776 p->bIgnore = 1; 4777 } 4778 } 4779 4780 return rc; 4781 } 4782 4783 4784 /* 4785 ** The phrase iterator passed as the second argument: 4786 ** 4787 ** * features at least one token that uses an incremental doclist, and 4788 ** 4789 ** * does not contain any deferred tokens. 4790 ** 4791 ** Advance it to the next matching document in the database and populate 4792 ** the Fts3Doclist.pList and nList fields. 4793 ** 4794 ** If there is no "next" entry and no error occurs, then *pbEof is set to 4795 ** 1 before returning. Otherwise, if no error occurs and the iterator is 4796 ** successfully advanced, *pbEof is set to 0. 4797 ** 4798 ** If an error occurs, return an SQLite error code. Otherwise, return 4799 ** SQLITE_OK. 4800 */ 4801 static int fts3EvalIncrPhraseNext( 4802 Fts3Cursor *pCsr, /* FTS Cursor handle */ 4803 Fts3Phrase *p, /* Phrase object to advance to next docid */ 4804 u8 *pbEof /* OUT: Set to 1 if EOF */ 4805 ){ 4806 int rc = SQLITE_OK; 4807 Fts3Doclist *pDL = &p->doclist; 4808 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; 4809 u8 bEof = 0; 4810 4811 /* This is only called if it is guaranteed that the phrase has at least 4812 ** one incremental token. In which case the bIncr flag is set. */ 4813 assert( p->bIncr==1 ); 4814 4815 if( p->nToken==1 ){ 4816 rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 4817 &pDL->iDocid, &pDL->pList, &pDL->nList 4818 ); 4819 if( pDL->pList==0 ) bEof = 1; 4820 }else{ 4821 int bDescDoclist = pCsr->bDesc; 4822 struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS]; 4823 4824 memset(a, 0, sizeof(a)); 4825 assert( p->nToken<=MAX_INCR_PHRASE_TOKENS ); 4826 assert( p->iDoclistTokennToken && bEof==0; i++){ 4835 rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof); 4836 if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){ 4837 iMax = a[i].iDocid; 4838 bMaxSet = 1; 4839 } 4840 } 4841 assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) ); 4842 assert( rc!=SQLITE_OK || bMaxSet ); 4843 4844 /* Keep advancing iterators until they all point to the same document */ 4845 for(i=0; inToken; i++){ 4846 while( rc==SQLITE_OK && bEof==0 4847 && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0 4848 ){ 4849 rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof); 4850 if( DOCID_CMP(a[i].iDocid, iMax)>0 ){ 4851 iMax = a[i].iDocid; 4852 i = 0; 4853 } 4854 } 4855 } 4856 4857 /* Check if the current entries really are a phrase match */ 4858 if( bEof==0 ){ 4859 int nList = 0; 4860 int nByte = a[p->nToken-1].nList; 4861 char *aDoclist = sqlite3_malloc64((i64)nByte+FTS3_BUFFER_PADDING); 4862 if( !aDoclist ) return SQLITE_NOMEM; 4863 memcpy(aDoclist, a[p->nToken-1].pList, nByte+1); 4864 memset(&aDoclist[nByte], 0, FTS3_BUFFER_PADDING); 4865 4866 for(i=0; i<(p->nToken-1); i++){ 4867 if( a[i].bIgnore==0 ){ 4868 char *pL = a[i].pList; 4869 char *pR = aDoclist; 4870 char *pOut = aDoclist; 4871 int nDist = p->nToken-1-i; 4872 int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR); 4873 if( res==0 ) break; 4874 nList = (int)(pOut - aDoclist); 4875 } 4876 } 4877 if( i==(p->nToken-1) ){ 4878 pDL->iDocid = iMax; 4879 pDL->pList = aDoclist; 4880 pDL->nList = nList; 4881 pDL->bFreeList = 1; 4882 break; 4883 } 4884 sqlite3_free(aDoclist); 4885 } 4886 } 4887 } 4888 4889 *pbEof = bEof; 4890 return rc; 4891 } 4892 4893 /* 4894 ** Attempt to move the phrase iterator to point to the next matching docid. 4895 ** If an error occurs, return an SQLite error code. Otherwise, return 4896 ** SQLITE_OK. 4897 ** 4898 ** If there is no "next" entry and no error occurs, then *pbEof is set to 4899 ** 1 before returning. Otherwise, if no error occurs and the iterator is 4900 ** successfully advanced, *pbEof is set to 0. 4901 */ 4902 static int fts3EvalPhraseNext( 4903 Fts3Cursor *pCsr, /* FTS Cursor handle */ 4904 Fts3Phrase *p, /* Phrase object to advance to next docid */ 4905 u8 *pbEof /* OUT: Set to 1 if EOF */ 4906 ){ 4907 int rc = SQLITE_OK; 4908 Fts3Doclist *pDL = &p->doclist; 4909 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; 4910 4911 if( p->bIncr ){ 4912 rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof); 4913 }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){ 4914 sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 4915 &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof 4916 ); 4917 pDL->pList = pDL->pNextDocid; 4918 }else{ 4919 fts3EvalDlPhraseNext(pTab, pDL, pbEof); 4920 } 4921 4922 return rc; 4923 } 4924 4925 /* 4926 ** 4927 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 4928 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the 4929 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any 4930 ** expressions for which all descendent tokens are deferred. 4931 ** 4932 ** If parameter bOptOk is zero, then it is guaranteed that the 4933 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for 4934 ** each phrase in the expression (subject to deferred token processing). 4935 ** Or, if bOptOk is non-zero, then one or more tokens within the expression 4936 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available. 4937 ** 4938 ** If an error occurs within this function, *pRc is set to an SQLite error 4939 ** code before returning. 4940 */ 4941 static void fts3EvalStartReaders( 4942 Fts3Cursor *pCsr, /* FTS Cursor handle */ 4943 Fts3Expr *pExpr, /* Expression to initialize phrases in */ 4944 int *pRc /* IN/OUT: Error code */ 4945 ){ 4946 if( pExpr && SQLITE_OK==*pRc ){ 4947 if( pExpr->eType==FTSQUERY_PHRASE ){ 4948 int nToken = pExpr->pPhrase->nToken; 4949 if( nToken ){ 4950 int i; 4951 for(i=0; ipPhrase->aToken[i].pDeferred==0 ) break; 4953 } 4954 pExpr->bDeferred = (i==nToken); 4955 } 4956 *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase); 4957 }else{ 4958 fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc); 4959 fts3EvalStartReaders(pCsr, pExpr->pRight, pRc); 4960 pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred); 4961 } 4962 } 4963 } 4964 4965 /* 4966 ** An array of the following structures is assembled as part of the process 4967 ** of selecting tokens to defer before the query starts executing (as part 4968 ** of the xFilter() method). There is one element in the array for each 4969 ** token in the FTS expression. 4970 ** 4971 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong 4972 ** to phrases that are connected only by AND and NEAR operators (not OR or 4973 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered 4974 ** separately. The root of a tokens AND/NEAR cluster is stored in 4975 ** Fts3TokenAndCost.pRoot. 4976 */ 4977 typedef struct Fts3TokenAndCost Fts3TokenAndCost; 4978 struct Fts3TokenAndCost { 4979 Fts3Phrase *pPhrase; /* The phrase the token belongs to */ 4980 int iToken; /* Position of token in phrase */ 4981 Fts3PhraseToken *pToken; /* The token itself */ 4982 Fts3Expr *pRoot; /* Root of NEAR/AND cluster */ 4983 int nOvfl; /* Number of overflow pages to load doclist */ 4984 int iCol; /* The column the token must match */ 4985 }; 4986 4987 /* 4988 ** This function is used to populate an allocated Fts3TokenAndCost array. 4989 ** 4990 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 4991 ** Otherwise, if an error occurs during execution, *pRc is set to an 4992 ** SQLite error code. 4993 */ 4994 static void fts3EvalTokenCosts( 4995 Fts3Cursor *pCsr, /* FTS Cursor handle */ 4996 Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */ 4997 Fts3Expr *pExpr, /* Expression to consider */ 4998 Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */ 4999 Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */ 5000 int *pRc /* IN/OUT: Error code */ 5001 ){ 5002 if( *pRc==SQLITE_OK ){ 5003 if( pExpr->eType==FTSQUERY_PHRASE ){ 5004 Fts3Phrase *pPhrase = pExpr->pPhrase; 5005 int i; 5006 for(i=0; *pRc==SQLITE_OK && inToken; i++){ 5007 Fts3TokenAndCost *pTC = (*ppTC)++; 5008 pTC->pPhrase = pPhrase; 5009 pTC->iToken = i; 5010 pTC->pRoot = pRoot; 5011 pTC->pToken = &pPhrase->aToken[i]; 5012 pTC->iCol = pPhrase->iColumn; 5013 *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl); 5014 } 5015 }else if( pExpr->eType!=FTSQUERY_NOT ){ 5016 assert( pExpr->eType==FTSQUERY_OR 5017 || pExpr->eType==FTSQUERY_AND 5018 || pExpr->eType==FTSQUERY_NEAR 5019 ); 5020 assert( pExpr->pLeft && pExpr->pRight ); 5021 if( pExpr->eType==FTSQUERY_OR ){ 5022 pRoot = pExpr->pLeft; 5023 **ppOr = pRoot; 5024 (*ppOr)++; 5025 } 5026 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc); 5027 if( pExpr->eType==FTSQUERY_OR ){ 5028 pRoot = pExpr->pRight; 5029 **ppOr = pRoot; 5030 (*ppOr)++; 5031 } 5032 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc); 5033 } 5034 } 5035 } 5036 5037 /* 5038 ** Determine the average document (row) size in pages. If successful, 5039 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return 5040 ** an SQLite error code. 5041 ** 5042 ** The average document size in pages is calculated by first calculating 5043 ** determining the average size in bytes, B. If B is less than the amount 5044 ** of data that will fit on a single leaf page of an intkey table in 5045 ** this database, then the average docsize is 1. Otherwise, it is 1 plus 5046 ** the number of overflow pages consumed by a record B bytes in size. 5047 */ 5048 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){ 5049 int rc = SQLITE_OK; 5050 if( pCsr->nRowAvg==0 ){ 5051 /* The average document size, which is required to calculate the cost 5052 ** of each doclist, has not yet been determined. Read the required 5053 ** data from the %_stat table to calculate it. 5054 ** 5055 ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 5056 ** varints, where nCol is the number of columns in the FTS3 table. 5057 ** The first varint is the number of documents currently stored in 5058 ** the table. The following nCol varints contain the total amount of 5059 ** data stored in all rows of each column of the table, from left 5060 ** to right. 5061 */ 5062 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab; 5063 sqlite3_stmt *pStmt; 5064 sqlite3_int64 nDoc = 0; 5065 sqlite3_int64 nByte = 0; 5066 const char *pEnd; 5067 const char *a; 5068 5069 rc = sqlite3Fts3SelectDoctotal(p, &pStmt); 5070 if( rc!=SQLITE_OK ) return rc; 5071 a = sqlite3_column_blob(pStmt, 0); 5072 testcase( a==0 ); /* If %_stat.value set to X'' */ 5073 if( a ){ 5074 pEnd = &a[sqlite3_column_bytes(pStmt, 0)]; 5075 a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc); 5076 while( anDoc = nDoc; 5086 pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz); 5087 assert( pCsr->nRowAvg>0 ); 5088 rc = sqlite3_reset(pStmt); 5089 } 5090 5091 *pnPage = pCsr->nRowAvg; 5092 return rc; 5093 } 5094 5095 /* 5096 ** This function is called to select the tokens (if any) that will be 5097 ** deferred. The array aTC[] has already been populated when this is 5098 ** called. 5099 ** 5100 ** This function is called once for each AND/NEAR cluster in the 5101 ** expression. Each invocation determines which tokens to defer within 5102 ** the cluster with root node pRoot. See comments above the definition 5103 ** of struct Fts3TokenAndCost for more details. 5104 ** 5105 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken() 5106 ** called on each token to defer. Otherwise, an SQLite error code is 5107 ** returned. 5108 */ 5109 static int fts3EvalSelectDeferred( 5110 Fts3Cursor *pCsr, /* FTS Cursor handle */ 5111 Fts3Expr *pRoot, /* Consider tokens with this root node */ 5112 Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */ 5113 int nTC /* Number of entries in aTC[] */ 5114 ){ 5115 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; 5116 int nDocSize = 0; /* Number of pages per doc loaded */ 5117 int rc = SQLITE_OK; /* Return code */ 5118 int ii; /* Iterator variable for various purposes */ 5119 int nOvfl = 0; /* Total overflow pages used by doclists */ 5120 int nToken = 0; /* Total number of tokens in cluster */ 5121 5122 int nMinEst = 0; /* The minimum count for any phrase so far. */ 5123 int nLoad4 = 1; /* (Phrases that will be loaded)^4. */ 5124 5125 /* Tokens are never deferred for FTS tables created using the content=xxx 5126 ** option. The reason being that it is not guaranteed that the content 5127 ** table actually contains the same data as the index. To prevent this from 5128 ** causing any problems, the deferred token optimization is completely 5129 ** disabled for content=xxx tables. */ 5130 if( pTab->zContentTbl ){ 5131 return SQLITE_OK; 5132 } 5133 5134 /* Count the tokens in this AND/NEAR cluster. If none of the doclists 5135 ** associated with the tokens spill onto overflow pages, or if there is 5136 ** only 1 token, exit early. No tokens to defer in this case. */ 5137 for(ii=0; ii0 ); 5148 5149 5150 /* Iterate through all tokens in this AND/NEAR cluster, in ascending order 5151 ** of the number of overflow pages that will be loaded by the pager layer 5152 ** to retrieve the entire doclist for the token from the full-text index. 5153 ** Load the doclists for tokens that are either: 5154 ** 5155 ** a. The cheapest token in the entire query (i.e. the one visited by the 5156 ** first iteration of this loop), or 5157 ** 5158 ** b. Part of a multi-token phrase. 5159 ** 5160 ** After each token doclist is loaded, merge it with the others from the 5161 ** same phrase and count the number of documents that the merged doclist 5162 ** contains. Set variable "nMinEst" to the smallest number of documents in 5163 ** any phrase doclist for which 1 or more token doclists have been loaded. 5164 ** Let nOther be the number of other phrases for which it is certain that 5165 ** one or more tokens will not be deferred. 5166 ** 5167 ** Then, for each token, defer it if loading the doclist would result in 5168 ** loading N or more overflow pages into memory, where N is computed as: 5169 ** 5170 ** (nMinEst + 4^nOther - 1) / (4^nOther) 5171 */ 5172 for(ii=0; iinOvfl) 5180 ){ 5181 pTC = &aTC[iTC]; 5182 } 5183 } 5184 assert( pTC ); 5185 5186 if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){ 5187 /* The number of overflow pages to load for this (and therefore all 5188 ** subsequent) tokens is greater than the estimated number of pages 5189 ** that will be loaded if all subsequent tokens are deferred. 5190 */ 5191 Fts3PhraseToken *pToken = pTC->pToken; 5192 rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol); 5193 fts3SegReaderCursorFree(pToken->pSegcsr); 5194 pToken->pSegcsr = 0; 5195 }else{ 5196 /* Set nLoad4 to the value of (4^nOther) for the next iteration of the 5197 ** for-loop. Except, limit the value to 2^24 to prevent it from 5198 ** overflowing the 32-bit integer it is stored in. */ 5199 if( ii<12 ) nLoad4 = nLoad4*4; 5200 5201 if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){ 5202 /* Either this is the cheapest token in the entire query, or it is 5203 ** part of a multi-token phrase. Either way, the entire doclist will 5204 ** (eventually) be loaded into memory. It may as well be now. */ 5205 Fts3PhraseToken *pToken = pTC->pToken; 5206 int nList = 0; 5207 char *pList = 0; 5208 rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList); 5209 assert( rc==SQLITE_OK || pList==0 ); 5210 if( rc==SQLITE_OK ){ 5211 rc = fts3EvalPhraseMergeToken( 5212 pTab, pTC->pPhrase, pTC->iToken,pList,nList 5213 ); 5214 } 5215 if( rc==SQLITE_OK ){ 5216 int nCount; 5217 nCount = fts3DoclistCountDocids( 5218 pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll 5219 ); 5220 if( ii==0 || nCountpToken = 0; 5225 } 5226 5227 return rc; 5228 } 5229 5230 /* 5231 ** This function is called from within the xFilter method. It initializes 5232 ** the full-text query currently stored in pCsr->pExpr. To iterate through 5233 ** the results of a query, the caller does: 5234 ** 5235 ** fts3EvalStart(pCsr); 5236 ** while( 1 ){ 5237 ** fts3EvalNext(pCsr); 5238 ** if( pCsr->bEof ) break; 5239 ** ... return row pCsr->iPrevId to the caller ... 5240 ** } 5241 */ 5242 static int fts3EvalStart(Fts3Cursor *pCsr){ 5243 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; 5244 int rc = SQLITE_OK; 5245 int nToken = 0; 5246 int nOr = 0; 5247 5248 /* Allocate a MultiSegReader for each token in the expression. */ 5249 fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc); 5250 5251 /* Determine which, if any, tokens in the expression should be deferred. */ 5252 #ifndef SQLITE_DISABLE_FTS4_DEFERRED 5253 if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){ 5254 Fts3TokenAndCost *aTC; 5255 aTC = (Fts3TokenAndCost *)sqlite3_malloc64( 5256 sizeof(Fts3TokenAndCost) * nToken 5257 + sizeof(Fts3Expr *) * nOr * 2 5258 ); 5259 5260 if( !aTC ){ 5261 rc = SQLITE_NOMEM; 5262 }else{ 5263 Fts3Expr **apOr = (Fts3Expr **)&aTC[nToken]; 5264 int ii; 5265 Fts3TokenAndCost *pTC = aTC; 5266 Fts3Expr **ppOr = apOr; 5267 5268 fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc); 5269 nToken = (int)(pTC-aTC); 5270 nOr = (int)(ppOr-apOr); 5271 5272 if( rc==SQLITE_OK ){ 5273 rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken); 5274 for(ii=0; rc==SQLITE_OK && iipExpr, &rc); 5285 return rc; 5286 } 5287 5288 /* 5289 ** Invalidate the current position list for phrase pPhrase. 5290 */ 5291 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){ 5292 if( pPhrase->doclist.bFreeList ){ 5293 sqlite3_free(pPhrase->doclist.pList); 5294 } 5295 pPhrase->doclist.pList = 0; 5296 pPhrase->doclist.nList = 0; 5297 pPhrase->doclist.bFreeList = 0; 5298 } 5299 5300 /* 5301 ** This function is called to edit the position list associated with 5302 ** the phrase object passed as the fifth argument according to a NEAR 5303 ** condition. For example: 5304 ** 5305 ** abc NEAR/5 "def ghi" 5306 ** 5307 ** Parameter nNear is passed the NEAR distance of the expression (5 in 5308 ** the example above). When this function is called, *paPoslist points to 5309 ** the position list, and *pnToken is the number of phrase tokens in the 5310 ** phrase on the other side of the NEAR operator to pPhrase. For example, 5311 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to 5312 ** the position list associated with phrase "abc". 5313 ** 5314 ** All positions in the pPhrase position list that are not sufficiently 5315 ** close to a position in the *paPoslist position list are removed. If this 5316 ** leaves 0 positions, zero is returned. Otherwise, non-zero. 5317 ** 5318 ** Before returning, *paPoslist is set to point to the position lsit 5319 ** associated with pPhrase. And *pnToken is set to the number of tokens in 5320 ** pPhrase. 5321 */ 5322 static int fts3EvalNearTrim( 5323 int nNear, /* NEAR distance. As in "NEAR/nNear". */ 5324 char *aTmp, /* Temporary space to use */ 5325 char **paPoslist, /* IN/OUT: Position list */ 5326 int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */ 5327 Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */ 5328 ){ 5329 int nParam1 = nNear + pPhrase->nToken; 5330 int nParam2 = nNear + *pnToken; 5331 int nNew; 5332 char *p2; 5333 char *pOut; 5334 int res; 5335 5336 assert( pPhrase->doclist.pList ); 5337 5338 p2 = pOut = pPhrase->doclist.pList; 5339 res = fts3PoslistNearMerge( 5340 &pOut, aTmp, nParam1, nParam2, paPoslist, &p2 5341 ); 5342 if( res ){ 5343 nNew = (int)(pOut - pPhrase->doclist.pList) - 1; 5344 assert_fts3_nc( nNew<=pPhrase->doclist.nList && nNew>0 ); 5345 if( nNew>=0 && nNew<=pPhrase->doclist.nList ){ 5346 assert( pPhrase->doclist.pList[nNew]=='\0' ); 5347 memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew); 5348 pPhrase->doclist.nList = nNew; 5349 } 5350 *paPoslist = pPhrase->doclist.pList; 5351 *pnToken = pPhrase->nToken; 5352 } 5353 5354 return res; 5355 } 5356 5357 /* 5358 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called. 5359 ** Otherwise, it advances the expression passed as the second argument to 5360 ** point to the next matching row in the database. Expressions iterate through 5361 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero, 5362 ** or descending if it is non-zero. 5363 ** 5364 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if 5365 ** successful, the following variables in pExpr are set: 5366 ** 5367 ** Fts3Expr.bEof (non-zero if EOF - there is no next row) 5368 ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row) 5369 ** 5370 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not 5371 ** at EOF, then the following variables are populated with the position list 5372 ** for the phrase for the visited row: 5373 ** 5374 ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes) 5375 ** FTs3Expr.pPhrase->doclist.pList (pointer to position list) 5376 ** 5377 ** It says above that this function advances the expression to the next 5378 ** matching row. This is usually true, but there are the following exceptions: 5379 ** 5380 ** 1. Deferred tokens are not taken into account. If a phrase consists 5381 ** entirely of deferred tokens, it is assumed to match every row in 5382 ** the db. In this case the position-list is not populated at all. 5383 ** 5384 ** Or, if a phrase contains one or more deferred tokens and one or 5385 ** more non-deferred tokens, then the expression is advanced to the 5386 ** next possible match, considering only non-deferred tokens. In other 5387 ** words, if the phrase is "A B C", and "B" is deferred, the expression 5388 ** is advanced to the next row that contains an instance of "A * C", 5389 ** where "*" may match any single token. The position list in this case 5390 ** is populated as for "A * C" before returning. 5391 ** 5392 ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is 5393 ** advanced to point to the next row that matches "x AND y". 5394 ** 5395 ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is 5396 ** really a match, taking into account deferred tokens and NEAR operators. 5397 */ 5398 static void fts3EvalNextRow( 5399 Fts3Cursor *pCsr, /* FTS Cursor handle */ 5400 Fts3Expr *pExpr, /* Expr. to advance to next matching row */ 5401 int *pRc /* IN/OUT: Error code */ 5402 ){ 5403 if( *pRc==SQLITE_OK && pExpr->bEof==0 ){ 5404 int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */ 5405 pExpr->bStart = 1; 5406 5407 switch( pExpr->eType ){ 5408 case FTSQUERY_NEAR: 5409 case FTSQUERY_AND: { 5410 Fts3Expr *pLeft = pExpr->pLeft; 5411 Fts3Expr *pRight = pExpr->pRight; 5412 assert( !pLeft->bDeferred || !pRight->bDeferred ); 5413 5414 if( pLeft->bDeferred ){ 5415 /* LHS is entirely deferred. So we assume it matches every row. 5416 ** Advance the RHS iterator to find the next row visited. */ 5417 fts3EvalNextRow(pCsr, pRight, pRc); 5418 pExpr->iDocid = pRight->iDocid; 5419 pExpr->bEof = pRight->bEof; 5420 }else if( pRight->bDeferred ){ 5421 /* RHS is entirely deferred. So we assume it matches every row. 5422 ** Advance the LHS iterator to find the next row visited. */ 5423 fts3EvalNextRow(pCsr, pLeft, pRc); 5424 pExpr->iDocid = pLeft->iDocid; 5425 pExpr->bEof = pLeft->bEof; 5426 }else{ 5427 /* Neither the RHS or LHS are deferred. */ 5428 fts3EvalNextRow(pCsr, pLeft, pRc); 5429 fts3EvalNextRow(pCsr, pRight, pRc); 5430 while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){ 5431 sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid); 5432 if( iDiff==0 ) break; 5433 if( iDiff<0 ){ 5434 fts3EvalNextRow(pCsr, pLeft, pRc); 5435 }else{ 5436 fts3EvalNextRow(pCsr, pRight, pRc); 5437 } 5438 } 5439 pExpr->iDocid = pLeft->iDocid; 5440 pExpr->bEof = (pLeft->bEof || pRight->bEof); 5441 if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){ 5442 assert( pRight->eType==FTSQUERY_PHRASE ); 5443 if( pRight->pPhrase->doclist.aAll ){ 5444 Fts3Doclist *pDl = &pRight->pPhrase->doclist; 5445 while( *pRc==SQLITE_OK && pRight->bEof==0 ){ 5446 memset(pDl->pList, 0, pDl->nList); 5447 fts3EvalNextRow(pCsr, pRight, pRc); 5448 } 5449 } 5450 if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){ 5451 Fts3Doclist *pDl = &pLeft->pPhrase->doclist; 5452 while( *pRc==SQLITE_OK && pLeft->bEof==0 ){ 5453 memset(pDl->pList, 0, pDl->nList); 5454 fts3EvalNextRow(pCsr, pLeft, pRc); 5455 } 5456 } 5457 pRight->bEof = pLeft->bEof = 1; 5458 } 5459 } 5460 break; 5461 } 5462 5463 case FTSQUERY_OR: { 5464 Fts3Expr *pLeft = pExpr->pLeft; 5465 Fts3Expr *pRight = pExpr->pRight; 5466 sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid); 5467 5468 assert_fts3_nc( pLeft->bStart || pLeft->iDocid==pRight->iDocid ); 5469 assert_fts3_nc( pRight->bStart || pLeft->iDocid==pRight->iDocid ); 5470 5471 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){ 5472 fts3EvalNextRow(pCsr, pLeft, pRc); 5473 }else if( pLeft->bEof || iCmp>0 ){ 5474 fts3EvalNextRow(pCsr, pRight, pRc); 5475 }else{ 5476 fts3EvalNextRow(pCsr, pLeft, pRc); 5477 fts3EvalNextRow(pCsr, pRight, pRc); 5478 } 5479 5480 pExpr->bEof = (pLeft->bEof && pRight->bEof); 5481 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid); 5482 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){ 5483 pExpr->iDocid = pLeft->iDocid; 5484 }else{ 5485 pExpr->iDocid = pRight->iDocid; 5486 } 5487 5488 break; 5489 } 5490 5491 case FTSQUERY_NOT: { 5492 Fts3Expr *pLeft = pExpr->pLeft; 5493 Fts3Expr *pRight = pExpr->pRight; 5494 5495 if( pRight->bStart==0 ){ 5496 fts3EvalNextRow(pCsr, pRight, pRc); 5497 assert( *pRc!=SQLITE_OK || pRight->bStart ); 5498 } 5499 5500 fts3EvalNextRow(pCsr, pLeft, pRc); 5501 if( pLeft->bEof==0 ){ 5502 while( !*pRc 5503 && !pRight->bEof 5504 && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 5505 ){ 5506 fts3EvalNextRow(pCsr, pRight, pRc); 5507 } 5508 } 5509 pExpr->iDocid = pLeft->iDocid; 5510 pExpr->bEof = pLeft->bEof; 5511 break; 5512 } 5513 5514 default: { 5515 Fts3Phrase *pPhrase = pExpr->pPhrase; 5516 fts3EvalInvalidatePoslist(pPhrase); 5517 *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof); 5518 pExpr->iDocid = pPhrase->doclist.iDocid; 5519 break; 5520 } 5521 } 5522 } 5523 } 5524 5525 /* 5526 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR 5527 ** cluster, then this function returns 1 immediately. 5528 ** 5529 ** Otherwise, it checks if the current row really does match the NEAR 5530 ** expression, using the data currently stored in the position lists 5531 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. 5532 ** 5533 ** If the current row is a match, the position list associated with each 5534 ** phrase in the NEAR expression is edited in place to contain only those 5535 ** phrase instances sufficiently close to their peers to satisfy all NEAR 5536 ** constraints. In this case it returns 1. If the NEAR expression does not 5537 ** match the current row, 0 is returned. The position lists may or may not 5538 ** be edited if 0 is returned. 5539 */ 5540 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){ 5541 int res = 1; 5542 5543 /* The following block runs if pExpr is the root of a NEAR query. 5544 ** For example, the query: 5545 ** 5546 ** "w" NEAR "x" NEAR "y" NEAR "z" 5547 ** 5548 ** which is represented in tree form as: 5549 ** 5550 ** | 5551 ** +--NEAR--+ <-- root of NEAR query 5552 ** | | 5553 ** +--NEAR--+ "z" 5554 ** | | 5555 ** +--NEAR--+ "y" 5556 ** | | 5557 ** "w" "x" 5558 ** 5559 ** The right-hand child of a NEAR node is always a phrase. The 5560 ** left-hand child may be either a phrase or a NEAR node. There are 5561 ** no exceptions to this - it's the way the parser in fts3_expr.c works. 5562 */ 5563 if( *pRc==SQLITE_OK 5564 && pExpr->eType==FTSQUERY_NEAR 5565 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR) 5566 ){ 5567 Fts3Expr *p; 5568 sqlite3_int64 nTmp = 0; /* Bytes of temp space */ 5569 char *aTmp; /* Temp space for PoslistNearMerge() */ 5570 5571 /* Allocate temporary working space. */ 5572 for(p=pExpr; p->pLeft; p=p->pLeft){ 5573 assert( p->pRight->pPhrase->doclist.nList>0 ); 5574 nTmp += p->pRight->pPhrase->doclist.nList; 5575 } 5576 nTmp += p->pPhrase->doclist.nList; 5577 aTmp = sqlite3_malloc64(nTmp*2 + FTS3_VARINT_MAX); 5578 if( !aTmp ){ 5579 *pRc = SQLITE_NOMEM; 5580 res = 0; 5581 }else{ 5582 char *aPoslist = p->pPhrase->doclist.pList; 5583 int nToken = p->pPhrase->nToken; 5584 5585 for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){ 5586 Fts3Phrase *pPhrase = p->pRight->pPhrase; 5587 int nNear = p->nNear; 5588 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); 5589 } 5590 5591 aPoslist = pExpr->pRight->pPhrase->doclist.pList; 5592 nToken = pExpr->pRight->pPhrase->nToken; 5593 for(p=pExpr->pLeft; p && res; p=p->pLeft){ 5594 int nNear; 5595 Fts3Phrase *pPhrase; 5596 assert( p->pParent && p->pParent->pLeft==p ); 5597 nNear = p->pParent->nNear; 5598 pPhrase = ( 5599 p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase 5600 ); 5601 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); 5602 } 5603 } 5604 5605 sqlite3_free(aTmp); 5606 } 5607 5608 return res; 5609 } 5610 5611 /* 5612 ** This function is a helper function for sqlite3Fts3EvalTestDeferred(). 5613 ** Assuming no error occurs or has occurred, It returns non-zero if the 5614 ** expression passed as the second argument matches the row that pCsr 5615 ** currently points to, or zero if it does not. 5616 ** 5617 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 5618 ** If an error occurs during execution of this function, *pRc is set to 5619 ** the appropriate SQLite error code. In this case the returned value is 5620 ** undefined. 5621 */ 5622 static int fts3EvalTestExpr( 5623 Fts3Cursor *pCsr, /* FTS cursor handle */ 5624 Fts3Expr *pExpr, /* Expr to test. May or may not be root. */ 5625 int *pRc /* IN/OUT: Error code */ 5626 ){ 5627 int bHit = 1; /* Return value */ 5628 if( *pRc==SQLITE_OK ){ 5629 switch( pExpr->eType ){ 5630 case FTSQUERY_NEAR: 5631 case FTSQUERY_AND: 5632 bHit = ( 5633 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc) 5634 && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc) 5635 && fts3EvalNearTest(pExpr, pRc) 5636 ); 5637 5638 /* If the NEAR expression does not match any rows, zero the doclist for 5639 ** all phrases involved in the NEAR. This is because the snippet(), 5640 ** offsets() and matchinfo() functions are not supposed to recognize 5641 ** any instances of phrases that are part of unmatched NEAR queries. 5642 ** For example if this expression: 5643 ** 5644 ** ... MATCH 'a OR (b NEAR c)' 5645 ** 5646 ** is matched against a row containing: 5647 ** 5648 ** 'a b d e' 5649 ** 5650 ** then any snippet() should ony highlight the "a" term, not the "b" 5651 ** (as "b" is part of a non-matching NEAR clause). 5652 */ 5653 if( bHit==0 5654 && pExpr->eType==FTSQUERY_NEAR 5655 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR) 5656 ){ 5657 Fts3Expr *p; 5658 for(p=pExpr; p->pPhrase==0; p=p->pLeft){ 5659 if( p->pRight->iDocid==pCsr->iPrevId ){ 5660 fts3EvalInvalidatePoslist(p->pRight->pPhrase); 5661 } 5662 } 5663 if( p->iDocid==pCsr->iPrevId ){ 5664 fts3EvalInvalidatePoslist(p->pPhrase); 5665 } 5666 } 5667 5668 break; 5669 5670 case FTSQUERY_OR: { 5671 int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc); 5672 int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc); 5673 bHit = bHit1 || bHit2; 5674 break; 5675 } 5676 5677 case FTSQUERY_NOT: 5678 bHit = ( 5679 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc) 5680 && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc) 5681 ); 5682 break; 5683 5684 default: { 5685 #ifndef SQLITE_DISABLE_FTS4_DEFERRED 5686 if( pCsr->pDeferred && (pExpr->bDeferred || ( 5687 pExpr->iDocid==pCsr->iPrevId && pExpr->pPhrase->doclist.pList 5688 ))){ 5689 Fts3Phrase *pPhrase = pExpr->pPhrase; 5690 if( pExpr->bDeferred ){ 5691 fts3EvalInvalidatePoslist(pPhrase); 5692 } 5693 *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase); 5694 bHit = (pPhrase->doclist.pList!=0); 5695 pExpr->iDocid = pCsr->iPrevId; 5696 }else 5697 #endif 5698 { 5699 bHit = ( 5700 pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId 5701 && pExpr->pPhrase->doclist.nList>0 5702 ); 5703 } 5704 break; 5705 } 5706 } 5707 } 5708 return bHit; 5709 } 5710 5711 /* 5712 ** This function is called as the second part of each xNext operation when 5713 ** iterating through the results of a full-text query. At this point the 5714 ** cursor points to a row that matches the query expression, with the 5715 ** following caveats: 5716 ** 5717 ** * Up until this point, "NEAR" operators in the expression have been 5718 ** treated as "AND". 5719 ** 5720 ** * Deferred tokens have not yet been considered. 5721 ** 5722 ** If *pRc is not SQLITE_OK when this function is called, it immediately 5723 ** returns 0. Otherwise, it tests whether or not after considering NEAR 5724 ** operators and deferred tokens the current row is still a match for the 5725 ** expression. It returns 1 if both of the following are true: 5726 ** 5727 ** 1. *pRc is SQLITE_OK when this function returns, and 5728 ** 5729 ** 2. After scanning the current FTS table row for the deferred tokens, 5730 ** it is determined that the row does *not* match the query. 5731 ** 5732 ** Or, if no error occurs and it seems the current row does match the FTS 5733 ** query, return 0. 5734 */ 5735 int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){ 5736 int rc = *pRc; 5737 int bMiss = 0; 5738 if( rc==SQLITE_OK ){ 5739 5740 /* If there are one or more deferred tokens, load the current row into 5741 ** memory and scan it to determine the position list for each deferred 5742 ** token. Then, see if this row is really a match, considering deferred 5743 ** tokens and NEAR operators (neither of which were taken into account 5744 ** earlier, by fts3EvalNextRow()). 5745 */ 5746 if( pCsr->pDeferred ){ 5747 rc = fts3CursorSeek(0, pCsr); 5748 if( rc==SQLITE_OK ){ 5749 rc = sqlite3Fts3CacheDeferredDoclists(pCsr); 5750 } 5751 } 5752 bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc)); 5753 5754 /* Free the position-lists accumulated for each deferred token above. */ 5755 sqlite3Fts3FreeDeferredDoclists(pCsr); 5756 *pRc = rc; 5757 } 5758 return (rc==SQLITE_OK && bMiss); 5759 } 5760 5761 /* 5762 ** Advance to the next document that matches the FTS expression in 5763 ** Fts3Cursor.pExpr. 5764 */ 5765 static int fts3EvalNext(Fts3Cursor *pCsr){ 5766 int rc = SQLITE_OK; /* Return Code */ 5767 Fts3Expr *pExpr = pCsr->pExpr; 5768 assert( pCsr->isEof==0 ); 5769 if( pExpr==0 ){ 5770 pCsr->isEof = 1; 5771 }else{ 5772 do { 5773 if( pCsr->isRequireSeek==0 ){ 5774 sqlite3_reset(pCsr->pStmt); 5775 } 5776 assert( sqlite3_data_count(pCsr->pStmt)==0 ); 5777 fts3EvalNextRow(pCsr, pExpr, &rc); 5778 pCsr->isEof = pExpr->bEof; 5779 pCsr->isRequireSeek = 1; 5780 pCsr->isMatchinfoNeeded = 1; 5781 pCsr->iPrevId = pExpr->iDocid; 5782 }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) ); 5783 } 5784 5785 /* Check if the cursor is past the end of the docid range specified 5786 ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */ 5787 if( rc==SQLITE_OK && ( 5788 (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid) 5789 || (pCsr->bDesc!=0 && pCsr->iPrevIdiMinDocid) 5790 )){ 5791 pCsr->isEof = 1; 5792 } 5793 5794 return rc; 5795 } 5796 5797 /* 5798 ** Restart iteration for expression pExpr so that the next call to 5799 ** fts3EvalNext() visits the first row. Do not allow incremental 5800 ** loading or merging of phrase doclists for this iteration. 5801 ** 5802 ** If *pRc is other than SQLITE_OK when this function is called, it is 5803 ** a no-op. If an error occurs within this function, *pRc is set to an 5804 ** SQLite error code before returning. 5805 */ 5806 static void fts3EvalRestart( 5807 Fts3Cursor *pCsr, 5808 Fts3Expr *pExpr, 5809 int *pRc 5810 ){ 5811 if( pExpr && *pRc==SQLITE_OK ){ 5812 Fts3Phrase *pPhrase = pExpr->pPhrase; 5813 5814 if( pPhrase ){ 5815 fts3EvalInvalidatePoslist(pPhrase); 5816 if( pPhrase->bIncr ){ 5817 int i; 5818 for(i=0; inToken; i++){ 5819 Fts3PhraseToken *pToken = &pPhrase->aToken[i]; 5820 assert( pToken->pDeferred==0 ); 5821 if( pToken->pSegcsr ){ 5822 sqlite3Fts3MsrIncrRestart(pToken->pSegcsr); 5823 } 5824 } 5825 *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase); 5826 } 5827 pPhrase->doclist.pNextDocid = 0; 5828 pPhrase->doclist.iDocid = 0; 5829 pPhrase->pOrPoslist = 0; 5830 } 5831 5832 pExpr->iDocid = 0; 5833 pExpr->bEof = 0; 5834 pExpr->bStart = 0; 5835 5836 fts3EvalRestart(pCsr, pExpr->pLeft, pRc); 5837 fts3EvalRestart(pCsr, pExpr->pRight, pRc); 5838 } 5839 } 5840 5841 /* 5842 ** Expression node pExpr is an MSR phrase. This function restarts pExpr 5843 ** so that it is a regular phrase query, not an MSR. SQLITE_OK is returned 5844 ** if successful, or an SQLite error code otherwise. 5845 */ 5846 int sqlite3Fts3MsrCancel(Fts3Cursor *pCsr, Fts3Expr *pExpr){ 5847 int rc = SQLITE_OK; 5848 if( pExpr->bEof==0 ){ 5849 i64 iDocid = pExpr->iDocid; 5850 fts3EvalRestart(pCsr, pExpr, &rc); 5851 while( rc==SQLITE_OK && pExpr->iDocid!=iDocid ){ 5852 fts3EvalNextRow(pCsr, pExpr, &rc); 5853 if( pExpr->bEof ) rc = FTS_CORRUPT_VTAB; 5854 } 5855 } 5856 return rc; 5857 } 5858 5859 /* 5860 ** After allocating the Fts3Expr.aMI[] array for each phrase in the 5861 ** expression rooted at pExpr, the cursor iterates through all rows matched 5862 ** by pExpr, calling this function for each row. This function increments 5863 ** the values in Fts3Expr.aMI[] according to the position-list currently 5864 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase 5865 ** expression nodes. 5866 */ 5867 static void fts3EvalUpdateCounts(Fts3Expr *pExpr, int nCol){ 5868 if( pExpr ){ 5869 Fts3Phrase *pPhrase = pExpr->pPhrase; 5870 if( pPhrase && pPhrase->doclist.pList ){ 5871 int iCol = 0; 5872 char *p = pPhrase->doclist.pList; 5873 5874 do{ 5875 u8 c = 0; 5876 int iCnt = 0; 5877 while( 0xFE & (*p | c) ){ 5878 if( (c&0x80)==0 ) iCnt++; 5879 c = *p++ & 0x80; 5880 } 5881 5882 /* aMI[iCol*3 + 1] = Number of occurrences 5883 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance 5884 */ 5885 pExpr->aMI[iCol*3 + 1] += iCnt; 5886 pExpr->aMI[iCol*3 + 2] += (iCnt>0); 5887 if( *p==0x00 ) break; 5888 p++; 5889 p += fts3GetVarint32(p, &iCol); 5890 }while( iColpLeft, nCol); 5894 fts3EvalUpdateCounts(pExpr->pRight, nCol); 5895 } 5896 } 5897 5898 /* 5899 ** This is an sqlite3Fts3ExprIterate() callback. If the Fts3Expr.aMI[] array 5900 ** has not yet been allocated, allocate and zero it. Otherwise, just zero 5901 ** it. 5902 */ 5903 static int fts3AllocateMSI(Fts3Expr *pExpr, int iPhrase, void *pCtx){ 5904 Fts3Table *pTab = (Fts3Table*)pCtx; 5905 UNUSED_PARAMETER(iPhrase); 5906 if( pExpr->aMI==0 ){ 5907 pExpr->aMI = (u32 *)sqlite3_malloc64(pTab->nColumn * 3 * sizeof(u32)); 5908 if( pExpr->aMI==0 ) return SQLITE_NOMEM; 5909 } 5910 memset(pExpr->aMI, 0, pTab->nColumn * 3 * sizeof(u32)); 5911 return SQLITE_OK; 5912 } 5913 5914 /* 5915 ** Expression pExpr must be of type FTSQUERY_PHRASE. 5916 ** 5917 ** If it is not already allocated and populated, this function allocates and 5918 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part 5919 ** of a NEAR expression, then it also allocates and populates the same array 5920 ** for all other phrases that are part of the NEAR expression. 5921 ** 5922 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and 5923 ** populated. Otherwise, if an error occurs, an SQLite error code is returned. 5924 */ 5925 static int fts3EvalGatherStats( 5926 Fts3Cursor *pCsr, /* Cursor object */ 5927 Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */ 5928 ){ 5929 int rc = SQLITE_OK; /* Return code */ 5930 5931 assert( pExpr->eType==FTSQUERY_PHRASE ); 5932 if( pExpr->aMI==0 ){ 5933 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; 5934 Fts3Expr *pRoot; /* Root of NEAR expression */ 5935 5936 sqlite3_int64 iPrevId = pCsr->iPrevId; 5937 sqlite3_int64 iDocid; 5938 u8 bEof; 5939 5940 /* Find the root of the NEAR expression */ 5941 pRoot = pExpr; 5942 while( pRoot->pParent 5943 && (pRoot->pParent->eType==FTSQUERY_NEAR || pRoot->bDeferred) 5944 ){ 5945 pRoot = pRoot->pParent; 5946 } 5947 iDocid = pRoot->iDocid; 5948 bEof = pRoot->bEof; 5949 assert( pRoot->bStart ); 5950 5951 /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */ 5952 rc = sqlite3Fts3ExprIterate(pRoot, fts3AllocateMSI, (void*)pTab); 5953 if( rc!=SQLITE_OK ) return rc; 5954 fts3EvalRestart(pCsr, pRoot, &rc); 5955 5956 while( pCsr->isEof==0 && rc==SQLITE_OK ){ 5957 5958 do { 5959 /* Ensure the %_content statement is reset. */ 5960 if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt); 5961 assert( sqlite3_data_count(pCsr->pStmt)==0 ); 5962 5963 /* Advance to the next document */ 5964 fts3EvalNextRow(pCsr, pRoot, &rc); 5965 pCsr->isEof = pRoot->bEof; 5966 pCsr->isRequireSeek = 1; 5967 pCsr->isMatchinfoNeeded = 1; 5968 pCsr->iPrevId = pRoot->iDocid; 5969 }while( pCsr->isEof==0 5970 && pRoot->eType==FTSQUERY_NEAR 5971 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) 5972 ); 5973 5974 if( rc==SQLITE_OK && pCsr->isEof==0 ){ 5975 fts3EvalUpdateCounts(pRoot, pTab->nColumn); 5976 } 5977 } 5978 5979 pCsr->isEof = 0; 5980 pCsr->iPrevId = iPrevId; 5981 5982 if( bEof ){ 5983 pRoot->bEof = bEof; 5984 }else{ 5985 /* Caution: pRoot may iterate through docids in ascending or descending 5986 ** order. For this reason, even though it seems more defensive, the 5987 ** do loop can not be written: 5988 ** 5989 ** do {...} while( pRoot->iDocidbEof==0 ); 5995 if( pRoot->bEof ) rc = FTS_CORRUPT_VTAB; 5996 }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK ); 5997 } 5998 } 5999 return rc; 6000 } 6001 6002 /* 6003 ** This function is used by the matchinfo() module to query a phrase 6004 ** expression node for the following information: 6005 ** 6006 ** 1. The total number of occurrences of the phrase in each column of 6007 ** the FTS table (considering all rows), and 6008 ** 6009 ** 2. For each column, the number of rows in the table for which the 6010 ** column contains at least one instance of the phrase. 6011 ** 6012 ** If no error occurs, SQLITE_OK is returned and the values for each column 6013 ** written into the array aiOut as follows: 6014 ** 6015 ** aiOut[iCol*3 + 1] = Number of occurrences 6016 ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance 6017 ** 6018 ** Caveats: 6019 ** 6020 ** * If a phrase consists entirely of deferred tokens, then all output 6021 ** values are set to the number of documents in the table. In other 6022 ** words we assume that very common tokens occur exactly once in each 6023 ** column of each row of the table. 6024 ** 6025 ** * If a phrase contains some deferred tokens (and some non-deferred 6026 ** tokens), count the potential occurrence identified by considering 6027 ** the non-deferred tokens instead of actual phrase occurrences. 6028 ** 6029 ** * If the phrase is part of a NEAR expression, then only phrase instances 6030 ** that meet the NEAR constraint are included in the counts. 6031 */ 6032 int sqlite3Fts3EvalPhraseStats( 6033 Fts3Cursor *pCsr, /* FTS cursor handle */ 6034 Fts3Expr *pExpr, /* Phrase expression */ 6035 u32 *aiOut /* Array to write results into (see above) */ 6036 ){ 6037 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; 6038 int rc = SQLITE_OK; 6039 int iCol; 6040 6041 if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){ 6042 assert( pCsr->nDoc>0 ); 6043 for(iCol=0; iColnColumn; iCol++){ 6044 aiOut[iCol*3 + 1] = (u32)pCsr->nDoc; 6045 aiOut[iCol*3 + 2] = (u32)pCsr->nDoc; 6046 } 6047 }else{ 6048 rc = fts3EvalGatherStats(pCsr, pExpr); 6049 if( rc==SQLITE_OK ){ 6050 assert( pExpr->aMI ); 6051 for(iCol=0; iColnColumn; iCol++){ 6052 aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1]; 6053 aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2]; 6054 } 6055 } 6056 } 6057 6058 return rc; 6059 } 6060 6061 /* 6062 ** The expression pExpr passed as the second argument to this function 6063 ** must be of type FTSQUERY_PHRASE. 6064 ** 6065 ** The returned value is either NULL or a pointer to a buffer containing 6066 ** a position-list indicating the occurrences of the phrase in column iCol 6067 ** of the current row. 6068 ** 6069 ** More specifically, the returned buffer contains 1 varint for each 6070 ** occurrence of the phrase in the column, stored using the normal (delta+2) 6071 ** compression and is terminated by either an 0x01 or 0x00 byte. For example, 6072 ** if the requested column contains "a b X c d X X" and the position-list 6073 ** for 'X' is requested, the buffer returned may contain: 6074 ** 6075 ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00 6076 ** 6077 ** This function works regardless of whether or not the phrase is deferred, 6078 ** incremental, or neither. 6079 */ 6080 int sqlite3Fts3EvalPhrasePoslist( 6081 Fts3Cursor *pCsr, /* FTS3 cursor object */ 6082 Fts3Expr *pExpr, /* Phrase to return doclist for */ 6083 int iCol, /* Column to return position list for */ 6084 char **ppOut /* OUT: Pointer to position list */ 6085 ){ 6086 Fts3Phrase *pPhrase = pExpr->pPhrase; 6087 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; 6088 char *pIter; 6089 int iThis; 6090 sqlite3_int64 iDocid; 6091 6092 /* If this phrase is applies specifically to some column other than 6093 ** column iCol, return a NULL pointer. */ 6094 *ppOut = 0; 6095 assert( iCol>=0 && iColnColumn ); 6096 if( (pPhrase->iColumnnColumn && pPhrase->iColumn!=iCol) ){ 6097 return SQLITE_OK; 6098 } 6099 6100 iDocid = pExpr->iDocid; 6101 pIter = pPhrase->doclist.pList; 6102 if( iDocid!=pCsr->iPrevId || pExpr->bEof ){ 6103 int rc = SQLITE_OK; 6104 int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */ 6105 int bOr = 0; 6106 u8 bTreeEof = 0; 6107 Fts3Expr *p; /* Used to iterate from pExpr to root */ 6108 Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */ 6109 Fts3Expr *pRun; /* Closest non-deferred ancestor of pNear */ 6110 int bMatch; 6111 6112 /* Check if this phrase descends from an OR expression node. If not, 6113 ** return NULL. Otherwise, the entry that corresponds to docid 6114 ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the 6115 ** tree that the node is part of has been marked as EOF, but the node 6116 ** itself is not EOF, then it may point to an earlier entry. */ 6117 pNear = pExpr; 6118 for(p=pExpr->pParent; p; p=p->pParent){ 6119 if( p->eType==FTSQUERY_OR ) bOr = 1; 6120 if( p->eType==FTSQUERY_NEAR ) pNear = p; 6121 if( p->bEof ) bTreeEof = 1; 6122 } 6123 if( bOr==0 ) return SQLITE_OK; 6124 pRun = pNear; 6125 while( pRun->bDeferred ){ 6126 assert( pRun->pParent ); 6127 pRun = pRun->pParent; 6128 } 6129 6130 /* This is the descendent of an OR node. In this case we cannot use 6131 ** an incremental phrase. Load the entire doclist for the phrase 6132 ** into memory in this case. */ 6133 if( pPhrase->bIncr ){ 6134 int bEofSave = pRun->bEof; 6135 fts3EvalRestart(pCsr, pRun, &rc); 6136 while( rc==SQLITE_OK && !pRun->bEof ){ 6137 fts3EvalNextRow(pCsr, pRun, &rc); 6138 if( bEofSave==0 && pRun->iDocid==iDocid ) break; 6139 } 6140 assert( rc!=SQLITE_OK || pPhrase->bIncr==0 ); 6141 if( rc==SQLITE_OK && pRun->bEof!=bEofSave ){ 6142 rc = FTS_CORRUPT_VTAB; 6143 } 6144 } 6145 if( bTreeEof ){ 6146 while( rc==SQLITE_OK && !pRun->bEof ){ 6147 fts3EvalNextRow(pCsr, pRun, &rc); 6148 } 6149 } 6150 if( rc!=SQLITE_OK ) return rc; 6151 6152 bMatch = 1; 6153 for(p=pNear; p; p=p->pLeft){ 6154 u8 bEof = 0; 6155 Fts3Expr *pTest = p; 6156 Fts3Phrase *pPh; 6157 assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE ); 6158 if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight; 6159 assert( pTest->eType==FTSQUERY_PHRASE ); 6160 pPh = pTest->pPhrase; 6161 6162 pIter = pPh->pOrPoslist; 6163 iDocid = pPh->iOrDocid; 6164 if( pCsr->bDesc==bDescDoclist ){ 6165 bEof = !pPh->doclist.nAll || 6166 (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll)); 6167 while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){ 6168 sqlite3Fts3DoclistNext( 6169 bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, 6170 &pIter, &iDocid, &bEof 6171 ); 6172 } 6173 }else{ 6174 bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll); 6175 while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){ 6176 int dummy; 6177 sqlite3Fts3DoclistPrev( 6178 bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, 6179 &pIter, &iDocid, &dummy, &bEof 6180 ); 6181 } 6182 } 6183 pPh->pOrPoslist = pIter; 6184 pPh->iOrDocid = iDocid; 6185 if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0; 6186 } 6187 6188 if( bMatch ){ 6189 pIter = pPhrase->pOrPoslist; 6190 }else{ 6191 pIter = 0; 6192 } 6193 } 6194 if( pIter==0 ) return SQLITE_OK; 6195 6196 if( *pIter==0x01 ){ 6197 pIter++; 6198 pIter += fts3GetVarint32(pIter, &iThis); 6199 }else{ 6200 iThis = 0; 6201 } 6202 while( iThisdoclist, and 6221 ** * any Fts3MultiSegReader objects held by phrase tokens. 6222 */ 6223 void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){ 6224 if( pPhrase ){ 6225 int i; 6226 sqlite3_free(pPhrase->doclist.aAll); 6227 fts3EvalInvalidatePoslist(pPhrase); 6228 memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist)); 6229 for(i=0; inToken; i++){ 6230 fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr); 6231 pPhrase->aToken[i].pSegcsr = 0; 6232 } 6233 } 6234 } 6235 6236 6237 /* 6238 ** Return SQLITE_CORRUPT_VTAB. 6239 */ 6240 #ifdef SQLITE_DEBUG 6241 int sqlite3Fts3Corrupt(){ 6242 return SQLITE_CORRUPT_VTAB; 6243 } 6244 #endif 6245 6246 #if !defined(SQLITE_CORE) 6247 /* 6248 ** Initialize API pointer table, if required. 6249 */ 6250 #ifdef _WIN32 6251 __declspec(dllexport) 6252 #endif 6253 int sqlite3_fts3_init( 6254 sqlite3 *db, 6255 char **pzErrMsg, 6256 const sqlite3_api_routines *pApi 6257 ){ 6258 SQLITE_EXTENSION_INIT2(pApi) 6259 return sqlite3Fts3Init(db); 6260 } 6261 #endif 6262 6263 #endif