Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/ext/fts3/fts3_snippet.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / ext / fts3 / fts3_snippet.c` 1780 lines ยท 59156 bytes Raw Blame History 1 /* 2 ** 2009 Oct 23 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 14 #include "fts3Int.h" 15 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) 16 17 #include 18 #include 19 20 /* 21 ** Characters that may appear in the second argument to matchinfo(). 22 */ 23 #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */ 24 #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */ 25 #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */ 26 #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */ 27 #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */ 28 #define FTS3_MATCHINFO_LCS 's' /* nCol values */ 29 #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */ 30 #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */ 31 #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */ 32 33 /* 34 ** The default value for the second argument to matchinfo(). 35 */ 36 #define FTS3_MATCHINFO_DEFAULT "pcx" 37 38 39 /* 40 ** Used as an sqlite3Fts3ExprIterate() context when loading phrase doclists to 41 ** Fts3Expr.aDoclist[]/nDoclist. 42 */ 43 typedef struct LoadDoclistCtx LoadDoclistCtx; 44 struct LoadDoclistCtx { 45 Fts3Cursor *pCsr; /* FTS3 Cursor */ 46 int nPhrase; /* Number of phrases seen so far */ 47 int nToken; /* Number of tokens seen so far */ 48 }; 49 50 /* 51 ** The following types are used as part of the implementation of the 52 ** fts3BestSnippet() routine. 53 */ 54 typedef struct SnippetIter SnippetIter; 55 typedef struct SnippetPhrase SnippetPhrase; 56 typedef struct SnippetFragment SnippetFragment; 57 58 struct SnippetIter { 59 Fts3Cursor *pCsr; /* Cursor snippet is being generated from */ 60 int iCol; /* Extract snippet from this column */ 61 int nSnippet; /* Requested snippet length (in tokens) */ 62 int nPhrase; /* Number of phrases in query */ 63 SnippetPhrase *aPhrase; /* Array of size nPhrase */ 64 int iCurrent; /* First token of current snippet */ 65 }; 66 67 struct SnippetPhrase { 68 int nToken; /* Number of tokens in phrase */ 69 char *pList; /* Pointer to start of phrase position list */ 70 i64 iHead; /* Next value in position list */ 71 char *pHead; /* Position list data following iHead */ 72 i64 iTail; /* Next value in trailing position list */ 73 char *pTail; /* Position list data following iTail */ 74 }; 75 76 struct SnippetFragment { 77 int iCol; /* Column snippet is extracted from */ 78 int iPos; /* Index of first token in snippet */ 79 u64 covered; /* Mask of query phrases covered */ 80 u64 hlmask; /* Mask of snippet terms to highlight */ 81 }; 82 83 /* 84 ** This type is used as an sqlite3Fts3ExprIterate() context object while 85 ** accumulating the data returned by the matchinfo() function. 86 */ 87 typedef struct MatchInfo MatchInfo; 88 struct MatchInfo { 89 Fts3Cursor *pCursor; /* FTS3 Cursor */ 90 int nCol; /* Number of columns in table */ 91 int nPhrase; /* Number of matchable phrases in query */ 92 sqlite3_int64 nDoc; /* Number of docs in database */ 93 char flag; 94 u32 *aMatchinfo; /* Pre-allocated buffer */ 95 }; 96 97 /* 98 ** An instance of this structure is used to manage a pair of buffers, each 99 ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below 100 ** for details. 101 */ 102 struct MatchinfoBuffer { 103 u8 aRef[3]; 104 int nElem; 105 int bGlobal; /* Set if global data is loaded */ 106 char *zMatchinfo; 107 u32 aMI[FLEXARRAY]; 108 }; 109 110 /* Size (in bytes) of a MatchinfoBuffer sufficient for N elements */ 111 #define SZ_MATCHINFOBUFFER(N) \ 112 (offsetof(MatchinfoBuffer,aMI)+(((N)+1)/2)*sizeof(u64)) 113 114 115 /* 116 ** The snippet() and offsets() functions both return text values. An instance 117 ** of the following structure is used to accumulate those values while the 118 ** functions are running. See fts3StringAppend() for details. 119 */ 120 typedef struct StrBuffer StrBuffer; 121 struct StrBuffer { 122 char *z; /* Pointer to buffer containing string */ 123 int n; /* Length of z in bytes (excl. nul-term) */ 124 int nAlloc; /* Allocated size of buffer z in bytes */ 125 }; 126 127 128 /************************************************************************* 129 ** Start of MatchinfoBuffer code. 130 */ 131 132 /* 133 ** Allocate a two-slot MatchinfoBuffer object. 134 */ 135 static MatchinfoBuffer *fts3MIBufferNew(i64 nElem, const char *zMatchinfo){ 136 MatchinfoBuffer *pRet; 137 sqlite3_int64 nByte = sizeof(u32) * (2*(i64)nElem+1) + SZ_MATCHINFOBUFFER(1); 138 sqlite3_int64 nStr = strlen(zMatchinfo); 139 140 pRet = sqlite3Fts3MallocZero(nByte + nStr+1); 141 if( pRet ){ 142 pRet->aMI[0] = (u8*)(&pRet->aMI[1]) - (u8*)pRet; 143 pRet->aMI[1+nElem] = pRet->aMI[0] 144 + sizeof(u32)*((int)nElem+1); 145 pRet->nElem = (int)nElem; 146 pRet->zMatchinfo = ((char*)pRet) + nByte; 147 memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1); 148 pRet->aRef[0] = 1; 149 } 150 151 return pRet; 152 } 153 154 static void fts3MIBufferFree(void *p){ 155 MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]); 156 157 assert( (u32*)p==&pBuf->aMI[1] 158 || (u32*)p==&pBuf->aMI[pBuf->nElem+2] 159 ); 160 if( (u32*)p==&pBuf->aMI[1] ){ 161 pBuf->aRef[1] = 0; 162 }else{ 163 pBuf->aRef[2] = 0; 164 } 165 166 if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){ 167 sqlite3_free(pBuf); 168 } 169 } 170 171 static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){ 172 void (*xRet)(void*) = 0; 173 u32 *aOut = 0; 174 175 if( p->aRef[1]==0 ){ 176 p->aRef[1] = 1; 177 aOut = &p->aMI[1]; 178 xRet = fts3MIBufferFree; 179 } 180 else if( p->aRef[2]==0 ){ 181 p->aRef[2] = 1; 182 aOut = &p->aMI[p->nElem+2]; 183 xRet = fts3MIBufferFree; 184 }else{ 185 aOut = (u32*)sqlite3_malloc64(p->nElem * sizeof(u32)); 186 if( aOut ){ 187 xRet = sqlite3_free; 188 if( p->bGlobal ) memcpy(aOut, &p->aMI[1], p->nElem*sizeof(u32)); 189 } 190 } 191 192 *paOut = aOut; 193 return xRet; 194 } 195 196 static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){ 197 p->bGlobal = 1; 198 memcpy(&p->aMI[2+p->nElem], &p->aMI[1], p->nElem*sizeof(u32)); 199 } 200 201 /* 202 ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew() 203 */ 204 void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){ 205 if( p ){ 206 assert( p->aRef[0]==1 ); 207 p->aRef[0] = 0; 208 if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){ 209 sqlite3_free(p); 210 } 211 } 212 } 213 214 /* 215 ** End of MatchinfoBuffer code. 216 *************************************************************************/ 217 218 219 /* 220 ** This function is used to help iterate through a position-list. A position 221 ** list is a list of unique integers, sorted from smallest to largest. Each 222 ** element of the list is represented by an FTS3 varint that takes the value 223 ** of the difference between the current element and the previous one plus 224 ** two. For example, to store the position-list: 225 ** 226 ** 4 9 113 227 ** 228 ** the three varints: 229 ** 230 ** 6 7 106 231 ** 232 ** are encoded. 233 ** 234 ** When this function is called, *pp points to the start of an element of 235 ** the list. *piPos contains the value of the previous entry in the list. 236 ** After it returns, *piPos contains the value of the next element of the 237 ** list and *pp is advanced to the following varint. 238 */ 239 static void fts3GetDeltaPosition(char **pp, i64 *piPos){ 240 int iVal; 241 *pp += fts3GetVarint32(*pp, &iVal); 242 *piPos += (iVal-2); 243 } 244 245 /* 246 ** Helper function for sqlite3Fts3ExprIterate() (see below). 247 */ 248 static int fts3ExprIterate2( 249 Fts3Expr *pExpr, /* Expression to iterate phrases of */ 250 int *piPhrase, /* Pointer to phrase counter */ 251 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */ 252 void *pCtx /* Second argument to pass to callback */ 253 ){ 254 int rc; /* Return code */ 255 int eType = pExpr->eType; /* Type of expression node pExpr */ 256 257 if( eType!=FTSQUERY_PHRASE ){ 258 assert( pExpr->pLeft && pExpr->pRight ); 259 rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx); 260 if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){ 261 rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx); 262 } 263 }else{ 264 rc = x(pExpr, *piPhrase, pCtx); 265 (*piPhrase)++; 266 } 267 return rc; 268 } 269 270 /* 271 ** Iterate through all phrase nodes in an FTS3 query, except those that 272 ** are part of a sub-tree that is the right-hand-side of a NOT operator. 273 ** For each phrase node found, the supplied callback function is invoked. 274 ** 275 ** If the callback function returns anything other than SQLITE_OK, 276 ** the iteration is abandoned and the error code returned immediately. 277 ** Otherwise, SQLITE_OK is returned after a callback has been made for 278 ** all eligible phrase nodes. 279 */ 280 int sqlite3Fts3ExprIterate( 281 Fts3Expr *pExpr, /* Expression to iterate phrases of */ 282 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */ 283 void *pCtx /* Second argument to pass to callback */ 284 ){ 285 int iPhrase = 0; /* Variable used as the phrase counter */ 286 return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx); 287 } 288 289 /* 290 ** This is an sqlite3Fts3ExprIterate() callback used while loading the 291 ** doclists for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also 292 ** fts3ExprLoadDoclists(). 293 */ 294 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){ 295 int rc = SQLITE_OK; 296 Fts3Phrase *pPhrase = pExpr->pPhrase; 297 LoadDoclistCtx *p = (LoadDoclistCtx *)ctx; 298 299 UNUSED_PARAMETER(iPhrase); 300 301 p->nPhrase++; 302 p->nToken += pPhrase->nToken; 303 304 return rc; 305 } 306 307 /* 308 ** Load the doclists for each phrase in the query associated with FTS3 cursor 309 ** pCsr. 310 ** 311 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 312 ** phrases in the expression (all phrases except those directly or 313 ** indirectly descended from the right-hand-side of a NOT operator). If 314 ** pnToken is not NULL, then it is set to the number of tokens in all 315 ** matchable phrases of the expression. 316 */ 317 static int fts3ExprLoadDoclists( 318 Fts3Cursor *pCsr, /* Fts3 cursor for current query */ 319 int *pnPhrase, /* OUT: Number of phrases in query */ 320 int *pnToken /* OUT: Number of tokens in query */ 321 ){ 322 int rc; /* Return Code */ 323 LoadDoclistCtx sCtx = {0,0,0}; /* Context for sqlite3Fts3ExprIterate() */ 324 sCtx.pCsr = pCsr; 325 rc = sqlite3Fts3ExprIterate(pCsr->pExpr,fts3ExprLoadDoclistsCb,(void*)&sCtx); 326 if( pnPhrase ) *pnPhrase = sCtx.nPhrase; 327 if( pnToken ) *pnToken = sCtx.nToken; 328 return rc; 329 } 330 331 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){ 332 (*(int *)ctx)++; 333 pExpr->iPhrase = iPhrase; 334 return SQLITE_OK; 335 } 336 static int fts3ExprPhraseCount(Fts3Expr *pExpr){ 337 int nPhrase = 0; 338 (void)sqlite3Fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase); 339 return nPhrase; 340 } 341 342 /* 343 ** Advance the position list iterator specified by the first two 344 ** arguments so that it points to the first element with a value greater 345 ** than or equal to parameter iNext. 346 */ 347 static void fts3SnippetAdvance(char **ppIter, i64 *piIter, int iNext){ 348 char *pIter = *ppIter; 349 if( pIter ){ 350 i64 iIter = *piIter; 351 352 while( iIteriCurrent<0 ){ 373 /* The SnippetIter object has just been initialized. The first snippet 374 ** candidate always starts at offset 0 (even if this candidate has a 375 ** score of 0.0). 376 */ 377 pIter->iCurrent = 0; 378 379 /* Advance the 'head' iterator of each phrase to the first offset that 380 ** is greater than or equal to (iNext+nSnippet). 381 */ 382 for(i=0; inPhrase; i++){ 383 SnippetPhrase *pPhrase = &pIter->aPhrase[i]; 384 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet); 385 } 386 }else{ 387 int iStart; 388 int iEnd = 0x7FFFFFFF; 389 390 for(i=0; inPhrase; i++){ 391 SnippetPhrase *pPhrase = &pIter->aPhrase[i]; 392 if( pPhrase->pHead && pPhrase->iHeadiHead; 394 } 395 } 396 if( iEnd==0x7FFFFFFF ){ 397 return 1; 398 } 399 400 assert( pIter->nSnippet>=0 ); 401 pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1; 402 for(i=0; inPhrase; i++){ 403 SnippetPhrase *pPhrase = &pIter->aPhrase[i]; 404 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1); 405 fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart); 406 } 407 } 408 409 return 0; 410 } 411 412 /* 413 ** Retrieve information about the current candidate snippet of snippet 414 ** iterator pIter. 415 */ 416 static void fts3SnippetDetails( 417 SnippetIter *pIter, /* Snippet iterator */ 418 u64 mCovered, /* Bitmask of phrases already covered */ 419 int *piToken, /* OUT: First token of proposed snippet */ 420 int *piScore, /* OUT: "Score" for this snippet */ 421 u64 *pmCover, /* OUT: Bitmask of phrases covered */ 422 u64 *pmHighlight /* OUT: Bitmask of terms to highlight */ 423 ){ 424 int iStart = pIter->iCurrent; /* First token of snippet */ 425 int iScore = 0; /* Score of this snippet */ 426 int i; /* Loop counter */ 427 u64 mCover = 0; /* Mask of phrases covered by this snippet */ 428 u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */ 429 430 for(i=0; inPhrase; i++){ 431 SnippetPhrase *pPhrase = &pIter->aPhrase[i]; 432 if( pPhrase->pTail ){ 433 char *pCsr = pPhrase->pTail; 434 i64 iCsr = pPhrase->iTail; 435 436 while( iCsr<(iStart+pIter->nSnippet) && iCsr>=iStart ){ 437 int j; 438 u64 mPhrase = (u64)1 << (i%64); 439 u64 mPos = (u64)1 << (iCsr - iStart); 440 assert( iCsr>=iStart && (iCsr - iStart)<=64 ); 441 assert( i>=0 ); 442 if( (mCover|mCovered)&mPhrase ){ 443 iScore++; 444 }else{ 445 iScore += 1000; 446 } 447 mCover |= mPhrase; 448 449 for(j=0; jnToken && jnSnippet; j++){ 450 mHighlight |= (mPos>>j); 451 } 452 453 if( 0==(*pCsr & 0x0FE) ) break; 454 fts3GetDeltaPosition(&pCsr, &iCsr); 455 } 456 } 457 } 458 459 /* Set the output variables before returning. */ 460 *piToken = iStart; 461 *piScore = iScore; 462 *pmCover = mCover; 463 *pmHighlight = mHighlight; 464 } 465 466 /* 467 ** This function is an sqlite3Fts3ExprIterate() callback used by 468 ** fts3BestSnippet(). Each invocation populates an element of the 469 ** SnippetIter.aPhrase[] array. 470 */ 471 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){ 472 SnippetIter *p = (SnippetIter *)ctx; 473 SnippetPhrase *pPhrase = &p->aPhrase[iPhrase]; 474 char *pCsr; 475 int rc; 476 477 pPhrase->nToken = pExpr->pPhrase->nToken; 478 rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr); 479 assert( rc==SQLITE_OK || pCsr==0 ); 480 if( pCsr ){ 481 i64 iFirst = 0; 482 pPhrase->pList = pCsr; 483 fts3GetDeltaPosition(&pCsr, &iFirst); 484 if( iFirst<0 ){ 485 rc = FTS_CORRUPT_VTAB; 486 }else{ 487 pPhrase->pHead = pCsr; 488 pPhrase->pTail = pCsr; 489 pPhrase->iHead = iFirst; 490 pPhrase->iTail = iFirst; 491 } 492 }else{ 493 assert( rc!=SQLITE_OK || ( 494 pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 495 )); 496 } 497 498 return rc; 499 } 500 501 /* 502 ** Select the fragment of text consisting of nFragment contiguous tokens 503 ** from column iCol that represent the "best" snippet. The best snippet 504 ** is the snippet with the highest score, where scores are calculated 505 ** by adding: 506 ** 507 ** (a) +1 point for each occurrence of a matchable phrase in the snippet. 508 ** 509 ** (b) +1000 points for the first occurrence of each matchable phrase in 510 ** the snippet for which the corresponding mCovered bit is not set. 511 ** 512 ** The selected snippet parameters are stored in structure *pFragment before 513 ** returning. The score of the selected snippet is stored in *piScore 514 ** before returning. 515 */ 516 static int fts3BestSnippet( 517 int nSnippet, /* Desired snippet length */ 518 Fts3Cursor *pCsr, /* Cursor to create snippet for */ 519 int iCol, /* Index of column to create snippet from */ 520 u64 mCovered, /* Mask of phrases already covered */ 521 u64 *pmSeen, /* IN/OUT: Mask of phrases seen */ 522 SnippetFragment *pFragment, /* OUT: Best snippet found */ 523 int *piScore /* OUT: Score of snippet pFragment */ 524 ){ 525 int rc; /* Return Code */ 526 int nList; /* Number of phrases in expression */ 527 SnippetIter sIter; /* Iterates through snippet candidates */ 528 sqlite3_int64 nByte; /* Number of bytes of space to allocate */ 529 int iBestScore = -1; /* Best snippet score found so far */ 530 int i; /* Loop counter */ 531 Fts3Expr *pExpr = pCsr->pExpr; 532 533 memset(&sIter, 0, sizeof(sIter)); 534 535 /* Iterate through the phrases in the expression to count them. The same 536 ** callback makes sure the doclists are loaded for each phrase. 537 */ 538 rc = fts3ExprLoadDoclists(pCsr, &nList, 0); 539 if( rc!=SQLITE_OK ){ 540 return rc; 541 } 542 543 /* Now that it is known how many phrases there are, allocate and zero 544 ** the required space using malloc(). 545 */ 546 nByte = sizeof(SnippetPhrase) * nList; 547 sIter.aPhrase = (SnippetPhrase *)sqlite3Fts3MallocZero(nByte); 548 if( !sIter.aPhrase ){ 549 return SQLITE_NOMEM; 550 } 551 552 /* Initialize the contents of the SnippetIter object. Then iterate through 553 ** the set of phrases in the expression to populate the aPhrase[] array. 554 */ 555 sIter.pCsr = pCsr; 556 sIter.iCol = iCol; 557 sIter.nSnippet = nSnippet; 558 sIter.nPhrase = nList; 559 sIter.iCurrent = -1; 560 rc = sqlite3Fts3ExprIterate(pExpr, fts3SnippetFindPositions, (void*)&sIter); 561 if( rc==SQLITE_OK ){ 562 /* Iterate through the expression twice, in case pointers garnered during 563 ** the first iteration are invalidated by a call to fts5EvalRestart(). */ 564 rc = sqlite3Fts3ExprIterate(pExpr, fts3SnippetFindPositions, (void*)&sIter); 565 } 566 if( rc==SQLITE_OK ){ 567 568 /* Set the *pmSeen output variable. */ 569 for(i=0; iiCol = iCol; 579 while( !fts3SnippetNextCandidate(&sIter) ){ 580 int iPos; 581 int iScore; 582 u64 mCover; 583 u64 mHighlite; 584 fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite); 585 assert( iScore>=0 ); 586 if( iScore>iBestScore ){ 587 pFragment->iPos = iPos; 588 pFragment->hlmask = mHighlite; 589 pFragment->covered = mCover; 590 iBestScore = iScore; 591 } 592 } 593 594 *piScore = iBestScore; 595 } 596 sqlite3_free(sIter.aPhrase); 597 return rc; 598 } 599 600 601 /* 602 ** Append a string to the string-buffer passed as the first argument. 603 ** 604 ** If nAppend is negative, then the length of the string zAppend is 605 ** determined using strlen(). 606 */ 607 static int fts3StringAppend( 608 StrBuffer *pStr, /* Buffer to append to */ 609 const char *zAppend, /* Pointer to data to append to buffer */ 610 int nAppend /* Size of zAppend in bytes (or -1) */ 611 ){ 612 if( nAppend<0 ){ 613 nAppend = (int)strlen(zAppend); 614 } 615 616 /* If there is insufficient space allocated at StrBuffer.z, use realloc() 617 ** to grow the buffer until so that it is big enough to accommodate the 618 ** appended data. 619 */ 620 if( (i64)pStr->n+(i64)nAppend+1>=(i64)pStr->nAlloc ){ 621 i64 nAlloc = pStr->nAlloc+(i64)nAppend+100; 622 char *zNew = sqlite3_realloc64(pStr->z, nAlloc); 623 if( !zNew ){ 624 return SQLITE_NOMEM; 625 } 626 pStr->z = zNew; 627 pStr->nAlloc = nAlloc; 628 } 629 assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) ); 630 631 /* Append the data to the string buffer. */ 632 memcpy(&pStr->z[pStr->n], zAppend, nAppend); 633 pStr->n += nAppend; 634 pStr->z[pStr->n] = '\0'; 635 636 return SQLITE_OK; 637 } 638 639 /* 640 ** The fts3BestSnippet() function often selects snippets that end with a 641 ** query term. That is, the final term of the snippet is always a term 642 ** that requires highlighting. For example, if 'X' is a highlighted term 643 ** and '.' is a non-highlighted term, BestSnippet() may select: 644 ** 645 ** ........X.....X 646 ** 647 ** This function "shifts" the beginning of the snippet forward in the 648 ** document so that there are approximately the same number of 649 ** non-highlighted terms to the right of the final highlighted term as there 650 ** are to the left of the first highlighted term. For example, to this: 651 ** 652 ** ....X.....X.... 653 ** 654 ** This is done as part of extracting the snippet text, not when selecting 655 ** the snippet. Snippet selection is done based on doclists only, so there 656 ** is no way for fts3BestSnippet() to know whether or not the document 657 ** actually contains terms that follow the final highlighted term. 658 */ 659 static int fts3SnippetShift( 660 Fts3Table *pTab, /* FTS3 table snippet comes from */ 661 int iLangid, /* Language id to use in tokenizing */ 662 int nSnippet, /* Number of tokens desired for snippet */ 663 const char *zDoc, /* Document text to extract snippet from */ 664 int nDoc, /* Size of buffer zDoc in bytes */ 665 int *piPos, /* IN/OUT: First token of snippet */ 666 u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */ 667 ){ 668 u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */ 669 670 if( hlmask ){ 671 int nLeft; /* Tokens to the left of first highlight */ 672 int nRight; /* Tokens to the right of last highlight */ 673 int nDesired; /* Ideal number of tokens to shift forward */ 674 675 for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++); 676 for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++); 677 assert( (nSnippet-1-nRight)<=63 && (nSnippet-1-nRight)>=0 ); 678 nDesired = (nLeft-nRight)/2; 679 680 /* Ideally, the start of the snippet should be pushed forward in the 681 ** document nDesired tokens. This block checks if there are actually 682 ** nDesired tokens to the right of the snippet. If so, *piPos and 683 ** *pHlMask are updated to shift the snippet nDesired tokens to the 684 ** right. Otherwise, the snippet is shifted by the number of tokens 685 ** available. 686 */ 687 if( nDesired>0 ){ 688 int nShift; /* Number of tokens to shift snippet by */ 689 int iCurrent = 0; /* Token counter */ 690 int rc; /* Return Code */ 691 sqlite3_tokenizer_module *pMod; 692 sqlite3_tokenizer_cursor *pC; 693 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule; 694 695 /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired) 696 ** or more tokens in zDoc/nDoc. 697 */ 698 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC); 699 if( rc!=SQLITE_OK ){ 700 return rc; 701 } 702 while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){ 703 const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0; 704 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent); 705 } 706 pMod->xClose(pC); 707 if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; } 708 709 nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet; 710 assert( nShift<=nDesired ); 711 if( nShift>0 ){ 712 *piPos += nShift; 713 *pHlmask = hlmask >> nShift; 714 } 715 } 716 } 717 return SQLITE_OK; 718 } 719 720 /* 721 ** Extract the snippet text for fragment pFragment from cursor pCsr and 722 ** append it to string buffer pOut. 723 */ 724 static int fts3SnippetText( 725 Fts3Cursor *pCsr, /* FTS3 Cursor */ 726 SnippetFragment *pFragment, /* Snippet to extract */ 727 int iFragment, /* Fragment number */ 728 int isLast, /* True for final fragment in snippet */ 729 int nSnippet, /* Number of tokens in extracted snippet */ 730 const char *zOpen, /* String inserted before highlighted term */ 731 const char *zClose, /* String inserted after highlighted term */ 732 const char *zEllipsis, /* String inserted between snippets */ 733 StrBuffer *pOut /* Write output here */ 734 ){ 735 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; 736 int rc; /* Return code */ 737 const char *zDoc; /* Document text to extract snippet from */ 738 int nDoc; /* Size of zDoc in bytes */ 739 int iCurrent = 0; /* Current token number of document */ 740 int iEnd = 0; /* Byte offset of end of current token */ 741 int isShiftDone = 0; /* True after snippet is shifted */ 742 int iPos = pFragment->iPos; /* First token of snippet */ 743 u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */ 744 int iCol = pFragment->iCol+1; /* Query column to extract text from */ 745 sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */ 746 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */ 747 748 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol); 749 if( zDoc==0 ){ 750 if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){ 751 return SQLITE_NOMEM; 752 } 753 return SQLITE_OK; 754 } 755 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol); 756 757 /* Open a token cursor on the document. */ 758 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule; 759 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC); 760 if( rc!=SQLITE_OK ){ 761 return rc; 762 } 763 764 while( rc==SQLITE_OK ){ 765 const char *ZDUMMY; /* Dummy argument used with tokenizer */ 766 int DUMMY1 = -1; /* Dummy argument used with tokenizer */ 767 int iBegin = 0; /* Offset in zDoc of start of token */ 768 int iFin = 0; /* Offset in zDoc of end of token */ 769 int isHighlight = 0; /* True for highlighted terms */ 770 771 /* Variable DUMMY1 is initialized to a negative value above. Elsewhere 772 ** in the FTS code the variable that the third argument to xNext points to 773 ** is initialized to zero before the first (*but not necessarily 774 ** subsequent*) call to xNext(). This is done for a particular application 775 ** that needs to know whether or not the tokenizer is being used for 776 ** snippet generation or for some other purpose. 777 ** 778 ** Extreme care is required when writing code to depend on this 779 ** initialization. It is not a documented part of the tokenizer interface. 780 ** If a tokenizer is used directly by any code outside of FTS, this 781 ** convention might not be respected. */ 782 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent); 783 if( rc!=SQLITE_OK ){ 784 if( rc==SQLITE_DONE ){ 785 /* Special case - the last token of the snippet is also the last token 786 ** of the column. Append any punctuation that occurred between the end 787 ** of the previous token and the end of the document to the output. 788 ** Then break out of the loop. */ 789 rc = fts3StringAppend(pOut, &zDoc[iEnd], -1); 790 } 791 break; 792 } 793 if( iCurrentiLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask 799 ); 800 isShiftDone = 1; 801 802 /* Now that the shift has been done, check if the initial "..." are 803 ** required. They are required if (a) this is not the first fragment, 804 ** or (b) this fragment does not begin at position 0 of its column. 805 */ 806 if( rc==SQLITE_OK ){ 807 if( iPos>0 || iFragment>0 ){ 808 rc = fts3StringAppend(pOut, zEllipsis, -1); 809 }else if( iBegin ){ 810 rc = fts3StringAppend(pOut, zDoc, iBegin); 811 } 812 } 813 if( rc!=SQLITE_OK || iCurrent=(iPos+nSnippet) ){ 817 if( isLast ){ 818 rc = fts3StringAppend(pOut, zEllipsis, -1); 819 } 820 break; 821 } 822 823 /* Set isHighlight to true if this term should be highlighted. */ 824 isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0; 825 826 if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd); 827 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1); 828 if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin); 829 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1); 830 831 iEnd = iFin; 832 } 833 834 pMod->xClose(pC); 835 return rc; 836 } 837 838 839 /* 840 ** This function is used to count the entries in a column-list (a 841 ** delta-encoded list of term offsets within a single column of a single 842 ** row). When this function is called, *ppCollist should point to the 843 ** beginning of the first varint in the column-list (the varint that 844 ** contains the position of the first matching term in the column data). 845 ** Before returning, *ppCollist is set to point to the first byte after 846 ** the last varint in the column-list (either the 0x00 signifying the end 847 ** of the position-list, or the 0x01 that precedes the column number of 848 ** the next column in the position-list). 849 ** 850 ** The number of elements in the column-list is returned. 851 */ 852 static int fts3ColumnlistCount(char **ppCollist){ 853 char *pEnd = *ppCollist; 854 char c = 0; 855 int nEntry = 0; 856 857 /* A column-list is terminated by either a 0x01 or 0x00. */ 858 while( 0xFE & (*pEnd | c) ){ 859 c = *pEnd++ & 0x80; 860 if( !c ) nEntry++; 861 } 862 863 *ppCollist = pEnd; 864 return nEntry; 865 } 866 867 /* 868 ** This function gathers 'y' or 'b' data for a single phrase. 869 */ 870 static int fts3ExprLHits( 871 Fts3Expr *pExpr, /* Phrase expression node */ 872 MatchInfo *p /* Matchinfo context */ 873 ){ 874 Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab; 875 int iStart; 876 Fts3Phrase *pPhrase = pExpr->pPhrase; 877 char *pIter = pPhrase->doclist.pList; 878 int iCol = 0; 879 880 assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS ); 881 if( p->flag==FTS3_MATCHINFO_LHITS ){ 882 iStart = pExpr->iPhrase * p->nCol; 883 }else{ 884 iStart = pExpr->iPhrase * ((p->nCol + 31) / 32); 885 } 886 887 if( pIter ) while( 1 ){ 888 int nHit = fts3ColumnlistCount(&pIter); 889 if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){ 890 if( p->flag==FTS3_MATCHINFO_LHITS ){ 891 p->aMatchinfo[iStart + iCol] = (u32)nHit; 892 }else if( nHit ){ 893 p->aMatchinfo[iStart + iCol/32] |= (1U << (iCol&0x1F)); 894 } 895 } 896 assert( *pIter==0x00 || *pIter==0x01 ); 897 if( *pIter!=0x01 ) break; 898 pIter++; 899 pIter += fts3GetVarint32(pIter, &iCol); 900 if( iCol>=p->nCol ) return FTS_CORRUPT_VTAB; 901 } 902 return SQLITE_OK; 903 } 904 905 /* 906 ** Gather the results for matchinfo directives 'y' and 'b'. 907 */ 908 static int fts3ExprLHitGather( 909 Fts3Expr *pExpr, 910 MatchInfo *p 911 ){ 912 int rc = SQLITE_OK; 913 assert( (pExpr->pLeft==0)==(pExpr->pRight==0) ); 914 if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){ 915 if( pExpr->pLeft ){ 916 rc = fts3ExprLHitGather(pExpr->pLeft, p); 917 if( rc==SQLITE_OK ) rc = fts3ExprLHitGather(pExpr->pRight, p); 918 }else{ 919 rc = fts3ExprLHits(pExpr, p); 920 } 921 } 922 return rc; 923 } 924 925 /* 926 ** sqlite3Fts3ExprIterate() callback used to collect the "global" matchinfo 927 ** stats for a single query. 928 ** 929 ** sqlite3Fts3ExprIterate() callback to load the 'global' elements of a 930 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 931 ** of the matchinfo array that are constant for all rows returned by the 932 ** current query. 933 ** 934 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This 935 ** function populates Matchinfo.aMatchinfo[] as follows: 936 ** 937 ** for(iCol=0; iColpCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol] 960 ); 961 } 962 963 /* 964 ** sqlite3Fts3ExprIterate() callback used to collect the "local" part of the 965 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 966 ** array that are different for each row returned by the query. 967 */ 968 static int fts3ExprLocalHitsCb( 969 Fts3Expr *pExpr, /* Phrase expression node */ 970 int iPhrase, /* Phrase number */ 971 void *pCtx /* Pointer to MatchInfo structure */ 972 ){ 973 int rc = SQLITE_OK; 974 MatchInfo *p = (MatchInfo *)pCtx; 975 int iStart = iPhrase * p->nCol * 3; 976 int i; 977 978 for(i=0; inCol && rc==SQLITE_OK; i++){ 979 char *pCsr; 980 rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr); 981 if( pCsr ){ 982 p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr); 983 }else{ 984 p->aMatchinfo[iStart+i*3] = 0; 985 } 986 } 987 988 return rc; 989 } 990 991 static int fts3MatchinfoCheck( 992 Fts3Table *pTab, 993 char cArg, 994 char **pzErr 995 ){ 996 if( (cArg==FTS3_MATCHINFO_NPHRASE) 997 || (cArg==FTS3_MATCHINFO_NCOL) 998 || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4) 999 || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4) 1000 || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize) 1001 || (cArg==FTS3_MATCHINFO_LCS) 1002 || (cArg==FTS3_MATCHINFO_HITS) 1003 || (cArg==FTS3_MATCHINFO_LHITS) 1004 || (cArg==FTS3_MATCHINFO_LHITS_BM) 1005 ){ 1006 return SQLITE_OK; 1007 } 1008 sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg); 1009 return SQLITE_ERROR; 1010 } 1011 1012 static i64 fts3MatchinfoSize(MatchInfo *pInfo, char cArg){ 1013 i64 nVal; /* Number of integers output by cArg */ 1014 1015 switch( cArg ){ 1016 case FTS3_MATCHINFO_NDOC: 1017 case FTS3_MATCHINFO_NPHRASE: 1018 case FTS3_MATCHINFO_NCOL: 1019 nVal = 1; 1020 break; 1021 1022 case FTS3_MATCHINFO_AVGLENGTH: 1023 case FTS3_MATCHINFO_LENGTH: 1024 case FTS3_MATCHINFO_LCS: 1025 nVal = pInfo->nCol; 1026 break; 1027 1028 case FTS3_MATCHINFO_LHITS: 1029 nVal = (i64)pInfo->nCol * pInfo->nPhrase; 1030 break; 1031 1032 case FTS3_MATCHINFO_LHITS_BM: 1033 nVal = (i64)pInfo->nPhrase * ((pInfo->nCol + 31) / 32); 1034 break; 1035 1036 default: 1037 assert( cArg==FTS3_MATCHINFO_HITS ); 1038 nVal = (i64)pInfo->nCol * pInfo->nPhrase * 3; 1039 break; 1040 } 1041 1042 return nVal; 1043 } 1044 1045 static int fts3MatchinfoSelectDoctotal( 1046 Fts3Table *pTab, 1047 sqlite3_stmt **ppStmt, 1048 sqlite3_int64 *pnDoc, 1049 const char **paLen, 1050 const char **ppEnd 1051 ){ 1052 sqlite3_stmt *pStmt; 1053 const char *a; 1054 const char *pEnd; 1055 sqlite3_int64 nDoc; 1056 int n; 1057 1058 1059 if( !*ppStmt ){ 1060 int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt); 1061 if( rc!=SQLITE_OK ) return rc; 1062 } 1063 pStmt = *ppStmt; 1064 assert( sqlite3_data_count(pStmt)==1 ); 1065 1066 n = sqlite3_column_bytes(pStmt, 0); 1067 a = sqlite3_column_blob(pStmt, 0); 1068 if( a==0 ){ 1069 return FTS_CORRUPT_VTAB; 1070 } 1071 pEnd = a + n; 1072 a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc); 1073 if( nDoc<=0 || a>pEnd ){ 1074 return FTS_CORRUPT_VTAB; 1075 } 1076 *pnDoc = nDoc; 1077 1078 if( paLen ) *paLen = a; 1079 if( ppEnd ) *ppEnd = pEnd; 1080 return SQLITE_OK; 1081 } 1082 1083 /* 1084 ** An instance of the following structure is used to store state while 1085 ** iterating through a multi-column position-list corresponding to the 1086 ** hits for a single phrase on a single row in order to calculate the 1087 ** values for a matchinfo() FTS3_MATCHINFO_LCS request. 1088 */ 1089 typedef struct LcsIterator LcsIterator; 1090 struct LcsIterator { 1091 Fts3Expr *pExpr; /* Pointer to phrase expression */ 1092 int iPosOffset; /* Tokens count up to end of this phrase */ 1093 char *pRead; /* Cursor used to iterate through aDoclist */ 1094 int iPos; /* Current position */ 1095 }; 1096 1097 /* 1098 ** If LcsIterator.iCol is set to the following value, the iterator has 1099 ** finished iterating through all offsets for all columns. 1100 */ 1101 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF; 1102 1103 static int fts3MatchinfoLcsCb( 1104 Fts3Expr *pExpr, /* Phrase expression node */ 1105 int iPhrase, /* Phrase number (numbered from zero) */ 1106 void *pCtx /* Pointer to MatchInfo structure */ 1107 ){ 1108 LcsIterator *aIter = (LcsIterator *)pCtx; 1109 aIter[iPhrase].pExpr = pExpr; 1110 return SQLITE_OK; 1111 } 1112 1113 /* 1114 ** Advance the iterator passed as an argument to the next position. Return 1115 ** 1 if the iterator is at EOF or if it now points to the start of the 1116 ** position list for the next column. 1117 */ 1118 static int fts3LcsIteratorAdvance(LcsIterator *pIter){ 1119 char *pRead; 1120 sqlite3_int64 iRead; 1121 int rc = 0; 1122 1123 if( NEVER(pIter==0) ) return 1; 1124 pRead = pIter->pRead; 1125 pRead += sqlite3Fts3GetVarint(pRead, &iRead); 1126 if( iRead==0 || iRead==1 ){ 1127 pRead = 0; 1128 rc = 1; 1129 }else{ 1130 pIter->iPos += (int)(iRead-2); 1131 } 1132 1133 pIter->pRead = pRead; 1134 return rc; 1135 } 1136 1137 /* 1138 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 1139 ** 1140 ** If the call is successful, the longest-common-substring lengths for each 1141 ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 1142 ** array before returning. SQLITE_OK is returned in this case. 1143 ** 1144 ** Otherwise, if an error occurs, an SQLite error code is returned and the 1145 ** data written to the first nCol elements of pInfo->aMatchinfo[] is 1146 ** undefined. 1147 */ 1148 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){ 1149 LcsIterator *aIter; 1150 int i; 1151 int iCol; 1152 int nToken = 0; 1153 int rc = SQLITE_OK; 1154 1155 /* Allocate and populate the array of LcsIterator objects. The array 1156 ** contains one element for each matchable phrase in the query. 1157 **/ 1158 aIter = sqlite3Fts3MallocZero(sizeof(LcsIterator) * pCsr->nPhrase); 1159 if( !aIter ) return SQLITE_NOMEM; 1160 (void)sqlite3Fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter); 1161 1162 for(i=0; inPhrase; i++){ 1163 LcsIterator *pIter = &aIter[i]; 1164 nToken -= pIter->pExpr->pPhrase->nToken; 1165 pIter->iPosOffset = nToken; 1166 } 1167 1168 for(iCol=0; iColnCol; iCol++){ 1169 int nLcs = 0; /* LCS value for this column */ 1170 int nLive = 0; /* Number of iterators in aIter not at EOF */ 1171 1172 for(i=0; inPhrase; i++){ 1173 LcsIterator *pIt = &aIter[i]; 1174 rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead); 1175 if( rc!=SQLITE_OK ) goto matchinfo_lcs_out; 1176 if( pIt->pRead ){ 1177 pIt->iPos = pIt->iPosOffset; 1178 fts3LcsIteratorAdvance(pIt); 1179 if( pIt->pRead==0 ){ 1180 rc = FTS_CORRUPT_VTAB; 1181 goto matchinfo_lcs_out; 1182 } 1183 nLive++; 1184 } 1185 } 1186 1187 while( nLive>0 ){ 1188 LcsIterator *pAdv = 0; /* The iterator to advance by one position */ 1189 int nThisLcs = 0; /* LCS for the current iterator positions */ 1190 1191 for(i=0; inPhrase; i++){ 1192 LcsIterator *pIter = &aIter[i]; 1193 if( pIter->pRead==0 ){ 1194 /* This iterator is already at EOF for this column. */ 1195 nThisLcs = 0; 1196 }else{ 1197 if( pAdv==0 || pIter->iPosiPos ){ 1198 pAdv = pIter; 1199 } 1200 if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){ 1201 nThisLcs++; 1202 }else{ 1203 nThisLcs = 1; 1204 } 1205 if( nThisLcs>nLcs ) nLcs = nThisLcs; 1206 } 1207 } 1208 if( fts3LcsIteratorAdvance(pAdv) ) nLive--; 1209 } 1210 1211 pInfo->aMatchinfo[iCol] = nLcs; 1212 } 1213 1214 matchinfo_lcs_out: 1215 sqlite3_free(aIter); 1216 return rc; 1217 } 1218 1219 /* 1220 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to 1221 ** be returned by the matchinfo() function. Argument zArg contains the 1222 ** format string passed as the second argument to matchinfo (or the 1223 ** default value "pcx" if no second argument was specified). The format 1224 ** string has already been validated and the pInfo->aMatchinfo[] array 1225 ** is guaranteed to be large enough for the output. 1226 ** 1227 ** If bGlobal is true, then populate all fields of the matchinfo() output. 1228 ** If it is false, then assume that those fields that do not change between 1229 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS) 1230 ** have already been populated. 1231 ** 1232 ** Return SQLITE_OK if successful, or an SQLite error code if an error 1233 ** occurs. If a value other than SQLITE_OK is returned, the state the 1234 ** pInfo->aMatchinfo[] buffer is left in is undefined. 1235 */ 1236 static int fts3MatchinfoValues( 1237 Fts3Cursor *pCsr, /* FTS3 cursor object */ 1238 int bGlobal, /* True to grab the global stats */ 1239 MatchInfo *pInfo, /* Matchinfo context object */ 1240 const char *zArg /* Matchinfo format string */ 1241 ){ 1242 int rc = SQLITE_OK; 1243 int i; 1244 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; 1245 sqlite3_stmt *pSelect = 0; 1246 1247 for(i=0; rc==SQLITE_OK && zArg[i]; i++){ 1248 pInfo->flag = zArg[i]; 1249 switch( zArg[i] ){ 1250 case FTS3_MATCHINFO_NPHRASE: 1251 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase; 1252 break; 1253 1254 case FTS3_MATCHINFO_NCOL: 1255 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol; 1256 break; 1257 1258 case FTS3_MATCHINFO_NDOC: 1259 if( bGlobal ){ 1260 sqlite3_int64 nDoc = 0; 1261 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0, 0); 1262 pInfo->aMatchinfo[0] = (u32)nDoc; 1263 } 1264 break; 1265 1266 case FTS3_MATCHINFO_AVGLENGTH: 1267 if( bGlobal ){ 1268 sqlite3_int64 nDoc; /* Number of rows in table */ 1269 const char *a; /* Aggregate column length array */ 1270 const char *pEnd; /* First byte past end of length array */ 1271 1272 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a, &pEnd); 1273 if( rc==SQLITE_OK ){ 1274 int iCol; 1275 for(iCol=0; iColnCol; iCol++){ 1276 u32 iVal; 1277 sqlite3_int64 nToken; 1278 a += sqlite3Fts3GetVarint(a, &nToken); 1279 if( a>pEnd ){ 1280 rc = SQLITE_CORRUPT_VTAB; 1281 break; 1282 } 1283 iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc); 1284 pInfo->aMatchinfo[iCol] = iVal; 1285 } 1286 } 1287 } 1288 break; 1289 1290 case FTS3_MATCHINFO_LENGTH: { 1291 sqlite3_stmt *pSelectDocsize = 0; 1292 rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize); 1293 if( rc==SQLITE_OK ){ 1294 int iCol; 1295 const char *a = sqlite3_column_blob(pSelectDocsize, 0); 1296 const char *pEnd = a + sqlite3_column_bytes(pSelectDocsize, 0); 1297 for(iCol=0; iColnCol; iCol++){ 1298 sqlite3_int64 nToken; 1299 a += sqlite3Fts3GetVarintBounded(a, pEnd, &nToken); 1300 if( a>pEnd ){ 1301 rc = SQLITE_CORRUPT_VTAB; 1302 break; 1303 } 1304 pInfo->aMatchinfo[iCol] = (u32)nToken; 1305 } 1306 } 1307 sqlite3_reset(pSelectDocsize); 1308 break; 1309 } 1310 1311 case FTS3_MATCHINFO_LCS: 1312 rc = fts3ExprLoadDoclists(pCsr, 0, 0); 1313 if( rc==SQLITE_OK ){ 1314 rc = fts3MatchinfoLcs(pCsr, pInfo); 1315 } 1316 break; 1317 1318 case FTS3_MATCHINFO_LHITS_BM: 1319 case FTS3_MATCHINFO_LHITS: { 1320 i64 nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32); 1321 memset(pInfo->aMatchinfo, 0, nZero); 1322 rc = fts3ExprLHitGather(pCsr->pExpr, pInfo); 1323 break; 1324 } 1325 1326 default: { 1327 Fts3Expr *pExpr; 1328 assert( zArg[i]==FTS3_MATCHINFO_HITS ); 1329 pExpr = pCsr->pExpr; 1330 rc = fts3ExprLoadDoclists(pCsr, 0, 0); 1331 if( rc!=SQLITE_OK ) break; 1332 if( bGlobal ){ 1333 if( pCsr->pDeferred ){ 1334 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc,0,0); 1335 if( rc!=SQLITE_OK ) break; 1336 } 1337 rc = sqlite3Fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo); 1338 sqlite3Fts3EvalTestDeferred(pCsr, &rc); 1339 if( rc!=SQLITE_OK ) break; 1340 } 1341 (void)sqlite3Fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo); 1342 break; 1343 } 1344 } 1345 1346 pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]); 1347 } 1348 1349 sqlite3_reset(pSelect); 1350 return rc; 1351 } 1352 1353 1354 /* 1355 ** Populate pCsr->aMatchinfo[] with data for the current row. The 1356 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32). 1357 */ 1358 static void fts3GetMatchinfo( 1359 sqlite3_context *pCtx, /* Return results here */ 1360 Fts3Cursor *pCsr, /* FTS3 Cursor object */ 1361 const char *zArg /* Second argument to matchinfo() function */ 1362 ){ 1363 MatchInfo sInfo; 1364 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; 1365 int rc = SQLITE_OK; 1366 int bGlobal = 0; /* Collect 'global' stats as well as local */ 1367 1368 u32 *aOut = 0; 1369 void (*xDestroyOut)(void*) = 0; 1370 1371 memset(&sInfo, 0, sizeof(MatchInfo)); 1372 sInfo.pCursor = pCsr; 1373 sInfo.nCol = pTab->nColumn; 1374 1375 /* If there is cached matchinfo() data, but the format string for the 1376 ** cache does not match the format string for this request, discard 1377 ** the cached data. */ 1378 if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){ 1379 sqlite3Fts3MIBufferFree(pCsr->pMIBuffer); 1380 pCsr->pMIBuffer = 0; 1381 } 1382 1383 /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the 1384 ** matchinfo function has been called for this query. In this case 1385 ** allocate the array used to accumulate the matchinfo data and 1386 ** initialize those elements that are constant for every row. 1387 */ 1388 if( pCsr->pMIBuffer==0 ){ 1389 i64 nMatchinfo = 0; /* Number of u32 elements in match-info */ 1390 int i; /* Used to iterate through zArg */ 1391 1392 /* Determine the number of phrases in the query */ 1393 pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr); 1394 sInfo.nPhrase = pCsr->nPhrase; 1395 1396 /* Determine the number of integers in the buffer returned by this call. */ 1397 for(i=0; zArg[i]; i++){ 1398 char *zErr = 0; 1399 if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){ 1400 sqlite3_result_error(pCtx, zErr, -1); 1401 sqlite3_free(zErr); 1402 return; 1403 } 1404 nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]); 1405 } 1406 1407 /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */ 1408 pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg); 1409 if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM; 1410 1411 pCsr->isMatchinfoNeeded = 1; 1412 bGlobal = 1; 1413 } 1414 1415 if( rc==SQLITE_OK ){ 1416 xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut); 1417 if( xDestroyOut==0 ){ 1418 rc = SQLITE_NOMEM; 1419 } 1420 } 1421 1422 if( rc==SQLITE_OK ){ 1423 sInfo.aMatchinfo = aOut; 1424 sInfo.nPhrase = pCsr->nPhrase; 1425 rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg); 1426 if( bGlobal ){ 1427 fts3MIBufferSetGlobal(pCsr->pMIBuffer); 1428 } 1429 } 1430 1431 if( rc!=SQLITE_OK ){ 1432 sqlite3_result_error_code(pCtx, rc); 1433 if( xDestroyOut ) xDestroyOut(aOut); 1434 }else{ 1435 int n = pCsr->pMIBuffer->nElem * sizeof(u32); 1436 sqlite3_result_blob(pCtx, aOut, n, xDestroyOut); 1437 } 1438 } 1439 1440 /* 1441 ** Implementation of snippet() function. 1442 */ 1443 void sqlite3Fts3Snippet( 1444 sqlite3_context *pCtx, /* SQLite function call context */ 1445 Fts3Cursor *pCsr, /* Cursor object */ 1446 const char *zStart, /* Snippet start text - "" */ 1447 const char *zEnd, /* Snippet end text - "" */ 1448 const char *zEllipsis, /* Snippet ellipsis text - "..." */ 1449 int iCol, /* Extract snippet from this column */ 1450 int nToken /* Approximate number of tokens in snippet */ 1451 ){ 1452 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; 1453 int rc = SQLITE_OK; 1454 int i; 1455 StrBuffer res = {0, 0, 0}; 1456 1457 /* The returned text includes up to four fragments of text extracted from 1458 ** the data in the current row. The first iteration of the for(...) loop 1459 ** below attempts to locate a single fragment of text nToken tokens in 1460 ** size that contains at least one instance of all phrases in the query 1461 ** expression that appear in the current row. If such a fragment of text 1462 ** cannot be found, the second iteration of the loop attempts to locate 1463 ** a pair of fragments, and so on. 1464 */ 1465 int nSnippet = 0; /* Number of fragments in this snippet */ 1466 SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */ 1467 int nFToken = -1; /* Number of tokens in each fragment */ 1468 1469 if( !pCsr->pExpr ){ 1470 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); 1471 return; 1472 } 1473 1474 /* The snippet length should already have been limited to 64 tokens. */ 1475 assert( nToken>=-64 && nToken<=64 ); 1476 1477 for(nSnippet=1; 1; nSnippet++){ 1478 1479 int iSnip; /* Loop counter 0..nSnippet-1 */ 1480 u64 mCovered = 0; /* Bitmask of phrases covered by snippet */ 1481 u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */ 1482 1483 if( nToken>=0 ){ 1484 nFToken = (nToken+nSnippet-1) / nSnippet; 1485 }else{ 1486 nFToken = -1 * nToken; 1487 } 1488 1489 for(iSnip=0; iSnipnColumn; iRead++){ 1501 SnippetFragment sF = {0, 0, 0, 0}; 1502 int iS = 0; 1503 if( iCol>=0 && iRead!=iCol ) continue; 1504 1505 /* Find the best snippet of nFToken tokens in column iRead. */ 1506 rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS); 1507 if( rc!=SQLITE_OK ){ 1508 goto snippet_out; 1509 } 1510 if( iS>iBestScore ){ 1511 *pFragment = sF; 1512 iBestScore = iS; 1513 } 1514 } 1515 1516 mCovered |= pFragment->covered; 1517 } 1518 1519 /* If all query phrases seen by fts3BestSnippet() are present in at least 1520 ** one of the nSnippet snippet fragments, break out of the loop. 1521 */ 1522 assert( (mCovered&mSeen)==mCovered ); 1523 if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break; 1524 } 1525 1526 assert( nFToken>0 ); 1527 1528 for(i=0; ipCsr, pExpr, p->iCol, &pList); 1575 nTerm = pExpr->pPhrase->nToken; 1576 if( pList ){ 1577 fts3GetDeltaPosition(&pList, &iPos); 1578 assert_fts3_nc( iPos>=0 ); 1579 } 1580 1581 for(iTerm=0; iTermaTerm[p->iTerm++]; 1583 pT->iOff = nTerm-iTerm-1; 1584 pT->pList = pList; 1585 pT->iPos = iPos; 1586 } 1587 1588 return rc; 1589 } 1590 1591 /* 1592 ** If expression pExpr is a phrase expression that uses an MSR query, 1593 ** restart it as a regular, non-incremental query. Return SQLITE_OK 1594 ** if successful, or an SQLite error code otherwise. 1595 */ 1596 static int fts3ExprRestartIfCb(Fts3Expr *pExpr, int iPhrase, void *ctx){ 1597 TermOffsetCtx *p = (TermOffsetCtx*)ctx; 1598 int rc = SQLITE_OK; 1599 UNUSED_PARAMETER(iPhrase); 1600 if( pExpr->pPhrase && pExpr->pPhrase->bIncr ){ 1601 rc = sqlite3Fts3MsrCancel(p->pCsr, pExpr); 1602 pExpr->pPhrase->bIncr = 0; 1603 } 1604 return rc; 1605 } 1606 1607 /* 1608 ** Implementation of offsets() function. 1609 */ 1610 void sqlite3Fts3Offsets( 1611 sqlite3_context *pCtx, /* SQLite function call context */ 1612 Fts3Cursor *pCsr /* Cursor object */ 1613 ){ 1614 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; 1615 sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule; 1616 int rc; /* Return Code */ 1617 int nToken; /* Number of tokens in query */ 1618 int iCol; /* Column currently being processed */ 1619 StrBuffer res = {0, 0, 0}; /* Result string */ 1620 TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */ 1621 1622 if( !pCsr->pExpr ){ 1623 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); 1624 return; 1625 } 1626 1627 memset(&sCtx, 0, sizeof(sCtx)); 1628 assert( pCsr->isRequireSeek==0 ); 1629 1630 /* Count the number of terms in the query */ 1631 rc = fts3ExprLoadDoclists(pCsr, 0, &nToken); 1632 if( rc!=SQLITE_OK ) goto offsets_out; 1633 1634 /* Allocate the array of TermOffset iterators. */ 1635 sCtx.aTerm = (TermOffset *)sqlite3Fts3MallocZero(sizeof(TermOffset)*nToken); 1636 if( 0==sCtx.aTerm ){ 1637 rc = SQLITE_NOMEM; 1638 goto offsets_out; 1639 } 1640 sCtx.iDocid = pCsr->iPrevId; 1641 sCtx.pCsr = pCsr; 1642 1643 /* If a query restart will be required, do it here, rather than later of 1644 ** after pointers to poslist buffers that may be invalidated by a restart 1645 ** have been saved. */ 1646 rc = sqlite3Fts3ExprIterate(pCsr->pExpr, fts3ExprRestartIfCb, (void*)&sCtx); 1647 if( rc!=SQLITE_OK ) goto offsets_out; 1648 1649 /* Loop through the table columns, appending offset information to 1650 ** string-buffer res for each column. 1651 */ 1652 for(iCol=0; iColnColumn; iCol++){ 1653 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */ 1654 const char *ZDUMMY; /* Dummy argument used with xNext() */ 1655 int NDUMMY = 0; /* Dummy argument used with xNext() */ 1656 int iStart = 0; 1657 int iEnd = 0; 1658 int iCurrent = 0; 1659 const char *zDoc; 1660 int nDoc; 1661 1662 /* Initialize the contents of sCtx.aTerm[] for column iCol. This 1663 ** operation may fail if the database contains corrupt records. 1664 */ 1665 sCtx.iCol = iCol; 1666 sCtx.iTerm = 0; 1667 rc = sqlite3Fts3ExprIterate( 1668 pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx 1669 ); 1670 if( rc!=SQLITE_OK ) goto offsets_out; 1671 1672 /* Retreive the text stored in column iCol. If an SQL NULL is stored 1673 ** in column iCol, jump immediately to the next iteration of the loop. 1674 ** If an OOM occurs while retrieving the data (this can happen if SQLite 1675 ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 1676 ** to the caller. 1677 */ 1678 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1); 1679 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1); 1680 if( zDoc==0 ){ 1681 if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){ 1682 continue; 1683 } 1684 rc = SQLITE_NOMEM; 1685 goto offsets_out; 1686 } 1687 1688 /* Initialize a tokenizer iterator to iterate through column iCol. */ 1689 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, 1690 zDoc, nDoc, &pC 1691 ); 1692 if( rc!=SQLITE_OK ) goto offsets_out; 1693 1694 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent); 1695 while( rc==SQLITE_OK ){ 1696 int i; /* Used to loop through terms */ 1697 int iMinPos = 0x7FFFFFFF; /* Position of next token */ 1698 TermOffset *pTerm = 0; /* TermOffset associated with next token */ 1699 1700 for(i=0; ipList && (pT->iPos-pT->iOff)iPos-pT->iOff; 1704 pTerm = pT; 1705 } 1706 } 1707 1708 if( !pTerm ){ 1709 /* All offsets for this column have been gathered. */ 1710 rc = SQLITE_DONE; 1711 }else{ 1712 assert_fts3_nc( iCurrent<=iMinPos ); 1713 if( 0==(0xFE&*pTerm->pList) ){ 1714 pTerm->pList = 0; 1715 }else{ 1716 fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos); 1717 } 1718 while( rc==SQLITE_OK && iCurrentxNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent); 1720 } 1721 if( rc==SQLITE_OK ){ 1722 char aBuffer[64]; 1723 sqlite3_snprintf(sizeof(aBuffer), aBuffer, 1724 "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart 1725 ); 1726 rc = fts3StringAppend(&res, aBuffer, -1); 1727 }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){ 1728 rc = FTS_CORRUPT_VTAB; 1729 } 1730 } 1731 } 1732 if( rc==SQLITE_DONE ){ 1733 rc = SQLITE_OK; 1734 } 1735 1736 pMod->xClose(pC); 1737 if( rc!=SQLITE_OK ) goto offsets_out; 1738 } 1739 1740 offsets_out: 1741 sqlite3_free(sCtx.aTerm); 1742 assert( rc!=SQLITE_DONE ); 1743 sqlite3Fts3SegmentsClose(pTab); 1744 if( rc!=SQLITE_OK ){ 1745 sqlite3_result_error_code(pCtx, rc); 1746 sqlite3_free(res.z); 1747 }else{ 1748 sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free); 1749 } 1750 return; 1751 } 1752 1753 /* 1754 ** Implementation of matchinfo() function. 1755 */ 1756 void sqlite3Fts3Matchinfo( 1757 sqlite3_context *pContext, /* Function call context */ 1758 Fts3Cursor *pCsr, /* FTS3 table cursor */ 1759 const char *zArg /* Second arg to matchinfo() function */ 1760 ){ 1761 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; 1762 const char *zFormat; 1763 1764 if( zArg ){ 1765 zFormat = zArg; 1766 }else{ 1767 zFormat = FTS3_MATCHINFO_DEFAULT; 1768 } 1769 1770 if( !pCsr->pExpr ){ 1771 sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC); 1772 return; 1773 }else{ 1774 /* Retrieve matchinfo() data. */ 1775 fts3GetMatchinfo(pContext, pCsr, zFormat); 1776 sqlite3Fts3SegmentsClose(pTab); 1777 } 1778 } 1779 1780 #endif