/ Check-in [ae502657]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Add support for OR and NOT terms in fts1. (CVS 3399)
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: ae50265791d1a7500aa3c405a78a9bca8ff0cc08
User & Date: drh 2006-09-09 23:11:51
Context
2006-09-10
03:34
Add some simple test cases for the OR and NOT logic of the fts1 module. Fix lots of bugs discovered while developing these test cases. (CVS 3400) check-in: 70bcff02 user: drh tags: trunk
2006-09-09
23:11
Add support for OR and NOT terms in fts1. (CVS 3399) check-in: ae502657 user: drh tags: trunk
2006-09-08
17:00
Write doclists using a segmented technique to amortize costs better. New items for a term are merged with the term's segment 0 doclist, until that doclist exceeds CHUNK_MAX. Then the segments are merged in exponential fashion, so that segment 1 contains approximately 2*CHUNK_MAX data, segment 2 4*CHUNK_MAX, and so on. (CVS 3398) check-in: b6b93a33 user: shess tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to ext/fts1/fts1.c.

230
231
232
233
234
235
236














237
238
239

240
241
242



243
244
245
246
247
248
249
250




251
252
253
254
255

256
257
258
259
260
261
262
263
264

265
266
267
268
269
270
271
...
274
275
276
277
278
279
280
281
282
283
284



285
286
287
288
289
290
291
...
295
296
297
298
299
300
301


302
303

304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324


325
326
327
328
329
330



































331
332
333
334
335
336
337
...
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534

























































535
536
537
538
539
540
541
....
1160
1161
1162
1163
1164
1165
1166







1167
1168
1169
1170
1171
1172
1173






1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184










1185
1186





1187
1188
1189
1190
1191



1192
1193
1194
1195




1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206























1207
1208
1209

1210
1211
1212



1213
1214
1215
1216




1217
1218


1219
1220

1221
1222
1223


1224
1225
1226
1227
1228
1229
1230
1231










1232
1233
1234
1235
1236
1237

1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251





1252







1253

1254
1255
1256
1257
1258
1259
1260
....
1284
1285
1286
1287
1288
1289
1290
1291



1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303








1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318


























1319
1320
1321
1322
1323
1324
1325
  addPos(d, iPos);
  appendVarint(d, iStartOffset-d->iLastOffset);
  d->iLastOffset = iStartOffset;
  appendVarint(d, iEndOffset-iStartOffset);
  appendVarint(d, 0);  /* add new terminator */
}















typedef struct DocListReader {
  DocList *pDoclist;
  char *p;

  int iLastPos;  /* the last position read, or -1 when not in a position list */
} DocListReader;




static void readerInit(DocListReader *r, DocList *pDoclist){
  r->pDoclist = pDoclist;
  if( pDoclist!=NULL ){
    r->p = pDoclist->pData;
  }
  r->iLastPos = -1;
}





static int atEnd(DocListReader *pReader){
  return pReader->p >= docListEnd(pReader->pDoclist);
}

/* Peek at the next docid without advancing the read pointer. */

static sqlite_int64 peekDocid(DocListReader *pReader){
  sqlite_int64 ret;
  assert( !atEnd(pReader) );
  assert( pReader->iLastPos==-1 );
  getVarint(pReader->p, &ret);
  return ret;
}

/* Read the next docid. */

static sqlite_int64 readDocid(DocListReader *pReader){
  sqlite_int64 ret;
  assert( !atEnd(pReader) );
  assert( pReader->iLastPos==-1 );
  pReader->p += getVarint(pReader->p, &ret);
  if( pReader->pDoclist->iType>=DL_POSITIONS ){
    pReader->iLastPos = 0;
................................................................................
}

/* Read the next position from a position list.
 * Returns the position, or -1 at the end of the list. */
static int readPosition(DocListReader *pReader){
  int i;
  int iType = pReader->pDoclist->iType;
  assert( iType>=DL_POSITIONS );
  assert( !atEnd(pReader) );
  assert( pReader->iLastPos!=-1 );




  pReader->p += getVarint32(pReader->p, &i);
  if( i==0 ){
    pReader->iLastPos = -1;
    return -1;
  }
  pReader->iLastPos += ((int) i)-1;
  if( iType>=DL_POSITIONS_OFFSETS ){
................................................................................
    pReader->p += getVarint32(pReader->p, &iEnd);
  }
  return pReader->iLastPos;
}

/* Skip past the end of a position list. */
static void skipPositionList(DocListReader *pReader){


  while( readPosition(pReader)!=-1 )
    ;

}

/* Skip over a docid, including its position list if the doclist has
 * positions. */
static void skipDocument(DocListReader *pReader){
  readDocid(pReader);
  if( pReader->pDoclist->iType>=DL_POSITIONS ){
    skipPositionList(pReader);
  }
}

/* Skip past all docids which are less than [iDocid].  Returns 1 if a docid
 * matching [iDocid] was found.  */
static int skipToDocid(DocListReader *pReader, sqlite_int64 iDocid){
  sqlite_int64 d = 0;
  while( !atEnd(pReader) && (d=peekDocid(pReader))<iDocid ){
    skipDocument(pReader);
  }
  return !atEnd(pReader) && d==iDocid;
}



static sqlite_int64 firstDocid(DocList *d){
  DocListReader r;
  readerInit(&r, d);
  return readDocid(&r);
}




































/* Helper function for docListUpdate() and docListAccumulate().
** Splices a doclist element into the doclist represented by r,
** leaving r pointing after the newly spliced element.
*/
static void docListSpliceElement(DocListReader *r, sqlite_int64 iDocid,
                                 const char *pSource, int nSource){
  DocList *d = r->pDoclist;
................................................................................
    char *pSource = updateReader.p;
    sqlite_int64 iDocid = readDocid(&updateReader);
    skipPositionList(&updateReader);
    docListSpliceElement(&accReader, iDocid, pSource, updateReader.p-pSource);
  }
}

/* A DocListMerge computes the AND of an in-memory DocList [in] and a chunked
 * on-disk doclist, resulting in another in-memory DocList [out].  [in]
 * and [out] may or may not store position information according to the
 * caller's wishes.  The on-disk doclist always comes with positions.
 *
 * The caller must read each chunk of the on-disk doclist in succession and
 * pass it to mergeBlock().
 *
 * If [in] has positions, then the merge output contains only documents with
 * matching positions in the two input doclists.  If [in] does not have
 * positions, then the merge output contains all documents common to the two
 * input doclists.
 *
 * If [in] is NULL, then the on-disk doclist is copied to [out] directly.
 *
 * A merge is performed using an integer [iPhrasePos] provided by the caller.
 * [iPhrasePos] is subtracted from each position in the on-disk doclist for the
 * purpose of position comparison; this is helpful in implementing phrase
 * searches.
 *
 * A DocListMerge is not yet able to propagate offsets through query
 * processing; we should add that capability soon.
*/
/* TODO(shess) Adam indicates that since we no longer can stream
** ordered doclist chunks, DocListMerge is no longer as useful and
** should be removed.  Not removing at this time so that the removal
** doesn't obscure the exponential-chunking change.
*/
typedef struct DocListMerge {
  DocListReader in;
  DocList *pOut;
  int iPhrasePos;
} DocListMerge;

static void mergeInit(DocListMerge *m,
                      DocList *pIn, int iPhrasePos, DocList *pOut){
  readerInit(&m->in, pIn);
  m->pOut = pOut;
  m->iPhrasePos = iPhrasePos;

  /* can't handle offsets yet */
  assert( pIn==NULL || pIn->iType<=DL_POSITIONS );
  assert( pOut->iType<=DL_POSITIONS );
}

/* A helper function for mergeBlock(), below.  Merge the position lists
 * pointed to by m->in and pBlockReader.
 * If the merge matches, write [iDocid] to m->pOut; if m->pOut
 * has positions then write all matching positions as well. */
static void mergePosList(DocListMerge *m, sqlite_int64 iDocid,
                         DocListReader *pBlockReader){
  int iBlockPos = readPosition(pBlockReader);
  int iInPos = readPosition(&m->in);
  int match = 0;

  /* Loop until we've reached the end of both position lists. */
  while( iBlockPos!=-1 || iInPos!=-1 ){
    if( iBlockPos-m->iPhrasePos==iInPos ){
      if( !match ){
        docListAddDocid(m->pOut, iDocid);
        match = 1;
      }
      if( m->pOut->iType>=DL_POSITIONS ){
        docListAddPos(m->pOut, iInPos);
      }
      iBlockPos = readPosition(pBlockReader);
      iInPos = readPosition(&m->in);
    } else if( iInPos==-1 || (iBlockPos!=-1 && iBlockPos-m->iPhrasePos<iInPos) ){
      iBlockPos = readPosition(pBlockReader);
    } else {
      iInPos = readPosition(&m->in);
    }
  }
}

/* A helper function for mergeBlock(), below.  Copy the docid and
 * position list (if wanted) from pBlockReader to pOut. */
static void copyDocument(DocList *pOut, sqlite_int64 iDocid,
                         DocListReader *pBlockReader){
  docListAddDocid(pOut, iDocid);
  if( pOut->iType<DL_POSITIONS ){
    skipPositionList(pBlockReader);
  } else {
    /* Copy all positions to the output doclist. */
    int pos;
    while( (pos = readPosition(pBlockReader))!=-1 ){
      docListAddPos(pOut, pos);
    }
  }
}

/* Merge one block of an on-disk doclist into a DocListMerge. */
static void mergeBlock(DocListMerge *m, DocList *pBlock){
  DocListReader blockReader;
  assert( pBlock->iType>=DL_POSITIONS );
  readerInit(&blockReader, pBlock);
  while( !atEnd(&blockReader) ){
    sqlite_int64 iDocid = readDocid(&blockReader);
    if( m->in.pDoclist==NULL ){
      /* Skip document delete crumbs */
      if( *blockReader.p=='\0' ){
        skipPositionList(&blockReader);
      } else {
        copyDocument(m->pOut, iDocid, &blockReader);
      }
      continue;
    }
    if( skipToDocid(&m->in, iDocid) ){  /* we have a docid match */
      readDocid(&m->in);
      /* Skip document delete crumbs */
      if( *blockReader.p=='\0' ){
        skipPositionList(&blockReader);
      }else{
        if( m->in.pDoclist->iType>=DL_POSITIONS ){
          mergePosList(m, iDocid, &blockReader);
        } else {
          copyDocument(m->pOut, iDocid, &blockReader);
        }
      }
    } else if( !atEnd(&m->in) ){
      skipPositionList(&blockReader);  /* skip this docid in the block */
    } else return;  /* nothing more to merge */

























































  }
}

/* Duplicate a string; the caller must free() the returned string.
 * (We don't use strdup() since it's not part of the standard C library and
 * may not be available everywhere.) */
static char *string_dup(const char *s){
................................................................................
      return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
    default:
      assert( 0 );
      return SQLITE_ERROR;  /* not reached */
  }
}








/* Read the posting list for [pTerm]; AND it with the doclist [pIn] to
 * produce the doclist [out], using the given phrase position [iPhrasePos].
 * (*pSelect) is used to hold an SQLite statement used inside this function;
 * the caller should initialize *pSelect to NULL before the first call.
 */
static int mergeQuery(fulltext_vtab *v, const char *pTerm, int nTerm,
                       DocList *pIn, int iPhrasePos, DocList *out){






  int rc;
  DocListMerge merge;
  DocList doclist;

  /* If [pIn] is already empty, there's no point in reading the
   * posting list to AND it in; return immediately. */
  if( pIn!=NULL && !pIn->nData ) return SQLITE_OK;

  rc = term_select_all(v, pTerm, nTerm, &doclist);
  if( rc!=SQLITE_OK ) return rc;











  mergeInit(&merge, pIn, iPhrasePos, out);
  mergeBlock(&merge, &doclist);





  docListDestroy(&doclist);

  return SQLITE_OK;
}




typedef struct QueryTerm {
  int isPhrase;    /* true if this term begins a new phrase */
  char *pTerm;
  int nTerm;




} QueryTerm;

/* A parsed query.
 *
 * As an example, parsing the query ["four score" years "new nation"] will
 * yield a Query with 5 terms:
 *   "four",   isPhrase = 1
 *   "score",  isPhrase = 0
 *   "years",  isPhrase = 1
 *   "new",    isPhrase = 1
 *   "nation", isPhrase = 0























 */
typedef struct Query {
  int nTerms;

  QueryTerm *pTerms;
} Query;




static void queryAdd(Query *q, int isPhrase, const char *pTerm, int nTerm){
  QueryTerm *t;
  ++q->nTerms;
  q->pTerms = realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0]));




  t = &q->pTerms[q->nTerms - 1];
  t->isPhrase = isPhrase;


  t->pTerm = malloc(nTerm);
  memcpy(t->pTerm, pTerm, nTerm);

  t->nTerm = nTerm;
}
    


static void queryDestroy(Query *q){
  int i;
  for(i = 0; i < q->nTerms; ++i){
    free(q->pTerms[i].pTerm);
  }
  free(q->pTerms);
}











static int tokenizeSegment(sqlite3_tokenizer *pTokenizer,
                            const char *pSegment, int nSegment, int inPhrase,
                            Query *pQuery){
  const sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
  sqlite3_tokenizer_cursor *pCursor;
  int is_first = 1;

  
  int rc = pModule->xOpen(pTokenizer, pSegment, nSegment, &pCursor);
  if( rc!=SQLITE_OK ) return rc;
  pCursor->pTokenizer = pTokenizer;

  while( 1 ){
    const char *pToken;
    int nToken, iDummyOffset, iDummyPos;

    rc = pModule->xNext(pCursor,
                        &pToken, &nToken,
                        &iDummyOffset, &iDummyOffset,
                        &iDummyPos);
    if( rc!=SQLITE_OK ) break;





    queryAdd(pQuery, !inPhrase || is_first, pToken, nToken);







    is_first = 0;

  }

  return pModule->xClose(pCursor);
}

/* Parse a query string, yielding a Query object [pQuery], which the caller
 * must free. */
................................................................................
  if(inPhrase) {  /* unmatched quote */
    queryDestroy(pQuery);
    return SQLITE_ERROR;
  }
  return SQLITE_OK;
}

/* Perform a full-text query; return a list of documents in [pResult]. */



static int fulltextQuery(fulltext_vtab *v, const char *pInput, int nInput,
                          DocList **pResult){
  Query q;
  int phrase_start = -1;
  int i;
  DocList *d = NULL;

  int rc = parseQuery(v, pInput, nInput, &q);
  if( rc!=SQLITE_OK ) return rc;

  /* Merge terms. */
  for(i = 0 ; i < q.nTerms ; ++i){








    /* In each merge step, we need to generate positions whenever we're
     * processing a phrase which hasn't ended yet. */
    int needPositions = i<q.nTerms-1 && !q.pTerms[i+1].isPhrase;
    DocList *next = docListNew(needPositions ? DL_POSITIONS : DL_DOCIDS);
    if( q.pTerms[i].isPhrase ){
      phrase_start = i;
    }
    rc = mergeQuery(v, q.pTerms[i].pTerm, q.pTerms[i].nTerm,
                     d, i-phrase_start, next);
    if( rc!=SQLITE_OK ) break;
    if( d!=NULL ){
      docListDelete(d);
    }
    d = next;
  }



























  queryDestroy(&q);
  *pResult = d;
  return rc;
}

static int fulltextFilter(sqlite3_vtab_cursor *pCursor,







>
>
>
>
>
>
>
>
>
>
>
>
>
>

|
<
>



>
>
>








>
>
>
>

|


|
>








|
>







 







|



>
>
>







 







>
>
|
<
>






<
|
<












>
>






>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>





|
|
>
>
>
>
>
>

<




|




>
>
>
>
>
>
>
>
>
>
|
<
>
>
>
>
>





>
>
>

|
<
<
>
>
>
>




<
<
<
<
<
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


<
>
|


>
>
>
|



>
>
>
>

<
>
>
|

>


|
>
>








>
>
>
>
>
>
>
>
>
>






>







|



|
<

>
>
>
>
>

>
>
>
>
>
>
>

>







 







|
>
>
>










|

>
>
>
>
>
>
>
>


|
|
|



|






>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252

253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
...
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
...
321
322
323
324
325
326
327
328
329
330

331
332
333
334
335
336
337

338

339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
...
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
....
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307

1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327

1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342


1343
1344
1345
1346
1347
1348
1349
1350





1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377

1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393

1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440

1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
....
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
  addPos(d, iPos);
  appendVarint(d, iStartOffset-d->iLastOffset);
  d->iLastOffset = iStartOffset;
  appendVarint(d, iEndOffset-iStartOffset);
  appendVarint(d, 0);  /* add new terminator */
}

/*
** A DocListReader object is a cursor into a doclist.  Initialize
** the cursor to the beginning of the doclist by calling readerInit().
** Then use routines
**
**      peekDocid()
**      readDocid()
**      readPosition()
**      skipPositionList()
**      and so forth...
**
** to read information out of the doclist.  When we reach the end
** of the doclist, atEnd() returns TRUE.
*/
typedef struct DocListReader {
  DocList *pDoclist;  /* The document list we are stepping through */

  char *p;            /* Pointer to next unread byte in the doclist */
  int iLastPos;  /* the last position read, or -1 when not in a position list */
} DocListReader;

/*
** Initialize the DocListReader r to point to the beginning of pDoclist.
*/
static void readerInit(DocListReader *r, DocList *pDoclist){
  r->pDoclist = pDoclist;
  if( pDoclist!=NULL ){
    r->p = pDoclist->pData;
  }
  r->iLastPos = -1;
}

/*
** Return TRUE if we have reached then end of pReader and there is
** nothing else left to read.
*/
static int atEnd(DocListReader *pReader){
  return pReader->pDoclist==0 || (pReader->p >= docListEnd(pReader->pDoclist));
}

/* Peek at the next docid without advancing the read pointer. 
*/
static sqlite_int64 peekDocid(DocListReader *pReader){
  sqlite_int64 ret;
  assert( !atEnd(pReader) );
  assert( pReader->iLastPos==-1 );
  getVarint(pReader->p, &ret);
  return ret;
}

/* Read the next docid. 
*/
static sqlite_int64 readDocid(DocListReader *pReader){
  sqlite_int64 ret;
  assert( !atEnd(pReader) );
  assert( pReader->iLastPos==-1 );
  pReader->p += getVarint(pReader->p, &ret);
  if( pReader->pDoclist->iType>=DL_POSITIONS ){
    pReader->iLastPos = 0;
................................................................................
}

/* Read the next position from a position list.
 * Returns the position, or -1 at the end of the list. */
static int readPosition(DocListReader *pReader){
  int i;
  int iType = pReader->pDoclist->iType;

  assert( !atEnd(pReader) );
  assert( pReader->iLastPos!=-1 );

  if( iType<DL_POSITIONS ){
    return -1;
  }
  pReader->p += getVarint32(pReader->p, &i);
  if( i==0 ){
    pReader->iLastPos = -1;
    return -1;
  }
  pReader->iLastPos += ((int) i)-1;
  if( iType>=DL_POSITIONS_OFFSETS ){
................................................................................
    pReader->p += getVarint32(pReader->p, &iEnd);
  }
  return pReader->iLastPos;
}

/* Skip past the end of a position list. */
static void skipPositionList(DocListReader *pReader){
  DocList *p = pReader->pDoclist;
  if( p && p->iType>=DL_POSITIONS ){
    while( readPosition(pReader)!=-1 ){}

  }
}

/* Skip over a docid, including its position list if the doclist has
 * positions. */
static void skipDocument(DocListReader *pReader){
  readDocid(pReader);

  skipPositionList(pReader);

}

/* Skip past all docids which are less than [iDocid].  Returns 1 if a docid
 * matching [iDocid] was found.  */
static int skipToDocid(DocListReader *pReader, sqlite_int64 iDocid){
  sqlite_int64 d = 0;
  while( !atEnd(pReader) && (d=peekDocid(pReader))<iDocid ){
    skipDocument(pReader);
  }
  return !atEnd(pReader) && d==iDocid;
}

/* Return the first document in a document list.
*/
static sqlite_int64 firstDocid(DocList *d){
  DocListReader r;
  readerInit(&r, d);
  return readDocid(&r);
}

#ifdef SQLITE_DEBUG
/*
** This routine is used for debugging purpose only.
**
** Write the content of a doclist to standard output.
*/
static void printDoclist(DocList *p){
  DocListReader r;
  const char *zSep = "";

  readerInit(&r, p);
  while( !atEnd(&r) ){
    sqlite_int64 docid = readDocid(&r);
    if( docid==0 ){
      skipPositionList(&r);
      continue;
    }
    printf("%s%lld", zSep, docid);
    zSep =  ",";
    if( p->iType>=DL_POSITIONS ){
      int iPos;
      const char *zDiv = "";
      printf("(");
      while( (iPos = readPosition(&r))>=0 ){
        printf("%s%d", zDiv, iPos);
        zDiv = ":";
      }
      printf(")");
    }
  }
  printf("\n");
  fflush(stdout);
}
#endif /* SQLITE_DEBUG */

/* Helper function for docListUpdate() and docListAccumulate().
** Splices a doclist element into the doclist represented by r,
** leaving r pointing after the newly spliced element.
*/
static void docListSpliceElement(DocListReader *r, sqlite_int64 iDocid,
                                 const char *pSource, int nSource){
  DocList *d = r->pDoclist;
................................................................................
    char *pSource = updateReader.p;
    sqlite_int64 iDocid = readDocid(&updateReader);
    skipPositionList(&updateReader);
    docListSpliceElement(&accReader, iDocid, pSource, updateReader.p-pSource);
  }
}

/*
** pLeft and pRight are two DocListReaders that are pointing to
** positions lists of the same document: iDocid. 
**
** If there are no instances in pLeft or pRight where the position
** of pLeft is iOffset less than the position of pRight, then this
** routine adds nothing to pOut.
**
** If there are one or more instances where positions from pLeft
** are exactly iOffset less than positions from pRight, then add a new
** document record to pOut and include the positions from pLeft.
**
** pLeft and pRight are left pointing at the next document.
*/
static void mergePosList(
  DocListReader *pLeft,    /* Left position list */
  DocListReader *pRight,   /* Right position list */
  sqlite_int64 iDocid,     /* The docid from pLeft and pRight */
  int iOffset,             /* Copy if pLeft.pos+iOffset==pRight.iPos */
  DocList *pOut            /* Write the merged document record here */
){
  int iLeftPos = readPosition(pLeft);
  int iRightPos = readPosition(pRight);
  int match = 0;

  /* Loop until we've reached the end of both position lists. */
  while( iLeftPos!=-1 && iRightPos!=-1 ){
    if( iLeftPos+iOffset==iRightPos ){
      if( !match ){
        docListAddDocid(pOut, iDocid);
        match = 1;
      }
      if( pOut->iType>=DL_POSITIONS ){
        docListAddPos(pOut, iLeftPos);
      }
      iLeftPos = readPosition(pLeft);
      iRightPos = readPosition(pRight);
    }else if( iRightPos<iLeftPos+iOffset ){
      iRightPos = readPosition(pRight);
    }else{
      iLeftPos = readPosition(pLeft);
    }
  }
  if( iLeftPos>=0 ) skipPositionList(pLeft);
  if( iRightPos>=0 ) skipPositionList(pRight);
}

/*
** Read the next non-deleted docid off of pIn.  Return
** 0 if we reach the end of pDoclist.
*/
static sqlite_int64 nextValidDocid(DocListReader *pIn){
  sqlite_int64 docid = 0;
  while( !atEnd(pIn) && (docid = readDocid(pIn))==0 ){
    skipPositionList(pIn);
  }
  return docid;
}

/* We have two doclists:  pLeft and pRight.
** Write the intersection of these two doclists into pOut.
**
** nLeftPhrase is the number of words of a phrase that have
** contributed to pLeft.
*/
static void mergeBlockAnd(
  DocList *pLeft,    /* Doclist resulting from the words on the left */
  DocList *pRight,   /* Doclist for the next word to the right */
  int nLeftPhrase,   /* Number of matching phrase terms in pLeft */
  DocList *pOut      /* Write the combined doclist here */
){
  DocListReader left, right;
  sqlite_int64 docidLeft, docidRight;

  readerInit(&left, pLeft);
  readerInit(&right, pRight);
  docidLeft = nextValidDocid(&left);
  docidRight = nextValidDocid(&right);

  while( docidLeft>0 && docidRight>0 ){
    if( docidLeft<docidRight ){
      skipPositionList(&left);
      docidLeft = nextValidDocid(&left);
    }else if( docidRight<docidLeft ){
      skipPositionList(&right);
      docidRight = nextValidDocid(&right);
    }else{
      /* Found a match */
      if( pLeft->iType>=DL_POSITIONS ){
        mergePosList(&left, &right, docidLeft, nLeftPhrase, pOut);
      }else{
        docListAddDocid(pOut, docidLeft);
        skipPositionList(&left);
        skipPositionList(&right);
      }
      docidLeft = nextValidDocid(&left);
      docidRight = nextValidDocid(&right);
    }
  }
}

/* We have two doclists:  pLeft and pRight.
** Write into pOut all documents that occur in pLeft but not
** in pRight.
**
** The output pOut never holds positions.
*/
static void mergeBlockExcept(
  DocList *pLeft,    /* Doclist resulting from the words on the left */
  DocList *pRight,   /* Doclist for the next word to the right */
  DocList *pOut      /* Write the combined doclist here */
){
  DocListReader left, right;
  sqlite_int64 docidLeft, docidRight, priorLeft;

  readerInit(&left, pLeft);
  readerInit(&right, pRight);
  docidLeft = nextValidDocid(&left);
  docidRight = nextValidDocid(&right);

  while( docidLeft>0 ){
    priorLeft = docidLeft;
    if( docidRight==0 || docidLeft<docidRight ){
      docListAddDocid(pOut, docidLeft);
    }
    if( docidRight==0 || docidLeft<=docidRight ){
      skipPositionList(&left);
      docidLeft = nextValidDocid(&left);
    }
    if( docidRight>0 && docidRight<=priorLeft ){
      skipPositionList(&right);
      docidRight = nextValidDocid(&right);
    }
  }
}

/* We have two doclists:  pLeft and pRight.
** Write the union of these two doclists into pOut.
**
** The output pOut never holds positions.
*/
static void mergeBlockOr(
  DocList *pLeft,    /* Doclist resulting from the words on the left */
  DocList *pRight,   /* Doclist for the next word to the right */
  DocList *pOut      /* Write the combined doclist here */
){
  DocListReader left, right;
  sqlite_int64 docidLeft, docidRight, priorLeft;

  readerInit(&left, pLeft);
  readerInit(&right, pRight);
  docidLeft = nextValidDocid(&left);
  docidRight = nextValidDocid(&right);

  while( docidLeft>0 && docidRight>0 ){
    if( docidLeft<=docidRight ){
      docListAddDocid(pOut, docidLeft);
    }else{
      docListAddDocid(pOut, docidRight);
    }
    priorLeft = docidLeft;
    if( docidLeft<=docidRight ){
      skipPositionList(&left);
      docidLeft = nextValidDocid(&left);
    }
    if( docidRight>0 && docidRight<=priorLeft ){
      skipPositionList(&right);
      docidRight = nextValidDocid(&right);
    }
  }
  while( docidLeft>0 ){
    docListAddDocid(pOut, docidLeft);
    skipPositionList(&left);
    docidLeft = nextValidDocid(&left);
  }
  while( docidRight>0 ){
    docListAddDocid(pOut, docidRight);
    skipPositionList(&right);
    docidRight = nextValidDocid(&right);
  }
}

/* Duplicate a string; the caller must free() the returned string.
 * (We don't use strdup() since it's not part of the standard C library and
 * may not be available everywhere.) */
static char *string_dup(const char *s){
................................................................................
      return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
    default:
      assert( 0 );
      return SQLITE_ERROR;  /* not reached */
  }
}

/*
** Different kinds of allowed document merge operations.
*/
#define MERGE_AND    1     /* Intersection of left and right */
#define MERGE_OR     2     /* Union of left and right */
#define MERGE_EXCEPT 3     /* Documents in left but not in right */

/* Read the posting list for [pTerm]; AND it with the doclist [pIn] to
 * produce the doclist [out], using the given phrase position [iPhrasePos].
 * (*pSelect) is used to hold an SQLite statement used inside this function;
 * the caller should initialize *pSelect to NULL before the first call.
 */
static int mergeQuery(
  fulltext_vtab *v,              /* The full text index virtual table */
  const char *pTerm, int nTerm,  /* Term we are searching for */
  DocList *pIn,                  /* Prior search results. NULL for first term */
  int iPhrasePos,                /* Offset to first term of phrase search */
  int eOp,                       /* MERGE_AND, MERGE_OR, or MERGE_EXCEPT */
  DocList *out                   /* Write results here */
){
  int rc;

  DocList doclist;

  /* If [pIn] is already empty, there's no point in reading the
   * posting list to AND it in; return immediately. */
  if( pIn!=NULL && eOp==MERGE_AND && !pIn->nData ) return SQLITE_OK;

  rc = term_select_all(v, pTerm, nTerm, &doclist);
  if( rc!=SQLITE_OK ) return rc;

  /* If there is no input and the output wants to contain position
  ** information, then make the result the doclist for pTerm.
  */
  if( pIn==0 && out->iType>=DL_POSITIONS ){
    docListDestroy(out);
    *out = doclist;
    return SQLITE_OK;
  }

  if( eOp==MERGE_AND && pIn!=0 ){
    mergeBlockAnd(pIn, &doclist, iPhrasePos, out);

  }else if( eOp==MERGE_OR || pIn==0 ){
    mergeBlockOr(pIn, &doclist, out);
  }else if( eOp==MERGE_EXCEPT ){
    mergeBlockExcept(pIn, &doclist, out);
  }
  docListDestroy(&doclist);

  return SQLITE_OK;
}

/* A single term in a query is represented by an instances of
** the following structure.
*/
typedef struct QueryTerm {
  int firstInPhrase; /* true if this term begins a new phrase */


  int isOr;          /* this term is preceded by "OR" */
  int isNot;         /* this term is preceded by "-" */
  char *pTerm;       /* text of the term.  '\000' terminated.  malloced */
  int nTerm;         /* Number of bytes in pTerm[] */
} QueryTerm;

/* A parsed query.
 *





 * We could, in theory, allow query strings to be complicated
 * nested expressions with precedence determined by parentheses.
 * But none of the major search engines do this.  (Perhaps the
 * feeling is that an parenthesized expression is two complex of
 * an idea for the average user to grasp.)  Taking our lead from
 * the major search engines, we will allow queries to be a list
 * of terms (with an implied AND operator) or phrases in double-quotes,
 * with a single optional "-" before each non-phrase term to designate
 * negation and an optional OR connector.
 *
 * OR binds more tightly than the implied AND, which is what the
 * major search engines seem to do.  So, for example:
 * 
 *    [one two OR three]     ==>    one AND (two OR three)
 *    [one OR two three]     ==>    (one OR two) AND three
 *
 * A "-" before a term matches all entries that lack that term.
 * The "-" must occur immediately before the term with in intervening
 * space.  This is how the search engines do it.
 *
 * A NOT term cannot be the right-hand operand of an OR.  If this
 * occurs in the query string, the NOT is ignored:
 *
 *    [one OR -two]          ==>    one OR two
 *
 */
typedef struct Query {

  int nTerms;           /* Number of terms in the query */
  QueryTerm *pTerms;    /* Array of terms.  Space obtained from malloc() */
} Query;

/* Add a new term pTerm[0..nTerm-1] to the query *q.  The new term is
** the beginning of a phrase is firstInPhrase is true.
*/
static void queryAdd(Query *q, int firstInPhrase, const char *pTerm, int nTerm){
  QueryTerm *t;
  ++q->nTerms;
  q->pTerms = realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0]));
  if( q->pTerms==0 ){
    q->nTerms = 0;
    return;
  }
  t = &q->pTerms[q->nTerms - 1];

  memset(t, 0, sizeof(*t));
  t->firstInPhrase = firstInPhrase;
  t->pTerm = malloc(nTerm+1);
  memcpy(t->pTerm, pTerm, nTerm);
  t->pTerm[nTerm] = 0;
  t->nTerm = nTerm;
}

/* Free all of the memory that was malloced in order to build *q.
*/
static void queryDestroy(Query *q){
  int i;
  for(i = 0; i < q->nTerms; ++i){
    free(q->pTerms[i].pTerm);
  }
  free(q->pTerms);
}

/*
** Parse the text at pSegment[0..nSegment-1].  Add additional terms
** to the query being assemblied in pQuery.
**
** inPhrase is true if pSegment[0..nSegement-1] is contained within
** double-quotes.  If inPhrase is true, then only the first term
** is marked with firstInPhrase and OR and "-" syntax is ignored.
** If inPhrase is false, then every term found is marked with
** firstInPhrase and OR and "-" syntax is significant.
*/
static int tokenizeSegment(sqlite3_tokenizer *pTokenizer,
                            const char *pSegment, int nSegment, int inPhrase,
                            Query *pQuery){
  const sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
  sqlite3_tokenizer_cursor *pCursor;
  int is_first = 1;
  int isOr = 0;
  
  int rc = pModule->xOpen(pTokenizer, pSegment, nSegment, &pCursor);
  if( rc!=SQLITE_OK ) return rc;
  pCursor->pTokenizer = pTokenizer;

  while( 1 ){
    const char *pToken;
    int nToken, iBegin, iEnd, iPos;

    rc = pModule->xNext(pCursor,
                        &pToken, &nToken,
                        &iBegin, &iEnd, &iPos);

    if( rc!=SQLITE_OK ) break;
    if( !inPhrase && pQuery->nTerms>0 && nToken==2
         && pSegment[iBegin]=='O' && pSegment[iBegin+1]=='R' ){
      isOr = 1;
      continue;
    }
    queryAdd(pQuery, !inPhrase || is_first, pToken, nToken);
    if( !inPhrase ){
      if( isOr ){
        pQuery->pTerms[pQuery->nTerms-1].isOr = 1;
      }else if( iBegin>0 && pSegment[iBegin-1]=='-' ){
        pQuery->pTerms[pQuery->nTerms-1].isNot = 1;
      }
    }
    is_first = 0;
    isOr = 0;
  }

  return pModule->xClose(pCursor);
}

/* Parse a query string, yielding a Query object [pQuery], which the caller
 * must free. */
................................................................................
  if(inPhrase) {  /* unmatched quote */
    queryDestroy(pQuery);
    return SQLITE_ERROR;
  }
  return SQLITE_OK;
}

/* Perform a full-text query using the search expression in
** pInput[0..nInput-1].  Return a list of matching documents
** in pResult.
*/
static int fulltextQuery(fulltext_vtab *v, const char *pInput, int nInput,
                          DocList **pResult){
  Query q;
  int phrase_start = -1;
  int i;
  DocList *d = NULL;

  int rc = parseQuery(v, pInput, nInput, &q);
  if( rc!=SQLITE_OK ) return rc;

  /* Merge AND terms. */
  for(i = 0 ; i < q.nTerms ; ++i){
    int needPositions;
    DocList *next;

    if( q.pTerms[i].isNot || q.pTerms[i].isOr ){
      /* Handle all OR and NOT terms in a separate pass */
      continue;
    }

    /* In each merge step, we need to generate positions whenever we're
     * processing a phrase which hasn't ended yet. */
    needPositions = i<q.nTerms-1 && !q.pTerms[i+1].firstInPhrase;
    next = docListNew(needPositions ? DL_POSITIONS : DL_DOCIDS);
    if( q.pTerms[i].firstInPhrase ){
      phrase_start = i;
    }
    rc = mergeQuery(v, q.pTerms[i].pTerm, q.pTerms[i].nTerm,
                     d, i-phrase_start, MERGE_AND, next);
    if( rc!=SQLITE_OK ) break;
    if( d!=NULL ){
      docListDelete(d);
    }
    d = next;
  }

  /* Do the OR terms */
  for(i=0; i<q.nTerms; i++){
    DocList *next;
    if( !q.pTerms[i].isOr ) continue;
    next = docListNew(DL_DOCIDS);
    rc = mergeQuery(v, q.pTerms[i].pTerm, q.pTerms[i].nTerm,
                    d, 0, MERGE_OR, next);
    if( d ){
      docListDelete(d);
    }
    d = next;
  }

  /* Do the EXCEPT terms */
  for(i=0; i<q.nTerms; i++){
    DocList *next;
    if( !q.pTerms[i].isNot ) continue;
    next = docListNew(DL_DOCIDS);
    rc = mergeQuery(v, q.pTerms[i].pTerm, q.pTerms[i].nTerm,
                    d, 0, MERGE_EXCEPT, next);
    if( d ){
      docListDelete(d);
    }
    d = next;
  }

  queryDestroy(&q);
  *pResult = d;
  return rc;
}

static int fulltextFilter(sqlite3_vtab_cursor *pCursor,