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/fts5/fts5_aux.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 / fts5 / fts5_aux.c` 846 lines ยท 28009 bytes Raw Blame History 1 /* 2 ** 2014 May 31 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 15 #include "fts5Int.h" 16 #include /* amalgamator: keep */ 17 18 /* 19 ** Object used to iterate through all "coalesced phrase instances" in 20 ** a single column of the current row. If the phrase instances in the 21 ** column being considered do not overlap, this object simply iterates 22 ** through them. Or, if they do overlap (share one or more tokens in 23 ** common), each set of overlapping instances is treated as a single 24 ** match. See documentation for the highlight() auxiliary function for 25 ** details. 26 ** 27 ** Usage is: 28 ** 29 ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter); 30 ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter); 31 ** rc = fts5CInstIterNext(&iter) 32 ** ){ 33 ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd); 34 ** } 35 ** 36 */ 37 typedef struct CInstIter CInstIter; 38 struct CInstIter { 39 const Fts5ExtensionApi *pApi; /* API offered by current FTS version */ 40 Fts5Context *pFts; /* First arg to pass to pApi functions */ 41 int iCol; /* Column to search */ 42 int iInst; /* Next phrase instance index */ 43 int nInst; /* Total number of phrase instances */ 44 45 /* Output variables */ 46 int iStart; /* First token in coalesced phrase instance */ 47 int iEnd; /* Last token in coalesced phrase instance */ 48 }; 49 50 /* 51 ** Advance the iterator to the next coalesced phrase instance. Return 52 ** an SQLite error code if an error occurs, or SQLITE_OK otherwise. 53 */ 54 static int fts5CInstIterNext(CInstIter *pIter){ 55 int rc = SQLITE_OK; 56 pIter->iStart = -1; 57 pIter->iEnd = -1; 58 59 while( rc==SQLITE_OK && pIter->iInstnInst ){ 60 int ip; int ic; int io; 61 rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io); 62 if( rc==SQLITE_OK ){ 63 if( ic==pIter->iCol ){ 64 int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip); 65 if( pIter->iStart<0 ){ 66 pIter->iStart = io; 67 pIter->iEnd = iEnd; 68 }else if( io<=pIter->iEnd ){ 69 if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd; 70 }else{ 71 break; 72 } 73 } 74 pIter->iInst++; 75 } 76 } 77 78 return rc; 79 } 80 81 /* 82 ** Initialize the iterator object indicated by the final parameter to 83 ** iterate through coalesced phrase instances in column iCol. 84 */ 85 static int fts5CInstIterInit( 86 const Fts5ExtensionApi *pApi, 87 Fts5Context *pFts, 88 int iCol, 89 CInstIter *pIter 90 ){ 91 int rc; 92 93 memset(pIter, 0, sizeof(CInstIter)); 94 pIter->pApi = pApi; 95 pIter->pFts = pFts; 96 pIter->iCol = iCol; 97 rc = pApi->xInstCount(pFts, &pIter->nInst); 98 99 if( rc==SQLITE_OK ){ 100 rc = fts5CInstIterNext(pIter); 101 } 102 103 return rc; 104 } 105 106 /* 107 ** Load error code rc into the context handle pCtx. Except, if 108 ** rc==SQLITE_ERROR and there is an error message in the associated db 109 ** handle, return that error message as well. 110 */ 111 static void fts5AuxResultError(sqlite3_context *pCtx, int rc){ 112 if( rc==SQLITE_ERROR ){ 113 sqlite3 *db = sqlite3_context_db_handle(pCtx); 114 if( sqlite3_errcode(db)==SQLITE_ERROR ){ 115 const char *zErr = sqlite3_errmsg(db); 116 sqlite3_result_error(pCtx, zErr, -1); 117 return; 118 } 119 } 120 sqlite3_result_error_code(pCtx, rc); 121 } 122 123 /************************************************************************* 124 ** Start of highlight() implementation. 125 */ 126 typedef struct HighlightContext HighlightContext; 127 struct HighlightContext { 128 /* Constant parameters to fts5HighlightCb() */ 129 int iRangeStart; /* First token to include */ 130 int iRangeEnd; /* If non-zero, last token to include */ 131 const char *zOpen; /* Opening highlight */ 132 const char *zClose; /* Closing highlight */ 133 const char *zIn; /* Input text */ 134 int nIn; /* Size of input text in bytes */ 135 136 /* Variables modified by fts5HighlightCb() */ 137 CInstIter iter; /* Coalesced Instance Iterator */ 138 int iPos; /* Current token offset in zIn[] */ 139 int iOff; /* Have copied up to this offset in zIn[] */ 140 int bOpen; /* True if highlight is open */ 141 char *zOut; /* Output value */ 142 }; 143 144 /* 145 ** Append text to the HighlightContext output string - p->zOut. Argument 146 ** z points to a buffer containing n bytes of text to append. If n is 147 ** negative, everything up until the first '\0' is appended to the output. 148 ** 149 ** If *pRc is set to any value other than SQLITE_OK when this function is 150 ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered, 151 ** *pRc is set to an error code before returning. 152 */ 153 static void fts5HighlightAppend( 154 int *pRc, 155 HighlightContext *p, 156 const char *z, int n 157 ){ 158 if( *pRc==SQLITE_OK && z ){ 159 if( n<0 ) n = (int)strlen(z); 160 p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z); 161 if( p->zOut==0 ) *pRc = SQLITE_NOMEM; 162 } 163 } 164 165 /* 166 ** Tokenizer callback used by implementation of highlight() function. 167 */ 168 static int fts5HighlightCb( 169 void *pContext, /* Pointer to HighlightContext object */ 170 int tflags, /* Mask of FTS5_TOKEN_* flags */ 171 const char *pToken, /* Buffer containing token */ 172 int nToken, /* Size of token in bytes */ 173 int iStartOff, /* Start byte offset of token */ 174 int iEndOff /* End byte offset of token */ 175 ){ 176 HighlightContext *p = (HighlightContext*)pContext; 177 int rc = SQLITE_OK; 178 int iPos; 179 180 UNUSED_PARAM2(pToken, nToken); 181 182 if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK; 183 iPos = p->iPos++; 184 185 if( p->iRangeEnd>=0 ){ 186 if( iPosiRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK; 187 if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff; 188 } 189 190 /* If the parenthesis is open, and this token is not part of the current 191 ** phrase, and the starting byte offset of this token is past the point 192 ** that has currently been copied into the output buffer, close the 193 ** parenthesis. */ 194 if( p->bOpen 195 && (iPos<=p->iter.iStart || p->iter.iStart<0) 196 && iStartOff>p->iOff 197 ){ 198 fts5HighlightAppend(&rc, p, p->zClose, -1); 199 p->bOpen = 0; 200 } 201 202 /* If this is the start of a new phrase, and the highlight is not open: 203 ** 204 ** * copy text from the input up to the start of the phrase, and 205 ** * open the highlight. 206 */ 207 if( iPos==p->iter.iStart && p->bOpen==0 ){ 208 fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff); 209 fts5HighlightAppend(&rc, p, p->zOpen, -1); 210 p->iOff = iStartOff; 211 p->bOpen = 1; 212 } 213 214 if( iPos==p->iter.iEnd ){ 215 if( p->bOpen==0 ){ 216 assert( p->iRangeEnd>=0 ); 217 fts5HighlightAppend(&rc, p, p->zOpen, -1); 218 p->bOpen = 1; 219 } 220 fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff); 221 p->iOff = iEndOff; 222 223 if( rc==SQLITE_OK ){ 224 rc = fts5CInstIterNext(&p->iter); 225 } 226 } 227 228 if( iPos==p->iRangeEnd ){ 229 if( p->bOpen ){ 230 if( p->iter.iStart>=0 && iPos>=p->iter.iStart ){ 231 fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff); 232 p->iOff = iEndOff; 233 } 234 fts5HighlightAppend(&rc, p, p->zClose, -1); 235 p->bOpen = 0; 236 } 237 fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff); 238 p->iOff = iEndOff; 239 } 240 241 return rc; 242 } 243 244 /* 245 ** Return the integer value of pVal, clamped to the range [-1, 0x7FFFFFFF]. 246 ** This is used for the column-number arguments of auxiliary functions, 247 ** so that 64-bit values that are too large or too small to fit in a 248 ** 32-bit signed integer are not truncated to what might be a valid 249 ** column number. 250 */ 251 static int fts5ValueClampedInt(sqlite3_value *pVal){ 252 return (int)MIN(MAX(sqlite3_value_int64(pVal), -1), 0x7FFFFFFF); 253 } 254 255 /* 256 ** Implementation of highlight() function. 257 */ 258 static void fts5HighlightFunction( 259 const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ 260 Fts5Context *pFts, /* First arg to pass to pApi functions */ 261 sqlite3_context *pCtx, /* Context for returning result/error */ 262 int nVal, /* Number of values in apVal[] array */ 263 sqlite3_value **apVal /* Array of trailing arguments */ 264 ){ 265 HighlightContext ctx; 266 int rc; 267 int iCol; 268 269 if( nVal!=3 ){ 270 const char *zErr = "wrong number of arguments to function highlight()"; 271 sqlite3_result_error(pCtx, zErr, -1); 272 return; 273 } 274 275 iCol = fts5ValueClampedInt(apVal[0]); 276 memset(&ctx, 0, sizeof(HighlightContext)); 277 ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]); 278 ctx.zClose = (const char*)sqlite3_value_text(apVal[2]); 279 ctx.iRangeEnd = -1; 280 rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn); 281 if( rc==SQLITE_RANGE ){ 282 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); 283 rc = SQLITE_OK; 284 }else if( ctx.zIn ){ 285 const char *pLoc = 0; /* Locale of column iCol */ 286 int nLoc = 0; /* Size of pLoc in bytes */ 287 if( rc==SQLITE_OK ){ 288 rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter); 289 } 290 291 if( rc==SQLITE_OK ){ 292 rc = pApi->xColumnLocale(pFts, iCol, &pLoc, &nLoc); 293 } 294 if( rc==SQLITE_OK ){ 295 rc = pApi->xTokenize_v2( 296 pFts, ctx.zIn, ctx.nIn, pLoc, nLoc, (void*)&ctx, fts5HighlightCb 297 ); 298 } 299 if( ctx.bOpen ){ 300 fts5HighlightAppend(&rc, &ctx, ctx.zClose, -1); 301 } 302 fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff); 303 304 if( rc==SQLITE_OK ){ 305 sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT); 306 } 307 sqlite3_free(ctx.zOut); 308 } 309 if( rc!=SQLITE_OK ){ 310 fts5AuxResultError(pCtx, rc); 311 } 312 } 313 /* 314 ** End of highlight() implementation. 315 **************************************************************************/ 316 317 /* 318 ** Context object passed to the fts5SentenceFinderCb() function. 319 */ 320 typedef struct Fts5SFinder Fts5SFinder; 321 struct Fts5SFinder { 322 int iPos; /* Current token position */ 323 int nFirstAlloc; /* Allocated size of aFirst[] */ 324 int nFirst; /* Number of entries in aFirst[] */ 325 int *aFirst; /* Array of first token in each sentence */ 326 const char *zDoc; /* Document being tokenized */ 327 }; 328 329 /* 330 ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if 331 ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an 332 ** error occurs. 333 */ 334 static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){ 335 if( p->nFirstAlloc==p->nFirst ){ 336 int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64; 337 int *aNew; 338 339 aNew = (int*)sqlite3_realloc64(p->aFirst, nNew*sizeof(int)); 340 if( aNew==0 ) return SQLITE_NOMEM; 341 p->aFirst = aNew; 342 p->nFirstAlloc = nNew; 343 } 344 p->aFirst[p->nFirst++] = iAdd; 345 return SQLITE_OK; 346 } 347 348 /* 349 ** This function is an xTokenize() callback used by the auxiliary snippet() 350 ** function. Its job is to identify tokens that are the first in a sentence. 351 ** For each such token, an entry is added to the SFinder.aFirst[] array. 352 */ 353 static int fts5SentenceFinderCb( 354 void *pContext, /* Pointer to HighlightContext object */ 355 int tflags, /* Mask of FTS5_TOKEN_* flags */ 356 const char *pToken, /* Buffer containing token */ 357 int nToken, /* Size of token in bytes */ 358 int iStartOff, /* Start offset of token */ 359 int iEndOff /* End offset of token */ 360 ){ 361 int rc = SQLITE_OK; 362 363 UNUSED_PARAM2(pToken, nToken); 364 UNUSED_PARAM(iEndOff); 365 366 if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){ 367 Fts5SFinder *p = (Fts5SFinder*)pContext; 368 if( p->iPos>0 ){ 369 int i; 370 char c = 0; 371 for(i=iStartOff-1; i>=0; i--){ 372 c = p->zDoc[i]; 373 if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break; 374 } 375 if( i!=iStartOff-1 && (c=='.' || c==':') ){ 376 rc = fts5SentenceFinderAdd(p, p->iPos); 377 } 378 }else{ 379 rc = fts5SentenceFinderAdd(p, 0); 380 } 381 p->iPos++; 382 } 383 return rc; 384 } 385 386 static int fts5SnippetScore( 387 const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ 388 Fts5Context *pFts, /* First arg to pass to pApi functions */ 389 int nDocsize, /* Size of column in tokens */ 390 unsigned char *aSeen, /* Array with one element per query phrase */ 391 int iCol, /* Column to score */ 392 int iPos, /* Starting offset to score */ 393 int nToken, /* Max tokens per snippet */ 394 int *pnScore, /* OUT: Score */ 395 int *piPos /* OUT: Adjusted offset */ 396 ){ 397 int rc; 398 int i; 399 int ip = 0; 400 int ic = 0; 401 int iOff = 0; 402 int iFirst = -1; 403 int nInst; 404 int nScore = 0; 405 int iLast = 0; 406 sqlite3_int64 iEnd = (sqlite3_int64)iPos + nToken; 407 408 rc = pApi->xInstCount(pFts, &nInst); 409 for(i=0; ixInst(pFts, i, &ip, &ic, &iOff); 411 if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOffxPhraseSize(pFts, ip); 416 } 417 } 418 419 *pnScore = nScore; 420 if( piPos ){ 421 sqlite3_int64 iAdj = iFirst - (nToken - (iLast-iFirst)) / 2; 422 if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken; 423 if( iAdj<0 ) iAdj = 0; 424 *piPos = (int)iAdj; 425 } 426 427 return rc; 428 } 429 430 /* 431 ** Return the value in pVal interpreted as utf-8 text. Except, if pVal 432 ** contains a NULL value, return a pointer to a static string zero 433 ** bytes in length instead of a NULL pointer. 434 */ 435 static const char *fts5ValueToText(sqlite3_value *pVal){ 436 const char *zRet = (const char*)sqlite3_value_text(pVal); 437 return zRet ? zRet : ""; 438 } 439 440 /* 441 ** Implementation of snippet() function. 442 */ 443 static void fts5SnippetFunction( 444 const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ 445 Fts5Context *pFts, /* First arg to pass to pApi functions */ 446 sqlite3_context *pCtx, /* Context for returning result/error */ 447 int nVal, /* Number of values in apVal[] array */ 448 sqlite3_value **apVal /* Array of trailing arguments */ 449 ){ 450 HighlightContext ctx; 451 int rc = SQLITE_OK; /* Return code */ 452 int iCol; /* 1st argument to snippet() */ 453 const char *zEllips; /* 4th argument to snippet() */ 454 i64 nToken; /* 5th argument to snippet() */ 455 int nInst = 0; /* Number of instance matches this row */ 456 int i; /* Used to iterate through instances */ 457 int nPhrase; /* Number of phrases in query */ 458 unsigned char *aSeen; /* Array of "seen instance" flags */ 459 int iBestCol; /* Column containing best snippet */ 460 int iBestStart = 0; /* First token of best snippet */ 461 int nBestScore = 0; /* Score of best snippet */ 462 int nColSize = 0; /* Total size of iBestCol in tokens */ 463 Fts5SFinder sFinder; /* Used to find the beginnings of sentences */ 464 int nCol; 465 466 if( nVal!=5 ){ 467 const char *zErr = "wrong number of arguments to function snippet()"; 468 sqlite3_result_error(pCtx, zErr, -1); 469 return; 470 } 471 472 nCol = pApi->xColumnCount(pFts); 473 memset(&ctx, 0, sizeof(HighlightContext)); 474 iCol = fts5ValueClampedInt(apVal[0]); 475 ctx.zOpen = fts5ValueToText(apVal[1]); 476 ctx.zClose = fts5ValueToText(apVal[2]); 477 ctx.iRangeEnd = -1; 478 zEllips = fts5ValueToText(apVal[3]); 479 nToken = (int)(MIN( MAX(sqlite3_value_int64(apVal[4]), 0), 64)); 480 481 iBestCol = (iCol>=0 ? iCol : 0); 482 nPhrase = pApi->xPhraseCount(pFts); 483 aSeen = sqlite3_malloc64(nPhrase); 484 if( aSeen==0 ){ 485 rc = SQLITE_NOMEM; 486 } 487 if( rc==SQLITE_OK ){ 488 rc = pApi->xInstCount(pFts, &nInst); 489 } 490 491 memset(&sFinder, 0, sizeof(Fts5SFinder)); 492 for(i=0; ixColumnText(pFts, i, &sFinder.zDoc, &nDoc); 502 if( rc!=SQLITE_OK ) break; 503 rc = pApi->xColumnLocale(pFts, i, &pLoc, &nLoc); 504 if( rc!=SQLITE_OK ) break; 505 rc = pApi->xTokenize_v2(pFts, 506 sFinder.zDoc, nDoc, pLoc, nLoc, (void*)&sFinder, fts5SentenceFinderCb 507 ); 508 if( rc!=SQLITE_OK ) break; 509 rc = pApi->xColumnSize(pFts, i, &nDocsize); 510 if( rc!=SQLITE_OK ) break; 511 512 for(ii=0; rc==SQLITE_OK && iixInst(pFts, ii, &ip, &ic, &io); 519 if( ic!=i ) continue; 520 if( io>nDocsize ) rc = FTS5_CORRUPT; 521 if( rc!=SQLITE_OK ) continue; 522 memset(aSeen, 0, nPhrase); 523 rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i, 524 io, nToken, &nScore, &iAdj 525 ); 526 if( rc==SQLITE_OK && nScore>nBestScore ){ 527 nBestScore = nScore; 528 iBestCol = i; 529 iBestStart = iAdj; 530 nColSize = nDocsize; 531 } 532 533 if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){ 534 for(jj=0; jj<(sFinder.nFirst-1); jj++){ 535 if( sFinder.aFirst[jj+1]>io ) break; 536 } 537 538 if( sFinder.aFirst[jj]nBestScore ){ 546 nBestScore = nScore; 547 iBestCol = i; 548 iBestStart = sFinder.aFirst[jj]; 549 nColSize = nDocsize; 550 } 551 } 552 } 553 } 554 } 555 } 556 557 if( rc==SQLITE_OK ){ 558 rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn); 559 } 560 if( rc==SQLITE_OK && nColSize==0 ){ 561 rc = pApi->xColumnSize(pFts, iBestCol, &nColSize); 562 } 563 if( ctx.zIn ){ 564 const char *pLoc = 0; /* Locale of column iBestCol */ 565 int nLoc = 0; /* Bytes in pLoc */ 566 567 if( rc==SQLITE_OK ){ 568 rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter); 569 } 570 571 ctx.iRangeStart = iBestStart; 572 ctx.iRangeEnd = iBestStart + nToken - 1; 573 574 if( iBestStart>0 ){ 575 fts5HighlightAppend(&rc, &ctx, zEllips, -1); 576 } 577 578 /* Advance iterator ctx.iter so that it points to the first coalesced 579 ** phrase instance at or following position iBestStart. */ 580 while( ctx.iter.iStart>=0 && ctx.iter.iStartxColumnLocale(pFts, iBestCol, &pLoc, &nLoc); 586 } 587 if( rc==SQLITE_OK ){ 588 rc = pApi->xTokenize_v2( 589 pFts, ctx.zIn, ctx.nIn, pLoc, nLoc, (void*)&ctx,fts5HighlightCb 590 ); 591 } 592 if( ctx.bOpen ){ 593 fts5HighlightAppend(&rc, &ctx, ctx.zClose, -1); 594 } 595 if( ctx.iRangeEnd>=(nColSize-1) ){ 596 fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff); 597 }else{ 598 fts5HighlightAppend(&rc, &ctx, zEllips, -1); 599 } 600 } 601 if( rc==SQLITE_OK ){ 602 sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT); 603 }else{ 604 fts5AuxResultError(pCtx, rc); 605 } 606 sqlite3_free(ctx.zOut); 607 sqlite3_free(aSeen); 608 sqlite3_free(sFinder.aFirst); 609 } 610 611 /************************************************************************/ 612 613 /* 614 ** The first time the bm25() function is called for a query, an instance 615 ** of the following structure is allocated and populated. 616 */ 617 typedef struct Fts5Bm25Data Fts5Bm25Data; 618 struct Fts5Bm25Data { 619 int nPhrase; /* Number of phrases in query */ 620 double avgdl; /* Average number of tokens in each row */ 621 double *aIDF; /* IDF for each phrase */ 622 double *aFreq; /* Array used to calculate phrase freq. */ 623 }; 624 625 /* 626 ** Callback used by fts5Bm25GetData() to count the number of rows in the 627 ** table matched by each individual phrase within the query. 628 */ 629 static int fts5CountCb( 630 const Fts5ExtensionApi *pApi, 631 Fts5Context *pFts, 632 void *pUserData /* Pointer to sqlite3_int64 variable */ 633 ){ 634 sqlite3_int64 *pn = (sqlite3_int64*)pUserData; 635 UNUSED_PARAM2(pApi, pFts); 636 (*pn)++; 637 return SQLITE_OK; 638 } 639 640 /* 641 ** Set *ppData to point to the Fts5Bm25Data object for the current query. 642 ** If the object has not already been allocated, allocate and populate it 643 ** now. 644 */ 645 static int fts5Bm25GetData( 646 const Fts5ExtensionApi *pApi, 647 Fts5Context *pFts, 648 Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */ 649 ){ 650 int rc = SQLITE_OK; /* Return code */ 651 Fts5Bm25Data *p; /* Object to return */ 652 653 p = (Fts5Bm25Data*)pApi->xGetAuxdata(pFts, 0); 654 if( p==0 ){ 655 int nPhrase; /* Number of phrases in query */ 656 sqlite3_int64 nRow = 0; /* Number of rows in table */ 657 sqlite3_int64 nToken = 0; /* Number of tokens in table */ 658 sqlite3_int64 nByte; /* Bytes of space to allocate */ 659 int i; 660 661 /* Allocate the Fts5Bm25Data object */ 662 nPhrase = pApi->xPhraseCount(pFts); 663 nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double); 664 p = (Fts5Bm25Data*)sqlite3_malloc64(nByte); 665 if( p==0 ){ 666 rc = SQLITE_NOMEM; 667 }else{ 668 memset(p, 0, (size_t)nByte); 669 p->nPhrase = nPhrase; 670 p->aIDF = (double*)&p[1]; 671 p->aFreq = &p->aIDF[nPhrase]; 672 } 673 674 /* Calculate the average document length for this FTS5 table */ 675 if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow); 676 assert( rc!=SQLITE_OK || nRow>0 ); 677 if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken); 678 if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow; 679 680 /* Calculate an IDF for each phrase in the query */ 681 for(i=0; rc==SQLITE_OK && ixQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb); 684 if( rc==SQLITE_OK ){ 685 /* Calculate the IDF (Inverse Document Frequency) for phrase i. 686 ** This is done using the standard BM25 formula as found on wikipedia: 687 ** 688 ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) ) 689 ** 690 ** where "N" is the total number of documents in the set and nHit 691 ** is the number that contain at least one instance of the phrase 692 ** under consideration. 693 ** 694 ** The problem with this is that if (N < 2*nHit), the IDF is 695 ** negative. Which is undesirable. So the minimum allowable IDF is 696 ** (1e-6) - roughly the same as a term that appears in just over 697 ** half of set of 5,000,000 documents. */ 698 double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) ); 699 if( idf<=0.0 ) idf = 1e-6; 700 p->aIDF[i] = idf; 701 } 702 } 703 704 if( rc!=SQLITE_OK ){ 705 sqlite3_free(p); 706 }else{ 707 rc = pApi->xSetAuxdata(pFts, p, sqlite3_free); 708 } 709 if( rc!=SQLITE_OK ) p = 0; 710 } 711 *ppData = p; 712 return rc; 713 } 714 715 /* 716 ** Implementation of bm25() function. 717 */ 718 static void fts5Bm25Function( 719 const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ 720 Fts5Context *pFts, /* First arg to pass to pApi functions */ 721 sqlite3_context *pCtx, /* Context for returning result/error */ 722 int nVal, /* Number of values in apVal[] array */ 723 sqlite3_value **apVal /* Array of trailing arguments */ 724 ){ 725 const double k1 = 1.2; /* Constant "k1" from BM25 formula */ 726 const double b = 0.75; /* Constant "b" from BM25 formula */ 727 int rc; /* Error code */ 728 double score = 0.0; /* SQL function return value */ 729 Fts5Bm25Data *pData; /* Values allocated/calculated once only */ 730 int i; /* Iterator variable */ 731 int nInst = 0; /* Value returned by xInstCount() */ 732 double D = 0.0; /* Total number of tokens in row */ 733 double *aFreq = 0; /* Array of phrase freq. for current row */ 734 735 /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation) 736 ** for each phrase in the query for the current row. */ 737 rc = fts5Bm25GetData(pApi, pFts, &pData); 738 if( rc==SQLITE_OK ){ 739 aFreq = pData->aFreq; 740 memset(aFreq, 0, sizeof(double) * pData->nPhrase); 741 rc = pApi->xInstCount(pFts, &nInst); 742 } 743 for(i=0; rc==SQLITE_OK && ixInst(pFts, i, &ip, &ic, &io); 746 if( rc==SQLITE_OK ){ 747 double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0; 748 aFreq[ip] += w; 749 } 750 } 751 752 /* Figure out the total size of the current row in tokens. */ 753 if( rc==SQLITE_OK ){ 754 int nTok; 755 rc = pApi->xColumnSize(pFts, -1, &nTok); 756 D = (double)nTok; 757 } 758 759 /* Determine and return the BM25 score for the current row. Or, if an 760 ** error has occurred, throw an exception. */ 761 if( rc==SQLITE_OK ){ 762 for(i=0; inPhrase; i++){ 763 score += pData->aIDF[i] * ( 764 ( aFreq[i] * (k1 + 1.0) ) / 765 ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) ) 766 ); 767 } 768 sqlite3_result_double(pCtx, -1.0 * score); 769 }else{ 770 fts5AuxResultError(pCtx, rc); 771 } 772 } 773 774 /* 775 ** Implementation of fts5_get_locale() function. 776 */ 777 static void fts5GetLocaleFunction( 778 const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ 779 Fts5Context *pFts, /* First arg to pass to pApi functions */ 780 sqlite3_context *pCtx, /* Context for returning result/error */ 781 int nVal, /* Number of values in apVal[] array */ 782 sqlite3_value **apVal /* Array of trailing arguments */ 783 ){ 784 int iCol = 0; 785 int eType = 0; 786 int rc = SQLITE_OK; 787 const char *zLocale = 0; 788 int nLocale = 0; 789 790 /* xColumnLocale() must be available */ 791 assert( pApi->iVersion>=4 ); 792 793 if( nVal!=1 ){ 794 const char *z = "wrong number of arguments to function fts5_get_locale()"; 795 sqlite3_result_error(pCtx, z, -1); 796 return; 797 } 798 799 eType = sqlite3_value_numeric_type(apVal[0]); 800 if( eType!=SQLITE_INTEGER ){ 801 const char *z = "non-integer argument passed to function fts5_get_locale()"; 802 sqlite3_result_error(pCtx, z, -1); 803 return; 804 } 805 806 iCol = fts5ValueClampedInt(apVal[0]); 807 if( iCol<0 || iCol>=pApi->xColumnCount(pFts) ){ 808 fts5AuxResultError(pCtx, SQLITE_RANGE); 809 return; 810 } 811 812 rc = pApi->xColumnLocale(pFts, iCol, &zLocale, &nLocale); 813 if( rc!=SQLITE_OK ){ 814 fts5AuxResultError(pCtx, rc); 815 return; 816 } 817 818 sqlite3_result_text(pCtx, zLocale, nLocale, SQLITE_TRANSIENT); 819 } 820 821 int sqlite3Fts5AuxInit(fts5_api *pApi){ 822 struct Builtin { 823 const char *zFunc; /* Function name (nul-terminated) */ 824 void *pUserData; /* User-data pointer */ 825 fts5_extension_function xFunc;/* Callback function */ 826 void (*xDestroy)(void*); /* Destructor function */ 827 } aBuiltin [] = { 828 { "snippet", 0, fts5SnippetFunction, 0 }, 829 { "highlight", 0, fts5HighlightFunction, 0 }, 830 { "bm25", 0, fts5Bm25Function, 0 }, 831 { "fts5_get_locale", 0, fts5GetLocaleFunction, 0 }, 832 }; 833 int rc = SQLITE_OK; /* Return code */ 834 int i; /* To iterate through builtin functions */ 835 836 for(i=0; rc==SQLITE_OK && ixCreateFunction(pApi, 838 aBuiltin[i].zFunc, 839 aBuiltin[i].pUserData, 840 aBuiltin[i].xFunc, 841 aBuiltin[i].xDestroy 842 ); 843 } 844 845 return rc; 846 }