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