Add a test for the fixes on this branch.
[sqlite.git] / ext / fts5 / fts5_expr.c
blob05c1b59c145cfad217d486f9b47b5a3c1480e52f
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.
11 ******************************************************************************
17 #include "fts5Int.h"
18 #include "fts5parse.h"
20 #ifndef SQLITE_FTS5_MAX_EXPR_DEPTH
21 # define SQLITE_FTS5_MAX_EXPR_DEPTH 256
22 #endif
25 ** All token types in the generated fts5parse.h file are greater than 0.
27 #define FTS5_EOF 0
29 #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
31 typedef struct Fts5ExprTerm Fts5ExprTerm;
34 ** Functions generated by lemon from fts5parse.y.
36 void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
37 void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
38 void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
39 #ifndef NDEBUG
40 #include <stdio.h>
41 void sqlite3Fts5ParserTrace(FILE*, char*);
42 #endif
43 int sqlite3Fts5ParserFallback(int);
46 struct Fts5Expr {
47 Fts5Index *pIndex;
48 Fts5Config *pConfig;
49 Fts5ExprNode *pRoot;
50 int bDesc; /* Iterate in descending rowid order */
51 int nPhrase; /* Number of phrases in expression */
52 Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
56 ** eType:
57 ** Expression node type. Always one of:
59 ** FTS5_AND (nChild, apChild valid)
60 ** FTS5_OR (nChild, apChild valid)
61 ** FTS5_NOT (nChild, apChild valid)
62 ** FTS5_STRING (pNear valid)
63 ** FTS5_TERM (pNear valid)
65 ** iHeight:
66 ** Distance from this node to furthest leaf. This is always 0 for nodes
67 ** of type FTS5_STRING and FTS5_TERM. For all other nodes it is one
68 ** greater than the largest child value.
70 struct Fts5ExprNode {
71 int eType; /* Node type */
72 int bEof; /* True at EOF */
73 int bNomatch; /* True if entry is not a match */
74 int iHeight; /* Distance to tree leaf nodes */
76 /* Next method for this node. */
77 int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
79 i64 iRowid; /* Current rowid */
80 Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
82 /* Child nodes. For a NOT node, this array always contains 2 entries. For
83 ** AND or OR nodes, it contains 2 or more entries. */
84 int nChild; /* Number of child nodes */
85 Fts5ExprNode *apChild[1]; /* Array of child nodes */
88 #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
91 ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
92 ** used as if it has the same signature as the xNext() methods themselves.
94 #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
97 ** An instance of the following structure represents a single search term
98 ** or term prefix.
100 struct Fts5ExprTerm {
101 u8 bPrefix; /* True for a prefix term */
102 u8 bFirst; /* True if token must be first in column */
103 char *pTerm; /* Term data */
104 int nQueryTerm; /* Effective size of term in bytes */
105 int nFullTerm; /* Size of term in bytes incl. tokendata */
106 Fts5IndexIter *pIter; /* Iterator for this term */
107 Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
111 ** A phrase. One or more terms that must appear in a contiguous sequence
112 ** within a document for it to match.
114 struct Fts5ExprPhrase {
115 Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
116 Fts5Buffer poslist; /* Current position list */
117 int nTerm; /* Number of entries in aTerm[] */
118 Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
122 ** One or more phrases that must appear within a certain token distance of
123 ** each other within each matching document.
125 struct Fts5ExprNearset {
126 int nNear; /* NEAR parameter */
127 Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
128 int nPhrase; /* Number of entries in aPhrase[] array */
129 Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
134 ** Parse context.
136 struct Fts5Parse {
137 Fts5Config *pConfig;
138 char *zErr;
139 int rc;
140 int nPhrase; /* Size of apPhrase array */
141 Fts5ExprPhrase **apPhrase; /* Array of all phrases */
142 Fts5ExprNode *pExpr; /* Result of a successful parse */
143 int bPhraseToAnd; /* Convert "a+b" to "a AND b" */
147 ** Check that the Fts5ExprNode.iHeight variables are set correctly in
148 ** the expression tree passed as the only argument.
150 #ifndef NDEBUG
151 static void assert_expr_depth_ok(int rc, Fts5ExprNode *p){
152 if( rc==SQLITE_OK ){
153 if( p->eType==FTS5_TERM || p->eType==FTS5_STRING || p->eType==0 ){
154 assert( p->iHeight==0 );
155 }else{
156 int ii;
157 int iMaxChild = 0;
158 for(ii=0; ii<p->nChild; ii++){
159 Fts5ExprNode *pChild = p->apChild[ii];
160 iMaxChild = MAX(iMaxChild, pChild->iHeight);
161 assert_expr_depth_ok(SQLITE_OK, pChild);
163 assert( p->iHeight==iMaxChild+1 );
167 #else
168 # define assert_expr_depth_ok(rc, p)
169 #endif
171 void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
172 va_list ap;
173 va_start(ap, zFmt);
174 if( pParse->rc==SQLITE_OK ){
175 assert( pParse->zErr==0 );
176 pParse->zErr = sqlite3_vmprintf(zFmt, ap);
177 pParse->rc = SQLITE_ERROR;
179 va_end(ap);
182 static int fts5ExprIsspace(char t){
183 return t==' ' || t=='\t' || t=='\n' || t=='\r';
187 ** Read the first token from the nul-terminated string at *pz.
189 static int fts5ExprGetToken(
190 Fts5Parse *pParse,
191 const char **pz, /* IN/OUT: Pointer into buffer */
192 Fts5Token *pToken
194 const char *z = *pz;
195 int tok;
197 /* Skip past any whitespace */
198 while( fts5ExprIsspace(*z) ) z++;
200 pToken->p = z;
201 pToken->n = 1;
202 switch( *z ){
203 case '(': tok = FTS5_LP; break;
204 case ')': tok = FTS5_RP; break;
205 case '{': tok = FTS5_LCP; break;
206 case '}': tok = FTS5_RCP; break;
207 case ':': tok = FTS5_COLON; break;
208 case ',': tok = FTS5_COMMA; break;
209 case '+': tok = FTS5_PLUS; break;
210 case '*': tok = FTS5_STAR; break;
211 case '-': tok = FTS5_MINUS; break;
212 case '^': tok = FTS5_CARET; break;
213 case '\0': tok = FTS5_EOF; break;
215 case '"': {
216 const char *z2;
217 tok = FTS5_STRING;
219 for(z2=&z[1]; 1; z2++){
220 if( z2[0]=='"' ){
221 z2++;
222 if( z2[0]!='"' ) break;
224 if( z2[0]=='\0' ){
225 sqlite3Fts5ParseError(pParse, "unterminated string");
226 return FTS5_EOF;
229 pToken->n = (z2 - z);
230 break;
233 default: {
234 const char *z2;
235 if( sqlite3Fts5IsBareword(z[0])==0 ){
236 sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
237 return FTS5_EOF;
239 tok = FTS5_STRING;
240 for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
241 pToken->n = (z2 - z);
242 if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
243 if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
244 if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
245 break;
249 *pz = &pToken->p[pToken->n];
250 return tok;
253 static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc64((sqlite3_int64)t);}
254 static void fts5ParseFree(void *p){ sqlite3_free(p); }
256 int sqlite3Fts5ExprNew(
257 Fts5Config *pConfig, /* FTS5 Configuration */
258 int bPhraseToAnd,
259 int iCol,
260 const char *zExpr, /* Expression text */
261 Fts5Expr **ppNew,
262 char **pzErr
264 Fts5Parse sParse;
265 Fts5Token token;
266 const char *z = zExpr;
267 int t; /* Next token type */
268 void *pEngine;
269 Fts5Expr *pNew;
271 *ppNew = 0;
272 *pzErr = 0;
273 memset(&sParse, 0, sizeof(sParse));
274 sParse.bPhraseToAnd = bPhraseToAnd;
275 pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
276 if( pEngine==0 ){ return SQLITE_NOMEM; }
277 sParse.pConfig = pConfig;
279 do {
280 t = fts5ExprGetToken(&sParse, &z, &token);
281 sqlite3Fts5Parser(pEngine, t, token, &sParse);
282 }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
283 sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
285 assert_expr_depth_ok(sParse.rc, sParse.pExpr);
287 /* If the LHS of the MATCH expression was a user column, apply the
288 ** implicit column-filter. */
289 if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
290 int n = sizeof(Fts5Colset);
291 Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
292 if( pColset ){
293 pColset->nCol = 1;
294 pColset->aiCol[0] = iCol;
295 sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
299 assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
300 if( sParse.rc==SQLITE_OK ){
301 *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
302 if( pNew==0 ){
303 sParse.rc = SQLITE_NOMEM;
304 sqlite3Fts5ParseNodeFree(sParse.pExpr);
305 }else{
306 if( !sParse.pExpr ){
307 const int nByte = sizeof(Fts5ExprNode);
308 pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
309 if( pNew->pRoot ){
310 pNew->pRoot->bEof = 1;
312 }else{
313 pNew->pRoot = sParse.pExpr;
315 pNew->pIndex = 0;
316 pNew->pConfig = pConfig;
317 pNew->apExprPhrase = sParse.apPhrase;
318 pNew->nPhrase = sParse.nPhrase;
319 pNew->bDesc = 0;
320 sParse.apPhrase = 0;
322 }else{
323 sqlite3Fts5ParseNodeFree(sParse.pExpr);
326 sqlite3_free(sParse.apPhrase);
327 *pzErr = sParse.zErr;
328 return sParse.rc;
332 ** Assuming that buffer z is at least nByte bytes in size and contains a
333 ** valid utf-8 string, return the number of characters in the string.
335 static int fts5ExprCountChar(const char *z, int nByte){
336 int nRet = 0;
337 int ii;
338 for(ii=0; ii<nByte; ii++){
339 if( (z[ii] & 0xC0)!=0x80 ) nRet++;
341 return nRet;
345 ** This function is only called when using the special 'trigram' tokenizer.
346 ** Argument zText contains the text of a LIKE or GLOB pattern matched
347 ** against column iCol. This function creates and compiles an FTS5 MATCH
348 ** expression that will match a superset of the rows matched by the LIKE or
349 ** GLOB. If successful, SQLITE_OK is returned. Otherwise, an SQLite error
350 ** code.
352 int sqlite3Fts5ExprPattern(
353 Fts5Config *pConfig, int bGlob, int iCol, const char *zText, Fts5Expr **pp
355 i64 nText = strlen(zText);
356 char *zExpr = (char*)sqlite3_malloc64(nText*4 + 1);
357 int rc = SQLITE_OK;
359 if( zExpr==0 ){
360 rc = SQLITE_NOMEM;
361 }else{
362 char aSpec[3];
363 int iOut = 0;
364 int i = 0;
365 int iFirst = 0;
367 if( bGlob==0 ){
368 aSpec[0] = '_';
369 aSpec[1] = '%';
370 aSpec[2] = 0;
371 }else{
372 aSpec[0] = '*';
373 aSpec[1] = '?';
374 aSpec[2] = '[';
377 while( i<=nText ){
378 if( i==nText
379 || zText[i]==aSpec[0] || zText[i]==aSpec[1] || zText[i]==aSpec[2]
382 if( fts5ExprCountChar(&zText[iFirst], i-iFirst)>=3 ){
383 int jj;
384 zExpr[iOut++] = '"';
385 for(jj=iFirst; jj<i; jj++){
386 zExpr[iOut++] = zText[jj];
387 if( zText[jj]=='"' ) zExpr[iOut++] = '"';
389 zExpr[iOut++] = '"';
390 zExpr[iOut++] = ' ';
392 if( zText[i]==aSpec[2] ){
393 i += 2;
394 if( zText[i-1]=='^' ) i++;
395 while( i<nText && zText[i]!=']' ) i++;
397 iFirst = i+1;
399 i++;
401 if( iOut>0 ){
402 int bAnd = 0;
403 if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
404 bAnd = 1;
405 if( pConfig->eDetail==FTS5_DETAIL_NONE ){
406 iCol = pConfig->nCol;
409 zExpr[iOut] = '\0';
410 rc = sqlite3Fts5ExprNew(pConfig, bAnd, iCol, zExpr, pp,pConfig->pzErrmsg);
411 }else{
412 *pp = 0;
414 sqlite3_free(zExpr);
417 return rc;
421 ** Free the expression node object passed as the only argument.
423 void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
424 if( p ){
425 int i;
426 for(i=0; i<p->nChild; i++){
427 sqlite3Fts5ParseNodeFree(p->apChild[i]);
429 sqlite3Fts5ParseNearsetFree(p->pNear);
430 sqlite3_free(p);
435 ** Free the expression object passed as the only argument.
437 void sqlite3Fts5ExprFree(Fts5Expr *p){
438 if( p ){
439 sqlite3Fts5ParseNodeFree(p->pRoot);
440 sqlite3_free(p->apExprPhrase);
441 sqlite3_free(p);
445 int sqlite3Fts5ExprAnd(Fts5Expr **pp1, Fts5Expr *p2){
446 Fts5Parse sParse;
447 memset(&sParse, 0, sizeof(sParse));
449 if( *pp1 && p2 ){
450 Fts5Expr *p1 = *pp1;
451 int nPhrase = p1->nPhrase + p2->nPhrase;
453 p1->pRoot = sqlite3Fts5ParseNode(&sParse, FTS5_AND, p1->pRoot, p2->pRoot,0);
454 p2->pRoot = 0;
456 if( sParse.rc==SQLITE_OK ){
457 Fts5ExprPhrase **ap = (Fts5ExprPhrase**)sqlite3_realloc(
458 p1->apExprPhrase, nPhrase * sizeof(Fts5ExprPhrase*)
460 if( ap==0 ){
461 sParse.rc = SQLITE_NOMEM;
462 }else{
463 int i;
464 memmove(&ap[p2->nPhrase], ap, p1->nPhrase*sizeof(Fts5ExprPhrase*));
465 for(i=0; i<p2->nPhrase; i++){
466 ap[i] = p2->apExprPhrase[i];
468 p1->nPhrase = nPhrase;
469 p1->apExprPhrase = ap;
472 sqlite3_free(p2->apExprPhrase);
473 sqlite3_free(p2);
474 }else if( p2 ){
475 *pp1 = p2;
478 return sParse.rc;
482 ** Argument pTerm must be a synonym iterator. Return the current rowid
483 ** that it points to.
485 static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
486 i64 iRet = 0;
487 int bRetValid = 0;
488 Fts5ExprTerm *p;
490 assert( pTerm );
491 assert( pTerm->pSynonym );
492 assert( bDesc==0 || bDesc==1 );
493 for(p=pTerm; p; p=p->pSynonym){
494 if( 0==sqlite3Fts5IterEof(p->pIter) ){
495 i64 iRowid = p->pIter->iRowid;
496 if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
497 iRet = iRowid;
498 bRetValid = 1;
503 if( pbEof && bRetValid==0 ) *pbEof = 1;
504 return iRet;
508 ** Argument pTerm must be a synonym iterator.
510 static int fts5ExprSynonymList(
511 Fts5ExprTerm *pTerm,
512 i64 iRowid,
513 Fts5Buffer *pBuf, /* Use this buffer for space if required */
514 u8 **pa, int *pn
516 Fts5PoslistReader aStatic[4];
517 Fts5PoslistReader *aIter = aStatic;
518 int nIter = 0;
519 int nAlloc = 4;
520 int rc = SQLITE_OK;
521 Fts5ExprTerm *p;
523 assert( pTerm->pSynonym );
524 for(p=pTerm; p; p=p->pSynonym){
525 Fts5IndexIter *pIter = p->pIter;
526 if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
527 if( pIter->nData==0 ) continue;
528 if( nIter==nAlloc ){
529 sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
530 Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc64(nByte);
531 if( aNew==0 ){
532 rc = SQLITE_NOMEM;
533 goto synonym_poslist_out;
535 memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
536 nAlloc = nAlloc*2;
537 if( aIter!=aStatic ) sqlite3_free(aIter);
538 aIter = aNew;
540 sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
541 assert( aIter[nIter].bEof==0 );
542 nIter++;
546 if( nIter==1 ){
547 *pa = (u8*)aIter[0].a;
548 *pn = aIter[0].n;
549 }else{
550 Fts5PoslistWriter writer = {0};
551 i64 iPrev = -1;
552 fts5BufferZero(pBuf);
553 while( 1 ){
554 int i;
555 i64 iMin = FTS5_LARGEST_INT64;
556 for(i=0; i<nIter; i++){
557 if( aIter[i].bEof==0 ){
558 if( aIter[i].iPos==iPrev ){
559 if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
561 if( aIter[i].iPos<iMin ){
562 iMin = aIter[i].iPos;
566 if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
567 rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
568 iPrev = iMin;
570 if( rc==SQLITE_OK ){
571 *pa = pBuf->p;
572 *pn = pBuf->n;
576 synonym_poslist_out:
577 if( aIter!=aStatic ) sqlite3_free(aIter);
578 return rc;
583 ** All individual term iterators in pPhrase are guaranteed to be valid and
584 ** pointing to the same rowid when this function is called. This function
585 ** checks if the current rowid really is a match, and if so populates
586 ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
587 ** is set to true if this is really a match, or false otherwise.
589 ** SQLITE_OK is returned if an error occurs, or an SQLite error code
590 ** otherwise. It is not considered an error code if the current rowid is
591 ** not a match.
593 static int fts5ExprPhraseIsMatch(
594 Fts5ExprNode *pNode, /* Node pPhrase belongs to */
595 Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
596 int *pbMatch /* OUT: Set to true if really a match */
598 Fts5PoslistWriter writer = {0};
599 Fts5PoslistReader aStatic[4];
600 Fts5PoslistReader *aIter = aStatic;
601 int i;
602 int rc = SQLITE_OK;
603 int bFirst = pPhrase->aTerm[0].bFirst;
605 fts5BufferZero(&pPhrase->poslist);
607 /* If the aStatic[] array is not large enough, allocate a large array
608 ** using sqlite3_malloc(). This approach could be improved upon. */
609 if( pPhrase->nTerm>ArraySize(aStatic) ){
610 sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
611 aIter = (Fts5PoslistReader*)sqlite3_malloc64(nByte);
612 if( !aIter ) return SQLITE_NOMEM;
614 memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
616 /* Initialize a term iterator for each term in the phrase */
617 for(i=0; i<pPhrase->nTerm; i++){
618 Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
619 int n = 0;
620 int bFlag = 0;
621 u8 *a = 0;
622 if( pTerm->pSynonym ){
623 Fts5Buffer buf = {0, 0, 0};
624 rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
625 if( rc ){
626 sqlite3_free(a);
627 goto ismatch_out;
629 if( a==buf.p ) bFlag = 1;
630 }else{
631 a = (u8*)pTerm->pIter->pData;
632 n = pTerm->pIter->nData;
634 sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
635 aIter[i].bFlag = (u8)bFlag;
636 if( aIter[i].bEof ) goto ismatch_out;
639 while( 1 ){
640 int bMatch;
641 i64 iPos = aIter[0].iPos;
642 do {
643 bMatch = 1;
644 for(i=0; i<pPhrase->nTerm; i++){
645 Fts5PoslistReader *pPos = &aIter[i];
646 i64 iAdj = iPos + i;
647 if( pPos->iPos!=iAdj ){
648 bMatch = 0;
649 while( pPos->iPos<iAdj ){
650 if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
652 if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
655 }while( bMatch==0 );
657 /* Append position iPos to the output */
658 if( bFirst==0 || FTS5_POS2OFFSET(iPos)==0 ){
659 rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
660 if( rc!=SQLITE_OK ) goto ismatch_out;
663 for(i=0; i<pPhrase->nTerm; i++){
664 if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
668 ismatch_out:
669 *pbMatch = (pPhrase->poslist.n>0);
670 for(i=0; i<pPhrase->nTerm; i++){
671 if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
673 if( aIter!=aStatic ) sqlite3_free(aIter);
674 return rc;
677 typedef struct Fts5LookaheadReader Fts5LookaheadReader;
678 struct Fts5LookaheadReader {
679 const u8 *a; /* Buffer containing position list */
680 int n; /* Size of buffer a[] in bytes */
681 int i; /* Current offset in position list */
682 i64 iPos; /* Current position */
683 i64 iLookahead; /* Next position */
686 #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
688 static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
689 p->iPos = p->iLookahead;
690 if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
691 p->iLookahead = FTS5_LOOKAHEAD_EOF;
693 return (p->iPos==FTS5_LOOKAHEAD_EOF);
696 static int fts5LookaheadReaderInit(
697 const u8 *a, int n, /* Buffer to read position list from */
698 Fts5LookaheadReader *p /* Iterator object to initialize */
700 memset(p, 0, sizeof(Fts5LookaheadReader));
701 p->a = a;
702 p->n = n;
703 fts5LookaheadReaderNext(p);
704 return fts5LookaheadReaderNext(p);
707 typedef struct Fts5NearTrimmer Fts5NearTrimmer;
708 struct Fts5NearTrimmer {
709 Fts5LookaheadReader reader; /* Input iterator */
710 Fts5PoslistWriter writer; /* Writer context */
711 Fts5Buffer *pOut; /* Output poslist */
715 ** The near-set object passed as the first argument contains more than
716 ** one phrase. All phrases currently point to the same row. The
717 ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
718 ** tests if the current row contains instances of each phrase sufficiently
719 ** close together to meet the NEAR constraint. Non-zero is returned if it
720 ** does, or zero otherwise.
722 ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
723 ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
724 ** occurs within this function (*pRc) is set accordingly before returning.
725 ** The return value is undefined in both these cases.
727 ** If no error occurs and non-zero (a match) is returned, the position-list
728 ** of each phrase object is edited to contain only those entries that
729 ** meet the constraint before returning.
731 static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
732 Fts5NearTrimmer aStatic[4];
733 Fts5NearTrimmer *a = aStatic;
734 Fts5ExprPhrase **apPhrase = pNear->apPhrase;
736 int i;
737 int rc = *pRc;
738 int bMatch;
740 assert( pNear->nPhrase>1 );
742 /* If the aStatic[] array is not large enough, allocate a large array
743 ** using sqlite3_malloc(). This approach could be improved upon. */
744 if( pNear->nPhrase>ArraySize(aStatic) ){
745 sqlite3_int64 nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
746 a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
747 }else{
748 memset(aStatic, 0, sizeof(aStatic));
750 if( rc!=SQLITE_OK ){
751 *pRc = rc;
752 return 0;
755 /* Initialize a lookahead iterator for each phrase. After passing the
756 ** buffer and buffer size to the lookaside-reader init function, zero
757 ** the phrase poslist buffer. The new poslist for the phrase (containing
758 ** the same entries as the original with some entries removed on account
759 ** of the NEAR constraint) is written over the original even as it is
760 ** being read. This is safe as the entries for the new poslist are a
761 ** subset of the old, so it is not possible for data yet to be read to
762 ** be overwritten. */
763 for(i=0; i<pNear->nPhrase; i++){
764 Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
765 fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
766 pPoslist->n = 0;
767 a[i].pOut = pPoslist;
770 while( 1 ){
771 int iAdv;
772 i64 iMin;
773 i64 iMax;
775 /* This block advances the phrase iterators until they point to a set of
776 ** entries that together comprise a match. */
777 iMax = a[0].reader.iPos;
778 do {
779 bMatch = 1;
780 for(i=0; i<pNear->nPhrase; i++){
781 Fts5LookaheadReader *pPos = &a[i].reader;
782 iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
783 if( pPos->iPos<iMin || pPos->iPos>iMax ){
784 bMatch = 0;
785 while( pPos->iPos<iMin ){
786 if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
788 if( pPos->iPos>iMax ) iMax = pPos->iPos;
791 }while( bMatch==0 );
793 /* Add an entry to each output position list */
794 for(i=0; i<pNear->nPhrase; i++){
795 i64 iPos = a[i].reader.iPos;
796 Fts5PoslistWriter *pWriter = &a[i].writer;
797 if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
798 sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
802 iAdv = 0;
803 iMin = a[0].reader.iLookahead;
804 for(i=0; i<pNear->nPhrase; i++){
805 if( a[i].reader.iLookahead < iMin ){
806 iMin = a[i].reader.iLookahead;
807 iAdv = i;
810 if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
813 ismatch_out: {
814 int bRet = a[0].pOut->n>0;
815 *pRc = rc;
816 if( a!=aStatic ) sqlite3_free(a);
817 return bRet;
822 ** Advance iterator pIter until it points to a value equal to or laster
823 ** than the initial value of *piLast. If this means the iterator points
824 ** to a value laster than *piLast, update *piLast to the new lastest value.
826 ** If the iterator reaches EOF, set *pbEof to true before returning. If
827 ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
828 ** are set, return a non-zero value. Otherwise, return zero.
830 static int fts5ExprAdvanceto(
831 Fts5IndexIter *pIter, /* Iterator to advance */
832 int bDesc, /* True if iterator is "rowid DESC" */
833 i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
834 int *pRc, /* OUT: Error code */
835 int *pbEof /* OUT: Set to true if EOF */
837 i64 iLast = *piLast;
838 i64 iRowid;
840 iRowid = pIter->iRowid;
841 if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
842 int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
843 if( rc || sqlite3Fts5IterEof(pIter) ){
844 *pRc = rc;
845 *pbEof = 1;
846 return 1;
848 iRowid = pIter->iRowid;
849 assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
851 *piLast = iRowid;
853 return 0;
856 static int fts5ExprSynonymAdvanceto(
857 Fts5ExprTerm *pTerm, /* Term iterator to advance */
858 int bDesc, /* True if iterator is "rowid DESC" */
859 i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
860 int *pRc /* OUT: Error code */
862 int rc = SQLITE_OK;
863 i64 iLast = *piLast;
864 Fts5ExprTerm *p;
865 int bEof = 0;
867 for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
868 if( sqlite3Fts5IterEof(p->pIter)==0 ){
869 i64 iRowid = p->pIter->iRowid;
870 if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
871 rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
876 if( rc!=SQLITE_OK ){
877 *pRc = rc;
878 bEof = 1;
879 }else{
880 *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
882 return bEof;
886 static int fts5ExprNearTest(
887 int *pRc,
888 Fts5Expr *pExpr, /* Expression that pNear is a part of */
889 Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
891 Fts5ExprNearset *pNear = pNode->pNear;
892 int rc = *pRc;
894 if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
895 Fts5ExprTerm *pTerm;
896 Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
897 pPhrase->poslist.n = 0;
898 for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
899 Fts5IndexIter *pIter = pTerm->pIter;
900 if( sqlite3Fts5IterEof(pIter)==0 ){
901 if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
902 pPhrase->poslist.n = 1;
906 return pPhrase->poslist.n;
907 }else{
908 int i;
910 /* Check that each phrase in the nearset matches the current row.
911 ** Populate the pPhrase->poslist buffers at the same time. If any
912 ** phrase is not a match, break out of the loop early. */
913 for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
914 Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
915 if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym
916 || pNear->pColset || pPhrase->aTerm[0].bFirst
918 int bMatch = 0;
919 rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
920 if( bMatch==0 ) break;
921 }else{
922 Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
923 fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
927 *pRc = rc;
928 if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
929 return 1;
931 return 0;
937 ** Initialize all term iterators in the pNear object. If any term is found
938 ** to match no documents at all, return immediately without initializing any
939 ** further iterators.
941 ** If an error occurs, return an SQLite error code. Otherwise, return
942 ** SQLITE_OK. It is not considered an error if some term matches zero
943 ** documents.
945 static int fts5ExprNearInitAll(
946 Fts5Expr *pExpr,
947 Fts5ExprNode *pNode
949 Fts5ExprNearset *pNear = pNode->pNear;
950 int i;
952 assert( pNode->bNomatch==0 );
953 for(i=0; i<pNear->nPhrase; i++){
954 Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
955 if( pPhrase->nTerm==0 ){
956 pNode->bEof = 1;
957 return SQLITE_OK;
958 }else{
959 int j;
960 for(j=0; j<pPhrase->nTerm; j++){
961 Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
962 Fts5ExprTerm *p;
963 int bHit = 0;
965 for(p=pTerm; p; p=p->pSynonym){
966 int rc;
967 if( p->pIter ){
968 sqlite3Fts5IterClose(p->pIter);
969 p->pIter = 0;
971 rc = sqlite3Fts5IndexQuery(
972 pExpr->pIndex, p->pTerm, p->nQueryTerm,
973 (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
974 (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
975 pNear->pColset,
976 &p->pIter
978 assert( (rc==SQLITE_OK)==(p->pIter!=0) );
979 if( rc!=SQLITE_OK ) return rc;
980 if( 0==sqlite3Fts5IterEof(p->pIter) ){
981 bHit = 1;
985 if( bHit==0 ){
986 pNode->bEof = 1;
987 return SQLITE_OK;
993 pNode->bEof = 0;
994 return SQLITE_OK;
998 ** If pExpr is an ASC iterator, this function returns a value with the
999 ** same sign as:
1001 ** (iLhs - iRhs)
1003 ** Otherwise, if this is a DESC iterator, the opposite is returned:
1005 ** (iRhs - iLhs)
1007 static int fts5RowidCmp(
1008 Fts5Expr *pExpr,
1009 i64 iLhs,
1010 i64 iRhs
1012 assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
1013 if( pExpr->bDesc==0 ){
1014 if( iLhs<iRhs ) return -1;
1015 return (iLhs > iRhs);
1016 }else{
1017 if( iLhs>iRhs ) return -1;
1018 return (iLhs < iRhs);
1022 static void fts5ExprSetEof(Fts5ExprNode *pNode){
1023 int i;
1024 pNode->bEof = 1;
1025 pNode->bNomatch = 0;
1026 for(i=0; i<pNode->nChild; i++){
1027 fts5ExprSetEof(pNode->apChild[i]);
1031 static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
1032 if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
1033 Fts5ExprNearset *pNear = pNode->pNear;
1034 int i;
1035 for(i=0; i<pNear->nPhrase; i++){
1036 Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
1037 pPhrase->poslist.n = 0;
1039 }else{
1040 int i;
1041 for(i=0; i<pNode->nChild; i++){
1042 fts5ExprNodeZeroPoslist(pNode->apChild[i]);
1050 ** Compare the values currently indicated by the two nodes as follows:
1052 ** res = (*p1) - (*p2)
1054 ** Nodes that point to values that come later in the iteration order are
1055 ** considered to be larger. Nodes at EOF are the largest of all.
1057 ** This means that if the iteration order is ASC, then numerically larger
1058 ** rowids are considered larger. Or if it is the default DESC, numerically
1059 ** smaller rowids are larger.
1061 static int fts5NodeCompare(
1062 Fts5Expr *pExpr,
1063 Fts5ExprNode *p1,
1064 Fts5ExprNode *p2
1066 if( p2->bEof ) return -1;
1067 if( p1->bEof ) return +1;
1068 return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
1072 ** All individual term iterators in pNear are guaranteed to be valid when
1073 ** this function is called. This function checks if all term iterators
1074 ** point to the same rowid, and if not, advances them until they do.
1075 ** If an EOF is reached before this happens, *pbEof is set to true before
1076 ** returning.
1078 ** SQLITE_OK is returned if an error occurs, or an SQLite error code
1079 ** otherwise. It is not considered an error code if an iterator reaches
1080 ** EOF.
1082 static int fts5ExprNodeTest_STRING(
1083 Fts5Expr *pExpr, /* Expression pPhrase belongs to */
1084 Fts5ExprNode *pNode
1086 Fts5ExprNearset *pNear = pNode->pNear;
1087 Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
1088 int rc = SQLITE_OK;
1089 i64 iLast; /* Lastest rowid any iterator points to */
1090 int i, j; /* Phrase and token index, respectively */
1091 int bMatch; /* True if all terms are at the same rowid */
1092 const int bDesc = pExpr->bDesc;
1094 /* Check that this node should not be FTS5_TERM */
1095 assert( pNear->nPhrase>1
1096 || pNear->apPhrase[0]->nTerm>1
1097 || pNear->apPhrase[0]->aTerm[0].pSynonym
1098 || pNear->apPhrase[0]->aTerm[0].bFirst
1101 /* Initialize iLast, the "lastest" rowid any iterator points to. If the
1102 ** iterator skips through rowids in the default ascending order, this means
1103 ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
1104 ** means the minimum rowid. */
1105 if( pLeft->aTerm[0].pSynonym ){
1106 iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
1107 }else{
1108 iLast = pLeft->aTerm[0].pIter->iRowid;
1111 do {
1112 bMatch = 1;
1113 for(i=0; i<pNear->nPhrase; i++){
1114 Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
1115 for(j=0; j<pPhrase->nTerm; j++){
1116 Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
1117 if( pTerm->pSynonym ){
1118 i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
1119 if( iRowid==iLast ) continue;
1120 bMatch = 0;
1121 if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
1122 pNode->bNomatch = 0;
1123 pNode->bEof = 1;
1124 return rc;
1126 }else{
1127 Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
1128 if( pIter->iRowid==iLast || pIter->bEof ) continue;
1129 bMatch = 0;
1130 if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
1131 return rc;
1136 }while( bMatch==0 );
1138 pNode->iRowid = iLast;
1139 pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
1140 assert( pNode->bEof==0 || pNode->bNomatch==0 );
1142 return rc;
1146 ** Advance the first term iterator in the first phrase of pNear. Set output
1147 ** variable *pbEof to true if it reaches EOF or if an error occurs.
1149 ** Return SQLITE_OK if successful, or an SQLite error code if an error
1150 ** occurs.
1152 static int fts5ExprNodeNext_STRING(
1153 Fts5Expr *pExpr, /* Expression pPhrase belongs to */
1154 Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
1155 int bFromValid,
1156 i64 iFrom
1158 Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
1159 int rc = SQLITE_OK;
1161 pNode->bNomatch = 0;
1162 if( pTerm->pSynonym ){
1163 int bEof = 1;
1164 Fts5ExprTerm *p;
1166 /* Find the firstest rowid any synonym points to. */
1167 i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
1169 /* Advance each iterator that currently points to iRowid. Or, if iFrom
1170 ** is valid - each iterator that points to a rowid before iFrom. */
1171 for(p=pTerm; p; p=p->pSynonym){
1172 if( sqlite3Fts5IterEof(p->pIter)==0 ){
1173 i64 ii = p->pIter->iRowid;
1174 if( ii==iRowid
1175 || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
1177 if( bFromValid ){
1178 rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
1179 }else{
1180 rc = sqlite3Fts5IterNext(p->pIter);
1182 if( rc!=SQLITE_OK ) break;
1183 if( sqlite3Fts5IterEof(p->pIter)==0 ){
1184 bEof = 0;
1186 }else{
1187 bEof = 0;
1192 /* Set the EOF flag if either all synonym iterators are at EOF or an
1193 ** error has occurred. */
1194 pNode->bEof = (rc || bEof);
1195 }else{
1196 Fts5IndexIter *pIter = pTerm->pIter;
1198 assert( Fts5NodeIsString(pNode) );
1199 if( bFromValid ){
1200 rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
1201 }else{
1202 rc = sqlite3Fts5IterNext(pIter);
1205 pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
1208 if( pNode->bEof==0 ){
1209 assert( rc==SQLITE_OK );
1210 rc = fts5ExprNodeTest_STRING(pExpr, pNode);
1213 return rc;
1217 static int fts5ExprNodeTest_TERM(
1218 Fts5Expr *pExpr, /* Expression that pNear is a part of */
1219 Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
1221 /* As this "NEAR" object is actually a single phrase that consists
1222 ** of a single term only, grab pointers into the poslist managed by the
1223 ** fts5_index.c iterator object. This is much faster than synthesizing
1224 ** a new poslist the way we have to for more complicated phrase or NEAR
1225 ** expressions. */
1226 Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
1227 Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
1229 assert( pNode->eType==FTS5_TERM );
1230 assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
1231 assert( pPhrase->aTerm[0].pSynonym==0 );
1233 pPhrase->poslist.n = pIter->nData;
1234 if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
1235 pPhrase->poslist.p = (u8*)pIter->pData;
1237 pNode->iRowid = pIter->iRowid;
1238 pNode->bNomatch = (pPhrase->poslist.n==0);
1239 return SQLITE_OK;
1243 ** xNext() method for a node of type FTS5_TERM.
1245 static int fts5ExprNodeNext_TERM(
1246 Fts5Expr *pExpr,
1247 Fts5ExprNode *pNode,
1248 int bFromValid,
1249 i64 iFrom
1251 int rc;
1252 Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
1254 assert( pNode->bEof==0 );
1255 if( bFromValid ){
1256 rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
1257 }else{
1258 rc = sqlite3Fts5IterNext(pIter);
1260 if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
1261 rc = fts5ExprNodeTest_TERM(pExpr, pNode);
1262 }else{
1263 pNode->bEof = 1;
1264 pNode->bNomatch = 0;
1266 return rc;
1269 static void fts5ExprNodeTest_OR(
1270 Fts5Expr *pExpr, /* Expression of which pNode is a part */
1271 Fts5ExprNode *pNode /* Expression node to test */
1273 Fts5ExprNode *pNext = pNode->apChild[0];
1274 int i;
1276 for(i=1; i<pNode->nChild; i++){
1277 Fts5ExprNode *pChild = pNode->apChild[i];
1278 int cmp = fts5NodeCompare(pExpr, pNext, pChild);
1279 if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
1280 pNext = pChild;
1283 pNode->iRowid = pNext->iRowid;
1284 pNode->bEof = pNext->bEof;
1285 pNode->bNomatch = pNext->bNomatch;
1288 static int fts5ExprNodeNext_OR(
1289 Fts5Expr *pExpr,
1290 Fts5ExprNode *pNode,
1291 int bFromValid,
1292 i64 iFrom
1294 int i;
1295 i64 iLast = pNode->iRowid;
1297 for(i=0; i<pNode->nChild; i++){
1298 Fts5ExprNode *p1 = pNode->apChild[i];
1299 assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
1300 if( p1->bEof==0 ){
1301 if( (p1->iRowid==iLast)
1302 || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
1304 int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
1305 if( rc!=SQLITE_OK ){
1306 pNode->bNomatch = 0;
1307 return rc;
1313 fts5ExprNodeTest_OR(pExpr, pNode);
1314 return SQLITE_OK;
1318 ** Argument pNode is an FTS5_AND node.
1320 static int fts5ExprNodeTest_AND(
1321 Fts5Expr *pExpr, /* Expression pPhrase belongs to */
1322 Fts5ExprNode *pAnd /* FTS5_AND node to advance */
1324 int iChild;
1325 i64 iLast = pAnd->iRowid;
1326 int rc = SQLITE_OK;
1327 int bMatch;
1329 assert( pAnd->bEof==0 );
1330 do {
1331 pAnd->bNomatch = 0;
1332 bMatch = 1;
1333 for(iChild=0; iChild<pAnd->nChild; iChild++){
1334 Fts5ExprNode *pChild = pAnd->apChild[iChild];
1335 int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
1336 if( cmp>0 ){
1337 /* Advance pChild until it points to iLast or laster */
1338 rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
1339 if( rc!=SQLITE_OK ){
1340 pAnd->bNomatch = 0;
1341 return rc;
1345 /* If the child node is now at EOF, so is the parent AND node. Otherwise,
1346 ** the child node is guaranteed to have advanced at least as far as
1347 ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
1348 ** new lastest rowid seen so far. */
1349 assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
1350 if( pChild->bEof ){
1351 fts5ExprSetEof(pAnd);
1352 bMatch = 1;
1353 break;
1354 }else if( iLast!=pChild->iRowid ){
1355 bMatch = 0;
1356 iLast = pChild->iRowid;
1359 if( pChild->bNomatch ){
1360 pAnd->bNomatch = 1;
1363 }while( bMatch==0 );
1365 if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
1366 fts5ExprNodeZeroPoslist(pAnd);
1368 pAnd->iRowid = iLast;
1369 return SQLITE_OK;
1372 static int fts5ExprNodeNext_AND(
1373 Fts5Expr *pExpr,
1374 Fts5ExprNode *pNode,
1375 int bFromValid,
1376 i64 iFrom
1378 int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
1379 if( rc==SQLITE_OK ){
1380 rc = fts5ExprNodeTest_AND(pExpr, pNode);
1381 }else{
1382 pNode->bNomatch = 0;
1384 return rc;
1387 static int fts5ExprNodeTest_NOT(
1388 Fts5Expr *pExpr, /* Expression pPhrase belongs to */
1389 Fts5ExprNode *pNode /* FTS5_NOT node to advance */
1391 int rc = SQLITE_OK;
1392 Fts5ExprNode *p1 = pNode->apChild[0];
1393 Fts5ExprNode *p2 = pNode->apChild[1];
1394 assert( pNode->nChild==2 );
1396 while( rc==SQLITE_OK && p1->bEof==0 ){
1397 int cmp = fts5NodeCompare(pExpr, p1, p2);
1398 if( cmp>0 ){
1399 rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
1400 cmp = fts5NodeCompare(pExpr, p1, p2);
1402 assert( rc!=SQLITE_OK || cmp<=0 );
1403 if( cmp || p2->bNomatch ) break;
1404 rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
1406 pNode->bEof = p1->bEof;
1407 pNode->bNomatch = p1->bNomatch;
1408 pNode->iRowid = p1->iRowid;
1409 if( p1->bEof ){
1410 fts5ExprNodeZeroPoslist(p2);
1412 return rc;
1415 static int fts5ExprNodeNext_NOT(
1416 Fts5Expr *pExpr,
1417 Fts5ExprNode *pNode,
1418 int bFromValid,
1419 i64 iFrom
1421 int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
1422 if( rc==SQLITE_OK ){
1423 rc = fts5ExprNodeTest_NOT(pExpr, pNode);
1425 if( rc!=SQLITE_OK ){
1426 pNode->bNomatch = 0;
1428 return rc;
1432 ** If pNode currently points to a match, this function returns SQLITE_OK
1433 ** without modifying it. Otherwise, pNode is advanced until it does point
1434 ** to a match or EOF is reached.
1436 static int fts5ExprNodeTest(
1437 Fts5Expr *pExpr, /* Expression of which pNode is a part */
1438 Fts5ExprNode *pNode /* Expression node to test */
1440 int rc = SQLITE_OK;
1441 if( pNode->bEof==0 ){
1442 switch( pNode->eType ){
1444 case FTS5_STRING: {
1445 rc = fts5ExprNodeTest_STRING(pExpr, pNode);
1446 break;
1449 case FTS5_TERM: {
1450 rc = fts5ExprNodeTest_TERM(pExpr, pNode);
1451 break;
1454 case FTS5_AND: {
1455 rc = fts5ExprNodeTest_AND(pExpr, pNode);
1456 break;
1459 case FTS5_OR: {
1460 fts5ExprNodeTest_OR(pExpr, pNode);
1461 break;
1464 default: assert( pNode->eType==FTS5_NOT ); {
1465 rc = fts5ExprNodeTest_NOT(pExpr, pNode);
1466 break;
1470 return rc;
1475 ** Set node pNode, which is part of expression pExpr, to point to the first
1476 ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
1478 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
1479 ** It is not an error if there are no matches.
1481 static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
1482 int rc = SQLITE_OK;
1483 pNode->bEof = 0;
1484 pNode->bNomatch = 0;
1486 if( Fts5NodeIsString(pNode) ){
1487 /* Initialize all term iterators in the NEAR object. */
1488 rc = fts5ExprNearInitAll(pExpr, pNode);
1489 }else if( pNode->xNext==0 ){
1490 pNode->bEof = 1;
1491 }else{
1492 int i;
1493 int nEof = 0;
1494 for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
1495 Fts5ExprNode *pChild = pNode->apChild[i];
1496 rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
1497 assert( pChild->bEof==0 || pChild->bEof==1 );
1498 nEof += pChild->bEof;
1500 pNode->iRowid = pNode->apChild[0]->iRowid;
1502 switch( pNode->eType ){
1503 case FTS5_AND:
1504 if( nEof>0 ) fts5ExprSetEof(pNode);
1505 break;
1507 case FTS5_OR:
1508 if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
1509 break;
1511 default:
1512 assert( pNode->eType==FTS5_NOT );
1513 pNode->bEof = pNode->apChild[0]->bEof;
1514 break;
1518 if( rc==SQLITE_OK ){
1519 rc = fts5ExprNodeTest(pExpr, pNode);
1521 return rc;
1526 ** Begin iterating through the set of documents in index pIdx matched by
1527 ** the MATCH expression passed as the first argument. If the "bDesc"
1528 ** parameter is passed a non-zero value, iteration is in descending rowid
1529 ** order. Or, if it is zero, in ascending order.
1531 ** If iterating in ascending rowid order (bDesc==0), the first document
1532 ** visited is that with the smallest rowid that is larger than or equal
1533 ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
1534 ** then the first document visited must have a rowid smaller than or
1535 ** equal to iFirst.
1537 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
1538 ** is not considered an error if the query does not match any documents.
1540 int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
1541 Fts5ExprNode *pRoot = p->pRoot;
1542 int rc; /* Return code */
1544 p->pIndex = pIdx;
1545 p->bDesc = bDesc;
1546 rc = fts5ExprNodeFirst(p, pRoot);
1548 /* If not at EOF but the current rowid occurs earlier than iFirst in
1549 ** the iteration order, move to document iFirst or later. */
1550 if( rc==SQLITE_OK
1551 && 0==pRoot->bEof
1552 && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
1554 rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
1557 /* If the iterator is not at a real match, skip forward until it is. */
1558 while( pRoot->bNomatch && rc==SQLITE_OK ){
1559 assert( pRoot->bEof==0 );
1560 rc = fts5ExprNodeNext(p, pRoot, 0, 0);
1562 return rc;
1566 ** Move to the next document
1568 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
1569 ** is not considered an error if the query does not match any documents.
1571 int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
1572 int rc;
1573 Fts5ExprNode *pRoot = p->pRoot;
1574 assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
1575 do {
1576 rc = fts5ExprNodeNext(p, pRoot, 0, 0);
1577 assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
1578 }while( pRoot->bNomatch );
1579 if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
1580 pRoot->bEof = 1;
1582 return rc;
1585 int sqlite3Fts5ExprEof(Fts5Expr *p){
1586 return p->pRoot->bEof;
1589 i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
1590 return p->pRoot->iRowid;
1593 static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
1594 int rc = SQLITE_OK;
1595 *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
1596 return rc;
1600 ** Free the phrase object passed as the only argument.
1602 static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
1603 if( pPhrase ){
1604 int i;
1605 for(i=0; i<pPhrase->nTerm; i++){
1606 Fts5ExprTerm *pSyn;
1607 Fts5ExprTerm *pNext;
1608 Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
1609 sqlite3_free(pTerm->pTerm);
1610 sqlite3Fts5IterClose(pTerm->pIter);
1611 for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
1612 pNext = pSyn->pSynonym;
1613 sqlite3Fts5IterClose(pSyn->pIter);
1614 fts5BufferFree((Fts5Buffer*)&pSyn[1]);
1615 sqlite3_free(pSyn);
1618 if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
1619 sqlite3_free(pPhrase);
1624 ** Set the "bFirst" flag on the first token of the phrase passed as the
1625 ** only argument.
1627 void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase *pPhrase){
1628 if( pPhrase && pPhrase->nTerm ){
1629 pPhrase->aTerm[0].bFirst = 1;
1634 ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
1635 ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
1636 ** appended to it and the results returned.
1638 ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
1639 ** NULL returned.
1641 Fts5ExprNearset *sqlite3Fts5ParseNearset(
1642 Fts5Parse *pParse, /* Parse context */
1643 Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
1644 Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
1646 const int SZALLOC = 8;
1647 Fts5ExprNearset *pRet = 0;
1649 if( pParse->rc==SQLITE_OK ){
1650 if( pPhrase==0 ){
1651 return pNear;
1653 if( pNear==0 ){
1654 sqlite3_int64 nByte;
1655 nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
1656 pRet = sqlite3_malloc64(nByte);
1657 if( pRet==0 ){
1658 pParse->rc = SQLITE_NOMEM;
1659 }else{
1660 memset(pRet, 0, (size_t)nByte);
1662 }else if( (pNear->nPhrase % SZALLOC)==0 ){
1663 int nNew = pNear->nPhrase + SZALLOC;
1664 sqlite3_int64 nByte;
1666 nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
1667 pRet = (Fts5ExprNearset*)sqlite3_realloc64(pNear, nByte);
1668 if( pRet==0 ){
1669 pParse->rc = SQLITE_NOMEM;
1671 }else{
1672 pRet = pNear;
1676 if( pRet==0 ){
1677 assert( pParse->rc!=SQLITE_OK );
1678 sqlite3Fts5ParseNearsetFree(pNear);
1679 sqlite3Fts5ParsePhraseFree(pPhrase);
1680 }else{
1681 if( pRet->nPhrase>0 ){
1682 Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
1683 assert( pParse!=0 );
1684 assert( pParse->apPhrase!=0 );
1685 assert( pParse->nPhrase>=2 );
1686 assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
1687 if( pPhrase->nTerm==0 ){
1688 fts5ExprPhraseFree(pPhrase);
1689 pRet->nPhrase--;
1690 pParse->nPhrase--;
1691 pPhrase = pLast;
1692 }else if( pLast->nTerm==0 ){
1693 fts5ExprPhraseFree(pLast);
1694 pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
1695 pParse->nPhrase--;
1696 pRet->nPhrase--;
1699 pRet->apPhrase[pRet->nPhrase++] = pPhrase;
1701 return pRet;
1704 typedef struct TokenCtx TokenCtx;
1705 struct TokenCtx {
1706 Fts5ExprPhrase *pPhrase;
1707 Fts5Config *pConfig;
1708 int rc;
1712 ** Callback for tokenizing terms used by ParseTerm().
1714 static int fts5ParseTokenize(
1715 void *pContext, /* Pointer to Fts5InsertCtx object */
1716 int tflags, /* Mask of FTS5_TOKEN_* flags */
1717 const char *pToken, /* Buffer containing token */
1718 int nToken, /* Size of token in bytes */
1719 int iUnused1, /* Start offset of token */
1720 int iUnused2 /* End offset of token */
1722 int rc = SQLITE_OK;
1723 const int SZALLOC = 8;
1724 TokenCtx *pCtx = (TokenCtx*)pContext;
1725 Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
1727 UNUSED_PARAM2(iUnused1, iUnused2);
1729 /* If an error has already occurred, this is a no-op */
1730 if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
1731 if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
1733 if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
1734 Fts5ExprTerm *pSyn;
1735 sqlite3_int64 nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
1736 pSyn = (Fts5ExprTerm*)sqlite3_malloc64(nByte);
1737 if( pSyn==0 ){
1738 rc = SQLITE_NOMEM;
1739 }else{
1740 memset(pSyn, 0, (size_t)nByte);
1741 pSyn->pTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
1742 pSyn->nFullTerm = pSyn->nQueryTerm = nToken;
1743 if( pCtx->pConfig->bTokendata ){
1744 pSyn->nQueryTerm = (int)strlen(pSyn->pTerm);
1746 memcpy(pSyn->pTerm, pToken, nToken);
1747 pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
1748 pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
1750 }else{
1751 Fts5ExprTerm *pTerm;
1752 if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
1753 Fts5ExprPhrase *pNew;
1754 int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
1756 pNew = (Fts5ExprPhrase*)sqlite3_realloc64(pPhrase,
1757 sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
1759 if( pNew==0 ){
1760 rc = SQLITE_NOMEM;
1761 }else{
1762 if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
1763 pCtx->pPhrase = pPhrase = pNew;
1764 pNew->nTerm = nNew - SZALLOC;
1768 if( rc==SQLITE_OK ){
1769 pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
1770 memset(pTerm, 0, sizeof(Fts5ExprTerm));
1771 pTerm->pTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
1772 pTerm->nFullTerm = pTerm->nQueryTerm = nToken;
1773 if( pCtx->pConfig->bTokendata && rc==SQLITE_OK ){
1774 pTerm->nQueryTerm = (int)strlen(pTerm->pTerm);
1779 pCtx->rc = rc;
1780 return rc;
1785 ** Free the phrase object passed as the only argument.
1787 void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
1788 fts5ExprPhraseFree(pPhrase);
1792 ** Free the phrase object passed as the second argument.
1794 void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
1795 if( pNear ){
1796 int i;
1797 for(i=0; i<pNear->nPhrase; i++){
1798 fts5ExprPhraseFree(pNear->apPhrase[i]);
1800 sqlite3_free(pNear->pColset);
1801 sqlite3_free(pNear);
1805 void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
1806 assert( pParse->pExpr==0 );
1807 pParse->pExpr = p;
1810 static int parseGrowPhraseArray(Fts5Parse *pParse){
1811 if( (pParse->nPhrase % 8)==0 ){
1812 sqlite3_int64 nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
1813 Fts5ExprPhrase **apNew;
1814 apNew = (Fts5ExprPhrase**)sqlite3_realloc64(pParse->apPhrase, nByte);
1815 if( apNew==0 ){
1816 pParse->rc = SQLITE_NOMEM;
1817 return SQLITE_NOMEM;
1819 pParse->apPhrase = apNew;
1821 return SQLITE_OK;
1825 ** This function is called by the parser to process a string token. The
1826 ** string may or may not be quoted. In any case it is tokenized and a
1827 ** phrase object consisting of all tokens returned.
1829 Fts5ExprPhrase *sqlite3Fts5ParseTerm(
1830 Fts5Parse *pParse, /* Parse context */
1831 Fts5ExprPhrase *pAppend, /* Phrase to append to */
1832 Fts5Token *pToken, /* String to tokenize */
1833 int bPrefix /* True if there is a trailing "*" */
1835 Fts5Config *pConfig = pParse->pConfig;
1836 TokenCtx sCtx; /* Context object passed to callback */
1837 int rc; /* Tokenize return code */
1838 char *z = 0;
1840 memset(&sCtx, 0, sizeof(TokenCtx));
1841 sCtx.pPhrase = pAppend;
1842 sCtx.pConfig = pConfig;
1844 rc = fts5ParseStringFromToken(pToken, &z);
1845 if( rc==SQLITE_OK ){
1846 int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
1847 int n;
1848 sqlite3Fts5Dequote(z);
1849 n = (int)strlen(z);
1850 rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
1852 sqlite3_free(z);
1853 if( rc || (rc = sCtx.rc) ){
1854 pParse->rc = rc;
1855 fts5ExprPhraseFree(sCtx.pPhrase);
1856 sCtx.pPhrase = 0;
1857 }else{
1859 if( pAppend==0 ){
1860 if( parseGrowPhraseArray(pParse) ){
1861 fts5ExprPhraseFree(sCtx.pPhrase);
1862 return 0;
1864 pParse->nPhrase++;
1867 if( sCtx.pPhrase==0 ){
1868 /* This happens when parsing a token or quoted phrase that contains
1869 ** no token characters at all. (e.g ... MATCH '""'). */
1870 sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
1871 }else if( sCtx.pPhrase->nTerm ){
1872 sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = (u8)bPrefix;
1874 pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
1877 return sCtx.pPhrase;
1881 ** Create a new FTS5 expression by cloning phrase iPhrase of the
1882 ** expression passed as the second argument.
1884 int sqlite3Fts5ExprClonePhrase(
1885 Fts5Expr *pExpr,
1886 int iPhrase,
1887 Fts5Expr **ppNew
1889 int rc = SQLITE_OK; /* Return code */
1890 Fts5ExprPhrase *pOrig = 0; /* The phrase extracted from pExpr */
1891 Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
1892 TokenCtx sCtx = {0,0,0}; /* Context object for fts5ParseTokenize */
1893 if( iPhrase<0 || iPhrase>=pExpr->nPhrase ){
1894 rc = SQLITE_RANGE;
1895 }else{
1896 pOrig = pExpr->apExprPhrase[iPhrase];
1897 pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
1899 if( rc==SQLITE_OK ){
1900 pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
1901 sizeof(Fts5ExprPhrase*));
1903 if( rc==SQLITE_OK ){
1904 pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
1905 sizeof(Fts5ExprNode));
1907 if( rc==SQLITE_OK ){
1908 pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
1909 sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
1911 if( rc==SQLITE_OK && ALWAYS(pOrig!=0) ){
1912 Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
1913 if( pColsetOrig ){
1914 sqlite3_int64 nByte;
1915 Fts5Colset *pColset;
1916 nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
1917 pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
1918 if( pColset ){
1919 memcpy(pColset, pColsetOrig, (size_t)nByte);
1921 pNew->pRoot->pNear->pColset = pColset;
1925 if( rc==SQLITE_OK ){
1926 if( pOrig->nTerm ){
1927 int i; /* Used to iterate through phrase terms */
1928 sCtx.pConfig = pExpr->pConfig;
1929 for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
1930 int tflags = 0;
1931 Fts5ExprTerm *p;
1932 for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
1933 rc = fts5ParseTokenize((void*)&sCtx,tflags,p->pTerm,p->nFullTerm,0,0);
1934 tflags = FTS5_TOKEN_COLOCATED;
1936 if( rc==SQLITE_OK ){
1937 sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
1938 sCtx.pPhrase->aTerm[i].bFirst = pOrig->aTerm[i].bFirst;
1941 }else{
1942 /* This happens when parsing a token or quoted phrase that contains
1943 ** no token characters at all. (e.g ... MATCH '""'). */
1944 sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
1948 if( rc==SQLITE_OK && ALWAYS(sCtx.pPhrase) ){
1949 /* All the allocations succeeded. Put the expression object together. */
1950 pNew->pIndex = pExpr->pIndex;
1951 pNew->pConfig = pExpr->pConfig;
1952 pNew->nPhrase = 1;
1953 pNew->apExprPhrase[0] = sCtx.pPhrase;
1954 pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
1955 pNew->pRoot->pNear->nPhrase = 1;
1956 sCtx.pPhrase->pNode = pNew->pRoot;
1958 if( pOrig->nTerm==1
1959 && pOrig->aTerm[0].pSynonym==0
1960 && pOrig->aTerm[0].bFirst==0
1962 pNew->pRoot->eType = FTS5_TERM;
1963 pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
1964 }else{
1965 pNew->pRoot->eType = FTS5_STRING;
1966 pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
1968 }else{
1969 sqlite3Fts5ExprFree(pNew);
1970 fts5ExprPhraseFree(sCtx.pPhrase);
1971 pNew = 0;
1974 *ppNew = pNew;
1975 return rc;
1980 ** Token pTok has appeared in a MATCH expression where the NEAR operator
1981 ** is expected. If token pTok does not contain "NEAR", store an error
1982 ** in the pParse object.
1984 void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
1985 if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
1986 sqlite3Fts5ParseError(
1987 pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
1992 void sqlite3Fts5ParseSetDistance(
1993 Fts5Parse *pParse,
1994 Fts5ExprNearset *pNear,
1995 Fts5Token *p
1997 if( pNear ){
1998 int nNear = 0;
1999 int i;
2000 if( p->n ){
2001 for(i=0; i<p->n; i++){
2002 char c = (char)p->p[i];
2003 if( c<'0' || c>'9' ){
2004 sqlite3Fts5ParseError(
2005 pParse, "expected integer, got \"%.*s\"", p->n, p->p
2007 return;
2009 nNear = nNear * 10 + (p->p[i] - '0');
2011 }else{
2012 nNear = FTS5_DEFAULT_NEARDIST;
2014 pNear->nNear = nNear;
2019 ** The second argument passed to this function may be NULL, or it may be
2020 ** an existing Fts5Colset object. This function returns a pointer to
2021 ** a new colset object containing the contents of (p) with new value column
2022 ** number iCol appended.
2024 ** If an OOM error occurs, store an error code in pParse and return NULL.
2025 ** The old colset object (if any) is not freed in this case.
2027 static Fts5Colset *fts5ParseColset(
2028 Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
2029 Fts5Colset *p, /* Existing colset object */
2030 int iCol /* New column to add to colset object */
2032 int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
2033 Fts5Colset *pNew; /* New colset object to return */
2035 assert( pParse->rc==SQLITE_OK );
2036 assert( iCol>=0 && iCol<pParse->pConfig->nCol );
2038 pNew = sqlite3_realloc64(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
2039 if( pNew==0 ){
2040 pParse->rc = SQLITE_NOMEM;
2041 }else{
2042 int *aiCol = pNew->aiCol;
2043 int i, j;
2044 for(i=0; i<nCol; i++){
2045 if( aiCol[i]==iCol ) return pNew;
2046 if( aiCol[i]>iCol ) break;
2048 for(j=nCol; j>i; j--){
2049 aiCol[j] = aiCol[j-1];
2051 aiCol[i] = iCol;
2052 pNew->nCol = nCol+1;
2054 #ifndef NDEBUG
2055 /* Check that the array is in order and contains no duplicate entries. */
2056 for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
2057 #endif
2060 return pNew;
2064 ** Allocate and return an Fts5Colset object specifying the inverse of
2065 ** the colset passed as the second argument. Free the colset passed
2066 ** as the second argument before returning.
2068 Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
2069 Fts5Colset *pRet;
2070 int nCol = pParse->pConfig->nCol;
2072 pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
2073 sizeof(Fts5Colset) + sizeof(int)*nCol
2075 if( pRet ){
2076 int i;
2077 int iOld = 0;
2078 for(i=0; i<nCol; i++){
2079 if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
2080 pRet->aiCol[pRet->nCol++] = i;
2081 }else{
2082 iOld++;
2087 sqlite3_free(p);
2088 return pRet;
2091 Fts5Colset *sqlite3Fts5ParseColset(
2092 Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
2093 Fts5Colset *pColset, /* Existing colset object */
2094 Fts5Token *p
2096 Fts5Colset *pRet = 0;
2097 int iCol;
2098 char *z; /* Dequoted copy of token p */
2100 z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
2101 if( pParse->rc==SQLITE_OK ){
2102 Fts5Config *pConfig = pParse->pConfig;
2103 sqlite3Fts5Dequote(z);
2104 for(iCol=0; iCol<pConfig->nCol; iCol++){
2105 if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
2107 if( iCol==pConfig->nCol ){
2108 sqlite3Fts5ParseError(pParse, "no such column: %s", z);
2109 }else{
2110 pRet = fts5ParseColset(pParse, pColset, iCol);
2112 sqlite3_free(z);
2115 if( pRet==0 ){
2116 assert( pParse->rc!=SQLITE_OK );
2117 sqlite3_free(pColset);
2120 return pRet;
2124 ** If argument pOrig is NULL, or if (*pRc) is set to anything other than
2125 ** SQLITE_OK when this function is called, NULL is returned.
2127 ** Otherwise, a copy of (*pOrig) is made into memory obtained from
2128 ** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
2129 ** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
2131 static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
2132 Fts5Colset *pRet;
2133 if( pOrig ){
2134 sqlite3_int64 nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
2135 pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
2136 if( pRet ){
2137 memcpy(pRet, pOrig, (size_t)nByte);
2139 }else{
2140 pRet = 0;
2142 return pRet;
2146 ** Remove from colset pColset any columns that are not also in colset pMerge.
2148 static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
2149 int iIn = 0; /* Next input in pColset */
2150 int iMerge = 0; /* Next input in pMerge */
2151 int iOut = 0; /* Next output slot in pColset */
2153 while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
2154 int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
2155 if( iDiff==0 ){
2156 pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
2157 iMerge++;
2158 iIn++;
2159 }else if( iDiff>0 ){
2160 iMerge++;
2161 }else{
2162 iIn++;
2165 pColset->nCol = iOut;
2169 ** Recursively apply colset pColset to expression node pNode and all of
2170 ** its decendents. If (*ppFree) is not NULL, it contains a spare copy
2171 ** of pColset. This function may use the spare copy and set (*ppFree) to
2172 ** zero, or it may create copies of pColset using fts5CloneColset().
2174 static void fts5ParseSetColset(
2175 Fts5Parse *pParse,
2176 Fts5ExprNode *pNode,
2177 Fts5Colset *pColset,
2178 Fts5Colset **ppFree
2180 if( pParse->rc==SQLITE_OK ){
2181 assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
2182 || pNode->eType==FTS5_AND || pNode->eType==FTS5_OR
2183 || pNode->eType==FTS5_NOT || pNode->eType==FTS5_EOF
2185 if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
2186 Fts5ExprNearset *pNear = pNode->pNear;
2187 if( pNear->pColset ){
2188 fts5MergeColset(pNear->pColset, pColset);
2189 if( pNear->pColset->nCol==0 ){
2190 pNode->eType = FTS5_EOF;
2191 pNode->xNext = 0;
2193 }else if( *ppFree ){
2194 pNear->pColset = pColset;
2195 *ppFree = 0;
2196 }else{
2197 pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
2199 }else{
2200 int i;
2201 assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
2202 for(i=0; i<pNode->nChild; i++){
2203 fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
2210 ** Apply colset pColset to expression node pExpr and all of its descendents.
2212 void sqlite3Fts5ParseSetColset(
2213 Fts5Parse *pParse,
2214 Fts5ExprNode *pExpr,
2215 Fts5Colset *pColset
2217 Fts5Colset *pFree = pColset;
2218 if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
2219 sqlite3Fts5ParseError(pParse,
2220 "fts5: column queries are not supported (detail=none)"
2222 }else{
2223 fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
2225 sqlite3_free(pFree);
2228 static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
2229 switch( pNode->eType ){
2230 case FTS5_STRING: {
2231 Fts5ExprNearset *pNear = pNode->pNear;
2232 if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
2233 && pNear->apPhrase[0]->aTerm[0].pSynonym==0
2234 && pNear->apPhrase[0]->aTerm[0].bFirst==0
2236 pNode->eType = FTS5_TERM;
2237 pNode->xNext = fts5ExprNodeNext_TERM;
2238 }else{
2239 pNode->xNext = fts5ExprNodeNext_STRING;
2241 break;
2244 case FTS5_OR: {
2245 pNode->xNext = fts5ExprNodeNext_OR;
2246 break;
2249 case FTS5_AND: {
2250 pNode->xNext = fts5ExprNodeNext_AND;
2251 break;
2254 default: assert( pNode->eType==FTS5_NOT ); {
2255 pNode->xNext = fts5ExprNodeNext_NOT;
2256 break;
2261 static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
2262 int ii = p->nChild;
2263 if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
2264 int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
2265 memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
2266 p->nChild += pSub->nChild;
2267 sqlite3_free(pSub);
2268 }else{
2269 p->apChild[p->nChild++] = pSub;
2271 for( ; ii<p->nChild; ii++){
2272 p->iHeight = MAX(p->iHeight, p->apChild[ii]->iHeight + 1);
2277 ** This function is used when parsing LIKE or GLOB patterns against
2278 ** trigram indexes that specify either detail=column or detail=none.
2279 ** It converts a phrase:
2281 ** abc + def + ghi
2283 ** into an AND tree:
2285 ** abc AND def AND ghi
2287 static Fts5ExprNode *fts5ParsePhraseToAnd(
2288 Fts5Parse *pParse,
2289 Fts5ExprNearset *pNear
2291 int nTerm = pNear->apPhrase[0]->nTerm;
2292 int ii;
2293 int nByte;
2294 Fts5ExprNode *pRet;
2296 assert( pNear->nPhrase==1 );
2297 assert( pParse->bPhraseToAnd );
2299 nByte = sizeof(Fts5ExprNode) + nTerm*sizeof(Fts5ExprNode*);
2300 pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
2301 if( pRet ){
2302 pRet->eType = FTS5_AND;
2303 pRet->nChild = nTerm;
2304 pRet->iHeight = 1;
2305 fts5ExprAssignXNext(pRet);
2306 pParse->nPhrase--;
2307 for(ii=0; ii<nTerm; ii++){
2308 Fts5ExprPhrase *pPhrase = (Fts5ExprPhrase*)sqlite3Fts5MallocZero(
2309 &pParse->rc, sizeof(Fts5ExprPhrase)
2311 if( pPhrase ){
2312 if( parseGrowPhraseArray(pParse) ){
2313 fts5ExprPhraseFree(pPhrase);
2314 }else{
2315 Fts5ExprTerm *p = &pNear->apPhrase[0]->aTerm[ii];
2316 Fts5ExprTerm *pTo = &pPhrase->aTerm[0];
2317 pParse->apPhrase[pParse->nPhrase++] = pPhrase;
2318 pPhrase->nTerm = 1;
2319 pTo->pTerm = sqlite3Fts5Strndup(&pParse->rc, p->pTerm, p->nFullTerm);
2320 pTo->nQueryTerm = p->nQueryTerm;
2321 pTo->nFullTerm = p->nFullTerm;
2322 pRet->apChild[ii] = sqlite3Fts5ParseNode(pParse, FTS5_STRING,
2323 0, 0, sqlite3Fts5ParseNearset(pParse, 0, pPhrase)
2329 if( pParse->rc ){
2330 sqlite3Fts5ParseNodeFree(pRet);
2331 pRet = 0;
2332 }else{
2333 sqlite3Fts5ParseNearsetFree(pNear);
2337 return pRet;
2341 ** Allocate and return a new expression object. If anything goes wrong (i.e.
2342 ** OOM error), leave an error code in pParse and return NULL.
2344 Fts5ExprNode *sqlite3Fts5ParseNode(
2345 Fts5Parse *pParse, /* Parse context */
2346 int eType, /* FTS5_STRING, AND, OR or NOT */
2347 Fts5ExprNode *pLeft, /* Left hand child expression */
2348 Fts5ExprNode *pRight, /* Right hand child expression */
2349 Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
2351 Fts5ExprNode *pRet = 0;
2353 if( pParse->rc==SQLITE_OK ){
2354 int nChild = 0; /* Number of children of returned node */
2355 sqlite3_int64 nByte; /* Bytes of space to allocate for this node */
2357 assert( (eType!=FTS5_STRING && !pNear)
2358 || (eType==FTS5_STRING && !pLeft && !pRight)
2360 if( eType==FTS5_STRING && pNear==0 ) return 0;
2361 if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
2362 if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
2364 if( eType==FTS5_STRING
2365 && pParse->bPhraseToAnd
2366 && pNear->apPhrase[0]->nTerm>1
2368 pRet = fts5ParsePhraseToAnd(pParse, pNear);
2369 }else{
2370 if( eType==FTS5_NOT ){
2371 nChild = 2;
2372 }else if( eType==FTS5_AND || eType==FTS5_OR ){
2373 nChild = 2;
2374 if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
2375 if( pRight->eType==eType ) nChild += pRight->nChild-1;
2378 nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
2379 pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
2381 if( pRet ){
2382 pRet->eType = eType;
2383 pRet->pNear = pNear;
2384 fts5ExprAssignXNext(pRet);
2385 if( eType==FTS5_STRING ){
2386 int iPhrase;
2387 for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
2388 pNear->apPhrase[iPhrase]->pNode = pRet;
2389 if( pNear->apPhrase[iPhrase]->nTerm==0 ){
2390 pRet->xNext = 0;
2391 pRet->eType = FTS5_EOF;
2395 if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL ){
2396 Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
2397 if( pNear->nPhrase!=1
2398 || pPhrase->nTerm>1
2399 || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst)
2401 sqlite3Fts5ParseError(pParse,
2402 "fts5: %s queries are not supported (detail!=full)",
2403 pNear->nPhrase==1 ? "phrase": "NEAR"
2405 sqlite3_free(pRet);
2406 pRet = 0;
2409 }else{
2410 fts5ExprAddChildren(pRet, pLeft);
2411 fts5ExprAddChildren(pRet, pRight);
2412 if( pRet->iHeight>SQLITE_FTS5_MAX_EXPR_DEPTH ){
2413 sqlite3Fts5ParseError(pParse,
2414 "fts5 expression tree is too large (maximum depth %d)",
2415 SQLITE_FTS5_MAX_EXPR_DEPTH
2417 sqlite3_free(pRet);
2418 pRet = 0;
2425 if( pRet==0 ){
2426 assert( pParse->rc!=SQLITE_OK );
2427 sqlite3Fts5ParseNodeFree(pLeft);
2428 sqlite3Fts5ParseNodeFree(pRight);
2429 sqlite3Fts5ParseNearsetFree(pNear);
2431 return pRet;
2434 Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
2435 Fts5Parse *pParse, /* Parse context */
2436 Fts5ExprNode *pLeft, /* Left hand child expression */
2437 Fts5ExprNode *pRight /* Right hand child expression */
2439 Fts5ExprNode *pRet = 0;
2440 Fts5ExprNode *pPrev;
2442 if( pParse->rc ){
2443 sqlite3Fts5ParseNodeFree(pLeft);
2444 sqlite3Fts5ParseNodeFree(pRight);
2445 }else{
2447 assert( pLeft->eType==FTS5_STRING
2448 || pLeft->eType==FTS5_TERM
2449 || pLeft->eType==FTS5_EOF
2450 || pLeft->eType==FTS5_AND
2452 assert( pRight->eType==FTS5_STRING
2453 || pRight->eType==FTS5_TERM
2454 || pRight->eType==FTS5_EOF
2457 if( pLeft->eType==FTS5_AND ){
2458 pPrev = pLeft->apChild[pLeft->nChild-1];
2459 }else{
2460 pPrev = pLeft;
2462 assert( pPrev->eType==FTS5_STRING
2463 || pPrev->eType==FTS5_TERM
2464 || pPrev->eType==FTS5_EOF
2467 if( pRight->eType==FTS5_EOF ){
2468 assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
2469 sqlite3Fts5ParseNodeFree(pRight);
2470 pRet = pLeft;
2471 pParse->nPhrase--;
2473 else if( pPrev->eType==FTS5_EOF ){
2474 Fts5ExprPhrase **ap;
2476 if( pPrev==pLeft ){
2477 pRet = pRight;
2478 }else{
2479 pLeft->apChild[pLeft->nChild-1] = pRight;
2480 pRet = pLeft;
2483 ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
2484 assert( ap[0]==pPrev->pNear->apPhrase[0] );
2485 memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
2486 pParse->nPhrase--;
2488 sqlite3Fts5ParseNodeFree(pPrev);
2490 else{
2491 pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
2495 return pRet;
2498 #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
2499 static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
2500 sqlite3_int64 nByte = 0;
2501 Fts5ExprTerm *p;
2502 char *zQuoted;
2504 /* Determine the maximum amount of space required. */
2505 for(p=pTerm; p; p=p->pSynonym){
2506 nByte += pTerm->nQueryTerm * 2 + 3 + 2;
2508 zQuoted = sqlite3_malloc64(nByte);
2510 if( zQuoted ){
2511 int i = 0;
2512 for(p=pTerm; p; p=p->pSynonym){
2513 char *zIn = p->pTerm;
2514 char *zEnd = &zIn[p->nQueryTerm];
2515 zQuoted[i++] = '"';
2516 while( zIn<zEnd ){
2517 if( *zIn=='"' ) zQuoted[i++] = '"';
2518 zQuoted[i++] = *zIn++;
2520 zQuoted[i++] = '"';
2521 if( p->pSynonym ) zQuoted[i++] = '|';
2523 if( pTerm->bPrefix ){
2524 zQuoted[i++] = ' ';
2525 zQuoted[i++] = '*';
2527 zQuoted[i++] = '\0';
2529 return zQuoted;
2532 static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
2533 char *zNew;
2534 va_list ap;
2535 va_start(ap, zFmt);
2536 zNew = sqlite3_vmprintf(zFmt, ap);
2537 va_end(ap);
2538 if( zApp && zNew ){
2539 char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
2540 sqlite3_free(zNew);
2541 zNew = zNew2;
2543 sqlite3_free(zApp);
2544 return zNew;
2548 ** Compose a tcl-readable representation of expression pExpr. Return a
2549 ** pointer to a buffer containing that representation. It is the
2550 ** responsibility of the caller to at some point free the buffer using
2551 ** sqlite3_free().
2553 static char *fts5ExprPrintTcl(
2554 Fts5Config *pConfig,
2555 const char *zNearsetCmd,
2556 Fts5ExprNode *pExpr
2558 char *zRet = 0;
2559 if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
2560 Fts5ExprNearset *pNear = pExpr->pNear;
2561 int i;
2562 int iTerm;
2564 zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
2565 if( zRet==0 ) return 0;
2566 if( pNear->pColset ){
2567 int *aiCol = pNear->pColset->aiCol;
2568 int nCol = pNear->pColset->nCol;
2569 if( nCol==1 ){
2570 zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
2571 }else{
2572 zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
2573 for(i=1; i<pNear->pColset->nCol; i++){
2574 zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
2576 zRet = fts5PrintfAppend(zRet, "} ");
2578 if( zRet==0 ) return 0;
2581 if( pNear->nPhrase>1 ){
2582 zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
2583 if( zRet==0 ) return 0;
2586 zRet = fts5PrintfAppend(zRet, "--");
2587 if( zRet==0 ) return 0;
2589 for(i=0; i<pNear->nPhrase; i++){
2590 Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
2592 zRet = fts5PrintfAppend(zRet, " {");
2593 for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
2594 Fts5ExprTerm *p = &pPhrase->aTerm[iTerm];
2595 zRet = fts5PrintfAppend(zRet, "%s%.*s", iTerm==0?"":" ",
2596 p->nQueryTerm, p->pTerm
2598 if( pPhrase->aTerm[iTerm].bPrefix ){
2599 zRet = fts5PrintfAppend(zRet, "*");
2603 if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
2604 if( zRet==0 ) return 0;
2607 }else if( pExpr->eType==0 ){
2608 zRet = sqlite3_mprintf("{}");
2609 }else{
2610 char const *zOp = 0;
2611 int i;
2612 switch( pExpr->eType ){
2613 case FTS5_AND: zOp = "AND"; break;
2614 case FTS5_NOT: zOp = "NOT"; break;
2615 default:
2616 assert( pExpr->eType==FTS5_OR );
2617 zOp = "OR";
2618 break;
2621 zRet = sqlite3_mprintf("%s", zOp);
2622 for(i=0; zRet && i<pExpr->nChild; i++){
2623 char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
2624 if( !z ){
2625 sqlite3_free(zRet);
2626 zRet = 0;
2627 }else{
2628 zRet = fts5PrintfAppend(zRet, " [%z]", z);
2633 return zRet;
2636 static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
2637 char *zRet = 0;
2638 if( pExpr->eType==0 ){
2639 return sqlite3_mprintf("\"\"");
2640 }else
2641 if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
2642 Fts5ExprNearset *pNear = pExpr->pNear;
2643 int i;
2644 int iTerm;
2646 if( pNear->pColset ){
2647 int ii;
2648 Fts5Colset *pColset = pNear->pColset;
2649 if( pColset->nCol>1 ) zRet = fts5PrintfAppend(zRet, "{");
2650 for(ii=0; ii<pColset->nCol; ii++){
2651 zRet = fts5PrintfAppend(zRet, "%s%s",
2652 pConfig->azCol[pColset->aiCol[ii]], ii==pColset->nCol-1 ? "" : " "
2655 if( zRet ){
2656 zRet = fts5PrintfAppend(zRet, "%s : ", pColset->nCol>1 ? "}" : "");
2658 if( zRet==0 ) return 0;
2661 if( pNear->nPhrase>1 ){
2662 zRet = fts5PrintfAppend(zRet, "NEAR(");
2663 if( zRet==0 ) return 0;
2666 for(i=0; i<pNear->nPhrase; i++){
2667 Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
2668 if( i!=0 ){
2669 zRet = fts5PrintfAppend(zRet, " ");
2670 if( zRet==0 ) return 0;
2672 for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
2673 char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
2674 if( zTerm ){
2675 zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
2676 sqlite3_free(zTerm);
2678 if( zTerm==0 || zRet==0 ){
2679 sqlite3_free(zRet);
2680 return 0;
2685 if( pNear->nPhrase>1 ){
2686 zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
2687 if( zRet==0 ) return 0;
2690 }else{
2691 char const *zOp = 0;
2692 int i;
2694 switch( pExpr->eType ){
2695 case FTS5_AND: zOp = " AND "; break;
2696 case FTS5_NOT: zOp = " NOT "; break;
2697 default:
2698 assert( pExpr->eType==FTS5_OR );
2699 zOp = " OR ";
2700 break;
2703 for(i=0; i<pExpr->nChild; i++){
2704 char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
2705 if( z==0 ){
2706 sqlite3_free(zRet);
2707 zRet = 0;
2708 }else{
2709 int e = pExpr->apChild[i]->eType;
2710 int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
2711 zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
2712 (i==0 ? "" : zOp),
2713 (b?"(":""), z, (b?")":"")
2716 if( zRet==0 ) break;
2720 return zRet;
2724 ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
2725 ** and fts5_expr_tcl() (bTcl!=0).
2727 static void fts5ExprFunction(
2728 sqlite3_context *pCtx, /* Function call context */
2729 int nArg, /* Number of args */
2730 sqlite3_value **apVal, /* Function arguments */
2731 int bTcl
2733 Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
2734 sqlite3 *db = sqlite3_context_db_handle(pCtx);
2735 const char *zExpr = 0;
2736 char *zErr = 0;
2737 Fts5Expr *pExpr = 0;
2738 int rc;
2739 int i;
2741 const char **azConfig; /* Array of arguments for Fts5Config */
2742 const char *zNearsetCmd = "nearset";
2743 int nConfig; /* Size of azConfig[] */
2744 Fts5Config *pConfig = 0;
2745 int iArg = 1;
2747 if( nArg<1 ){
2748 zErr = sqlite3_mprintf("wrong number of arguments to function %s",
2749 bTcl ? "fts5_expr_tcl" : "fts5_expr"
2751 sqlite3_result_error(pCtx, zErr, -1);
2752 sqlite3_free(zErr);
2753 return;
2756 if( bTcl && nArg>1 ){
2757 zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
2758 iArg = 2;
2761 nConfig = 3 + (nArg-iArg);
2762 azConfig = (const char**)sqlite3_malloc64(sizeof(char*) * nConfig);
2763 if( azConfig==0 ){
2764 sqlite3_result_error_nomem(pCtx);
2765 return;
2767 azConfig[0] = 0;
2768 azConfig[1] = "main";
2769 azConfig[2] = "tbl";
2770 for(i=3; iArg<nArg; iArg++){
2771 const char *z = (const char*)sqlite3_value_text(apVal[iArg]);
2772 azConfig[i++] = (z ? z : "");
2775 zExpr = (const char*)sqlite3_value_text(apVal[0]);
2776 if( zExpr==0 ) zExpr = "";
2778 rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
2779 if( rc==SQLITE_OK ){
2780 rc = sqlite3Fts5ExprNew(pConfig, 0, pConfig->nCol, zExpr, &pExpr, &zErr);
2782 if( rc==SQLITE_OK ){
2783 char *zText;
2784 if( pExpr->pRoot->xNext==0 ){
2785 zText = sqlite3_mprintf("");
2786 }else if( bTcl ){
2787 zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
2788 }else{
2789 zText = fts5ExprPrint(pConfig, pExpr->pRoot);
2791 if( zText==0 ){
2792 rc = SQLITE_NOMEM;
2793 }else{
2794 sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
2795 sqlite3_free(zText);
2799 if( rc!=SQLITE_OK ){
2800 if( zErr ){
2801 sqlite3_result_error(pCtx, zErr, -1);
2802 sqlite3_free(zErr);
2803 }else{
2804 sqlite3_result_error_code(pCtx, rc);
2807 sqlite3_free((void *)azConfig);
2808 sqlite3Fts5ConfigFree(pConfig);
2809 sqlite3Fts5ExprFree(pExpr);
2812 static void fts5ExprFunctionHr(
2813 sqlite3_context *pCtx, /* Function call context */
2814 int nArg, /* Number of args */
2815 sqlite3_value **apVal /* Function arguments */
2817 fts5ExprFunction(pCtx, nArg, apVal, 0);
2819 static void fts5ExprFunctionTcl(
2820 sqlite3_context *pCtx, /* Function call context */
2821 int nArg, /* Number of args */
2822 sqlite3_value **apVal /* Function arguments */
2824 fts5ExprFunction(pCtx, nArg, apVal, 1);
2828 ** The implementation of an SQLite user-defined-function that accepts a
2829 ** single integer as an argument. If the integer is an alpha-numeric
2830 ** unicode code point, 1 is returned. Otherwise 0.
2832 static void fts5ExprIsAlnum(
2833 sqlite3_context *pCtx, /* Function call context */
2834 int nArg, /* Number of args */
2835 sqlite3_value **apVal /* Function arguments */
2837 int iCode;
2838 u8 aArr[32];
2839 if( nArg!=1 ){
2840 sqlite3_result_error(pCtx,
2841 "wrong number of arguments to function fts5_isalnum", -1
2843 return;
2845 memset(aArr, 0, sizeof(aArr));
2846 sqlite3Fts5UnicodeCatParse("L*", aArr);
2847 sqlite3Fts5UnicodeCatParse("N*", aArr);
2848 sqlite3Fts5UnicodeCatParse("Co", aArr);
2849 iCode = sqlite3_value_int(apVal[0]);
2850 sqlite3_result_int(pCtx, aArr[sqlite3Fts5UnicodeCategory((u32)iCode)]);
2853 static void fts5ExprFold(
2854 sqlite3_context *pCtx, /* Function call context */
2855 int nArg, /* Number of args */
2856 sqlite3_value **apVal /* Function arguments */
2858 if( nArg!=1 && nArg!=2 ){
2859 sqlite3_result_error(pCtx,
2860 "wrong number of arguments to function fts5_fold", -1
2862 }else{
2863 int iCode;
2864 int bRemoveDiacritics = 0;
2865 iCode = sqlite3_value_int(apVal[0]);
2866 if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
2867 sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
2870 #endif /* if SQLITE_TEST || SQLITE_FTS5_DEBUG */
2873 ** This is called during initialization to register the fts5_expr() scalar
2874 ** UDF with the SQLite handle passed as the only argument.
2876 int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
2877 #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
2878 struct Fts5ExprFunc {
2879 const char *z;
2880 void (*x)(sqlite3_context*,int,sqlite3_value**);
2881 } aFunc[] = {
2882 { "fts5_expr", fts5ExprFunctionHr },
2883 { "fts5_expr_tcl", fts5ExprFunctionTcl },
2884 { "fts5_isalnum", fts5ExprIsAlnum },
2885 { "fts5_fold", fts5ExprFold },
2887 int i;
2888 int rc = SQLITE_OK;
2889 void *pCtx = (void*)pGlobal;
2891 for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
2892 struct Fts5ExprFunc *p = &aFunc[i];
2893 rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
2895 #else
2896 int rc = SQLITE_OK;
2897 UNUSED_PARAM2(pGlobal,db);
2898 #endif
2900 /* Avoid warnings indicating that sqlite3Fts5ParserTrace() and
2901 ** sqlite3Fts5ParserFallback() are unused */
2902 #ifndef NDEBUG
2903 (void)sqlite3Fts5ParserTrace;
2904 #endif
2905 (void)sqlite3Fts5ParserFallback;
2907 return rc;
2911 ** Return the number of phrases in expression pExpr.
2913 int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
2914 return (pExpr ? pExpr->nPhrase : 0);
2918 ** Return the number of terms in the iPhrase'th phrase in pExpr.
2920 int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
2921 if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
2922 return pExpr->apExprPhrase[iPhrase]->nTerm;
2926 ** This function is used to access the current position list for phrase
2927 ** iPhrase.
2929 int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
2930 int nRet;
2931 Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
2932 Fts5ExprNode *pNode = pPhrase->pNode;
2933 if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
2934 *pa = pPhrase->poslist.p;
2935 nRet = pPhrase->poslist.n;
2936 }else{
2937 *pa = 0;
2938 nRet = 0;
2940 return nRet;
2943 struct Fts5PoslistPopulator {
2944 Fts5PoslistWriter writer;
2945 int bOk; /* True if ok to populate */
2946 int bMiss;
2950 ** Clear the position lists associated with all phrases in the expression
2951 ** passed as the first argument. Argument bLive is true if the expression
2952 ** might be pointing to a real entry, otherwise it has just been reset.
2954 ** At present this function is only used for detail=col and detail=none
2955 ** fts5 tables. This implies that all phrases must be at most 1 token
2956 ** in size, as phrase matches are not supported without detail=full.
2958 Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
2959 Fts5PoslistPopulator *pRet;
2960 pRet = sqlite3_malloc64(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
2961 if( pRet ){
2962 int i;
2963 memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
2964 for(i=0; i<pExpr->nPhrase; i++){
2965 Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
2966 Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
2967 assert( pExpr->apExprPhrase[i]->nTerm<=1 );
2968 if( bLive &&
2969 (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
2971 pRet[i].bMiss = 1;
2972 }else{
2973 pBuf->n = 0;
2977 return pRet;
2980 struct Fts5ExprCtx {
2981 Fts5Expr *pExpr;
2982 Fts5PoslistPopulator *aPopulator;
2983 i64 iOff;
2985 typedef struct Fts5ExprCtx Fts5ExprCtx;
2988 ** TODO: Make this more efficient!
2990 static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
2991 int i;
2992 for(i=0; i<pColset->nCol; i++){
2993 if( pColset->aiCol[i]==iCol ) return 1;
2995 return 0;
2999 ** pToken is a buffer nToken bytes in size that may or may not contain
3000 ** an embedded 0x00 byte. If it does, return the number of bytes in
3001 ** the buffer before the 0x00. If it does not, return nToken.
3003 static int fts5QueryTerm(const char *pToken, int nToken){
3004 int ii;
3005 for(ii=0; ii<nToken && pToken[ii]; ii++){}
3006 return ii;
3009 static int fts5ExprPopulatePoslistsCb(
3010 void *pCtx, /* Copy of 2nd argument to xTokenize() */
3011 int tflags, /* Mask of FTS5_TOKEN_* flags */
3012 const char *pToken, /* Pointer to buffer containing token */
3013 int nToken, /* Size of token in bytes */
3014 int iUnused1, /* Byte offset of token within input text */
3015 int iUnused2 /* Byte offset of end of token within input text */
3017 Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
3018 Fts5Expr *pExpr = p->pExpr;
3019 int i;
3020 int nQuery = nToken;
3021 i64 iRowid = pExpr->pRoot->iRowid;
3023 UNUSED_PARAM2(iUnused1, iUnused2);
3025 if( nQuery>FTS5_MAX_TOKEN_SIZE ) nQuery = FTS5_MAX_TOKEN_SIZE;
3026 if( pExpr->pConfig->bTokendata ){
3027 nQuery = fts5QueryTerm(pToken, nQuery);
3029 if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
3030 for(i=0; i<pExpr->nPhrase; i++){
3031 Fts5ExprTerm *pT;
3032 if( p->aPopulator[i].bOk==0 ) continue;
3033 for(pT=&pExpr->apExprPhrase[i]->aTerm[0]; pT; pT=pT->pSynonym){
3034 if( (pT->nQueryTerm==nQuery || (pT->nQueryTerm<nQuery && pT->bPrefix))
3035 && memcmp(pT->pTerm, pToken, pT->nQueryTerm)==0
3037 int rc = sqlite3Fts5PoslistWriterAppend(
3038 &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
3040 if( rc==SQLITE_OK && pExpr->pConfig->bTokendata && !pT->bPrefix ){
3041 int iCol = p->iOff>>32;
3042 int iTokOff = p->iOff & 0x7FFFFFFF;
3043 rc = sqlite3Fts5IndexIterWriteTokendata(
3044 pT->pIter, pToken, nToken, iRowid, iCol, iTokOff
3047 if( rc ) return rc;
3048 break;
3052 return SQLITE_OK;
3055 int sqlite3Fts5ExprPopulatePoslists(
3056 Fts5Config *pConfig,
3057 Fts5Expr *pExpr,
3058 Fts5PoslistPopulator *aPopulator,
3059 int iCol,
3060 const char *z, int n
3062 int i;
3063 Fts5ExprCtx sCtx;
3064 sCtx.pExpr = pExpr;
3065 sCtx.aPopulator = aPopulator;
3066 sCtx.iOff = (((i64)iCol) << 32) - 1;
3068 for(i=0; i<pExpr->nPhrase; i++){
3069 Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
3070 Fts5Colset *pColset = pNode->pNear->pColset;
3071 if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
3072 || aPopulator[i].bMiss
3074 aPopulator[i].bOk = 0;
3075 }else{
3076 aPopulator[i].bOk = 1;
3080 return sqlite3Fts5Tokenize(pConfig,
3081 FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
3085 static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
3086 if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
3087 pNode->pNear->apPhrase[0]->poslist.n = 0;
3088 }else{
3089 int i;
3090 for(i=0; i<pNode->nChild; i++){
3091 fts5ExprClearPoslists(pNode->apChild[i]);
3096 static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
3097 pNode->iRowid = iRowid;
3098 pNode->bEof = 0;
3099 switch( pNode->eType ){
3100 case FTS5_TERM:
3101 case FTS5_STRING:
3102 return (pNode->pNear->apPhrase[0]->poslist.n>0);
3104 case FTS5_AND: {
3105 int i;
3106 for(i=0; i<pNode->nChild; i++){
3107 if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
3108 fts5ExprClearPoslists(pNode);
3109 return 0;
3112 break;
3115 case FTS5_OR: {
3116 int i;
3117 int bRet = 0;
3118 for(i=0; i<pNode->nChild; i++){
3119 if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
3120 bRet = 1;
3123 return bRet;
3126 default: {
3127 assert( pNode->eType==FTS5_NOT );
3128 if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
3129 || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
3131 fts5ExprClearPoslists(pNode);
3132 return 0;
3134 break;
3137 return 1;
3140 void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
3141 fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
3145 ** This function is only called for detail=columns tables.
3147 int sqlite3Fts5ExprPhraseCollist(
3148 Fts5Expr *pExpr,
3149 int iPhrase,
3150 const u8 **ppCollist,
3151 int *pnCollist
3153 Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
3154 Fts5ExprNode *pNode = pPhrase->pNode;
3155 int rc = SQLITE_OK;
3157 assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
3158 assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
3160 if( pNode->bEof==0
3161 && pNode->iRowid==pExpr->pRoot->iRowid
3162 && pPhrase->poslist.n>0
3164 Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
3165 if( pTerm->pSynonym ){
3166 Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
3167 rc = fts5ExprSynonymList(
3168 pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
3170 }else{
3171 *ppCollist = pPhrase->aTerm[0].pIter->pData;
3172 *pnCollist = pPhrase->aTerm[0].pIter->nData;
3174 }else{
3175 *ppCollist = 0;
3176 *pnCollist = 0;
3179 return rc;
3183 ** Does the work of the fts5_api.xQueryToken() API method.
3185 int sqlite3Fts5ExprQueryToken(
3186 Fts5Expr *pExpr,
3187 int iPhrase,
3188 int iToken,
3189 const char **ppOut,
3190 int *pnOut
3192 Fts5ExprPhrase *pPhrase = 0;
3194 if( iPhrase<0 || iPhrase>=pExpr->nPhrase ){
3195 return SQLITE_RANGE;
3197 pPhrase = pExpr->apExprPhrase[iPhrase];
3198 if( iToken<0 || iToken>=pPhrase->nTerm ){
3199 return SQLITE_RANGE;
3202 *ppOut = pPhrase->aTerm[iToken].pTerm;
3203 *pnOut = pPhrase->aTerm[iToken].nFullTerm;
3204 return SQLITE_OK;
3208 ** Does the work of the fts5_api.xInstToken() API method.
3210 int sqlite3Fts5ExprInstToken(
3211 Fts5Expr *pExpr,
3212 i64 iRowid,
3213 int iPhrase,
3214 int iCol,
3215 int iOff,
3216 int iToken,
3217 const char **ppOut,
3218 int *pnOut
3220 Fts5ExprPhrase *pPhrase = 0;
3221 Fts5ExprTerm *pTerm = 0;
3222 int rc = SQLITE_OK;
3224 if( iPhrase<0 || iPhrase>=pExpr->nPhrase ){
3225 return SQLITE_RANGE;
3227 pPhrase = pExpr->apExprPhrase[iPhrase];
3228 if( iToken<0 || iToken>=pPhrase->nTerm ){
3229 return SQLITE_RANGE;
3231 pTerm = &pPhrase->aTerm[iToken];
3232 if( pTerm->bPrefix==0 ){
3233 if( pExpr->pConfig->bTokendata ){
3234 rc = sqlite3Fts5IterToken(
3235 pTerm->pIter, iRowid, iCol, iOff+iToken, ppOut, pnOut
3237 }else{
3238 *ppOut = pTerm->pTerm;
3239 *pnOut = pTerm->nFullTerm;
3242 return rc;
3246 ** Clear the token mappings for all Fts5IndexIter objects mannaged by
3247 ** the expression passed as the only argument.
3249 void sqlite3Fts5ExprClearTokens(Fts5Expr *pExpr){
3250 int ii;
3251 for(ii=0; ii<pExpr->nPhrase; ii++){
3252 Fts5ExprTerm *pT;
3253 for(pT=&pExpr->apExprPhrase[ii]->aTerm[0]; pT; pT=pT->pSynonym){
3254 sqlite3Fts5IndexIterClearTokendata(pT->pIter);