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; |
| 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 next docid. It has one position 72 (72-2) and then |
| 105 ** 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 ** TODO(shess) Provide a VACUUM type operation to clear out all |
| 291 ** deletions and duplications. This would basically be a forced merge |
| 292 ** into a single segment. |
| 293 */ |
| 294 |
| 295 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) |
| 296 |
| 297 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE) |
| 298 # define SQLITE_CORE 1 |
| 299 #endif |
| 300 |
| 301 #include "fts3Int.h" |
| 302 |
| 303 #include <assert.h> |
| 304 #include <stdlib.h> |
| 305 #include <stddef.h> |
| 306 #include <stdio.h> |
| 307 #include <string.h> |
| 308 #include <stdarg.h> |
| 309 |
| 310 #include "fts3.h" |
| 311 #ifndef SQLITE_CORE |
| 312 # include "sqlite3ext.h" |
| 313 SQLITE_EXTENSION_INIT1 |
| 314 #endif |
| 315 |
| 316 /* |
| 317 ** Write a 64-bit variable-length integer to memory starting at p[0]. |
| 318 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes. |
| 319 ** The number of bytes written is returned. |
| 320 */ |
| 321 int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){ |
| 322 unsigned char *q = (unsigned char *) p; |
| 323 sqlite_uint64 vu = v; |
| 324 do{ |
| 325 *q++ = (unsigned char) ((vu & 0x7f) | 0x80); |
| 326 vu >>= 7; |
| 327 }while( vu!=0 ); |
| 328 q[-1] &= 0x7f; /* turn off high bit in final byte */ |
| 329 assert( q - (unsigned char *)p <= FTS3_VARINT_MAX ); |
| 330 return (int) (q - (unsigned char *)p); |
| 331 } |
| 332 |
| 333 /* |
| 334 ** Read a 64-bit variable-length integer from memory starting at p[0]. |
| 335 ** Return the number of bytes read, or 0 on error. |
| 336 ** The value is stored in *v. |
| 337 */ |
| 338 int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){ |
| 339 const unsigned char *q = (const unsigned char *) p; |
| 340 sqlite_uint64 x = 0, y = 1; |
| 341 while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){ |
| 342 x += y * (*q++ & 0x7f); |
| 343 y <<= 7; |
| 344 } |
| 345 x += y * (*q++); |
| 346 *v = (sqlite_int64) x; |
| 347 return (int) (q - (unsigned char *)p); |
| 348 } |
| 349 |
| 350 /* |
| 351 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a |
| 352 ** 32-bit integer before it is returned. |
| 353 */ |
| 354 int sqlite3Fts3GetVarint32(const char *p, int *pi){ |
| 355 sqlite_int64 i; |
| 356 int ret = sqlite3Fts3GetVarint(p, &i); |
| 357 *pi = (int) i; |
| 358 return ret; |
| 359 } |
| 360 |
| 361 /* |
| 362 ** Return the number of bytes required to encode v as a varint |
| 363 */ |
| 364 int sqlite3Fts3VarintLen(sqlite3_uint64 v){ |
| 365 int i = 0; |
| 366 do{ |
| 367 i++; |
| 368 v >>= 7; |
| 369 }while( v!=0 ); |
| 370 return i; |
| 371 } |
| 372 |
| 373 /* |
| 374 ** Convert an SQL-style quoted string into a normal string by removing |
| 375 ** the quote characters. The conversion is done in-place. If the |
| 376 ** input does not begin with a quote character, then this routine |
| 377 ** is a no-op. |
| 378 ** |
| 379 ** Examples: |
| 380 ** |
| 381 ** "abc" becomes abc |
| 382 ** 'xyz' becomes xyz |
| 383 ** [pqr] becomes pqr |
| 384 ** `mno` becomes mno |
| 385 ** |
| 386 */ |
| 387 void sqlite3Fts3Dequote(char *z){ |
| 388 char quote; /* Quote character (if any ) */ |
| 389 |
| 390 quote = z[0]; |
| 391 if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){ |
| 392 int iIn = 1; /* Index of next byte to read from input */ |
| 393 int iOut = 0; /* Index of next byte to write to output */ |
| 394 |
| 395 /* If the first byte was a '[', then the close-quote character is a ']' */ |
| 396 if( quote=='[' ) quote = ']'; |
| 397 |
| 398 while( ALWAYS(z[iIn]) ){ |
| 399 if( z[iIn]==quote ){ |
| 400 if( z[iIn+1]!=quote ) break; |
| 401 z[iOut++] = quote; |
| 402 iIn += 2; |
| 403 }else{ |
| 404 z[iOut++] = z[iIn++]; |
| 405 } |
| 406 } |
| 407 z[iOut] = '\0'; |
| 408 } |
| 409 } |
| 410 |
| 411 /* |
| 412 ** Read a single varint from the doclist at *pp and advance *pp to point |
| 413 ** to the first byte past the end of the varint. Add the value of the varint |
| 414 ** to *pVal. |
| 415 */ |
| 416 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){ |
| 417 sqlite3_int64 iVal; |
| 418 *pp += sqlite3Fts3GetVarint(*pp, &iVal); |
| 419 *pVal += iVal; |
| 420 } |
| 421 |
| 422 /* |
| 423 ** As long as *pp has not reached its end (pEnd), then do the same |
| 424 ** as fts3GetDeltaVarint(): read a single varint and add it to *pVal. |
| 425 ** But if we have reached the end of the varint, just set *pp=0 and |
| 426 ** leave *pVal unchanged. |
| 427 */ |
| 428 static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){ |
| 429 if( *pp>=pEnd ){ |
| 430 *pp = 0; |
| 431 }else{ |
| 432 fts3GetDeltaVarint(pp, pVal); |
| 433 } |
| 434 } |
| 435 |
| 436 /* |
| 437 ** The xDisconnect() virtual table method. |
| 438 */ |
| 439 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){ |
| 440 Fts3Table *p = (Fts3Table *)pVtab; |
| 441 int i; |
| 442 |
| 443 assert( p->nPendingData==0 ); |
| 444 assert( p->pSegments==0 ); |
| 445 |
| 446 /* Free any prepared statements held */ |
| 447 for(i=0; i<SizeofArray(p->aStmt); i++){ |
| 448 sqlite3_finalize(p->aStmt[i]); |
| 449 } |
| 450 sqlite3_free(p->zSegmentsTbl); |
| 451 sqlite3_free(p->zReadExprlist); |
| 452 sqlite3_free(p->zWriteExprlist); |
| 453 |
| 454 /* Invoke the tokenizer destructor to free the tokenizer. */ |
| 455 p->pTokenizer->pModule->xDestroy(p->pTokenizer); |
| 456 |
| 457 sqlite3_free(p); |
| 458 return SQLITE_OK; |
| 459 } |
| 460 |
| 461 /* |
| 462 ** Construct one or more SQL statements from the format string given |
| 463 ** and then evaluate those statements. The success code is written |
| 464 ** into *pRc. |
| 465 ** |
| 466 ** If *pRc is initially non-zero then this routine is a no-op. |
| 467 */ |
| 468 static void fts3DbExec( |
| 469 int *pRc, /* Success code */ |
| 470 sqlite3 *db, /* Database in which to run SQL */ |
| 471 const char *zFormat, /* Format string for SQL */ |
| 472 ... /* Arguments to the format string */ |
| 473 ){ |
| 474 va_list ap; |
| 475 char *zSql; |
| 476 if( *pRc ) return; |
| 477 va_start(ap, zFormat); |
| 478 zSql = sqlite3_vmprintf(zFormat, ap); |
| 479 va_end(ap); |
| 480 if( zSql==0 ){ |
| 481 *pRc = SQLITE_NOMEM; |
| 482 }else{ |
| 483 *pRc = sqlite3_exec(db, zSql, 0, 0, 0); |
| 484 sqlite3_free(zSql); |
| 485 } |
| 486 } |
| 487 |
| 488 /* |
| 489 ** The xDestroy() virtual table method. |
| 490 */ |
| 491 static int fts3DestroyMethod(sqlite3_vtab *pVtab){ |
| 492 int rc = SQLITE_OK; /* Return code */ |
| 493 Fts3Table *p = (Fts3Table *)pVtab; |
| 494 sqlite3 *db = p->db; |
| 495 |
| 496 /* Drop the shadow tables */ |
| 497 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName); |
| 498 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName); |
| 499 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName); |
| 500 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName); |
| 501 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName); |
| 502 |
| 503 /* If everything has worked, invoke fts3DisconnectMethod() to free the |
| 504 ** memory associated with the Fts3Table structure and return SQLITE_OK. |
| 505 ** Otherwise, return an SQLite error code. |
| 506 */ |
| 507 return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc); |
| 508 } |
| 509 |
| 510 |
| 511 /* |
| 512 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table |
| 513 ** passed as the first argument. This is done as part of the xConnect() |
| 514 ** and xCreate() methods. |
| 515 ** |
| 516 ** If *pRc is non-zero when this function is called, it is a no-op. |
| 517 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc |
| 518 ** before returning. |
| 519 */ |
| 520 static void fts3DeclareVtab(int *pRc, Fts3Table *p){ |
| 521 if( *pRc==SQLITE_OK ){ |
| 522 int i; /* Iterator variable */ |
| 523 int rc; /* Return code */ |
| 524 char *zSql; /* SQL statement passed to declare_vtab() */ |
| 525 char *zCols; /* List of user defined columns */ |
| 526 |
| 527 /* Create a list of user columns for the virtual table */ |
| 528 zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]); |
| 529 for(i=1; zCols && i<p->nColumn; i++){ |
| 530 zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]); |
| 531 } |
| 532 |
| 533 /* Create the whole "CREATE TABLE" statement to pass to SQLite */ |
| 534 zSql = sqlite3_mprintf( |
| 535 "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName |
| 536 ); |
| 537 if( !zCols || !zSql ){ |
| 538 rc = SQLITE_NOMEM; |
| 539 }else{ |
| 540 rc = sqlite3_declare_vtab(p->db, zSql); |
| 541 } |
| 542 |
| 543 sqlite3_free(zSql); |
| 544 sqlite3_free(zCols); |
| 545 *pRc = rc; |
| 546 } |
| 547 } |
| 548 |
| 549 /* |
| 550 ** Create the backing store tables (%_content, %_segments and %_segdir) |
| 551 ** required by the FTS3 table passed as the only argument. This is done |
| 552 ** as part of the vtab xCreate() method. |
| 553 ** |
| 554 ** If the p->bHasDocsize boolean is true (indicating that this is an |
| 555 ** FTS4 table, not an FTS3 table) then also create the %_docsize and |
| 556 ** %_stat tables required by FTS4. |
| 557 */ |
| 558 static int fts3CreateTables(Fts3Table *p){ |
| 559 int rc = SQLITE_OK; /* Return code */ |
| 560 int i; /* Iterator variable */ |
| 561 char *zContentCols; /* Columns of %_content table */ |
| 562 sqlite3 *db = p->db; /* The database connection */ |
| 563 |
| 564 /* Create a list of user columns for the content table */ |
| 565 zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY"); |
| 566 for(i=0; zContentCols && i<p->nColumn; i++){ |
| 567 char *z = p->azColumn[i]; |
| 568 zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z); |
| 569 } |
| 570 if( zContentCols==0 ) rc = SQLITE_NOMEM; |
| 571 |
| 572 /* Create the content table */ |
| 573 fts3DbExec(&rc, db, |
| 574 "CREATE TABLE %Q.'%q_content'(%s)", |
| 575 p->zDb, p->zName, zContentCols |
| 576 ); |
| 577 sqlite3_free(zContentCols); |
| 578 /* Create other tables */ |
| 579 fts3DbExec(&rc, db, |
| 580 "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);", |
| 581 p->zDb, p->zName |
| 582 ); |
| 583 fts3DbExec(&rc, db, |
| 584 "CREATE TABLE %Q.'%q_segdir'(" |
| 585 "level INTEGER," |
| 586 "idx INTEGER," |
| 587 "start_block INTEGER," |
| 588 "leaves_end_block INTEGER," |
| 589 "end_block INTEGER," |
| 590 "root BLOB," |
| 591 "PRIMARY KEY(level, idx)" |
| 592 ");", |
| 593 p->zDb, p->zName |
| 594 ); |
| 595 if( p->bHasDocsize ){ |
| 596 fts3DbExec(&rc, db, |
| 597 "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);", |
| 598 p->zDb, p->zName |
| 599 ); |
| 600 } |
| 601 if( p->bHasStat ){ |
| 602 fts3DbExec(&rc, db, |
| 603 "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);", |
| 604 p->zDb, p->zName |
| 605 ); |
| 606 } |
| 607 return rc; |
| 608 } |
| 609 |
| 610 /* |
| 611 ** Store the current database page-size in bytes in p->nPgsz. |
| 612 ** |
| 613 ** If *pRc is non-zero when this function is called, it is a no-op. |
| 614 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc |
| 615 ** before returning. |
| 616 */ |
| 617 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){ |
| 618 if( *pRc==SQLITE_OK ){ |
| 619 int rc; /* Return code */ |
| 620 char *zSql; /* SQL text "PRAGMA %Q.page_size" */ |
| 621 sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */ |
| 622 |
| 623 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb); |
| 624 if( !zSql ){ |
| 625 rc = SQLITE_NOMEM; |
| 626 }else{ |
| 627 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); |
| 628 if( rc==SQLITE_OK ){ |
| 629 sqlite3_step(pStmt); |
| 630 p->nPgsz = sqlite3_column_int(pStmt, 0); |
| 631 rc = sqlite3_finalize(pStmt); |
| 632 } |
| 633 } |
| 634 assert( p->nPgsz>0 || rc!=SQLITE_OK ); |
| 635 sqlite3_free(zSql); |
| 636 *pRc = rc; |
| 637 } |
| 638 } |
| 639 |
| 640 /* |
| 641 ** "Special" FTS4 arguments are column specifications of the following form: |
| 642 ** |
| 643 ** <key> = <value> |
| 644 ** |
| 645 ** There may not be whitespace surrounding the "=" character. The <value> |
| 646 ** term may be quoted, but the <key> may not. |
| 647 */ |
| 648 static int fts3IsSpecialColumn( |
| 649 const char *z, |
| 650 int *pnKey, |
| 651 char **pzValue |
| 652 ){ |
| 653 char *zValue; |
| 654 const char *zCsr = z; |
| 655 |
| 656 while( *zCsr!='=' ){ |
| 657 if( *zCsr=='\0' ) return 0; |
| 658 zCsr++; |
| 659 } |
| 660 |
| 661 *pnKey = (int)(zCsr-z); |
| 662 zValue = sqlite3_mprintf("%s", &zCsr[1]); |
| 663 if( zValue ){ |
| 664 sqlite3Fts3Dequote(zValue); |
| 665 } |
| 666 *pzValue = zValue; |
| 667 return 1; |
| 668 } |
| 669 |
| 670 /* |
| 671 ** Append the output of a printf() style formatting to an existing string. |
| 672 */ |
| 673 static void fts3Appendf( |
| 674 int *pRc, /* IN/OUT: Error code */ |
| 675 char **pz, /* IN/OUT: Pointer to string buffer */ |
| 676 const char *zFormat, /* Printf format string to append */ |
| 677 ... /* Arguments for printf format string */ |
| 678 ){ |
| 679 if( *pRc==SQLITE_OK ){ |
| 680 va_list ap; |
| 681 char *z; |
| 682 va_start(ap, zFormat); |
| 683 z = sqlite3_vmprintf(zFormat, ap); |
| 684 if( z && *pz ){ |
| 685 char *z2 = sqlite3_mprintf("%s%s", *pz, z); |
| 686 sqlite3_free(z); |
| 687 z = z2; |
| 688 } |
| 689 if( z==0 ) *pRc = SQLITE_NOMEM; |
| 690 sqlite3_free(*pz); |
| 691 *pz = z; |
| 692 } |
| 693 } |
| 694 |
| 695 /* |
| 696 ** Return a copy of input string zInput enclosed in double-quotes (") and |
| 697 ** with all double quote characters escaped. For example: |
| 698 ** |
| 699 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\"" |
| 700 ** |
| 701 ** The pointer returned points to memory obtained from sqlite3_malloc(). It |
| 702 ** is the callers responsibility to call sqlite3_free() to release this |
| 703 ** memory. |
| 704 */ |
| 705 static char *fts3QuoteId(char const *zInput){ |
| 706 int nRet; |
| 707 char *zRet; |
| 708 nRet = 2 + strlen(zInput)*2 + 1; |
| 709 zRet = sqlite3_malloc(nRet); |
| 710 if( zRet ){ |
| 711 int i; |
| 712 char *z = zRet; |
| 713 *(z++) = '"'; |
| 714 for(i=0; zInput[i]; i++){ |
| 715 if( zInput[i]=='"' ) *(z++) = '"'; |
| 716 *(z++) = zInput[i]; |
| 717 } |
| 718 *(z++) = '"'; |
| 719 *(z++) = '\0'; |
| 720 } |
| 721 return zRet; |
| 722 } |
| 723 |
| 724 /* |
| 725 ** Return a list of comma separated SQL expressions that could be used |
| 726 ** in a SELECT statement such as the following: |
| 727 ** |
| 728 ** SELECT <list of expressions> FROM %_content AS x ... |
| 729 ** |
| 730 ** to return the docid, followed by each column of text data in order |
| 731 ** from left to write. If parameter zFunc is not NULL, then instead of |
| 732 ** being returned directly each column of text data is passed to an SQL |
| 733 ** function named zFunc first. For example, if zFunc is "unzip" and the |
| 734 ** table has the three user-defined columns "a", "b", and "c", the following |
| 735 ** string is returned: |
| 736 ** |
| 737 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c')" |
| 738 ** |
| 739 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It |
| 740 ** is the responsibility of the caller to eventually free it. |
| 741 ** |
| 742 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and |
| 743 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered |
| 744 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If |
| 745 ** no error occurs, *pRc is left unmodified. |
| 746 */ |
| 747 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){ |
| 748 char *zRet = 0; |
| 749 char *zFree = 0; |
| 750 char *zFunction; |
| 751 int i; |
| 752 |
| 753 if( !zFunc ){ |
| 754 zFunction = ""; |
| 755 }else{ |
| 756 zFree = zFunction = fts3QuoteId(zFunc); |
| 757 } |
| 758 fts3Appendf(pRc, &zRet, "docid"); |
| 759 for(i=0; i<p->nColumn; i++){ |
| 760 fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]); |
| 761 } |
| 762 sqlite3_free(zFree); |
| 763 return zRet; |
| 764 } |
| 765 |
| 766 /* |
| 767 ** Return a list of N comma separated question marks, where N is the number |
| 768 ** of columns in the %_content table (one for the docid plus one for each |
| 769 ** user-defined text column). |
| 770 ** |
| 771 ** If argument zFunc is not NULL, then all but the first question mark |
| 772 ** is preceded by zFunc and an open bracket, and followed by a closed |
| 773 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three |
| 774 ** user-defined text columns, the following string is returned: |
| 775 ** |
| 776 ** "?, zip(?), zip(?), zip(?)" |
| 777 ** |
| 778 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It |
| 779 ** is the responsibility of the caller to eventually free it. |
| 780 ** |
| 781 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and |
| 782 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered |
| 783 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If |
| 784 ** no error occurs, *pRc is left unmodified. |
| 785 */ |
| 786 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){ |
| 787 char *zRet = 0; |
| 788 char *zFree = 0; |
| 789 char *zFunction; |
| 790 int i; |
| 791 |
| 792 if( !zFunc ){ |
| 793 zFunction = ""; |
| 794 }else{ |
| 795 zFree = zFunction = fts3QuoteId(zFunc); |
| 796 } |
| 797 fts3Appendf(pRc, &zRet, "?"); |
| 798 for(i=0; i<p->nColumn; i++){ |
| 799 fts3Appendf(pRc, &zRet, ",%s(?)", zFunction); |
| 800 } |
| 801 sqlite3_free(zFree); |
| 802 return zRet; |
| 803 } |
| 804 |
| 805 /* |
| 806 ** This function is the implementation of both the xConnect and xCreate |
| 807 ** methods of the FTS3 virtual table. |
| 808 ** |
| 809 ** The argv[] array contains the following: |
| 810 ** |
| 811 ** argv[0] -> module name ("fts3" or "fts4") |
| 812 ** argv[1] -> database name |
| 813 ** argv[2] -> table name |
| 814 ** argv[...] -> "column name" and other module argument fields. |
| 815 */ |
| 816 static int fts3InitVtab( |
| 817 int isCreate, /* True for xCreate, false for xConnect */ |
| 818 sqlite3 *db, /* The SQLite database connection */ |
| 819 void *pAux, /* Hash table containing tokenizers */ |
| 820 int argc, /* Number of elements in argv array */ |
| 821 const char * const *argv, /* xCreate/xConnect argument array */ |
| 822 sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ |
| 823 char **pzErr /* Write any error message here */ |
| 824 ){ |
| 825 Fts3Hash *pHash = (Fts3Hash *)pAux; |
| 826 Fts3Table *p = 0; /* Pointer to allocated vtab */ |
| 827 int rc = SQLITE_OK; /* Return code */ |
| 828 int i; /* Iterator variable */ |
| 829 int nByte; /* Size of allocation used for *p */ |
| 830 int iCol; /* Column index */ |
| 831 int nString = 0; /* Bytes required to hold all column names */ |
| 832 int nCol = 0; /* Number of columns in the FTS table */ |
| 833 char *zCsr; /* Space for holding column names */ |
| 834 int nDb; /* Bytes required to hold database name */ |
| 835 int nName; /* Bytes required to hold table name */ |
| 836 int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */ |
| 837 int bNoDocsize = 0; /* True to omit %_docsize table */ |
| 838 const char **aCol; /* Array of column names */ |
| 839 sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */ |
| 840 |
| 841 char *zCompress = 0; |
| 842 char *zUncompress = 0; |
| 843 |
| 844 assert( strlen(argv[0])==4 ); |
| 845 assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4) |
| 846 || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4) |
| 847 ); |
| 848 |
| 849 nDb = (int)strlen(argv[1]) + 1; |
| 850 nName = (int)strlen(argv[2]) + 1; |
| 851 |
| 852 aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) ); |
| 853 if( !aCol ) return SQLITE_NOMEM; |
| 854 memset((void *)aCol, 0, sizeof(const char *) * (argc-2)); |
| 855 |
| 856 /* Loop through all of the arguments passed by the user to the FTS3/4 |
| 857 ** module (i.e. all the column names and special arguments). This loop |
| 858 ** does the following: |
| 859 ** |
| 860 ** + Figures out the number of columns the FTSX table will have, and |
| 861 ** the number of bytes of space that must be allocated to store copies |
| 862 ** of the column names. |
| 863 ** |
| 864 ** + If there is a tokenizer specification included in the arguments, |
| 865 ** initializes the tokenizer pTokenizer. |
| 866 */ |
| 867 for(i=3; rc==SQLITE_OK && i<argc; i++){ |
| 868 char const *z = argv[i]; |
| 869 int nKey; |
| 870 char *zVal; |
| 871 |
| 872 /* Check if this is a tokenizer specification */ |
| 873 if( !pTokenizer |
| 874 && strlen(z)>8 |
| 875 && 0==sqlite3_strnicmp(z, "tokenize", 8) |
| 876 && 0==sqlite3Fts3IsIdChar(z[8]) |
| 877 ){ |
| 878 rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr); |
| 879 } |
| 880 |
| 881 /* Check if it is an FTS4 special argument. */ |
| 882 else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){ |
| 883 if( !zVal ){ |
| 884 rc = SQLITE_NOMEM; |
| 885 goto fts3_init_out; |
| 886 } |
| 887 if( nKey==9 && 0==sqlite3_strnicmp(z, "matchinfo", 9) ){ |
| 888 if( strlen(zVal)==4 && 0==sqlite3_strnicmp(zVal, "fts3", 4) ){ |
| 889 bNoDocsize = 1; |
| 890 }else{ |
| 891 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal); |
| 892 rc = SQLITE_ERROR; |
| 893 } |
| 894 }else if( nKey==8 && 0==sqlite3_strnicmp(z, "compress", 8) ){ |
| 895 zCompress = zVal; |
| 896 zVal = 0; |
| 897 }else if( nKey==10 && 0==sqlite3_strnicmp(z, "uncompress", 10) ){ |
| 898 zUncompress = zVal; |
| 899 zVal = 0; |
| 900 }else{ |
| 901 *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z); |
| 902 rc = SQLITE_ERROR; |
| 903 } |
| 904 sqlite3_free(zVal); |
| 905 } |
| 906 |
| 907 /* Otherwise, the argument is a column name. */ |
| 908 else { |
| 909 nString += (int)(strlen(z) + 1); |
| 910 aCol[nCol++] = z; |
| 911 } |
| 912 } |
| 913 if( rc!=SQLITE_OK ) goto fts3_init_out; |
| 914 |
| 915 if( nCol==0 ){ |
| 916 assert( nString==0 ); |
| 917 aCol[0] = "content"; |
| 918 nString = 8; |
| 919 nCol = 1; |
| 920 } |
| 921 |
| 922 if( pTokenizer==0 ){ |
| 923 rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr); |
| 924 if( rc!=SQLITE_OK ) goto fts3_init_out; |
| 925 } |
| 926 assert( pTokenizer ); |
| 927 |
| 928 |
| 929 /* Allocate and populate the Fts3Table structure. */ |
| 930 nByte = sizeof(Fts3Table) + /* Fts3Table */ |
| 931 nCol * sizeof(char *) + /* azColumn */ |
| 932 nName + /* zName */ |
| 933 nDb + /* zDb */ |
| 934 nString; /* Space for azColumn strings */ |
| 935 p = (Fts3Table*)sqlite3_malloc(nByte); |
| 936 if( p==0 ){ |
| 937 rc = SQLITE_NOMEM; |
| 938 goto fts3_init_out; |
| 939 } |
| 940 memset(p, 0, nByte); |
| 941 p->db = db; |
| 942 p->nColumn = nCol; |
| 943 p->nPendingData = 0; |
| 944 p->azColumn = (char **)&p[1]; |
| 945 p->pTokenizer = pTokenizer; |
| 946 p->nNodeSize = 1000; |
| 947 p->nMaxPendingData = FTS3_MAX_PENDING_DATA; |
| 948 p->bHasDocsize = (isFts4 && bNoDocsize==0); |
| 949 p->bHasStat = isFts4; |
| 950 fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1); |
| 951 |
| 952 /* Fill in the zName and zDb fields of the vtab structure. */ |
| 953 zCsr = (char *)&p->azColumn[nCol]; |
| 954 p->zName = zCsr; |
| 955 memcpy(zCsr, argv[2], nName); |
| 956 zCsr += nName; |
| 957 p->zDb = zCsr; |
| 958 memcpy(zCsr, argv[1], nDb); |
| 959 zCsr += nDb; |
| 960 |
| 961 /* Fill in the azColumn array */ |
| 962 for(iCol=0; iCol<nCol; iCol++){ |
| 963 char *z; |
| 964 int n; |
| 965 z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n); |
| 966 memcpy(zCsr, z, n); |
| 967 zCsr[n] = '\0'; |
| 968 sqlite3Fts3Dequote(zCsr); |
| 969 p->azColumn[iCol] = zCsr; |
| 970 zCsr += n+1; |
| 971 assert( zCsr <= &((char *)p)[nByte] ); |
| 972 } |
| 973 |
| 974 if( (zCompress==0)!=(zUncompress==0) ){ |
| 975 char const *zMiss = (zCompress==0 ? "compress" : "uncompress"); |
| 976 rc = SQLITE_ERROR; |
| 977 *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss); |
| 978 } |
| 979 p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc); |
| 980 p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc); |
| 981 if( rc!=SQLITE_OK ) goto fts3_init_out; |
| 982 |
| 983 /* If this is an xCreate call, create the underlying tables in the |
| 984 ** database. TODO: For xConnect(), it could verify that said tables exist. |
| 985 */ |
| 986 if( isCreate ){ |
| 987 rc = fts3CreateTables(p); |
| 988 } |
| 989 |
| 990 /* Figure out the page-size for the database. This is required in order to |
| 991 ** estimate the cost of loading large doclists from the database (see |
| 992 ** function sqlite3Fts3SegReaderCost() for details). |
| 993 */ |
| 994 fts3DatabasePageSize(&rc, p); |
| 995 |
| 996 /* Declare the table schema to SQLite. */ |
| 997 fts3DeclareVtab(&rc, p); |
| 998 |
| 999 fts3_init_out: |
| 1000 sqlite3_free(zCompress); |
| 1001 sqlite3_free(zUncompress); |
| 1002 sqlite3_free((void *)aCol); |
| 1003 if( rc!=SQLITE_OK ){ |
| 1004 if( p ){ |
| 1005 fts3DisconnectMethod((sqlite3_vtab *)p); |
| 1006 }else if( pTokenizer ){ |
| 1007 pTokenizer->pModule->xDestroy(pTokenizer); |
| 1008 } |
| 1009 }else{ |
| 1010 *ppVTab = &p->base; |
| 1011 } |
| 1012 return rc; |
| 1013 } |
| 1014 |
| 1015 /* |
| 1016 ** The xConnect() and xCreate() methods for the virtual table. All the |
| 1017 ** work is done in function fts3InitVtab(). |
| 1018 */ |
| 1019 static int fts3ConnectMethod( |
| 1020 sqlite3 *db, /* Database connection */ |
| 1021 void *pAux, /* Pointer to tokenizer hash table */ |
| 1022 int argc, /* Number of elements in argv array */ |
| 1023 const char * const *argv, /* xCreate/xConnect argument array */ |
| 1024 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ |
| 1025 char **pzErr /* OUT: sqlite3_malloc'd error message */ |
| 1026 ){ |
| 1027 return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr); |
| 1028 } |
| 1029 static int fts3CreateMethod( |
| 1030 sqlite3 *db, /* Database connection */ |
| 1031 void *pAux, /* Pointer to tokenizer hash table */ |
| 1032 int argc, /* Number of elements in argv array */ |
| 1033 const char * const *argv, /* xCreate/xConnect argument array */ |
| 1034 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ |
| 1035 char **pzErr /* OUT: sqlite3_malloc'd error message */ |
| 1036 ){ |
| 1037 return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr); |
| 1038 } |
| 1039 |
| 1040 /* |
| 1041 ** Implementation of the xBestIndex method for FTS3 tables. There |
| 1042 ** are three possible strategies, in order of preference: |
| 1043 ** |
| 1044 ** 1. Direct lookup by rowid or docid. |
| 1045 ** 2. Full-text search using a MATCH operator on a non-docid column. |
| 1046 ** 3. Linear scan of %_content table. |
| 1047 */ |
| 1048 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ |
| 1049 Fts3Table *p = (Fts3Table *)pVTab; |
| 1050 int i; /* Iterator variable */ |
| 1051 int iCons = -1; /* Index of constraint to use */ |
| 1052 |
| 1053 /* By default use a full table scan. This is an expensive option, |
| 1054 ** so search through the constraints to see if a more efficient |
| 1055 ** strategy is possible. |
| 1056 */ |
| 1057 pInfo->idxNum = FTS3_FULLSCAN_SEARCH; |
| 1058 pInfo->estimatedCost = 500000; |
| 1059 for(i=0; i<pInfo->nConstraint; i++){ |
| 1060 struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i]; |
| 1061 if( pCons->usable==0 ) continue; |
| 1062 |
| 1063 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */ |
| 1064 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ |
| 1065 && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 ) |
| 1066 ){ |
| 1067 pInfo->idxNum = FTS3_DOCID_SEARCH; |
| 1068 pInfo->estimatedCost = 1.0; |
| 1069 iCons = i; |
| 1070 } |
| 1071 |
| 1072 /* A MATCH constraint. Use a full-text search. |
| 1073 ** |
| 1074 ** If there is more than one MATCH constraint available, use the first |
| 1075 ** one encountered. If there is both a MATCH constraint and a direct |
| 1076 ** rowid/docid lookup, prefer the MATCH strategy. This is done even |
| 1077 ** though the rowid/docid lookup is faster than a MATCH query, selecting |
| 1078 ** it would lead to an "unable to use function MATCH in the requested |
| 1079 ** context" error. |
| 1080 */ |
| 1081 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH |
| 1082 && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn |
| 1083 ){ |
| 1084 pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn; |
| 1085 pInfo->estimatedCost = 2.0; |
| 1086 iCons = i; |
| 1087 break; |
| 1088 } |
| 1089 } |
| 1090 |
| 1091 if( iCons>=0 ){ |
| 1092 pInfo->aConstraintUsage[iCons].argvIndex = 1; |
| 1093 pInfo->aConstraintUsage[iCons].omit = 1; |
| 1094 } |
| 1095 return SQLITE_OK; |
| 1096 } |
| 1097 |
| 1098 /* |
| 1099 ** Implementation of xOpen method. |
| 1100 */ |
| 1101 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ |
| 1102 sqlite3_vtab_cursor *pCsr; /* Allocated cursor */ |
| 1103 |
| 1104 UNUSED_PARAMETER(pVTab); |
| 1105 |
| 1106 /* Allocate a buffer large enough for an Fts3Cursor structure. If the |
| 1107 ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, |
| 1108 ** if the allocation fails, return SQLITE_NOMEM. |
| 1109 */ |
| 1110 *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor)); |
| 1111 if( !pCsr ){ |
| 1112 return SQLITE_NOMEM; |
| 1113 } |
| 1114 memset(pCsr, 0, sizeof(Fts3Cursor)); |
| 1115 return SQLITE_OK; |
| 1116 } |
| 1117 |
| 1118 /* |
| 1119 ** Close the cursor. For additional information see the documentation |
| 1120 ** on the xClose method of the virtual table interface. |
| 1121 */ |
| 1122 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){ |
| 1123 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; |
| 1124 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); |
| 1125 sqlite3_finalize(pCsr->pStmt); |
| 1126 sqlite3Fts3ExprFree(pCsr->pExpr); |
| 1127 sqlite3Fts3FreeDeferredTokens(pCsr); |
| 1128 sqlite3_free(pCsr->aDoclist); |
| 1129 sqlite3_free(pCsr->aMatchinfo); |
| 1130 sqlite3_free(pCsr); |
| 1131 return SQLITE_OK; |
| 1132 } |
| 1133 |
| 1134 /* |
| 1135 ** Position the pCsr->pStmt statement so that it is on the row |
| 1136 ** of the %_content table that contains the last match. Return |
| 1137 ** SQLITE_OK on success. |
| 1138 */ |
| 1139 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){ |
| 1140 if( pCsr->isRequireSeek ){ |
| 1141 pCsr->isRequireSeek = 0; |
| 1142 sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId); |
| 1143 if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){ |
| 1144 return SQLITE_OK; |
| 1145 }else{ |
| 1146 int rc = sqlite3_reset(pCsr->pStmt); |
| 1147 if( rc==SQLITE_OK ){ |
| 1148 /* If no row was found and no error has occured, then the %_content |
| 1149 ** table is missing a row that is present in the full-text index. |
| 1150 ** The data structures are corrupt. |
| 1151 */ |
| 1152 rc = SQLITE_CORRUPT; |
| 1153 } |
| 1154 pCsr->isEof = 1; |
| 1155 if( pContext ){ |
| 1156 sqlite3_result_error_code(pContext, rc); |
| 1157 } |
| 1158 return rc; |
| 1159 } |
| 1160 }else{ |
| 1161 return SQLITE_OK; |
| 1162 } |
| 1163 } |
| 1164 |
| 1165 /* |
| 1166 ** This function is used to process a single interior node when searching |
| 1167 ** a b-tree for a term or term prefix. The node data is passed to this |
| 1168 ** function via the zNode/nNode parameters. The term to search for is |
| 1169 ** passed in zTerm/nTerm. |
| 1170 ** |
| 1171 ** If piFirst is not NULL, then this function sets *piFirst to the blockid |
| 1172 ** of the child node that heads the sub-tree that may contain the term. |
| 1173 ** |
| 1174 ** If piLast is not NULL, then *piLast is set to the right-most child node |
| 1175 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is |
| 1176 ** a prefix. |
| 1177 ** |
| 1178 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK. |
| 1179 */ |
| 1180 static int fts3ScanInteriorNode( |
| 1181 const char *zTerm, /* Term to select leaves for */ |
| 1182 int nTerm, /* Size of term zTerm in bytes */ |
| 1183 const char *zNode, /* Buffer containing segment interior node */ |
| 1184 int nNode, /* Size of buffer at zNode */ |
| 1185 sqlite3_int64 *piFirst, /* OUT: Selected child node */ |
| 1186 sqlite3_int64 *piLast /* OUT: Selected child node */ |
| 1187 ){ |
| 1188 int rc = SQLITE_OK; /* Return code */ |
| 1189 const char *zCsr = zNode; /* Cursor to iterate through node */ |
| 1190 const char *zEnd = &zCsr[nNode];/* End of interior node buffer */ |
| 1191 char *zBuffer = 0; /* Buffer to load terms into */ |
| 1192 int nAlloc = 0; /* Size of allocated buffer */ |
| 1193 int isFirstTerm = 1; /* True when processing first term on page */ |
| 1194 sqlite3_int64 iChild; /* Block id of child node to descend to */ |
| 1195 |
| 1196 /* Skip over the 'height' varint that occurs at the start of every |
| 1197 ** interior node. Then load the blockid of the left-child of the b-tree |
| 1198 ** node into variable iChild. |
| 1199 ** |
| 1200 ** Even if the data structure on disk is corrupted, this (reading two |
| 1201 ** varints from the buffer) does not risk an overread. If zNode is a |
| 1202 ** root node, then the buffer comes from a SELECT statement. SQLite does |
| 1203 ** not make this guarantee explicitly, but in practice there are always |
| 1204 ** either more than 20 bytes of allocated space following the nNode bytes of |
| 1205 ** contents, or two zero bytes. Or, if the node is read from the %_segments |
| 1206 ** table, then there are always 20 bytes of zeroed padding following the |
| 1207 ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details). |
| 1208 */ |
| 1209 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild); |
| 1210 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild); |
| 1211 if( zCsr>zEnd ){ |
| 1212 return SQLITE_CORRUPT; |
| 1213 } |
| 1214 |
| 1215 while( zCsr<zEnd && (piFirst || piLast) ){ |
| 1216 int cmp; /* memcmp() result */ |
| 1217 int nSuffix; /* Size of term suffix */ |
| 1218 int nPrefix = 0; /* Size of term prefix */ |
| 1219 int nBuffer; /* Total term size */ |
| 1220 |
| 1221 /* Load the next term on the node into zBuffer. Use realloc() to expand |
| 1222 ** the size of zBuffer if required. */ |
| 1223 if( !isFirstTerm ){ |
| 1224 zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix); |
| 1225 } |
| 1226 isFirstTerm = 0; |
| 1227 zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix); |
| 1228 |
| 1229 if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){ |
| 1230 rc = SQLITE_CORRUPT; |
| 1231 goto finish_scan; |
| 1232 } |
| 1233 if( nPrefix+nSuffix>nAlloc ){ |
| 1234 char *zNew; |
| 1235 nAlloc = (nPrefix+nSuffix) * 2; |
| 1236 zNew = (char *)sqlite3_realloc(zBuffer, nAlloc); |
| 1237 if( !zNew ){ |
| 1238 rc = SQLITE_NOMEM; |
| 1239 goto finish_scan; |
| 1240 } |
| 1241 zBuffer = zNew; |
| 1242 } |
| 1243 memcpy(&zBuffer[nPrefix], zCsr, nSuffix); |
| 1244 nBuffer = nPrefix + nSuffix; |
| 1245 zCsr += nSuffix; |
| 1246 |
| 1247 /* Compare the term we are searching for with the term just loaded from |
| 1248 ** the interior node. If the specified term is greater than or equal |
| 1249 ** to the term from the interior node, then all terms on the sub-tree |
| 1250 ** headed by node iChild are smaller than zTerm. No need to search |
| 1251 ** iChild. |
| 1252 ** |
| 1253 ** If the interior node term is larger than the specified term, then |
| 1254 ** the tree headed by iChild may contain the specified term. |
| 1255 */ |
| 1256 cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer)); |
| 1257 if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){ |
| 1258 *piFirst = iChild; |
| 1259 piFirst = 0; |
| 1260 } |
| 1261 |
| 1262 if( piLast && cmp<0 ){ |
| 1263 *piLast = iChild; |
| 1264 piLast = 0; |
| 1265 } |
| 1266 |
| 1267 iChild++; |
| 1268 }; |
| 1269 |
| 1270 if( piFirst ) *piFirst = iChild; |
| 1271 if( piLast ) *piLast = iChild; |
| 1272 |
| 1273 finish_scan: |
| 1274 sqlite3_free(zBuffer); |
| 1275 return rc; |
| 1276 } |
| 1277 |
| 1278 |
| 1279 /* |
| 1280 ** The buffer pointed to by argument zNode (size nNode bytes) contains an |
| 1281 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes) |
| 1282 ** contains a term. This function searches the sub-tree headed by the zNode |
| 1283 ** node for the range of leaf nodes that may contain the specified term |
| 1284 ** or terms for which the specified term is a prefix. |
| 1285 ** |
| 1286 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the |
| 1287 ** left-most leaf node in the tree that may contain the specified term. |
| 1288 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the |
| 1289 ** right-most leaf node that may contain a term for which the specified |
| 1290 ** term is a prefix. |
| 1291 ** |
| 1292 ** It is possible that the range of returned leaf nodes does not contain |
| 1293 ** the specified term or any terms for which it is a prefix. However, if the |
| 1294 ** segment does contain any such terms, they are stored within the identified |
| 1295 ** range. Because this function only inspects interior segment nodes (and |
| 1296 ** never loads leaf nodes into memory), it is not possible to be sure. |
| 1297 ** |
| 1298 ** If an error occurs, an error code other than SQLITE_OK is returned. |
| 1299 */ |
| 1300 static int fts3SelectLeaf( |
| 1301 Fts3Table *p, /* Virtual table handle */ |
| 1302 const char *zTerm, /* Term to select leaves for */ |
| 1303 int nTerm, /* Size of term zTerm in bytes */ |
| 1304 const char *zNode, /* Buffer containing segment interior node */ |
| 1305 int nNode, /* Size of buffer at zNode */ |
| 1306 sqlite3_int64 *piLeaf, /* Selected leaf node */ |
| 1307 sqlite3_int64 *piLeaf2 /* Selected leaf node */ |
| 1308 ){ |
| 1309 int rc; /* Return code */ |
| 1310 int iHeight; /* Height of this node in tree */ |
| 1311 |
| 1312 assert( piLeaf || piLeaf2 ); |
| 1313 |
| 1314 sqlite3Fts3GetVarint32(zNode, &iHeight); |
| 1315 rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2); |
| 1316 assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) ); |
| 1317 |
| 1318 if( rc==SQLITE_OK && iHeight>1 ){ |
| 1319 char *zBlob = 0; /* Blob read from %_segments table */ |
| 1320 int nBlob; /* Size of zBlob in bytes */ |
| 1321 |
| 1322 if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){ |
| 1323 rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob); |
| 1324 if( rc==SQLITE_OK ){ |
| 1325 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0); |
| 1326 } |
| 1327 sqlite3_free(zBlob); |
| 1328 piLeaf = 0; |
| 1329 zBlob = 0; |
| 1330 } |
| 1331 |
| 1332 if( rc==SQLITE_OK ){ |
| 1333 rc = sqlite3Fts3ReadBlock(p, piLeaf ? *piLeaf : *piLeaf2, &zBlob, &nBlob); |
| 1334 } |
| 1335 if( rc==SQLITE_OK ){ |
| 1336 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2); |
| 1337 } |
| 1338 sqlite3_free(zBlob); |
| 1339 } |
| 1340 |
| 1341 return rc; |
| 1342 } |
| 1343 |
| 1344 /* |
| 1345 ** This function is used to create delta-encoded serialized lists of FTS3 |
| 1346 ** varints. Each call to this function appends a single varint to a list. |
| 1347 */ |
| 1348 static void fts3PutDeltaVarint( |
| 1349 char **pp, /* IN/OUT: Output pointer */ |
| 1350 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ |
| 1351 sqlite3_int64 iVal /* Write this value to the list */ |
| 1352 ){ |
| 1353 assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) ); |
| 1354 *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev); |
| 1355 *piPrev = iVal; |
| 1356 } |
| 1357 |
| 1358 /* |
| 1359 ** When this function is called, *ppPoslist is assumed to point to the |
| 1360 ** start of a position-list. After it returns, *ppPoslist points to the |
| 1361 ** first byte after the position-list. |
| 1362 ** |
| 1363 ** A position list is list of positions (delta encoded) and columns for |
| 1364 ** a single document record of a doclist. So, in other words, this |
| 1365 ** routine advances *ppPoslist so that it points to the next docid in |
| 1366 ** the doclist, or to the first byte past the end of the doclist. |
| 1367 ** |
| 1368 ** If pp is not NULL, then the contents of the position list are copied |
| 1369 ** to *pp. *pp is set to point to the first byte past the last byte copied |
| 1370 ** before this function returns. |
| 1371 */ |
| 1372 static void fts3PoslistCopy(char **pp, char **ppPoslist){ |
| 1373 char *pEnd = *ppPoslist; |
| 1374 char c = 0; |
| 1375 |
| 1376 /* The end of a position list is marked by a zero encoded as an FTS3 |
| 1377 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by |
| 1378 ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail |
| 1379 ** of some other, multi-byte, value. |
| 1380 ** |
| 1381 ** The following while-loop moves pEnd to point to the first byte that is not |
| 1382 ** immediately preceded by a byte with the 0x80 bit set. Then increments |
| 1383 ** pEnd once more so that it points to the byte immediately following the |
| 1384 ** last byte in the position-list. |
| 1385 */ |
| 1386 while( *pEnd | c ){ |
| 1387 c = *pEnd++ & 0x80; |
| 1388 testcase( c!=0 && (*pEnd)==0 ); |
| 1389 } |
| 1390 pEnd++; /* Advance past the POS_END terminator byte */ |
| 1391 |
| 1392 if( pp ){ |
| 1393 int n = (int)(pEnd - *ppPoslist); |
| 1394 char *p = *pp; |
| 1395 memcpy(p, *ppPoslist, n); |
| 1396 p += n; |
| 1397 *pp = p; |
| 1398 } |
| 1399 *ppPoslist = pEnd; |
| 1400 } |
| 1401 |
| 1402 /* |
| 1403 ** When this function is called, *ppPoslist is assumed to point to the |
| 1404 ** start of a column-list. After it returns, *ppPoslist points to the |
| 1405 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list. |
| 1406 ** |
| 1407 ** A column-list is list of delta-encoded positions for a single column |
| 1408 ** within a single document within a doclist. |
| 1409 ** |
| 1410 ** The column-list is terminated either by a POS_COLUMN varint (1) or |
| 1411 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to |
| 1412 ** the POS_COLUMN or POS_END that terminates the column-list. |
| 1413 ** |
| 1414 ** If pp is not NULL, then the contents of the column-list are copied |
| 1415 ** to *pp. *pp is set to point to the first byte past the last byte copied |
| 1416 ** before this function returns. The POS_COLUMN or POS_END terminator |
| 1417 ** is not copied into *pp. |
| 1418 */ |
| 1419 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){ |
| 1420 char *pEnd = *ppPoslist; |
| 1421 char c = 0; |
| 1422 |
| 1423 /* A column-list is terminated by either a 0x01 or 0x00 byte that is |
| 1424 ** not part of a multi-byte varint. |
| 1425 */ |
| 1426 while( 0xFE & (*pEnd | c) ){ |
| 1427 c = *pEnd++ & 0x80; |
| 1428 testcase( c!=0 && ((*pEnd)&0xfe)==0 ); |
| 1429 } |
| 1430 if( pp ){ |
| 1431 int n = (int)(pEnd - *ppPoslist); |
| 1432 char *p = *pp; |
| 1433 memcpy(p, *ppPoslist, n); |
| 1434 p += n; |
| 1435 *pp = p; |
| 1436 } |
| 1437 *ppPoslist = pEnd; |
| 1438 } |
| 1439 |
| 1440 /* |
| 1441 ** Value used to signify the end of an position-list. This is safe because |
| 1442 ** it is not possible to have a document with 2^31 terms. |
| 1443 */ |
| 1444 #define POSITION_LIST_END 0x7fffffff |
| 1445 |
| 1446 /* |
| 1447 ** This function is used to help parse position-lists. When this function is |
| 1448 ** called, *pp may point to the start of the next varint in the position-list |
| 1449 ** being parsed, or it may point to 1 byte past the end of the position-list |
| 1450 ** (in which case **pp will be a terminator bytes POS_END (0) or |
| 1451 ** (1)). |
| 1452 ** |
| 1453 ** If *pp points past the end of the current position-list, set *pi to |
| 1454 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp, |
| 1455 ** increment the current value of *pi by the value read, and set *pp to |
| 1456 ** point to the next value before returning. |
| 1457 ** |
| 1458 ** Before calling this routine *pi must be initialized to the value of |
| 1459 ** the previous position, or zero if we are reading the first position |
| 1460 ** in the position-list. Because positions are delta-encoded, the value |
| 1461 ** of the previous position is needed in order to compute the value of |
| 1462 ** the next position. |
| 1463 */ |
| 1464 static void fts3ReadNextPos( |
| 1465 char **pp, /* IN/OUT: Pointer into position-list buffer */ |
| 1466 sqlite3_int64 *pi /* IN/OUT: Value read from position-list */ |
| 1467 ){ |
| 1468 if( (**pp)&0xFE ){ |
| 1469 fts3GetDeltaVarint(pp, pi); |
| 1470 *pi -= 2; |
| 1471 }else{ |
| 1472 *pi = POSITION_LIST_END; |
| 1473 } |
| 1474 } |
| 1475 |
| 1476 /* |
| 1477 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by |
| 1478 ** the value of iCol encoded as a varint to *pp. This will start a new |
| 1479 ** column list. |
| 1480 ** |
| 1481 ** Set *pp to point to the byte just after the last byte written before |
| 1482 ** returning (do not modify it if iCol==0). Return the total number of bytes |
| 1483 ** written (0 if iCol==0). |
| 1484 */ |
| 1485 static int fts3PutColNumber(char **pp, int iCol){ |
| 1486 int n = 0; /* Number of bytes written */ |
| 1487 if( iCol ){ |
| 1488 char *p = *pp; /* Output pointer */ |
| 1489 n = 1 + sqlite3Fts3PutVarint(&p[1], iCol); |
| 1490 *p = 0x01; |
| 1491 *pp = &p[n]; |
| 1492 } |
| 1493 return n; |
| 1494 } |
| 1495 |
| 1496 /* |
| 1497 ** Compute the union of two position lists. The output written |
| 1498 ** into *pp contains all positions of both *pp1 and *pp2 in sorted |
| 1499 ** order and with any duplicates removed. All pointers are |
| 1500 ** updated appropriately. The caller is responsible for insuring |
| 1501 ** that there is enough space in *pp to hold the complete output. |
| 1502 */ |
| 1503 static void fts3PoslistMerge( |
| 1504 char **pp, /* Output buffer */ |
| 1505 char **pp1, /* Left input list */ |
| 1506 char **pp2 /* Right input list */ |
| 1507 ){ |
| 1508 char *p = *pp; |
| 1509 char *p1 = *pp1; |
| 1510 char *p2 = *pp2; |
| 1511 |
| 1512 while( *p1 || *p2 ){ |
| 1513 int iCol1; /* The current column index in pp1 */ |
| 1514 int iCol2; /* The current column index in pp2 */ |
| 1515 |
| 1516 if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1); |
| 1517 else if( *p1==POS_END ) iCol1 = POSITION_LIST_END; |
| 1518 else iCol1 = 0; |
| 1519 |
| 1520 if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2); |
| 1521 else if( *p2==POS_END ) iCol2 = POSITION_LIST_END; |
| 1522 else iCol2 = 0; |
| 1523 |
| 1524 if( iCol1==iCol2 ){ |
| 1525 sqlite3_int64 i1 = 0; /* Last position from pp1 */ |
| 1526 sqlite3_int64 i2 = 0; /* Last position from pp2 */ |
| 1527 sqlite3_int64 iPrev = 0; |
| 1528 int n = fts3PutColNumber(&p, iCol1); |
| 1529 p1 += n; |
| 1530 p2 += n; |
| 1531 |
| 1532 /* At this point, both p1 and p2 point to the start of column-lists |
| 1533 ** for the same column (the column with index iCol1 and iCol2). |
| 1534 ** A column-list is a list of non-negative delta-encoded varints, each |
| 1535 ** incremented by 2 before being stored. Each list is terminated by a |
| 1536 ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists |
| 1537 ** and writes the results to buffer p. p is left pointing to the byte |
| 1538 ** after the list written. No terminator (POS_END or POS_COLUMN) is |
| 1539 ** written to the output. |
| 1540 */ |
| 1541 fts3GetDeltaVarint(&p1, &i1); |
| 1542 fts3GetDeltaVarint(&p2, &i2); |
| 1543 do { |
| 1544 fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); |
| 1545 iPrev -= 2; |
| 1546 if( i1==i2 ){ |
| 1547 fts3ReadNextPos(&p1, &i1); |
| 1548 fts3ReadNextPos(&p2, &i2); |
| 1549 }else if( i1<i2 ){ |
| 1550 fts3ReadNextPos(&p1, &i1); |
| 1551 }else{ |
| 1552 fts3ReadNextPos(&p2, &i2); |
| 1553 } |
| 1554 }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END ); |
| 1555 }else if( iCol1<iCol2 ){ |
| 1556 p1 += fts3PutColNumber(&p, iCol1); |
| 1557 fts3ColumnlistCopy(&p, &p1); |
| 1558 }else{ |
| 1559 p2 += fts3PutColNumber(&p, iCol2); |
| 1560 fts3ColumnlistCopy(&p, &p2); |
| 1561 } |
| 1562 } |
| 1563 |
| 1564 *p++ = POS_END; |
| 1565 *pp = p; |
| 1566 *pp1 = p1 + 1; |
| 1567 *pp2 = p2 + 1; |
| 1568 } |
| 1569 |
| 1570 /* |
| 1571 ** nToken==1 searches for adjacent positions. |
| 1572 ** |
| 1573 ** This function is used to merge two position lists into one. When it is |
| 1574 ** called, *pp1 and *pp2 must both point to position lists. A position-list is |
| 1575 ** the part of a doclist that follows each document id. For example, if a row |
| 1576 ** contains: |
| 1577 ** |
| 1578 ** 'a b c'|'x y z'|'a b b a' |
| 1579 ** |
| 1580 ** Then the position list for this row for token 'b' would consist of: |
| 1581 ** |
| 1582 ** 0x02 0x01 0x02 0x03 0x03 0x00 |
| 1583 ** |
| 1584 ** When this function returns, both *pp1 and *pp2 are left pointing to the |
| 1585 ** byte following the 0x00 terminator of their respective position lists. |
| 1586 ** |
| 1587 ** If isSaveLeft is 0, an entry is added to the output position list for |
| 1588 ** each position in *pp2 for which there exists one or more positions in |
| 1589 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e. |
| 1590 ** when the *pp1 token appears before the *pp2 token, but not more than nToken |
| 1591 ** slots before it. |
| 1592 */ |
| 1593 static int fts3PoslistPhraseMerge( |
| 1594 char **pp, /* IN/OUT: Preallocated output buffer */ |
| 1595 int nToken, /* Maximum difference in token positions */ |
| 1596 int isSaveLeft, /* Save the left position */ |
| 1597 int isExact, /* If *pp1 is exactly nTokens before *pp2 */ |
| 1598 char **pp1, /* IN/OUT: Left input list */ |
| 1599 char **pp2 /* IN/OUT: Right input list */ |
| 1600 ){ |
| 1601 char *p = (pp ? *pp : 0); |
| 1602 char *p1 = *pp1; |
| 1603 char *p2 = *pp2; |
| 1604 int iCol1 = 0; |
| 1605 int iCol2 = 0; |
| 1606 |
| 1607 /* Never set both isSaveLeft and isExact for the same invocation. */ |
| 1608 assert( isSaveLeft==0 || isExact==0 ); |
| 1609 |
| 1610 assert( *p1!=0 && *p2!=0 ); |
| 1611 if( *p1==POS_COLUMN ){ |
| 1612 p1++; |
| 1613 p1 += sqlite3Fts3GetVarint32(p1, &iCol1); |
| 1614 } |
| 1615 if( *p2==POS_COLUMN ){ |
| 1616 p2++; |
| 1617 p2 += sqlite3Fts3GetVarint32(p2, &iCol2); |
| 1618 } |
| 1619 |
| 1620 while( 1 ){ |
| 1621 if( iCol1==iCol2 ){ |
| 1622 char *pSave = p; |
| 1623 sqlite3_int64 iPrev = 0; |
| 1624 sqlite3_int64 iPos1 = 0; |
| 1625 sqlite3_int64 iPos2 = 0; |
| 1626 |
| 1627 if( pp && iCol1 ){ |
| 1628 *p++ = POS_COLUMN; |
| 1629 p += sqlite3Fts3PutVarint(p, iCol1); |
| 1630 } |
| 1631 |
| 1632 assert( *p1!=POS_END && *p1!=POS_COLUMN ); |
| 1633 assert( *p2!=POS_END && *p2!=POS_COLUMN ); |
| 1634 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; |
| 1635 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; |
| 1636 |
| 1637 while( 1 ){ |
| 1638 if( iPos2==iPos1+nToken |
| 1639 || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) |
| 1640 ){ |
| 1641 sqlite3_int64 iSave; |
| 1642 if( !pp ){ |
| 1643 fts3PoslistCopy(0, &p2); |
| 1644 fts3PoslistCopy(0, &p1); |
| 1645 *pp1 = p1; |
| 1646 *pp2 = p2; |
| 1647 return 1; |
| 1648 } |
| 1649 iSave = isSaveLeft ? iPos1 : iPos2; |
| 1650 fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2; |
| 1651 pSave = 0; |
| 1652 } |
| 1653 if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){ |
| 1654 if( (*p2&0xFE)==0 ) break; |
| 1655 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; |
| 1656 }else{ |
| 1657 if( (*p1&0xFE)==0 ) break; |
| 1658 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; |
| 1659 } |
| 1660 } |
| 1661 |
| 1662 if( pSave ){ |
| 1663 assert( pp && p ); |
| 1664 p = pSave; |
| 1665 } |
| 1666 |
| 1667 fts3ColumnlistCopy(0, &p1); |
| 1668 fts3ColumnlistCopy(0, &p2); |
| 1669 assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 ); |
| 1670 if( 0==*p1 || 0==*p2 ) break; |
| 1671 |
| 1672 p1++; |
| 1673 p1 += sqlite3Fts3GetVarint32(p1, &iCol1); |
| 1674 p2++; |
| 1675 p2 += sqlite3Fts3GetVarint32(p2, &iCol2); |
| 1676 } |
| 1677 |
| 1678 /* Advance pointer p1 or p2 (whichever corresponds to the smaller of |
| 1679 ** iCol1 and iCol2) so that it points to either the 0x00 that marks the |
| 1680 ** end of the position list, or the 0x01 that precedes the next |
| 1681 ** column-number in the position list. |
| 1682 */ |
| 1683 else if( iCol1<iCol2 ){ |
| 1684 fts3ColumnlistCopy(0, &p1); |
| 1685 if( 0==*p1 ) break; |
| 1686 p1++; |
| 1687 p1 += sqlite3Fts3GetVarint32(p1, &iCol1); |
| 1688 }else{ |
| 1689 fts3ColumnlistCopy(0, &p2); |
| 1690 if( 0==*p2 ) break; |
| 1691 p2++; |
| 1692 p2 += sqlite3Fts3GetVarint32(p2, &iCol2); |
| 1693 } |
| 1694 } |
| 1695 |
| 1696 fts3PoslistCopy(0, &p2); |
| 1697 fts3PoslistCopy(0, &p1); |
| 1698 *pp1 = p1; |
| 1699 *pp2 = p2; |
| 1700 if( !pp || *pp==p ){ |
| 1701 return 0; |
| 1702 } |
| 1703 *p++ = 0x00; |
| 1704 *pp = p; |
| 1705 return 1; |
| 1706 } |
| 1707 |
| 1708 /* |
| 1709 ** Merge two position-lists as required by the NEAR operator. |
| 1710 */ |
| 1711 static int fts3PoslistNearMerge( |
| 1712 char **pp, /* Output buffer */ |
| 1713 char *aTmp, /* Temporary buffer space */ |
| 1714 int nRight, /* Maximum difference in token positions */ |
| 1715 int nLeft, /* Maximum difference in token positions */ |
| 1716 char **pp1, /* IN/OUT: Left input list */ |
| 1717 char **pp2 /* IN/OUT: Right input list */ |
| 1718 ){ |
| 1719 char *p1 = *pp1; |
| 1720 char *p2 = *pp2; |
| 1721 |
| 1722 if( !pp ){ |
| 1723 if( fts3PoslistPhraseMerge(0, nRight, 0, 0, pp1, pp2) ) return 1; |
| 1724 *pp1 = p1; |
| 1725 *pp2 = p2; |
| 1726 return fts3PoslistPhraseMerge(0, nLeft, 0, 0, pp2, pp1); |
| 1727 }else{ |
| 1728 char *pTmp1 = aTmp; |
| 1729 char *pTmp2; |
| 1730 char *aTmp2; |
| 1731 int res = 1; |
| 1732 |
| 1733 fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2); |
| 1734 aTmp2 = pTmp2 = pTmp1; |
| 1735 *pp1 = p1; |
| 1736 *pp2 = p2; |
| 1737 fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1); |
| 1738 if( pTmp1!=aTmp && pTmp2!=aTmp2 ){ |
| 1739 fts3PoslistMerge(pp, &aTmp, &aTmp2); |
| 1740 }else if( pTmp1!=aTmp ){ |
| 1741 fts3PoslistCopy(pp, &aTmp); |
| 1742 }else if( pTmp2!=aTmp2 ){ |
| 1743 fts3PoslistCopy(pp, &aTmp2); |
| 1744 }else{ |
| 1745 res = 0; |
| 1746 } |
| 1747 |
| 1748 return res; |
| 1749 } |
| 1750 } |
| 1751 |
| 1752 /* |
| 1753 ** Values that may be used as the first parameter to fts3DoclistMerge(). |
| 1754 */ |
| 1755 #define MERGE_NOT 2 /* D + D -> D */ |
| 1756 #define MERGE_AND 3 /* D + D -> D */ |
| 1757 #define MERGE_OR 4 /* D + D -> D */ |
| 1758 #define MERGE_POS_OR 5 /* P + P -> P */ |
| 1759 #define MERGE_PHRASE 6 /* P + P -> D */ |
| 1760 #define MERGE_POS_PHRASE 7 /* P + P -> P */ |
| 1761 #define MERGE_NEAR 8 /* P + P -> D */ |
| 1762 #define MERGE_POS_NEAR 9 /* P + P -> P */ |
| 1763 |
| 1764 /* |
| 1765 ** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2 |
| 1766 ** (size n2 bytes). The output is written to pre-allocated buffer aBuffer, |
| 1767 ** which is guaranteed to be large enough to hold the results. The number |
| 1768 ** of bytes written to aBuffer is stored in *pnBuffer before returning. |
| 1769 ** |
| 1770 ** If successful, SQLITE_OK is returned. Otherwise, if a malloc error |
| 1771 ** occurs while allocating a temporary buffer as part of the merge operation, |
| 1772 ** SQLITE_NOMEM is returned. |
| 1773 */ |
| 1774 static int fts3DoclistMerge( |
| 1775 int mergetype, /* One of the MERGE_XXX constants */ |
| 1776 int nParam1, /* Used by MERGE_NEAR and MERGE_POS_NEAR */ |
| 1777 int nParam2, /* Used by MERGE_NEAR and MERGE_POS_NEAR */ |
| 1778 char *aBuffer, /* Pre-allocated output buffer */ |
| 1779 int *pnBuffer, /* OUT: Bytes written to aBuffer */ |
| 1780 char *a1, /* Buffer containing first doclist */ |
| 1781 int n1, /* Size of buffer a1 */ |
| 1782 char *a2, /* Buffer containing second doclist */ |
| 1783 int n2, /* Size of buffer a2 */ |
| 1784 int *pnDoc /* OUT: Number of docids in output */ |
| 1785 ){ |
| 1786 sqlite3_int64 i1 = 0; |
| 1787 sqlite3_int64 i2 = 0; |
| 1788 sqlite3_int64 iPrev = 0; |
| 1789 |
| 1790 char *p = aBuffer; |
| 1791 char *p1 = a1; |
| 1792 char *p2 = a2; |
| 1793 char *pEnd1 = &a1[n1]; |
| 1794 char *pEnd2 = &a2[n2]; |
| 1795 int nDoc = 0; |
| 1796 |
| 1797 assert( mergetype==MERGE_OR || mergetype==MERGE_POS_OR |
| 1798 || mergetype==MERGE_AND || mergetype==MERGE_NOT |
| 1799 || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE |
| 1800 || mergetype==MERGE_NEAR || mergetype==MERGE_POS_NEAR |
| 1801 ); |
| 1802 |
| 1803 if( !aBuffer ){ |
| 1804 *pnBuffer = 0; |
| 1805 return SQLITE_NOMEM; |
| 1806 } |
| 1807 |
| 1808 /* Read the first docid from each doclist */ |
| 1809 fts3GetDeltaVarint2(&p1, pEnd1, &i1); |
| 1810 fts3GetDeltaVarint2(&p2, pEnd2, &i2); |
| 1811 |
| 1812 switch( mergetype ){ |
| 1813 case MERGE_OR: |
| 1814 case MERGE_POS_OR: |
| 1815 while( p1 || p2 ){ |
| 1816 if( p2 && p1 && i1==i2 ){ |
| 1817 fts3PutDeltaVarint(&p, &iPrev, i1); |
| 1818 if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2); |
| 1819 fts3GetDeltaVarint2(&p1, pEnd1, &i1); |
| 1820 fts3GetDeltaVarint2(&p2, pEnd2, &i2); |
| 1821 }else if( !p2 || (p1 && i1<i2) ){ |
| 1822 fts3PutDeltaVarint(&p, &iPrev, i1); |
| 1823 if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1); |
| 1824 fts3GetDeltaVarint2(&p1, pEnd1, &i1); |
| 1825 }else{ |
| 1826 fts3PutDeltaVarint(&p, &iPrev, i2); |
| 1827 if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2); |
| 1828 fts3GetDeltaVarint2(&p2, pEnd2, &i2); |
| 1829 } |
| 1830 } |
| 1831 break; |
| 1832 |
| 1833 case MERGE_AND: |
| 1834 while( p1 && p2 ){ |
| 1835 if( i1==i2 ){ |
| 1836 fts3PutDeltaVarint(&p, &iPrev, i1); |
| 1837 fts3GetDeltaVarint2(&p1, pEnd1, &i1); |
| 1838 fts3GetDeltaVarint2(&p2, pEnd2, &i2); |
| 1839 nDoc++; |
| 1840 }else if( i1<i2 ){ |
| 1841 fts3GetDeltaVarint2(&p1, pEnd1, &i1); |
| 1842 }else{ |
| 1843 fts3GetDeltaVarint2(&p2, pEnd2, &i2); |
| 1844 } |
| 1845 } |
| 1846 break; |
| 1847 |
| 1848 case MERGE_NOT: |
| 1849 while( p1 ){ |
| 1850 if( p2 && i1==i2 ){ |
| 1851 fts3GetDeltaVarint2(&p1, pEnd1, &i1); |
| 1852 fts3GetDeltaVarint2(&p2, pEnd2, &i2); |
| 1853 }else if( !p2 || i1<i2 ){ |
| 1854 fts3PutDeltaVarint(&p, &iPrev, i1); |
| 1855 fts3GetDeltaVarint2(&p1, pEnd1, &i1); |
| 1856 }else{ |
| 1857 fts3GetDeltaVarint2(&p2, pEnd2, &i2); |
| 1858 } |
| 1859 } |
| 1860 break; |
| 1861 |
| 1862 case MERGE_POS_PHRASE: |
| 1863 case MERGE_PHRASE: { |
| 1864 char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p); |
| 1865 while( p1 && p2 ){ |
| 1866 if( i1==i2 ){ |
| 1867 char *pSave = p; |
| 1868 sqlite3_int64 iPrevSave = iPrev; |
| 1869 fts3PutDeltaVarint(&p, &iPrev, i1); |
| 1870 if( 0==fts3PoslistPhraseMerge(ppPos, nParam1, 0, 1, &p1, &p2) ){ |
| 1871 p = pSave; |
| 1872 iPrev = iPrevSave; |
| 1873 }else{ |
| 1874 nDoc++; |
| 1875 } |
| 1876 fts3GetDeltaVarint2(&p1, pEnd1, &i1); |
| 1877 fts3GetDeltaVarint2(&p2, pEnd2, &i2); |
| 1878 }else if( i1<i2 ){ |
| 1879 fts3PoslistCopy(0, &p1); |
| 1880 fts3GetDeltaVarint2(&p1, pEnd1, &i1); |
| 1881 }else{ |
| 1882 fts3PoslistCopy(0, &p2); |
| 1883 fts3GetDeltaVarint2(&p2, pEnd2, &i2); |
| 1884 } |
| 1885 } |
| 1886 break; |
| 1887 } |
| 1888 |
| 1889 default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); { |
| 1890 char *aTmp = 0; |
| 1891 char **ppPos = 0; |
| 1892 |
| 1893 if( mergetype==MERGE_POS_NEAR ){ |
| 1894 ppPos = &p; |
| 1895 aTmp = sqlite3_malloc(2*(n1+n2+1)); |
| 1896 if( !aTmp ){ |
| 1897 return SQLITE_NOMEM; |
| 1898 } |
| 1899 } |
| 1900 |
| 1901 while( p1 && p2 ){ |
| 1902 if( i1==i2 ){ |
| 1903 char *pSave = p; |
| 1904 sqlite3_int64 iPrevSave = iPrev; |
| 1905 fts3PutDeltaVarint(&p, &iPrev, i1); |
| 1906 |
| 1907 if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){ |
| 1908 iPrev = iPrevSave; |
| 1909 p = pSave; |
| 1910 } |
| 1911 |
| 1912 fts3GetDeltaVarint2(&p1, pEnd1, &i1); |
| 1913 fts3GetDeltaVarint2(&p2, pEnd2, &i2); |
| 1914 }else if( i1<i2 ){ |
| 1915 fts3PoslistCopy(0, &p1); |
| 1916 fts3GetDeltaVarint2(&p1, pEnd1, &i1); |
| 1917 }else{ |
| 1918 fts3PoslistCopy(0, &p2); |
| 1919 fts3GetDeltaVarint2(&p2, pEnd2, &i2); |
| 1920 } |
| 1921 } |
| 1922 sqlite3_free(aTmp); |
| 1923 break; |
| 1924 } |
| 1925 } |
| 1926 |
| 1927 if( pnDoc ) *pnDoc = nDoc; |
| 1928 *pnBuffer = (int)(p-aBuffer); |
| 1929 return SQLITE_OK; |
| 1930 } |
| 1931 |
| 1932 /* |
| 1933 ** A pointer to an instance of this structure is used as the context |
| 1934 ** argument to sqlite3Fts3SegReaderIterate() |
| 1935 */ |
| 1936 typedef struct TermSelect TermSelect; |
| 1937 struct TermSelect { |
| 1938 int isReqPos; |
| 1939 char *aaOutput[16]; /* Malloc'd output buffer */ |
| 1940 int anOutput[16]; /* Size of output in bytes */ |
| 1941 }; |
| 1942 |
| 1943 /* |
| 1944 ** Merge all doclists in the TermSelect.aaOutput[] array into a single |
| 1945 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all |
| 1946 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK. |
| 1947 ** |
| 1948 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is |
| 1949 ** the responsibility of the caller to free any doclists left in the |
| 1950 ** TermSelect.aaOutput[] array. |
| 1951 */ |
| 1952 static int fts3TermSelectMerge(TermSelect *pTS){ |
| 1953 int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR); |
| 1954 char *aOut = 0; |
| 1955 int nOut = 0; |
| 1956 int i; |
| 1957 |
| 1958 /* Loop through the doclists in the aaOutput[] array. Merge them all |
| 1959 ** into a single doclist. |
| 1960 */ |
| 1961 for(i=0; i<SizeofArray(pTS->aaOutput); i++){ |
| 1962 if( pTS->aaOutput[i] ){ |
| 1963 if( !aOut ){ |
| 1964 aOut = pTS->aaOutput[i]; |
| 1965 nOut = pTS->anOutput[i]; |
| 1966 pTS->aaOutput[i] = 0; |
| 1967 }else{ |
| 1968 int nNew = nOut + pTS->anOutput[i]; |
| 1969 char *aNew = sqlite3_malloc(nNew); |
| 1970 if( !aNew ){ |
| 1971 sqlite3_free(aOut); |
| 1972 return SQLITE_NOMEM; |
| 1973 } |
| 1974 fts3DoclistMerge(mergetype, 0, 0, |
| 1975 aNew, &nNew, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, 0 |
| 1976 ); |
| 1977 sqlite3_free(pTS->aaOutput[i]); |
| 1978 sqlite3_free(aOut); |
| 1979 pTS->aaOutput[i] = 0; |
| 1980 aOut = aNew; |
| 1981 nOut = nNew; |
| 1982 } |
| 1983 } |
| 1984 } |
| 1985 |
| 1986 pTS->aaOutput[0] = aOut; |
| 1987 pTS->anOutput[0] = nOut; |
| 1988 return SQLITE_OK; |
| 1989 } |
| 1990 |
| 1991 /* |
| 1992 ** This function is used as the sqlite3Fts3SegReaderIterate() callback when |
| 1993 ** querying the full-text index for a doclist associated with a term or |
| 1994 ** term-prefix. |
| 1995 */ |
| 1996 static int fts3TermSelectCb( |
| 1997 Fts3Table *p, /* Virtual table object */ |
| 1998 void *pContext, /* Pointer to TermSelect structure */ |
| 1999 char *zTerm, |
| 2000 int nTerm, |
| 2001 char *aDoclist, |
| 2002 int nDoclist |
| 2003 ){ |
| 2004 TermSelect *pTS = (TermSelect *)pContext; |
| 2005 |
| 2006 UNUSED_PARAMETER(p); |
| 2007 UNUSED_PARAMETER(zTerm); |
| 2008 UNUSED_PARAMETER(nTerm); |
| 2009 |
| 2010 if( pTS->aaOutput[0]==0 ){ |
| 2011 /* If this is the first term selected, copy the doclist to the output |
| 2012 ** buffer using memcpy(). TODO: Add a way to transfer control of the |
| 2013 ** aDoclist buffer from the caller so as to avoid the memcpy(). |
| 2014 */ |
| 2015 pTS->aaOutput[0] = sqlite3_malloc(nDoclist); |
| 2016 pTS->anOutput[0] = nDoclist; |
| 2017 if( pTS->aaOutput[0] ){ |
| 2018 memcpy(pTS->aaOutput[0], aDoclist, nDoclist); |
| 2019 }else{ |
| 2020 return SQLITE_NOMEM; |
| 2021 } |
| 2022 }else{ |
| 2023 int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR); |
| 2024 char *aMerge = aDoclist; |
| 2025 int nMerge = nDoclist; |
| 2026 int iOut; |
| 2027 |
| 2028 for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){ |
| 2029 char *aNew; |
| 2030 int nNew; |
| 2031 if( pTS->aaOutput[iOut]==0 ){ |
| 2032 assert( iOut>0 ); |
| 2033 pTS->aaOutput[iOut] = aMerge; |
| 2034 pTS->anOutput[iOut] = nMerge; |
| 2035 break; |
| 2036 } |
| 2037 |
| 2038 nNew = nMerge + pTS->anOutput[iOut]; |
| 2039 aNew = sqlite3_malloc(nNew); |
| 2040 if( !aNew ){ |
| 2041 if( aMerge!=aDoclist ){ |
| 2042 sqlite3_free(aMerge); |
| 2043 } |
| 2044 return SQLITE_NOMEM; |
| 2045 } |
| 2046 fts3DoclistMerge(mergetype, 0, 0, aNew, &nNew, |
| 2047 pTS->aaOutput[iOut], pTS->anOutput[iOut], aMerge, nMerge, 0 |
| 2048 ); |
| 2049 |
| 2050 if( iOut>0 ) sqlite3_free(aMerge); |
| 2051 sqlite3_free(pTS->aaOutput[iOut]); |
| 2052 pTS->aaOutput[iOut] = 0; |
| 2053 |
| 2054 aMerge = aNew; |
| 2055 nMerge = nNew; |
| 2056 if( (iOut+1)==SizeofArray(pTS->aaOutput) ){ |
| 2057 pTS->aaOutput[iOut] = aMerge; |
| 2058 pTS->anOutput[iOut] = nMerge; |
| 2059 } |
| 2060 } |
| 2061 } |
| 2062 return SQLITE_OK; |
| 2063 } |
| 2064 |
| 2065 static int fts3DeferredTermSelect( |
| 2066 Fts3DeferredToken *pToken, /* Phrase token */ |
| 2067 int isTermPos, /* True to include positions */ |
| 2068 int *pnOut, /* OUT: Size of list */ |
| 2069 char **ppOut /* OUT: Body of list */ |
| 2070 ){ |
| 2071 char *aSource; |
| 2072 int nSource; |
| 2073 |
| 2074 aSource = sqlite3Fts3DeferredDoclist(pToken, &nSource); |
| 2075 if( !aSource ){ |
| 2076 *pnOut = 0; |
| 2077 *ppOut = 0; |
| 2078 }else if( isTermPos ){ |
| 2079 *ppOut = sqlite3_malloc(nSource); |
| 2080 if( !*ppOut ) return SQLITE_NOMEM; |
| 2081 memcpy(*ppOut, aSource, nSource); |
| 2082 *pnOut = nSource; |
| 2083 }else{ |
| 2084 sqlite3_int64 docid; |
| 2085 *pnOut = sqlite3Fts3GetVarint(aSource, &docid); |
| 2086 *ppOut = sqlite3_malloc(*pnOut); |
| 2087 if( !*ppOut ) return SQLITE_NOMEM; |
| 2088 sqlite3Fts3PutVarint(*ppOut, docid); |
| 2089 } |
| 2090 |
| 2091 return SQLITE_OK; |
| 2092 } |
| 2093 |
| 2094 int sqlite3Fts3SegReaderCursor( |
| 2095 Fts3Table *p, /* FTS3 table handle */ |
| 2096 int iLevel, /* Level of segments to scan */ |
| 2097 const char *zTerm, /* Term to query for */ |
| 2098 int nTerm, /* Size of zTerm in bytes */ |
| 2099 int isPrefix, /* True for a prefix search */ |
| 2100 int isScan, /* True to scan from zTerm to EOF */ |
| 2101 Fts3SegReaderCursor *pCsr /* Cursor object to populate */ |
| 2102 ){ |
| 2103 int rc = SQLITE_OK; |
| 2104 int rc2; |
| 2105 int iAge = 0; |
| 2106 sqlite3_stmt *pStmt = 0; |
| 2107 Fts3SegReader *pPending = 0; |
| 2108 |
| 2109 assert( iLevel==FTS3_SEGCURSOR_ALL |
| 2110 || iLevel==FTS3_SEGCURSOR_PENDING |
| 2111 || iLevel>=0 |
| 2112 ); |
| 2113 assert( FTS3_SEGCURSOR_PENDING<0 ); |
| 2114 assert( FTS3_SEGCURSOR_ALL<0 ); |
| 2115 assert( iLevel==FTS3_SEGCURSOR_ALL || (zTerm==0 && isPrefix==1) ); |
| 2116 assert( isPrefix==0 || isScan==0 ); |
| 2117 |
| 2118 |
| 2119 memset(pCsr, 0, sizeof(Fts3SegReaderCursor)); |
| 2120 |
| 2121 /* If iLevel is less than 0, include a seg-reader for the pending-terms. */ |
| 2122 assert( isScan==0 || fts3HashCount(&p->pendingTerms)==0 ); |
| 2123 if( iLevel<0 && isScan==0 ){ |
| 2124 rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &pPending); |
| 2125 if( rc==SQLITE_OK && pPending ){ |
| 2126 int nByte = (sizeof(Fts3SegReader *) * 16); |
| 2127 pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte); |
| 2128 if( pCsr->apSegment==0 ){ |
| 2129 rc = SQLITE_NOMEM; |
| 2130 }else{ |
| 2131 pCsr->apSegment[0] = pPending; |
| 2132 pCsr->nSegment = 1; |
| 2133 pPending = 0; |
| 2134 } |
| 2135 } |
| 2136 } |
| 2137 |
| 2138 if( iLevel!=FTS3_SEGCURSOR_PENDING ){ |
| 2139 if( rc==SQLITE_OK ){ |
| 2140 rc = sqlite3Fts3AllSegdirs(p, iLevel, &pStmt); |
| 2141 } |
| 2142 while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){ |
| 2143 |
| 2144 /* Read the values returned by the SELECT into local variables. */ |
| 2145 sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1); |
| 2146 sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2); |
| 2147 sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3); |
| 2148 int nRoot = sqlite3_column_bytes(pStmt, 4); |
| 2149 char const *zRoot = sqlite3_column_blob(pStmt, 4); |
| 2150 |
| 2151 /* If nSegment is a multiple of 16 the array needs to be extended. */ |
| 2152 if( (pCsr->nSegment%16)==0 ){ |
| 2153 Fts3SegReader **apNew; |
| 2154 int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*); |
| 2155 apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte); |
| 2156 if( !apNew ){ |
| 2157 rc = SQLITE_NOMEM; |
| 2158 goto finished; |
| 2159 } |
| 2160 pCsr->apSegment = apNew; |
| 2161 } |
| 2162 |
| 2163 /* If zTerm is not NULL, and this segment is not stored entirely on its |
| 2164 ** root node, the range of leaves scanned can be reduced. Do this. */ |
| 2165 if( iStartBlock && zTerm ){ |
| 2166 sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0); |
| 2167 rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi); |
| 2168 if( rc!=SQLITE_OK ) goto finished; |
| 2169 if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock; |
| 2170 } |
| 2171 |
| 2172 rc = sqlite3Fts3SegReaderNew(iAge, iStartBlock, iLeavesEndBlock, |
| 2173 iEndBlock, zRoot, nRoot, &pCsr->apSegment[pCsr->nSegment] |
| 2174 ); |
| 2175 if( rc!=SQLITE_OK ) goto finished; |
| 2176 pCsr->nSegment++; |
| 2177 iAge++; |
| 2178 } |
| 2179 } |
| 2180 |
| 2181 finished: |
| 2182 rc2 = sqlite3_reset(pStmt); |
| 2183 if( rc==SQLITE_DONE ) rc = rc2; |
| 2184 sqlite3Fts3SegReaderFree(pPending); |
| 2185 |
| 2186 return rc; |
| 2187 } |
| 2188 |
| 2189 |
| 2190 static int fts3TermSegReaderCursor( |
| 2191 Fts3Cursor *pCsr, /* Virtual table cursor handle */ |
| 2192 const char *zTerm, /* Term to query for */ |
| 2193 int nTerm, /* Size of zTerm in bytes */ |
| 2194 int isPrefix, /* True for a prefix search */ |
| 2195 Fts3SegReaderCursor **ppSegcsr /* OUT: Allocated seg-reader cursor */ |
| 2196 ){ |
| 2197 Fts3SegReaderCursor *pSegcsr; /* Object to allocate and return */ |
| 2198 int rc = SQLITE_NOMEM; /* Return code */ |
| 2199 |
| 2200 pSegcsr = sqlite3_malloc(sizeof(Fts3SegReaderCursor)); |
| 2201 if( pSegcsr ){ |
| 2202 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; |
| 2203 int i; |
| 2204 int nCost = 0; |
| 2205 rc = sqlite3Fts3SegReaderCursor( |
| 2206 p, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr); |
| 2207 |
| 2208 for(i=0; rc==SQLITE_OK && i<pSegcsr->nSegment; i++){ |
| 2209 rc = sqlite3Fts3SegReaderCost(pCsr, pSegcsr->apSegment[i], &nCost); |
| 2210 } |
| 2211 pSegcsr->nCost = nCost; |
| 2212 } |
| 2213 |
| 2214 *ppSegcsr = pSegcsr; |
| 2215 return rc; |
| 2216 } |
| 2217 |
| 2218 static void fts3SegReaderCursorFree(Fts3SegReaderCursor *pSegcsr){ |
| 2219 sqlite3Fts3SegReaderFinish(pSegcsr); |
| 2220 sqlite3_free(pSegcsr); |
| 2221 } |
| 2222 |
| 2223 /* |
| 2224 ** This function retreives the doclist for the specified term (or term |
| 2225 ** prefix) from the database. |
| 2226 ** |
| 2227 ** The returned doclist may be in one of two formats, depending on the |
| 2228 ** value of parameter isReqPos. If isReqPos is zero, then the doclist is |
| 2229 ** a sorted list of delta-compressed docids (a bare doclist). If isReqPos |
| 2230 ** is non-zero, then the returned list is in the same format as is stored |
| 2231 ** in the database without the found length specifier at the start of on-disk |
| 2232 ** doclists. |
| 2233 */ |
| 2234 static int fts3TermSelect( |
| 2235 Fts3Table *p, /* Virtual table handle */ |
| 2236 Fts3PhraseToken *pTok, /* Token to query for */ |
| 2237 int iColumn, /* Column to query (or -ve for all columns) */ |
| 2238 int isReqPos, /* True to include position lists in output */ |
| 2239 int *pnOut, /* OUT: Size of buffer at *ppOut */ |
| 2240 char **ppOut /* OUT: Malloced result buffer */ |
| 2241 ){ |
| 2242 int rc; /* Return code */ |
| 2243 Fts3SegReaderCursor *pSegcsr; /* Seg-reader cursor for this term */ |
| 2244 TermSelect tsc; /* Context object for fts3TermSelectCb() */ |
| 2245 Fts3SegFilter filter; /* Segment term filter configuration */ |
| 2246 |
| 2247 pSegcsr = pTok->pSegcsr; |
| 2248 memset(&tsc, 0, sizeof(TermSelect)); |
| 2249 tsc.isReqPos = isReqPos; |
| 2250 |
| 2251 filter.flags = FTS3_SEGMENT_IGNORE_EMPTY |
| 2252 | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0) |
| 2253 | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0) |
| 2254 | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0); |
| 2255 filter.iCol = iColumn; |
| 2256 filter.zTerm = pTok->z; |
| 2257 filter.nTerm = pTok->n; |
| 2258 |
| 2259 rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter); |
| 2260 while( SQLITE_OK==rc |
| 2261 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) |
| 2262 ){ |
| 2263 rc = fts3TermSelectCb(p, (void *)&tsc, |
| 2264 pSegcsr->zTerm, pSegcsr->nTerm, pSegcsr->aDoclist, pSegcsr->nDoclist |
| 2265 ); |
| 2266 } |
| 2267 |
| 2268 if( rc==SQLITE_OK ){ |
| 2269 rc = fts3TermSelectMerge(&tsc); |
| 2270 } |
| 2271 if( rc==SQLITE_OK ){ |
| 2272 *ppOut = tsc.aaOutput[0]; |
| 2273 *pnOut = tsc.anOutput[0]; |
| 2274 }else{ |
| 2275 int i; |
| 2276 for(i=0; i<SizeofArray(tsc.aaOutput); i++){ |
| 2277 sqlite3_free(tsc.aaOutput[i]); |
| 2278 } |
| 2279 } |
| 2280 |
| 2281 fts3SegReaderCursorFree(pSegcsr); |
| 2282 pTok->pSegcsr = 0; |
| 2283 return rc; |
| 2284 } |
| 2285 |
| 2286 /* |
| 2287 ** This function counts the total number of docids in the doclist stored |
| 2288 ** in buffer aList[], size nList bytes. |
| 2289 ** |
| 2290 ** If the isPoslist argument is true, then it is assumed that the doclist |
| 2291 ** contains a position-list following each docid. Otherwise, it is assumed |
| 2292 ** that the doclist is simply a list of docids stored as delta encoded |
| 2293 ** varints. |
| 2294 */ |
| 2295 static int fts3DoclistCountDocids(int isPoslist, char *aList, int nList){ |
| 2296 int nDoc = 0; /* Return value */ |
| 2297 if( aList ){ |
| 2298 char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */ |
| 2299 char *p = aList; /* Cursor */ |
| 2300 if( !isPoslist ){ |
| 2301 /* The number of docids in the list is the same as the number of |
| 2302 ** varints. In FTS3 a varint consists of a single byte with the 0x80 |
| 2303 ** bit cleared and zero or more bytes with the 0x80 bit set. So to |
| 2304 ** count the varints in the buffer, just count the number of bytes |
| 2305 ** with the 0x80 bit clear. */ |
| 2306 while( p<aEnd ) nDoc += (((*p++)&0x80)==0); |
| 2307 }else{ |
| 2308 while( p<aEnd ){ |
| 2309 nDoc++; |
| 2310 while( (*p++)&0x80 ); /* Skip docid varint */ |
| 2311 fts3PoslistCopy(0, &p); /* Skip over position list */ |
| 2312 } |
| 2313 } |
| 2314 } |
| 2315 |
| 2316 return nDoc; |
| 2317 } |
| 2318 |
| 2319 /* |
| 2320 ** Call sqlite3Fts3DeferToken() for each token in the expression pExpr. |
| 2321 */ |
| 2322 static int fts3DeferExpression(Fts3Cursor *pCsr, Fts3Expr *pExpr){ |
| 2323 int rc = SQLITE_OK; |
| 2324 if( pExpr ){ |
| 2325 rc = fts3DeferExpression(pCsr, pExpr->pLeft); |
| 2326 if( rc==SQLITE_OK ){ |
| 2327 rc = fts3DeferExpression(pCsr, pExpr->pRight); |
| 2328 } |
| 2329 if( pExpr->eType==FTSQUERY_PHRASE ){ |
| 2330 int iCol = pExpr->pPhrase->iColumn; |
| 2331 int i; |
| 2332 for(i=0; rc==SQLITE_OK && i<pExpr->pPhrase->nToken; i++){ |
| 2333 Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i]; |
| 2334 if( pToken->pDeferred==0 ){ |
| 2335 rc = sqlite3Fts3DeferToken(pCsr, pToken, iCol); |
| 2336 } |
| 2337 } |
| 2338 } |
| 2339 } |
| 2340 return rc; |
| 2341 } |
| 2342 |
| 2343 /* |
| 2344 ** This function removes the position information from a doclist. When |
| 2345 ** called, buffer aList (size *pnList bytes) contains a doclist that includes |
| 2346 ** position information. This function removes the position information so |
| 2347 ** that aList contains only docids, and adjusts *pnList to reflect the new |
| 2348 ** (possibly reduced) size of the doclist. |
| 2349 */ |
| 2350 static void fts3DoclistStripPositions( |
| 2351 char *aList, /* IN/OUT: Buffer containing doclist */ |
| 2352 int *pnList /* IN/OUT: Size of doclist in bytes */ |
| 2353 ){ |
| 2354 if( aList ){ |
| 2355 char *aEnd = &aList[*pnList]; /* Pointer to one byte after EOF */ |
| 2356 char *p = aList; /* Input cursor */ |
| 2357 char *pOut = aList; /* Output cursor */ |
| 2358 |
| 2359 while( p<aEnd ){ |
| 2360 sqlite3_int64 delta; |
| 2361 p += sqlite3Fts3GetVarint(p, &delta); |
| 2362 fts3PoslistCopy(0, &p); |
| 2363 pOut += sqlite3Fts3PutVarint(pOut, delta); |
| 2364 } |
| 2365 |
| 2366 *pnList = (int)(pOut - aList); |
| 2367 } |
| 2368 } |
| 2369 |
| 2370 /* |
| 2371 ** Return a DocList corresponding to the phrase *pPhrase. |
| 2372 ** |
| 2373 ** If this function returns SQLITE_OK, but *pnOut is set to a negative value, |
| 2374 ** then no tokens in the phrase were looked up in the full-text index. This |
| 2375 ** is only possible when this function is called from within xFilter(). The |
| 2376 ** caller should assume that all documents match the phrase. The actual |
| 2377 ** filtering will take place in xNext(). |
| 2378 */ |
| 2379 static int fts3PhraseSelect( |
| 2380 Fts3Cursor *pCsr, /* Virtual table cursor handle */ |
| 2381 Fts3Phrase *pPhrase, /* Phrase to return a doclist for */ |
| 2382 int isReqPos, /* True if output should contain positions */ |
| 2383 char **paOut, /* OUT: Pointer to malloc'd result buffer */ |
| 2384 int *pnOut /* OUT: Size of buffer at *paOut */ |
| 2385 ){ |
| 2386 char *pOut = 0; |
| 2387 int nOut = 0; |
| 2388 int rc = SQLITE_OK; |
| 2389 int ii; |
| 2390 int iCol = pPhrase->iColumn; |
| 2391 int isTermPos = (pPhrase->nToken>1 || isReqPos); |
| 2392 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; |
| 2393 int isFirst = 1; |
| 2394 |
| 2395 int iPrevTok = 0; |
| 2396 int nDoc = 0; |
| 2397 |
| 2398 /* If this is an xFilter() evaluation, create a segment-reader for each |
| 2399 ** phrase token. Or, if this is an xNext() or snippet/offsets/matchinfo |
| 2400 ** evaluation, only create segment-readers if there are no Fts3DeferredToken |
| 2401 ** objects attached to the phrase-tokens. |
| 2402 */ |
| 2403 for(ii=0; ii<pPhrase->nToken; ii++){ |
| 2404 Fts3PhraseToken *pTok = &pPhrase->aToken[ii]; |
| 2405 if( pTok->pSegcsr==0 ){ |
| 2406 if( (pCsr->eEvalmode==FTS3_EVAL_FILTER) |
| 2407 || (pCsr->eEvalmode==FTS3_EVAL_NEXT && pCsr->pDeferred==0) |
| 2408 || (pCsr->eEvalmode==FTS3_EVAL_MATCHINFO && pTok->bFulltext) |
| 2409 ){ |
| 2410 rc = fts3TermSegReaderCursor( |
| 2411 pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pSegcsr |
| 2412 ); |
| 2413 if( rc!=SQLITE_OK ) return rc; |
| 2414 } |
| 2415 } |
| 2416 } |
| 2417 |
| 2418 for(ii=0; ii<pPhrase->nToken; ii++){ |
| 2419 Fts3PhraseToken *pTok; /* Token to find doclist for */ |
| 2420 int iTok = 0; /* The token being queried this iteration */ |
| 2421 char *pList = 0; /* Pointer to token doclist */ |
| 2422 int nList = 0; /* Size of buffer at pList */ |
| 2423 |
| 2424 /* Select a token to process. If this is an xFilter() call, then tokens |
| 2425 ** are processed in order from least to most costly. Otherwise, tokens |
| 2426 ** are processed in the order in which they occur in the phrase. |
| 2427 */ |
| 2428 if( pCsr->eEvalmode==FTS3_EVAL_MATCHINFO ){ |
| 2429 assert( isReqPos ); |
| 2430 iTok = ii; |
| 2431 pTok = &pPhrase->aToken[iTok]; |
| 2432 if( pTok->bFulltext==0 ) continue; |
| 2433 }else if( pCsr->eEvalmode==FTS3_EVAL_NEXT || isReqPos ){ |
| 2434 iTok = ii; |
| 2435 pTok = &pPhrase->aToken[iTok]; |
| 2436 }else{ |
| 2437 int nMinCost = 0x7FFFFFFF; |
| 2438 int jj; |
| 2439 |
| 2440 /* Find the remaining token with the lowest cost. */ |
| 2441 for(jj=0; jj<pPhrase->nToken; jj++){ |
| 2442 Fts3SegReaderCursor *pSegcsr = pPhrase->aToken[jj].pSegcsr; |
| 2443 if( pSegcsr && pSegcsr->nCost<nMinCost ){ |
| 2444 iTok = jj; |
| 2445 nMinCost = pSegcsr->nCost; |
| 2446 } |
| 2447 } |
| 2448 pTok = &pPhrase->aToken[iTok]; |
| 2449 |
| 2450 /* This branch is taken if it is determined that loading the doclist |
| 2451 ** for the next token would require more IO than loading all documents |
| 2452 ** currently identified by doclist pOut/nOut. No further doclists will |
| 2453 ** be loaded from the full-text index for this phrase. |
| 2454 */ |
| 2455 if( nMinCost>nDoc && ii>0 ){ |
| 2456 rc = fts3DeferExpression(pCsr, pCsr->pExpr); |
| 2457 break; |
| 2458 } |
| 2459 } |
| 2460 |
| 2461 if( pCsr->eEvalmode==FTS3_EVAL_NEXT && pTok->pDeferred ){ |
| 2462 rc = fts3DeferredTermSelect(pTok->pDeferred, isTermPos, &nList, &pList); |
| 2463 }else{ |
| 2464 if( pTok->pSegcsr ){ |
| 2465 rc = fts3TermSelect(p, pTok, iCol, isTermPos, &nList, &pList); |
| 2466 } |
| 2467 pTok->bFulltext = 1; |
| 2468 } |
| 2469 assert( rc!=SQLITE_OK || pCsr->eEvalmode || pTok->pSegcsr==0 ); |
| 2470 if( rc!=SQLITE_OK ) break; |
| 2471 |
| 2472 if( isFirst ){ |
| 2473 pOut = pList; |
| 2474 nOut = nList; |
| 2475 if( pCsr->eEvalmode==FTS3_EVAL_FILTER && pPhrase->nToken>1 ){ |
| 2476 nDoc = fts3DoclistCountDocids(1, pOut, nOut); |
| 2477 } |
| 2478 isFirst = 0; |
| 2479 iPrevTok = iTok; |
| 2480 }else{ |
| 2481 /* Merge the new term list and the current output. */ |
| 2482 char *aLeft, *aRight; |
| 2483 int nLeft, nRight; |
| 2484 int nDist; |
| 2485 int mt; |
| 2486 |
| 2487 /* If this is the final token of the phrase, and positions were not |
| 2488 ** requested by the caller, use MERGE_PHRASE instead of POS_PHRASE. |
| 2489 ** This drops the position information from the output list. |
| 2490 */ |
| 2491 mt = MERGE_POS_PHRASE; |
| 2492 if( ii==pPhrase->nToken-1 && !isReqPos ) mt = MERGE_PHRASE; |
| 2493 |
| 2494 assert( iPrevTok!=iTok ); |
| 2495 if( iPrevTok<iTok ){ |
| 2496 aLeft = pOut; |
| 2497 nLeft = nOut; |
| 2498 aRight = pList; |
| 2499 nRight = nList; |
| 2500 nDist = iTok-iPrevTok; |
| 2501 iPrevTok = iTok; |
| 2502 }else{ |
| 2503 aRight = pOut; |
| 2504 nRight = nOut; |
| 2505 aLeft = pList; |
| 2506 nLeft = nList; |
| 2507 nDist = iPrevTok-iTok; |
| 2508 } |
| 2509 pOut = aRight; |
| 2510 fts3DoclistMerge( |
| 2511 mt, nDist, 0, pOut, &nOut, aLeft, nLeft, aRight, nRight, &nDoc |
| 2512 ); |
| 2513 sqlite3_free(aLeft); |
| 2514 } |
| 2515 assert( nOut==0 || pOut!=0 ); |
| 2516 } |
| 2517 |
| 2518 if( rc==SQLITE_OK ){ |
| 2519 if( ii!=pPhrase->nToken ){ |
| 2520 assert( pCsr->eEvalmode==FTS3_EVAL_FILTER && isReqPos==0 ); |
| 2521 fts3DoclistStripPositions(pOut, &nOut); |
| 2522 } |
| 2523 *paOut = pOut; |
| 2524 *pnOut = nOut; |
| 2525 }else{ |
| 2526 sqlite3_free(pOut); |
| 2527 } |
| 2528 return rc; |
| 2529 } |
| 2530 |
| 2531 /* |
| 2532 ** This function merges two doclists according to the requirements of a |
| 2533 ** NEAR operator. |
| 2534 ** |
| 2535 ** Both input doclists must include position information. The output doclist |
| 2536 ** includes position information if the first argument to this function |
| 2537 ** is MERGE_POS_NEAR, or does not if it is MERGE_NEAR. |
| 2538 */ |
| 2539 static int fts3NearMerge( |
| 2540 int mergetype, /* MERGE_POS_NEAR or MERGE_NEAR */ |
| 2541 int nNear, /* Parameter to NEAR operator */ |
| 2542 int nTokenLeft, /* Number of tokens in LHS phrase arg */ |
| 2543 char *aLeft, /* Doclist for LHS (incl. positions) */ |
| 2544 int nLeft, /* Size of LHS doclist in bytes */ |
| 2545 int nTokenRight, /* As nTokenLeft */ |
| 2546 char *aRight, /* As aLeft */ |
| 2547 int nRight, /* As nRight */ |
| 2548 char **paOut, /* OUT: Results of merge (malloced) */ |
| 2549 int *pnOut /* OUT: Sized of output buffer */ |
| 2550 ){ |
| 2551 char *aOut; /* Buffer to write output doclist to */ |
| 2552 int rc; /* Return code */ |
| 2553 |
| 2554 assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR ); |
| 2555 |
| 2556 aOut = sqlite3_malloc(nLeft+nRight+1); |
| 2557 if( aOut==0 ){ |
| 2558 rc = SQLITE_NOMEM; |
| 2559 }else{ |
| 2560 rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft, |
| 2561 aOut, pnOut, aLeft, nLeft, aRight, nRight, 0 |
| 2562 ); |
| 2563 if( rc!=SQLITE_OK ){ |
| 2564 sqlite3_free(aOut); |
| 2565 aOut = 0; |
| 2566 } |
| 2567 } |
| 2568 |
| 2569 *paOut = aOut; |
| 2570 return rc; |
| 2571 } |
| 2572 |
| 2573 /* |
| 2574 ** This function is used as part of the processing for the snippet() and |
| 2575 ** offsets() functions. |
| 2576 ** |
| 2577 ** Both pLeft and pRight are expression nodes of type FTSQUERY_PHRASE. Both |
| 2578 ** have their respective doclists (including position information) loaded |
| 2579 ** in Fts3Expr.aDoclist/nDoclist. This function removes all entries from |
| 2580 ** each doclist that are not within nNear tokens of a corresponding entry |
| 2581 ** in the other doclist. |
| 2582 */ |
| 2583 int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){ |
| 2584 int rc; /* Return code */ |
| 2585 |
| 2586 assert( pLeft->eType==FTSQUERY_PHRASE ); |
| 2587 assert( pRight->eType==FTSQUERY_PHRASE ); |
| 2588 assert( pLeft->isLoaded && pRight->isLoaded ); |
| 2589 |
| 2590 if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){ |
| 2591 sqlite3_free(pLeft->aDoclist); |
| 2592 sqlite3_free(pRight->aDoclist); |
| 2593 pRight->aDoclist = 0; |
| 2594 pLeft->aDoclist = 0; |
| 2595 rc = SQLITE_OK; |
| 2596 }else{ |
| 2597 char *aOut; /* Buffer in which to assemble new doclist */ |
| 2598 int nOut; /* Size of buffer aOut in bytes */ |
| 2599 |
| 2600 rc = fts3NearMerge(MERGE_POS_NEAR, nNear, |
| 2601 pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist, |
| 2602 pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist, |
| 2603 &aOut, &nOut |
| 2604 ); |
| 2605 if( rc!=SQLITE_OK ) return rc; |
| 2606 sqlite3_free(pRight->aDoclist); |
| 2607 pRight->aDoclist = aOut; |
| 2608 pRight->nDoclist = nOut; |
| 2609 |
| 2610 rc = fts3NearMerge(MERGE_POS_NEAR, nNear, |
| 2611 pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist, |
| 2612 pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist, |
| 2613 &aOut, &nOut |
| 2614 ); |
| 2615 sqlite3_free(pLeft->aDoclist); |
| 2616 pLeft->aDoclist = aOut; |
| 2617 pLeft->nDoclist = nOut; |
| 2618 } |
| 2619 return rc; |
| 2620 } |
| 2621 |
| 2622 |
| 2623 /* |
| 2624 ** Allocate an Fts3SegReaderArray for each token in the expression pExpr. |
| 2625 ** The allocated objects are stored in the Fts3PhraseToken.pArray member |
| 2626 ** variables of each token structure. |
| 2627 */ |
| 2628 static int fts3ExprAllocateSegReaders( |
| 2629 Fts3Cursor *pCsr, /* FTS3 table */ |
| 2630 Fts3Expr *pExpr, /* Expression to create seg-readers for */ |
| 2631 int *pnExpr /* OUT: Number of AND'd expressions */ |
| 2632 ){ |
| 2633 int rc = SQLITE_OK; /* Return code */ |
| 2634 |
| 2635 assert( pCsr->eEvalmode==FTS3_EVAL_FILTER ); |
| 2636 if( pnExpr && pExpr->eType!=FTSQUERY_AND ){ |
| 2637 (*pnExpr)++; |
| 2638 pnExpr = 0; |
| 2639 } |
| 2640 |
| 2641 if( pExpr->eType==FTSQUERY_PHRASE ){ |
| 2642 Fts3Phrase *pPhrase = pExpr->pPhrase; |
| 2643 int ii; |
| 2644 |
| 2645 for(ii=0; rc==SQLITE_OK && ii<pPhrase->nToken; ii++){ |
| 2646 Fts3PhraseToken *pTok = &pPhrase->aToken[ii]; |
| 2647 if( pTok->pSegcsr==0 ){ |
| 2648 rc = fts3TermSegReaderCursor( |
| 2649 pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pSegcsr |
| 2650 ); |
| 2651 } |
| 2652 } |
| 2653 }else{ |
| 2654 rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pLeft, pnExpr); |
| 2655 if( rc==SQLITE_OK ){ |
| 2656 rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pRight, pnExpr); |
| 2657 } |
| 2658 } |
| 2659 return rc; |
| 2660 } |
| 2661 |
| 2662 /* |
| 2663 ** Free the Fts3SegReaderArray objects associated with each token in the |
| 2664 ** expression pExpr. In other words, this function frees the resources |
| 2665 ** allocated by fts3ExprAllocateSegReaders(). |
| 2666 */ |
| 2667 static void fts3ExprFreeSegReaders(Fts3Expr *pExpr){ |
| 2668 if( pExpr ){ |
| 2669 Fts3Phrase *pPhrase = pExpr->pPhrase; |
| 2670 if( pPhrase ){ |
| 2671 int kk; |
| 2672 for(kk=0; kk<pPhrase->nToken; kk++){ |
| 2673 fts3SegReaderCursorFree(pPhrase->aToken[kk].pSegcsr); |
| 2674 pPhrase->aToken[kk].pSegcsr = 0; |
| 2675 } |
| 2676 } |
| 2677 fts3ExprFreeSegReaders(pExpr->pLeft); |
| 2678 fts3ExprFreeSegReaders(pExpr->pRight); |
| 2679 } |
| 2680 } |
| 2681 |
| 2682 /* |
| 2683 ** Return the sum of the costs of all tokens in the expression pExpr. This |
| 2684 ** function must be called after Fts3SegReaderArrays have been allocated |
| 2685 ** for all tokens using fts3ExprAllocateSegReaders(). |
| 2686 */ |
| 2687 static int fts3ExprCost(Fts3Expr *pExpr){ |
| 2688 int nCost; /* Return value */ |
| 2689 if( pExpr->eType==FTSQUERY_PHRASE ){ |
| 2690 Fts3Phrase *pPhrase = pExpr->pPhrase; |
| 2691 int ii; |
| 2692 nCost = 0; |
| 2693 for(ii=0; ii<pPhrase->nToken; ii++){ |
| 2694 Fts3SegReaderCursor *pSegcsr = pPhrase->aToken[ii].pSegcsr; |
| 2695 if( pSegcsr ) nCost += pSegcsr->nCost; |
| 2696 } |
| 2697 }else{ |
| 2698 nCost = fts3ExprCost(pExpr->pLeft) + fts3ExprCost(pExpr->pRight); |
| 2699 } |
| 2700 return nCost; |
| 2701 } |
| 2702 |
| 2703 /* |
| 2704 ** The following is a helper function (and type) for fts3EvalExpr(). It |
| 2705 ** must be called after Fts3SegReaders have been allocated for every token |
| 2706 ** in the expression. See the context it is called from in fts3EvalExpr() |
| 2707 ** for further explanation. |
| 2708 */ |
| 2709 typedef struct ExprAndCost ExprAndCost; |
| 2710 struct ExprAndCost { |
| 2711 Fts3Expr *pExpr; |
| 2712 int nCost; |
| 2713 }; |
| 2714 static void fts3ExprAssignCosts( |
| 2715 Fts3Expr *pExpr, /* Expression to create seg-readers for */ |
| 2716 ExprAndCost **ppExprCost /* OUT: Write to *ppExprCost */ |
| 2717 ){ |
| 2718 if( pExpr->eType==FTSQUERY_AND ){ |
| 2719 fts3ExprAssignCosts(pExpr->pLeft, ppExprCost); |
| 2720 fts3ExprAssignCosts(pExpr->pRight, ppExprCost); |
| 2721 }else{ |
| 2722 (*ppExprCost)->pExpr = pExpr; |
| 2723 (*ppExprCost)->nCost = fts3ExprCost(pExpr); |
| 2724 (*ppExprCost)++; |
| 2725 } |
| 2726 } |
| 2727 |
| 2728 /* |
| 2729 ** Evaluate the full-text expression pExpr against FTS3 table pTab. Store |
| 2730 ** the resulting doclist in *paOut and *pnOut. This routine mallocs for |
| 2731 ** the space needed to store the output. The caller is responsible for |
| 2732 ** freeing the space when it has finished. |
| 2733 ** |
| 2734 ** This function is called in two distinct contexts: |
| 2735 ** |
| 2736 ** * From within the virtual table xFilter() method. In this case, the |
| 2737 ** output doclist contains entries for all rows in the table, based on |
| 2738 ** data read from the full-text index. |
| 2739 ** |
| 2740 ** In this case, if the query expression contains one or more tokens that |
| 2741 ** are very common, then the returned doclist may contain a superset of |
| 2742 ** the documents that actually match the expression. |
| 2743 ** |
| 2744 ** * From within the virtual table xNext() method. This call is only made |
| 2745 ** if the call from within xFilter() found that there were very common |
| 2746 ** tokens in the query expression and did return a superset of the |
| 2747 ** matching documents. In this case the returned doclist contains only |
| 2748 ** entries that correspond to the current row of the table. Instead of |
| 2749 ** reading the data for each token from the full-text index, the data is |
| 2750 ** already available in-memory in the Fts3PhraseToken.pDeferred structures. |
| 2751 ** See fts3EvalDeferred() for how it gets there. |
| 2752 ** |
| 2753 ** In the first case above, Fts3Cursor.doDeferred==0. In the second (if it is |
| 2754 ** required) Fts3Cursor.doDeferred==1. |
| 2755 ** |
| 2756 ** If the SQLite invokes the snippet(), offsets() or matchinfo() function |
| 2757 ** as part of a SELECT on an FTS3 table, this function is called on each |
| 2758 ** individual phrase expression in the query. If there were very common tokens |
| 2759 ** found in the xFilter() call, then this function is called once for phrase |
| 2760 ** for each row visited, and the returned doclist contains entries for the |
| 2761 ** current row only. Otherwise, if there were no very common tokens, then this |
| 2762 ** function is called once only for each phrase in the query and the returned |
| 2763 ** doclist contains entries for all rows of the table. |
| 2764 ** |
| 2765 ** Fts3Cursor.doDeferred==1 when this function is called on phrases as a |
| 2766 ** result of a snippet(), offsets() or matchinfo() invocation. |
| 2767 */ |
| 2768 static int fts3EvalExpr( |
| 2769 Fts3Cursor *p, /* Virtual table cursor handle */ |
| 2770 Fts3Expr *pExpr, /* Parsed fts3 expression */ |
| 2771 char **paOut, /* OUT: Pointer to malloc'd result buffer */ |
| 2772 int *pnOut, /* OUT: Size of buffer at *paOut */ |
| 2773 int isReqPos /* Require positions in output buffer */ |
| 2774 ){ |
| 2775 int rc = SQLITE_OK; /* Return code */ |
| 2776 |
| 2777 /* Zero the output parameters. */ |
| 2778 *paOut = 0; |
| 2779 *pnOut = 0; |
| 2780 |
| 2781 if( pExpr ){ |
| 2782 assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR |
| 2783 || pExpr->eType==FTSQUERY_AND || pExpr->eType==FTSQUERY_NOT |
| 2784 || pExpr->eType==FTSQUERY_PHRASE |
| 2785 ); |
| 2786 assert( pExpr->eType==FTSQUERY_PHRASE || isReqPos==0 ); |
| 2787 |
| 2788 if( pExpr->eType==FTSQUERY_PHRASE ){ |
| 2789 rc = fts3PhraseSelect(p, pExpr->pPhrase, |
| 2790 isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR), |
| 2791 paOut, pnOut |
| 2792 ); |
| 2793 fts3ExprFreeSegReaders(pExpr); |
| 2794 }else if( p->eEvalmode==FTS3_EVAL_FILTER && pExpr->eType==FTSQUERY_AND ){ |
| 2795 ExprAndCost *aExpr = 0; /* Array of AND'd expressions and costs */ |
| 2796 int nExpr = 0; /* Size of aExpr[] */ |
| 2797 char *aRet = 0; /* Doclist to return to caller */ |
| 2798 int nRet = 0; /* Length of aRet[] in bytes */ |
| 2799 int nDoc = 0x7FFFFFFF; |
| 2800 |
| 2801 assert( !isReqPos ); |
| 2802 |
| 2803 rc = fts3ExprAllocateSegReaders(p, pExpr, &nExpr); |
| 2804 if( rc==SQLITE_OK ){ |
| 2805 assert( nExpr>1 ); |
| 2806 aExpr = sqlite3_malloc(sizeof(ExprAndCost) * nExpr); |
| 2807 if( !aExpr ) rc = SQLITE_NOMEM; |
| 2808 } |
| 2809 if( rc==SQLITE_OK ){ |
| 2810 int ii; /* Used to iterate through expressions */ |
| 2811 |
| 2812 fts3ExprAssignCosts(pExpr, &aExpr); |
| 2813 aExpr -= nExpr; |
| 2814 for(ii=0; ii<nExpr; ii++){ |
| 2815 char *aNew; |
| 2816 int nNew; |
| 2817 int jj; |
| 2818 ExprAndCost *pBest = 0; |
| 2819 |
| 2820 for(jj=0; jj<nExpr; jj++){ |
| 2821 ExprAndCost *pCand = &aExpr[jj]; |
| 2822 if( pCand->pExpr && (pBest==0 || pCand->nCost<pBest->nCost) ){ |
| 2823 pBest = pCand; |
| 2824 } |
| 2825 } |
| 2826 |
| 2827 if( pBest->nCost>nDoc ){ |
| 2828 rc = fts3DeferExpression(p, p->pExpr); |
| 2829 break; |
| 2830 }else{ |
| 2831 rc = fts3EvalExpr(p, pBest->pExpr, &aNew, &nNew, 0); |
| 2832 if( rc!=SQLITE_OK ) break; |
| 2833 pBest->pExpr = 0; |
| 2834 if( ii==0 ){ |
| 2835 aRet = aNew; |
| 2836 nRet = nNew; |
| 2837 nDoc = fts3DoclistCountDocids(0, aRet, nRet); |
| 2838 }else{ |
| 2839 fts3DoclistMerge( |
| 2840 MERGE_AND, 0, 0, aRet, &nRet, aRet, nRet, aNew, nNew, &nDoc |
| 2841 ); |
| 2842 sqlite3_free(aNew); |
| 2843 } |
| 2844 } |
| 2845 } |
| 2846 } |
| 2847 |
| 2848 if( rc==SQLITE_OK ){ |
| 2849 *paOut = aRet; |
| 2850 *pnOut = nRet; |
| 2851 }else{ |
| 2852 assert( *paOut==0 ); |
| 2853 sqlite3_free(aRet); |
| 2854 } |
| 2855 sqlite3_free(aExpr); |
| 2856 fts3ExprFreeSegReaders(pExpr); |
| 2857 |
| 2858 }else{ |
| 2859 char *aLeft; |
| 2860 char *aRight; |
| 2861 int nLeft; |
| 2862 int nRight; |
| 2863 |
| 2864 assert( pExpr->eType==FTSQUERY_NEAR |
| 2865 || pExpr->eType==FTSQUERY_OR |
| 2866 || pExpr->eType==FTSQUERY_NOT |
| 2867 || (pExpr->eType==FTSQUERY_AND && p->eEvalmode==FTS3_EVAL_NEXT) |
| 2868 ); |
| 2869 |
| 2870 if( 0==(rc = fts3EvalExpr(p, pExpr->pRight, &aRight, &nRight, isReqPos)) |
| 2871 && 0==(rc = fts3EvalExpr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos)) |
| 2872 ){ |
| 2873 switch( pExpr->eType ){ |
| 2874 case FTSQUERY_NEAR: { |
| 2875 Fts3Expr *pLeft; |
| 2876 Fts3Expr *pRight; |
| 2877 int mergetype = MERGE_NEAR; |
| 2878 if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){ |
| 2879 mergetype = MERGE_POS_NEAR; |
| 2880 } |
| 2881 pLeft = pExpr->pLeft; |
| 2882 while( pLeft->eType==FTSQUERY_NEAR ){ |
| 2883 pLeft=pLeft->pRight; |
| 2884 } |
| 2885 pRight = pExpr->pRight; |
| 2886 assert( pRight->eType==FTSQUERY_PHRASE ); |
| 2887 assert( pLeft->eType==FTSQUERY_PHRASE ); |
| 2888 |
| 2889 rc = fts3NearMerge(mergetype, pExpr->nNear, |
| 2890 pLeft->pPhrase->nToken, aLeft, nLeft, |
| 2891 pRight->pPhrase->nToken, aRight, nRight, |
| 2892 paOut, pnOut |
| 2893 ); |
| 2894 sqlite3_free(aLeft); |
| 2895 break; |
| 2896 } |
| 2897 |
| 2898 case FTSQUERY_OR: { |
| 2899 /* Allocate a buffer for the output. The maximum size is the |
| 2900 ** sum of the sizes of the two input buffers. The +1 term is |
| 2901 ** so that a buffer of zero bytes is never allocated - this can |
| 2902 ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM. |
| 2903 */ |
| 2904 char *aBuffer = sqlite3_malloc(nRight+nLeft+1); |
| 2905 rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut, |
| 2906 aLeft, nLeft, aRight, nRight, 0 |
| 2907 ); |
| 2908 *paOut = aBuffer; |
| 2909 sqlite3_free(aLeft); |
| 2910 break; |
| 2911 } |
| 2912 |
| 2913 default: { |
| 2914 assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND ); |
| 2915 fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut, |
| 2916 aLeft, nLeft, aRight, nRight, 0 |
| 2917 ); |
| 2918 *paOut = aLeft; |
| 2919 break; |
| 2920 } |
| 2921 } |
| 2922 } |
| 2923 sqlite3_free(aRight); |
| 2924 } |
| 2925 } |
| 2926 |
| 2927 assert( rc==SQLITE_OK || *paOut==0 ); |
| 2928 return rc; |
| 2929 } |
| 2930 |
| 2931 /* |
| 2932 ** This function is called from within xNext() for each row visited by |
| 2933 ** an FTS3 query. If evaluating the FTS3 query expression within xFilter() |
| 2934 ** was able to determine the exact set of matching rows, this function sets |
| 2935 ** *pbRes to true and returns SQLITE_IO immediately. |
| 2936 ** |
| 2937 ** Otherwise, if evaluating the query expression within xFilter() returned a |
| 2938 ** superset of the matching documents instead of an exact set (this happens |
| 2939 ** when the query includes very common tokens and it is deemed too expensive to |
| 2940 ** load their doclists from disk), this function tests if the current row |
| 2941 ** really does match the FTS3 query. |
| 2942 ** |
| 2943 ** If an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK |
| 2944 ** is returned and *pbRes is set to true if the current row matches the |
| 2945 ** FTS3 query (and should be included in the results returned to SQLite), or |
| 2946 ** false otherwise. |
| 2947 */ |
| 2948 static int fts3EvalDeferred( |
| 2949 Fts3Cursor *pCsr, /* FTS3 cursor pointing at row to test */ |
| 2950 int *pbRes /* OUT: Set to true if row is a match */ |
| 2951 ){ |
| 2952 int rc = SQLITE_OK; |
| 2953 if( pCsr->pDeferred==0 ){ |
| 2954 *pbRes = 1; |
| 2955 }else{ |
| 2956 rc = fts3CursorSeek(0, pCsr); |
| 2957 if( rc==SQLITE_OK ){ |
| 2958 sqlite3Fts3FreeDeferredDoclists(pCsr); |
| 2959 rc = sqlite3Fts3CacheDeferredDoclists(pCsr); |
| 2960 } |
| 2961 if( rc==SQLITE_OK ){ |
| 2962 char *a = 0; |
| 2963 int n = 0; |
| 2964 rc = fts3EvalExpr(pCsr, pCsr->pExpr, &a, &n, 0); |
| 2965 assert( n>=0 ); |
| 2966 *pbRes = (n>0); |
| 2967 sqlite3_free(a); |
| 2968 } |
| 2969 } |
| 2970 return rc; |
| 2971 } |
| 2972 |
| 2973 /* |
| 2974 ** Advance the cursor to the next row in the %_content table that |
| 2975 ** matches the search criteria. For a MATCH search, this will be |
| 2976 ** the next row that matches. For a full-table scan, this will be |
| 2977 ** simply the next row in the %_content table. For a docid lookup, |
| 2978 ** this routine simply sets the EOF flag. |
| 2979 ** |
| 2980 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned |
| 2981 ** even if we reach end-of-file. The fts3EofMethod() will be called |
| 2982 ** subsequently to determine whether or not an EOF was hit. |
| 2983 */ |
| 2984 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){ |
| 2985 int res; |
| 2986 int rc = SQLITE_OK; /* Return code */ |
| 2987 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; |
| 2988 |
| 2989 pCsr->eEvalmode = FTS3_EVAL_NEXT; |
| 2990 do { |
| 2991 if( pCsr->aDoclist==0 ){ |
| 2992 if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){ |
| 2993 pCsr->isEof = 1; |
| 2994 rc = sqlite3_reset(pCsr->pStmt); |
| 2995 break; |
| 2996 } |
| 2997 pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0); |
| 2998 }else{ |
| 2999 if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){ |
| 3000 pCsr->isEof = 1; |
| 3001 break; |
| 3002 } |
| 3003 sqlite3_reset(pCsr->pStmt); |
| 3004 fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId); |
| 3005 pCsr->isRequireSeek = 1; |
| 3006 pCsr->isMatchinfoNeeded = 1; |
| 3007 } |
| 3008 }while( SQLITE_OK==(rc = fts3EvalDeferred(pCsr, &res)) && res==0 ); |
| 3009 |
| 3010 return rc; |
| 3011 } |
| 3012 |
| 3013 /* |
| 3014 ** This is the xFilter interface for the virtual table. See |
| 3015 ** the virtual table xFilter method documentation for additional |
| 3016 ** information. |
| 3017 ** |
| 3018 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against |
| 3019 ** the %_content table. |
| 3020 ** |
| 3021 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry |
| 3022 ** in the %_content table. |
| 3023 ** |
| 3024 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The |
| 3025 ** column on the left-hand side of the MATCH operator is column |
| 3026 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand |
| 3027 ** side of the MATCH operator. |
| 3028 */ |
| 3029 static int fts3FilterMethod( |
| 3030 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ |
| 3031 int idxNum, /* Strategy index */ |
| 3032 const char *idxStr, /* Unused */ |
| 3033 int nVal, /* Number of elements in apVal */ |
| 3034 sqlite3_value **apVal /* Arguments for the indexing scheme */ |
| 3035 ){ |
| 3036 const char *azSql[] = { |
| 3037 "SELECT %s FROM %Q.'%q_content' AS x WHERE docid = ?", /* non-full-scan */ |
| 3038 "SELECT %s FROM %Q.'%q_content' AS x ", /* full-scan */ |
| 3039 }; |
| 3040 int rc; /* Return code */ |
| 3041 char *zSql; /* SQL statement used to access %_content */ |
| 3042 Fts3Table *p = (Fts3Table *)pCursor->pVtab; |
| 3043 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; |
| 3044 |
| 3045 UNUSED_PARAMETER(idxStr); |
| 3046 UNUSED_PARAMETER(nVal); |
| 3047 |
| 3048 assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) ); |
| 3049 assert( nVal==0 || nVal==1 ); |
| 3050 assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) ); |
| 3051 assert( p->pSegments==0 ); |
| 3052 |
| 3053 /* In case the cursor has been used before, clear it now. */ |
| 3054 sqlite3_finalize(pCsr->pStmt); |
| 3055 sqlite3_free(pCsr->aDoclist); |
| 3056 sqlite3Fts3ExprFree(pCsr->pExpr); |
| 3057 memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor)); |
| 3058 |
| 3059 if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){ |
| 3060 int iCol = idxNum-FTS3_FULLTEXT_SEARCH; |
| 3061 const char *zQuery = (const char *)sqlite3_value_text(apVal[0]); |
| 3062 |
| 3063 if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ |
| 3064 return SQLITE_NOMEM; |
| 3065 } |
| 3066 |
| 3067 rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn, |
| 3068 iCol, zQuery, -1, &pCsr->pExpr |
| 3069 ); |
| 3070 if( rc!=SQLITE_OK ){ |
| 3071 if( rc==SQLITE_ERROR ){ |
| 3072 p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]", |
| 3073 zQuery); |
| 3074 } |
| 3075 return rc; |
| 3076 } |
| 3077 |
| 3078 rc = sqlite3Fts3ReadLock(p); |
| 3079 if( rc!=SQLITE_OK ) return rc; |
| 3080 |
| 3081 rc = fts3EvalExpr(pCsr, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0); |
| 3082 sqlite3Fts3SegmentsClose(p); |
| 3083 if( rc!=SQLITE_OK ) return rc; |
| 3084 pCsr->pNextId = pCsr->aDoclist; |
| 3085 pCsr->iPrevId = 0; |
| 3086 } |
| 3087 |
| 3088 /* Compile a SELECT statement for this cursor. For a full-table-scan, the |
| 3089 ** statement loops through all rows of the %_content table. For a |
| 3090 ** full-text query or docid lookup, the statement retrieves a single |
| 3091 ** row by docid. |
| 3092 */ |
| 3093 zSql = (char *)azSql[idxNum==FTS3_FULLSCAN_SEARCH]; |
| 3094 zSql = sqlite3_mprintf(zSql, p->zReadExprlist, p->zDb, p->zName); |
| 3095 if( !zSql ){ |
| 3096 rc = SQLITE_NOMEM; |
| 3097 }else{ |
| 3098 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0); |
| 3099 sqlite3_free(zSql); |
| 3100 } |
| 3101 if( rc==SQLITE_OK && idxNum==FTS3_DOCID_SEARCH ){ |
| 3102 rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]); |
| 3103 } |
| 3104 pCsr->eSearch = (i16)idxNum; |
| 3105 |
| 3106 if( rc!=SQLITE_OK ) return rc; |
| 3107 return fts3NextMethod(pCursor); |
| 3108 } |
| 3109 |
| 3110 /* |
| 3111 ** This is the xEof method of the virtual table. SQLite calls this |
| 3112 ** routine to find out if it has reached the end of a result set. |
| 3113 */ |
| 3114 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){ |
| 3115 return ((Fts3Cursor *)pCursor)->isEof; |
| 3116 } |
| 3117 |
| 3118 /* |
| 3119 ** This is the xRowid method. The SQLite core calls this routine to |
| 3120 ** retrieve the rowid for the current row of the result set. fts3 |
| 3121 ** exposes %_content.docid as the rowid for the virtual table. The |
| 3122 ** rowid should be written to *pRowid. |
| 3123 */ |
| 3124 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ |
| 3125 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor; |
| 3126 if( pCsr->aDoclist ){ |
| 3127 *pRowid = pCsr->iPrevId; |
| 3128 }else{ |
| 3129 /* This branch runs if the query is implemented using a full-table scan |
| 3130 ** (not using the full-text index). In this case grab the rowid from the |
| 3131 ** SELECT statement. |
| 3132 */ |
| 3133 assert( pCsr->isRequireSeek==0 ); |
| 3134 *pRowid = sqlite3_column_int64(pCsr->pStmt, 0); |
| 3135 } |
| 3136 return SQLITE_OK; |
| 3137 } |
| 3138 |
| 3139 /* |
| 3140 ** This is the xColumn method, called by SQLite to request a value from |
| 3141 ** the row that the supplied cursor currently points to. |
| 3142 */ |
| 3143 static int fts3ColumnMethod( |
| 3144 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ |
| 3145 sqlite3_context *pContext, /* Context for sqlite3_result_xxx() calls */ |
| 3146 int iCol /* Index of column to read value from */ |
| 3147 ){ |
| 3148 int rc; /* Return Code */ |
| 3149 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor; |
| 3150 Fts3Table *p = (Fts3Table *)pCursor->pVtab; |
| 3151 |
| 3152 /* The column value supplied by SQLite must be in range. */ |
| 3153 assert( iCol>=0 && iCol<=p->nColumn+1 ); |
| 3154 |
| 3155 if( iCol==p->nColumn+1 ){ |
| 3156 /* This call is a request for the "docid" column. Since "docid" is an |
| 3157 ** alias for "rowid", use the xRowid() method to obtain the value. |
| 3158 */ |
| 3159 sqlite3_int64 iRowid; |
| 3160 rc = fts3RowidMethod(pCursor, &iRowid); |
| 3161 sqlite3_result_int64(pContext, iRowid); |
| 3162 }else if( iCol==p->nColumn ){ |
| 3163 /* The extra column whose name is the same as the table. |
| 3164 ** Return a blob which is a pointer to the cursor. |
| 3165 */ |
| 3166 sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT); |
| 3167 rc = SQLITE_OK; |
| 3168 }else{ |
| 3169 rc = fts3CursorSeek(0, pCsr); |
| 3170 if( rc==SQLITE_OK ){ |
| 3171 sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1)); |
| 3172 } |
| 3173 } |
| 3174 return rc; |
| 3175 } |
| 3176 |
| 3177 /* |
| 3178 ** This function is the implementation of the xUpdate callback used by |
| 3179 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be |
| 3180 ** inserted, updated or deleted. |
| 3181 */ |
| 3182 static int fts3UpdateMethod( |
| 3183 sqlite3_vtab *pVtab, /* Virtual table handle */ |
| 3184 int nArg, /* Size of argument array */ |
| 3185 sqlite3_value **apVal, /* Array of arguments */ |
| 3186 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ |
| 3187 ){ |
| 3188 return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid); |
| 3189 } |
| 3190 |
| 3191 /* |
| 3192 ** Implementation of xSync() method. Flush the contents of the pending-terms |
| 3193 ** hash-table to the database. |
| 3194 */ |
| 3195 static int fts3SyncMethod(sqlite3_vtab *pVtab){ |
| 3196 int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab); |
| 3197 sqlite3Fts3SegmentsClose((Fts3Table *)pVtab); |
| 3198 return rc; |
| 3199 } |
| 3200 |
| 3201 /* |
| 3202 ** Implementation of xBegin() method. This is a no-op. |
| 3203 */ |
| 3204 static int fts3BeginMethod(sqlite3_vtab *pVtab){ |
| 3205 UNUSED_PARAMETER(pVtab); |
| 3206 assert( ((Fts3Table *)pVtab)->nPendingData==0 ); |
| 3207 return SQLITE_OK; |
| 3208 } |
| 3209 |
| 3210 /* |
| 3211 ** Implementation of xCommit() method. This is a no-op. The contents of |
| 3212 ** the pending-terms hash-table have already been flushed into the database |
| 3213 ** by fts3SyncMethod(). |
| 3214 */ |
| 3215 static int fts3CommitMethod(sqlite3_vtab *pVtab){ |
| 3216 UNUSED_PARAMETER(pVtab); |
| 3217 assert( ((Fts3Table *)pVtab)->nPendingData==0 ); |
| 3218 return SQLITE_OK; |
| 3219 } |
| 3220 |
| 3221 /* |
| 3222 ** Implementation of xRollback(). Discard the contents of the pending-terms |
| 3223 ** hash-table. Any changes made to the database are reverted by SQLite. |
| 3224 */ |
| 3225 static int fts3RollbackMethod(sqlite3_vtab *pVtab){ |
| 3226 sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab); |
| 3227 return SQLITE_OK; |
| 3228 } |
| 3229 |
| 3230 /* |
| 3231 ** Load the doclist associated with expression pExpr to pExpr->aDoclist. |
| 3232 ** The loaded doclist contains positions as well as the document ids. |
| 3233 ** This is used by the matchinfo(), snippet() and offsets() auxillary |
| 3234 ** functions. |
| 3235 */ |
| 3236 int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *pCsr, Fts3Expr *pExpr){ |
| 3237 int rc; |
| 3238 assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase ); |
| 3239 assert( pCsr->eEvalmode==FTS3_EVAL_NEXT ); |
| 3240 rc = fts3EvalExpr(pCsr, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1); |
| 3241 return rc; |
| 3242 } |
| 3243 |
| 3244 int sqlite3Fts3ExprLoadFtDoclist( |
| 3245 Fts3Cursor *pCsr, |
| 3246 Fts3Expr *pExpr, |
| 3247 char **paDoclist, |
| 3248 int *pnDoclist |
| 3249 ){ |
| 3250 int rc; |
| 3251 assert( pCsr->eEvalmode==FTS3_EVAL_NEXT ); |
| 3252 assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase ); |
| 3253 pCsr->eEvalmode = FTS3_EVAL_MATCHINFO; |
| 3254 rc = fts3EvalExpr(pCsr, pExpr, paDoclist, pnDoclist, 1); |
| 3255 pCsr->eEvalmode = FTS3_EVAL_NEXT; |
| 3256 return rc; |
| 3257 } |
| 3258 |
| 3259 /* |
| 3260 ** After ExprLoadDoclist() (see above) has been called, this function is |
| 3261 ** used to iterate/search through the position lists that make up the doclist |
| 3262 ** stored in pExpr->aDoclist. |
| 3263 */ |
| 3264 char *sqlite3Fts3FindPositions( |
| 3265 Fts3Expr *pExpr, /* Access this expressions doclist */ |
| 3266 sqlite3_int64 iDocid, /* Docid associated with requested pos-list */ |
| 3267 int iCol /* Column of requested pos-list */ |
| 3268 ){ |
| 3269 assert( pExpr->isLoaded ); |
| 3270 if( pExpr->aDoclist ){ |
| 3271 char *pEnd = &pExpr->aDoclist[pExpr->nDoclist]; |
| 3272 char *pCsr; |
| 3273 |
| 3274 if( pExpr->pCurrent==0 ){ |
| 3275 pExpr->pCurrent = pExpr->aDoclist; |
| 3276 pExpr->iCurrent = 0; |
| 3277 pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent,&pExpr->iCurrent); |
| 3278 } |
| 3279 pCsr = pExpr->pCurrent; |
| 3280 assert( pCsr ); |
| 3281 |
| 3282 while( pCsr<pEnd ){ |
| 3283 if( pExpr->iCurrent<iDocid ){ |
| 3284 fts3PoslistCopy(0, &pCsr); |
| 3285 if( pCsr<pEnd ){ |
| 3286 fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent); |
| 3287 } |
| 3288 pExpr->pCurrent = pCsr; |
| 3289 }else{ |
| 3290 if( pExpr->iCurrent==iDocid ){ |
| 3291 int iThis = 0; |
| 3292 if( iCol<0 ){ |
| 3293 /* If iCol is negative, return a pointer to the start of the |
| 3294 ** position-list (instead of a pointer to the start of a list |
| 3295 ** of offsets associated with a specific column). |
| 3296 */ |
| 3297 return pCsr; |
| 3298 } |
| 3299 while( iThis<iCol ){ |
| 3300 fts3ColumnlistCopy(0, &pCsr); |
| 3301 if( *pCsr==0x00 ) return 0; |
| 3302 pCsr++; |
| 3303 pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis); |
| 3304 } |
| 3305 if( iCol==iThis && (*pCsr&0xFE) ) return pCsr; |
| 3306 } |
| 3307 return 0; |
| 3308 } |
| 3309 } |
| 3310 } |
| 3311 |
| 3312 return 0; |
| 3313 } |
| 3314 |
| 3315 /* |
| 3316 ** Helper function used by the implementation of the overloaded snippet(), |
| 3317 ** offsets() and optimize() SQL functions. |
| 3318 ** |
| 3319 ** If the value passed as the third argument is a blob of size |
| 3320 ** sizeof(Fts3Cursor*), then the blob contents are copied to the |
| 3321 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error |
| 3322 ** message is written to context pContext and SQLITE_ERROR returned. The |
| 3323 ** string passed via zFunc is used as part of the error message. |
| 3324 */ |
| 3325 static int fts3FunctionArg( |
| 3326 sqlite3_context *pContext, /* SQL function call context */ |
| 3327 const char *zFunc, /* Function name */ |
| 3328 sqlite3_value *pVal, /* argv[0] passed to function */ |
| 3329 Fts3Cursor **ppCsr /* OUT: Store cursor handle here */ |
| 3330 ){ |
| 3331 Fts3Cursor *pRet; |
| 3332 if( sqlite3_value_type(pVal)!=SQLITE_BLOB |
| 3333 || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *) |
| 3334 ){ |
| 3335 char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc); |
| 3336 sqlite3_result_error(pContext, zErr, -1); |
| 3337 sqlite3_free(zErr); |
| 3338 return SQLITE_ERROR; |
| 3339 } |
| 3340 memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *)); |
| 3341 *ppCsr = pRet; |
| 3342 return SQLITE_OK; |
| 3343 } |
| 3344 |
| 3345 /* |
| 3346 ** Implementation of the snippet() function for FTS3 |
| 3347 */ |
| 3348 static void fts3SnippetFunc( |
| 3349 sqlite3_context *pContext, /* SQLite function call context */ |
| 3350 int nVal, /* Size of apVal[] array */ |
| 3351 sqlite3_value **apVal /* Array of arguments */ |
| 3352 ){ |
| 3353 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ |
| 3354 const char *zStart = "<b>"; |
| 3355 const char *zEnd = "</b>"; |
| 3356 const char *zEllipsis = "<b>...</b>"; |
| 3357 int iCol = -1; |
| 3358 int nToken = 15; /* Default number of tokens in snippet */ |
| 3359 |
| 3360 /* There must be at least one argument passed to this function (otherwise |
| 3361 ** the non-overloaded version would have been called instead of this one). |
| 3362 */ |
| 3363 assert( nVal>=1 ); |
| 3364 |
| 3365 if( nVal>6 ){ |
| 3366 sqlite3_result_error(pContext, |
| 3367 "wrong number of arguments to function snippet()", -1); |
| 3368 return; |
| 3369 } |
| 3370 if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return; |
| 3371 |
| 3372 switch( nVal ){ |
| 3373 case 6: nToken = sqlite3_value_int(apVal[5]); |
| 3374 case 5: iCol = sqlite3_value_int(apVal[4]); |
| 3375 case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]); |
| 3376 case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]); |
| 3377 case 2: zStart = (const char*)sqlite3_value_text(apVal[1]); |
| 3378 } |
| 3379 if( !zEllipsis || !zEnd || !zStart ){ |
| 3380 sqlite3_result_error_nomem(pContext); |
| 3381 }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ |
| 3382 sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken); |
| 3383 } |
| 3384 } |
| 3385 |
| 3386 /* |
| 3387 ** Implementation of the offsets() function for FTS3 |
| 3388 */ |
| 3389 static void fts3OffsetsFunc( |
| 3390 sqlite3_context *pContext, /* SQLite function call context */ |
| 3391 int nVal, /* Size of argument array */ |
| 3392 sqlite3_value **apVal /* Array of arguments */ |
| 3393 ){ |
| 3394 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ |
| 3395 |
| 3396 UNUSED_PARAMETER(nVal); |
| 3397 |
| 3398 assert( nVal==1 ); |
| 3399 if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return; |
| 3400 assert( pCsr ); |
| 3401 if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ |
| 3402 sqlite3Fts3Offsets(pContext, pCsr); |
| 3403 } |
| 3404 } |
| 3405 |
| 3406 /* |
| 3407 ** Implementation of the special optimize() function for FTS3. This |
| 3408 ** function merges all segments in the database to a single segment. |
| 3409 ** Example usage is: |
| 3410 ** |
| 3411 ** SELECT optimize(t) FROM t LIMIT 1; |
| 3412 ** |
| 3413 ** where 't' is the name of an FTS3 table. |
| 3414 */ |
| 3415 static void fts3OptimizeFunc( |
| 3416 sqlite3_context *pContext, /* SQLite function call context */ |
| 3417 int nVal, /* Size of argument array */ |
| 3418 sqlite3_value **apVal /* Array of arguments */ |
| 3419 ){ |
| 3420 int rc; /* Return code */ |
| 3421 Fts3Table *p; /* Virtual table handle */ |
| 3422 Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */ |
| 3423 |
| 3424 UNUSED_PARAMETER(nVal); |
| 3425 |
| 3426 assert( nVal==1 ); |
| 3427 if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return; |
| 3428 p = (Fts3Table *)pCursor->base.pVtab; |
| 3429 assert( p ); |
| 3430 |
| 3431 rc = sqlite3Fts3Optimize(p); |
| 3432 |
| 3433 switch( rc ){ |
| 3434 case SQLITE_OK: |
| 3435 sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC); |
| 3436 break; |
| 3437 case SQLITE_DONE: |
| 3438 sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC); |
| 3439 break; |
| 3440 default: |
| 3441 sqlite3_result_error_code(pContext, rc); |
| 3442 break; |
| 3443 } |
| 3444 } |
| 3445 |
| 3446 /* |
| 3447 ** Implementation of the matchinfo() function for FTS3 |
| 3448 */ |
| 3449 static void fts3MatchinfoFunc( |
| 3450 sqlite3_context *pContext, /* SQLite function call context */ |
| 3451 int nVal, /* Size of argument array */ |
| 3452 sqlite3_value **apVal /* Array of arguments */ |
| 3453 ){ |
| 3454 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ |
| 3455 assert( nVal==1 || nVal==2 ); |
| 3456 if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){ |
| 3457 const char *zArg = 0; |
| 3458 if( nVal>1 ){ |
| 3459 zArg = (const char *)sqlite3_value_text(apVal[1]); |
| 3460 } |
| 3461 sqlite3Fts3Matchinfo(pContext, pCsr, zArg); |
| 3462 } |
| 3463 } |
| 3464 |
| 3465 /* |
| 3466 ** This routine implements the xFindFunction method for the FTS3 |
| 3467 ** virtual table. |
| 3468 */ |
| 3469 static int fts3FindFunctionMethod( |
| 3470 sqlite3_vtab *pVtab, /* Virtual table handle */ |
| 3471 int nArg, /* Number of SQL function arguments */ |
| 3472 const char *zName, /* Name of SQL function */ |
| 3473 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ |
| 3474 void **ppArg /* Unused */ |
| 3475 ){ |
| 3476 struct Overloaded { |
| 3477 const char *zName; |
| 3478 void (*xFunc)(sqlite3_context*,int,sqlite3_value**); |
| 3479 } aOverload[] = { |
| 3480 { "snippet", fts3SnippetFunc }, |
| 3481 { "offsets", fts3OffsetsFunc }, |
| 3482 { "optimize", fts3OptimizeFunc }, |
| 3483 { "matchinfo", fts3MatchinfoFunc }, |
| 3484 }; |
| 3485 int i; /* Iterator variable */ |
| 3486 |
| 3487 UNUSED_PARAMETER(pVtab); |
| 3488 UNUSED_PARAMETER(nArg); |
| 3489 UNUSED_PARAMETER(ppArg); |
| 3490 |
| 3491 for(i=0; i<SizeofArray(aOverload); i++){ |
| 3492 if( strcmp(zName, aOverload[i].zName)==0 ){ |
| 3493 *pxFunc = aOverload[i].xFunc; |
| 3494 return 1; |
| 3495 } |
| 3496 } |
| 3497 |
| 3498 /* No function of the specified name was found. Return 0. */ |
| 3499 return 0; |
| 3500 } |
| 3501 |
| 3502 /* |
| 3503 ** Implementation of FTS3 xRename method. Rename an fts3 table. |
| 3504 */ |
| 3505 static int fts3RenameMethod( |
| 3506 sqlite3_vtab *pVtab, /* Virtual table handle */ |
| 3507 const char *zName /* New name of table */ |
| 3508 ){ |
| 3509 Fts3Table *p = (Fts3Table *)pVtab; |
| 3510 sqlite3 *db = p->db; /* Database connection */ |
| 3511 int rc; /* Return Code */ |
| 3512 |
| 3513 rc = sqlite3Fts3PendingTermsFlush(p); |
| 3514 if( rc!=SQLITE_OK ){ |
| 3515 return rc; |
| 3516 } |
| 3517 |
| 3518 fts3DbExec(&rc, db, |
| 3519 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';", |
| 3520 p->zDb, p->zName, zName |
| 3521 ); |
| 3522 if( p->bHasDocsize ){ |
| 3523 fts3DbExec(&rc, db, |
| 3524 "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';", |
| 3525 p->zDb, p->zName, zName |
| 3526 ); |
| 3527 } |
| 3528 if( p->bHasStat ){ |
| 3529 fts3DbExec(&rc, db, |
| 3530 "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';", |
| 3531 p->zDb, p->zName, zName |
| 3532 ); |
| 3533 } |
| 3534 fts3DbExec(&rc, db, |
| 3535 "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';", |
| 3536 p->zDb, p->zName, zName |
| 3537 ); |
| 3538 fts3DbExec(&rc, db, |
| 3539 "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';", |
| 3540 p->zDb, p->zName, zName |
| 3541 ); |
| 3542 return rc; |
| 3543 } |
| 3544 |
| 3545 static const sqlite3_module fts3Module = { |
| 3546 /* iVersion */ 0, |
| 3547 /* xCreate */ fts3CreateMethod, |
| 3548 /* xConnect */ fts3ConnectMethod, |
| 3549 /* xBestIndex */ fts3BestIndexMethod, |
| 3550 /* xDisconnect */ fts3DisconnectMethod, |
| 3551 /* xDestroy */ fts3DestroyMethod, |
| 3552 /* xOpen */ fts3OpenMethod, |
| 3553 /* xClose */ fts3CloseMethod, |
| 3554 /* xFilter */ fts3FilterMethod, |
| 3555 /* xNext */ fts3NextMethod, |
| 3556 /* xEof */ fts3EofMethod, |
| 3557 /* xColumn */ fts3ColumnMethod, |
| 3558 /* xRowid */ fts3RowidMethod, |
| 3559 /* xUpdate */ fts3UpdateMethod, |
| 3560 /* xBegin */ fts3BeginMethod, |
| 3561 /* xSync */ fts3SyncMethod, |
| 3562 /* xCommit */ fts3CommitMethod, |
| 3563 /* xRollback */ fts3RollbackMethod, |
| 3564 /* xFindFunction */ fts3FindFunctionMethod, |
| 3565 /* xRename */ fts3RenameMethod, |
| 3566 }; |
| 3567 |
| 3568 /* |
| 3569 ** This function is registered as the module destructor (called when an |
| 3570 ** FTS3 enabled database connection is closed). It frees the memory |
| 3571 ** allocated for the tokenizer hash table. |
| 3572 */ |
| 3573 static void hashDestroy(void *p){ |
| 3574 Fts3Hash *pHash = (Fts3Hash *)p; |
| 3575 sqlite3Fts3HashClear(pHash); |
| 3576 sqlite3_free(pHash); |
| 3577 } |
| 3578 |
| 3579 /* |
| 3580 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are |
| 3581 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c |
| 3582 ** respectively. The following three forward declarations are for functions |
| 3583 ** declared in these files used to retrieve the respective implementations. |
| 3584 ** |
| 3585 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed |
| 3586 ** to by the argument to point to the "simple" tokenizer implementation. |
| 3587 ** And so on. |
| 3588 */ |
| 3589 void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); |
| 3590 void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule); |
| 3591 #ifdef SQLITE_ENABLE_ICU |
| 3592 void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule); |
| 3593 #endif |
| 3594 |
| 3595 /* |
| 3596 ** Initialise the fts3 extension. If this extension is built as part |
| 3597 ** of the sqlite library, then this function is called directly by |
| 3598 ** SQLite. If fts3 is built as a dynamically loadable extension, this |
| 3599 ** function is called by the sqlite3_extension_init() entry point. |
| 3600 */ |
| 3601 int sqlite3Fts3Init(sqlite3 *db){ |
| 3602 int rc = SQLITE_OK; |
| 3603 Fts3Hash *pHash = 0; |
| 3604 const sqlite3_tokenizer_module *pSimple = 0; |
| 3605 const sqlite3_tokenizer_module *pPorter = 0; |
| 3606 |
| 3607 #ifdef SQLITE_ENABLE_ICU |
| 3608 const sqlite3_tokenizer_module *pIcu = 0; |
| 3609 sqlite3Fts3IcuTokenizerModule(&pIcu); |
| 3610 #endif |
| 3611 |
| 3612 rc = sqlite3Fts3InitAux(db); |
| 3613 if( rc!=SQLITE_OK ) return rc; |
| 3614 |
| 3615 sqlite3Fts3SimpleTokenizerModule(&pSimple); |
| 3616 sqlite3Fts3PorterTokenizerModule(&pPorter); |
| 3617 |
| 3618 /* Allocate and initialise the hash-table used to store tokenizers. */ |
| 3619 pHash = sqlite3_malloc(sizeof(Fts3Hash)); |
| 3620 if( !pHash ){ |
| 3621 rc = SQLITE_NOMEM; |
| 3622 }else{ |
| 3623 sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1); |
| 3624 } |
| 3625 |
| 3626 /* Load the built-in tokenizers into the hash table */ |
| 3627 if( rc==SQLITE_OK ){ |
| 3628 if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple) |
| 3629 || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) |
| 3630 #ifdef SQLITE_ENABLE_ICU |
| 3631 || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu)) |
| 3632 #endif |
| 3633 ){ |
| 3634 rc = SQLITE_NOMEM; |
| 3635 } |
| 3636 } |
| 3637 |
| 3638 #ifdef SQLITE_TEST |
| 3639 if( rc==SQLITE_OK ){ |
| 3640 rc = sqlite3Fts3ExprInitTestInterface(db); |
| 3641 } |
| 3642 #endif |
| 3643 |
| 3644 /* Create the virtual table wrapper around the hash-table and overload |
| 3645 ** the two scalar functions. If this is successful, register the |
| 3646 ** module with sqlite. |
| 3647 */ |
| 3648 if( SQLITE_OK==rc |
| 3649 && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer")) |
| 3650 && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1)) |
| 3651 && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1)) |
| 3652 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1)) |
| 3653 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2)) |
| 3654 && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1)) |
| 3655 ){ |
| 3656 rc = sqlite3_create_module_v2( |
| 3657 db, "fts3", &fts3Module, (void *)pHash, hashDestroy |
| 3658 ); |
| 3659 if( rc==SQLITE_OK ){ |
| 3660 rc = sqlite3_create_module_v2( |
| 3661 db, "fts4", &fts3Module, (void *)pHash, 0 |
| 3662 ); |
| 3663 } |
| 3664 return rc; |
| 3665 } |
| 3666 |
| 3667 /* An error has occurred. Delete the hash table and return the error code. */ |
| 3668 assert( rc!=SQLITE_OK ); |
| 3669 if( pHash ){ |
| 3670 sqlite3Fts3HashClear(pHash); |
| 3671 sqlite3_free(pHash); |
| 3672 } |
| 3673 return rc; |
| 3674 } |
| 3675 |
| 3676 #if !SQLITE_CORE |
| 3677 int sqlite3_extension_init( |
| 3678 sqlite3 *db, |
| 3679 char **pzErrMsg, |
| 3680 const sqlite3_api_routines *pApi |
| 3681 ){ |
| 3682 SQLITE_EXTENSION_INIT2(pApi) |
| 3683 return sqlite3Fts3Init(db); |
| 3684 } |
| 3685 #endif |
| 3686 |
| 3687 #endif |
OLD | NEW |