SQLite4
Check-in [dd018f834a]
Not logged in

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

Overview
Comment:Add support for prefix queries to fts5. Still no support for prefix indexes, just prefix queries using the regular term index.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: dd018f834ac0787f34ea26bd7c4e3628bc702506
User & Date: dan 2012-12-30 11:45:31
Context
2012-12-30
12:03
Add support for the "columnname : phrase" syntax to fts5. check-in: 069e299d06 user: dan tags: trunk
11:45
Add support for prefix queries to fts5. Still no support for prefix indexes, just prefix queries using the regular term index. check-in: dd018f834a user: dan tags: trunk
2012-12-29
15:16
Add fts5rnd1.test, a modified version of fts3rnd.test that works with fts5. check-in: 29d07b13f0 user: dan tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to src/callback.c.

420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
...
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
void sqlite4SchemaClear(sqlite4_env *pEnv, Schema *pSchema){
  Hash temp1;
  Hash temp2;
  HashElem *pElem;

  temp1 = pSchema->tblHash;
  temp2 = pSchema->trigHash;
  sqlite4HashInit(pEnv, &pSchema->trigHash);
  sqlite4HashClear(&pSchema->idxHash);
  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
    sqlite4DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  }
  sqlite4HashClear(&temp2);
  sqlite4HashInit(pEnv, &pSchema->tblHash);
  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
    Table *pTab = sqliteHashData(pElem);
    sqlite4DeleteTable(0, pTab);
  }
  sqlite4HashClear(&temp1);
  sqlite4HashClear(&pSchema->fkeyHash);
  pSchema->pSeqTab = 0;
................................................................................
*/
Schema *sqlite4SchemaGet(sqlite4 *db){
  Schema * p;
  p = (Schema *)sqlite4DbMallocZero(0, sizeof(Schema));
  if( !p ){
    db->mallocFailed = 1;
  }else if ( 0==p->file_format ){
    sqlite4HashInit(db->pEnv, &p->tblHash);
    sqlite4HashInit(db->pEnv, &p->idxHash);
    sqlite4HashInit(db->pEnv, &p->trigHash);
    sqlite4HashInit(db->pEnv, &p->fkeyHash);
    p->enc = SQLITE4_UTF8;
  }
  return p;
}







|





|







 







|
|
|
|




420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
...
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
void sqlite4SchemaClear(sqlite4_env *pEnv, Schema *pSchema){
  Hash temp1;
  Hash temp2;
  HashElem *pElem;

  temp1 = pSchema->tblHash;
  temp2 = pSchema->trigHash;
  sqlite4HashInit(pEnv, &pSchema->trigHash, 0);
  sqlite4HashClear(&pSchema->idxHash);
  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
    sqlite4DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  }
  sqlite4HashClear(&temp2);
  sqlite4HashInit(pEnv, &pSchema->tblHash, 0);
  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
    Table *pTab = sqliteHashData(pElem);
    sqlite4DeleteTable(0, pTab);
  }
  sqlite4HashClear(&temp1);
  sqlite4HashClear(&pSchema->fkeyHash);
  pSchema->pSeqTab = 0;
................................................................................
*/
Schema *sqlite4SchemaGet(sqlite4 *db){
  Schema * p;
  p = (Schema *)sqlite4DbMallocZero(0, sizeof(Schema));
  if( !p ){
    db->mallocFailed = 1;
  }else if ( 0==p->file_format ){
    sqlite4HashInit(db->pEnv, &p->tblHash, 0);
    sqlite4HashInit(db->pEnv, &p->idxHash, 0);
    sqlite4HashInit(db->pEnv, &p->trigHash, 0);
    sqlite4HashInit(db->pEnv, &p->fkeyHash, 0);
    p->enc = SQLITE4_UTF8;
  }
  return p;
}

Changes to src/fts5.c.

78
79
80
81
82
83
84



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
...
114
115
116
117
118
119
120














121
122
123
124
125
126
127
128
129
130
131


132
133
134
135
136
137
138
...
204
205
206
207
208
209
210



211
212
213
214
215
216
217
218
219
220
221
222
223
224
...
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
...
289
290
291
292
293
294
295





296
297
298
299
300
301
302
...
530
531
532
533
534
535
536















537
538
539
540
541
542
543
...
598
599
600
601
602
603
604




605
606
607
608
609
610
611
...
615
616
617
618
619
620
621




622
623
624
625
626
627
628
....
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
....
1484
1485
1486
1487
1488
1489
1490








































































































































































































































































































































1491
1492
1493
1494
1495
1496
1497
....
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510


1511
1512
1513
1514
1515
1516
1517
....
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
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
....
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
....
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798

1799

1800
1801
1802
1803
1804
1805
1806
....
2028
2029
2030
2031
2032
2033
2034
2035
2036



2037
2038
2039
2040
2041
2042
2043
**   expr := expr OR  expr
**   expr := LP expr RP
*/

/*
** Context object used by expression parser.
*/



typedef struct Fts5Parser Fts5Parser;
typedef struct Fts5ParserToken Fts5ParserToken;

typedef struct Fts5Token Fts5Token;
typedef struct Fts5Str Fts5Str;
typedef struct Fts5Phrase Fts5Phrase;
typedef struct Fts5ExprNode Fts5ExprNode;
typedef struct Fts5Expr Fts5Expr;


struct Fts5ParserToken {
  int eType;                      /* Token type */
  int n;                          /* Size of z[] in bytes */
  const char *z;                  /* Token value */
};
................................................................................
  int iRoot;                      /* Root page number of FTS index */

  /* Space for dequoted copies of strings */
  char *aSpace;
  int iSpace;
  int nSpace;                     /* Total size of aSpace in bytes */
};















struct Fts5Token {
  /* TODO: The first three members are redundant in some senses, since the
  ** same information is encoded in the aPrefix[]/nPrefix key. */
  int bPrefix;                    /* True for a prefix search */
  int n;                          /* Size of z[] in bytes */
  char *z;                        /* Token value */

  KVCursor *pCsr;                 /* Cursor to iterate thru entries for token */
  KVByteArray *aPrefix;           /* KV prefix to iterate through */
  KVSize nPrefix;                 /* Size of aPrefix in bytes */


};

struct Fts5Str {
  Fts5Token *aToken;
  int nToken;
  u8 *aList;
  int nList;
................................................................................
      p->iWeight = (iVal>>2);
    }
    else{
      p->iOff += (iVal>>1);
      bRet = 0;
    }
  }




  p->iList = i;
  return bRet;
}

static int fts5InstanceListEof(InstanceList *p){
  return (p->iList>=p->nList);
}

static void fts5InstanceListAppend(
  InstanceList *p,                /* Instance list to append to */
  int iCol,                       /* Column of new entry */
  int iWeight,                    /* Weight of new entry */
  int iOff                        /* Offset of new entry */
................................................................................
}

/*
** Return true if argument c is one of the special non-whitespace 
** characters that ends an unquoted expression token. 
*/
static int fts5IsSpecial(char c){
  return (c==':' || c=='(' || c==')' || c=='+' || c=='"');
}

static int fts5NextToken(
  Fts5Parser *pParse,             /* Parser context */
  Fts5ParserToken *p              /* OUT: Populate this object */
){
  const char *z = pParse->zExpr;
................................................................................
    p->eType = TOKEN_COLON;
  }

  else if( c=='+' ){
    pParse->iExpr++;
    p->eType = TOKEN_PLUS;
  }






  else if( c=='"' ){
    char *zOut = &pParse->aSpace[pParse->iSpace];
    const char *zPrimitive = zOut;
    int i = pParse->iExpr+1;

    while( z[i] ){
................................................................................
    }else{
      rc = fts5AppendTokens(pParse, pStr, zPrim, nPrim);
    }
  }

  return rc;
}
















static void fts5PhraseFree(sqlite4 *db, Fts5Phrase *p){
  if( p ){
    int i;
    for(i=0; i<p->nStr; i++){
      int iTok;
      for(iTok=0; iTok<p->aStr[i].nToken; iTok++){
................................................................................

    /* Add the first Fts5Str to the new phrase object. Populate it with the
    ** results of tokenizing t.z/t.n. */
    rc = fts5PhraseNewStr(pParse, pPhrase, 0);
    if( rc==SQLITE4_OK ){
      rc = fts5PhraseAppend(pParse, pPhrase, t.z, t.n);
    }





    /* Add any further primitives connected by "+" or NEAR operators. */
    while( rc==SQLITE4_OK && 
        (pParse->next.eType==TOKEN_PLUS || pParse->next.eType==TOKEN_NEAR)
    ){
      rc = fts5NextToken2(pParse, &t);
      if( rc==SQLITE4_OK ){
................................................................................
        }
        rc = fts5NextToken2(pParse, &t);
        if( rc!=SQLITE4_OK ) goto token_or_phrase_out;
        if( t.eType!=TOKEN_PRIMITIVE ){
          rc = SQLITE4_ERROR;
        }else{
          rc = fts5PhraseAppend(pParse, pPhrase, t.z, t.n);




        }
      }
    }
  }

 token_or_phrase_out:
  if( rc!=SQLITE4_OK ){
................................................................................
  int nPK;
  HashElem *pElem;

  pStore = db->aDb[pInfo->iDb].pKV;
  sCtx.rc = SQLITE4_OK;
  sCtx.db = db;
  sCtx.nMax = 0;
  sqlite4HashInit(db->pEnv, &sCtx.hash);

  pPK = (const u8 *)sqlite4_value_blob(pKey);
  nPK = sqlite4_value_bytes(pKey);
  
  nTnum = getVarint32(pPK, dummy);
  nPK -= nTnum;
  pPK += nTnum;
................................................................................
      );
    }
  }

  *piCksum = sCtx.cksum;
  return rc;
}









































































































































































































































































































































static int fts5OpenExprCursors(sqlite4 *db, Fts5Info *pInfo, Fts5ExprNode *p){
  int rc = SQLITE4_OK;
  if( p ){
    if( p->eType==TOKEN_PRIMITIVE ){
      KVStore *pStore = db->aDb[pInfo->iDb].pKV;
      Fts5Phrase *pPhrase = p->pPhrase;
................................................................................

      for(iStr=0; rc==SQLITE4_OK && iStr<pPhrase->nStr; iStr++){
        Fts5Str *pStr = &pPhrase->aStr[iStr];
        int i;
        for(i=0; rc==SQLITE4_OK && i<pStr->nToken; i++){
          Fts5Token *pToken = &pStr->aToken[i];
          rc = sqlite4KVStoreOpenCursor(pStore, &pToken->pCsr);
          if( rc==SQLITE4_OK ){
            rc = sqlite4KVCursorSeek(
                pToken->pCsr, pToken->aPrefix, pToken->nPrefix, 1
            );
            if( rc==SQLITE4_INEXACT ) rc = SQLITE4_OK;


          }
        }
      }
    }
    if( rc==SQLITE4_OK ) rc = fts5OpenExprCursors(db, pInfo, p->pLeft);
    if( rc==SQLITE4_OK ) rc = fts5OpenExprCursors(db, pInfo, p->pRight);
  }
................................................................................
  if( pCsr ){
    fts5ExpressionFree(db, pCsr->pExpr);
    sqlite4DbFree(db, pCsr->aKey);
    sqlite4DbFree(db, pCsr);
  }
}

/*
** Obtain the primary key value from the entry cursor pToken->pCsr currently
** points to. Set *paPk to point to a buffer containing the PK, and *pnPk
** to the size of the buffer in bytes before returning.
**
** Return SQLITE4_OK if everything goes according to plan, or an error code
** if an error occurs. If an error occurs the final values of *paPk and *pnPk
** are undefined.
*/
static int fts5TokenPk(Fts5Token *p, const u8 **paPk, int *pnPk){
  int rc;
  const u8 *aKey;
  int nKey;

  rc = sqlite4KVCursorKey(p->pCsr, &aKey, &nKey);
  if( rc==SQLITE4_OK ){
    if( nKey<p->nPrefix || memcmp(p->aPrefix, aKey, p->nPrefix) ){
      rc = SQLITE4_NOTFOUND;
    }else{
      *paPk = &aKey[p->nPrefix];
      *pnPk = nKey - p->nPrefix;
    }
  }

  return rc;
}

/*
** Compare keys (aLeft/nLeft) and (aRight/nRight) using the ordinary memcmp()
** method. Except, if either aLeft or aRight are NULL, consider them larger
** than all other values.
*/
static int fts5KeyCompare(
  const u8 *aLeft, int nLeft, 
  const u8 *aRight, int nRight
){
  int res;
  int nMin;

  res = (aLeft==0) - (aRight==0);
  if( res==0 ){
    nMin = (nLeft > nRight) ? nRight : nLeft;
    res = memcmp(aLeft, aRight, nMin);
  }
  return (res ? res : (nLeft-nRight));
}

static int fts5TokenAdvanceToMatch(
  InstanceList *p,
  InstanceList *pFirst,
  int iOff,
  int *pbEof
){
  int iReq = pFirst->iOff + iOff;
................................................................................
  memset(&out, 0, sizeof(InstanceList));

  aIn = (InstanceList *)sqlite4DbMallocZero(pCsr->db, nByte);
  if( !aIn ) rc = SQLITE4_NOMEM;
  for(i=0; rc==SQLITE4_OK && i<pStr->nToken; i++){
    const u8 *aData;
    int nData;
    rc = sqlite4KVCursorData(pStr->aToken[i].pCsr, 0, -1, &aData, &nData);
    if( rc==SQLITE4_OK ){
      fts5InstanceListInit((u8 *)aData, nData, &aIn[i]);
      fts5InstanceListNext(&aIn[i]);
    }
  }

  /* Allocate the output list */
................................................................................
static int fts5PhraseAdvanceToMatch(Fts5Cursor *pCsr, Fts5Phrase *pPhrase){
  int rc;
  do {
    int bMatch;
    Fts5Token *pAdvance = 0;
    rc = fts5PhraseIsMatch(pCsr, pPhrase, &bMatch, &pAdvance);
    if( rc!=SQLITE4_OK || bMatch ) break;
    rc = sqlite4KVCursorNext(pAdvance->pCsr);
  }while( rc==SQLITE4_OK );
  return rc;
}

static int fts5ExprAdvance(Fts5Cursor *pCsr, Fts5ExprNode *p, int bFirst){
  int rc = SQLITE4_OK;

  switch( p->eType ){
    case TOKEN_PRIMITIVE: {
      Fts5Phrase *pPhrase = p->pPhrase;

      if( bFirst==0 ) rc = sqlite4KVCursorNext(pPhrase->aStr[0].aToken[0].pCsr);

      if( rc==SQLITE4_OK ) rc = fts5PhraseAdvanceToMatch(pCsr, pPhrase);
      if( rc==SQLITE4_OK ){
        rc = fts5TokenPk(&pPhrase->aStr[0].aToken[0], &p->aPk, &p->nPk);
      }else{
        p->aPk = 0;
        p->nPk = 0;
        if( rc==SQLITE4_NOTFOUND ) rc = SQLITE4_OK;
................................................................................
        if( iToken>0 ) zRet[nRet++] = '+';
        zRet[nRet++] = '"';

        for(i=0; i<n; i++){
          if( z[i]=='"' ) zRet[nRet++] = '"';
          zRet[nRet++] = z[i];
        }

        zRet[nRet++] = '"';



        zRet[nRet++] = '\0';
      }
    }
  }else{
    fts5PrintExprNodeParen(db, azCol, pNode->pLeft, &zRet);
    switch( pNode->eType ){
      case TOKEN_AND:







>
>
>


<
|
|
|
<
|







 







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








<


>
>







 







>
>
>






|







 







|







 







>
>
>
>
>







 







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







 







>
>
>
>







 







>
>
>
>







 







|







 







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







 







<
|
|
|
|
>
>







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







|







 







|










>
|
>







 







<

>
>
>







78
79
80
81
82
83
84
85
86
87
88
89

90
91
92

93
94
95
96
97
98
99
100
...
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143

144
145
146
147
148
149
150
151
152
153
154
...
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
...
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
...
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
...
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
...
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
...
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
....
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
....
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
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
....
1874
1875
1876
1877
1878
1879
1880

1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
....
1906
1907
1908
1909
1910
1911
1912















































1913
1914
1915
1916
1917
1918
1919
....
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
....
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
....
2359
2360
2361
2362
2363
2364
2365

2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
**   expr := expr OR  expr
**   expr := LP expr RP
*/

/*
** Context object used by expression parser.
*/
typedef struct Fts5Expr Fts5Expr;
typedef struct Fts5ExprNode Fts5ExprNode;
typedef struct Fts5List Fts5List;
typedef struct Fts5Parser Fts5Parser;
typedef struct Fts5ParserToken Fts5ParserToken;

typedef struct Fts5Phrase Fts5Phrase;
typedef struct Fts5Prefix Fts5Prefix;
typedef struct Fts5Str Fts5Str;

typedef struct Fts5Token Fts5Token;


struct Fts5ParserToken {
  int eType;                      /* Token type */
  int n;                          /* Size of z[] in bytes */
  const char *z;                  /* Token value */
};
................................................................................
  int iRoot;                      /* Root page number of FTS index */

  /* Space for dequoted copies of strings */
  char *aSpace;
  int iSpace;
  int nSpace;                     /* Total size of aSpace in bytes */
};

struct Fts5List {
  u8 *aData;
  int nData;
};

struct Fts5Prefix {
  u8 *aPk;                        /* Buffer containing PK */
  int nPk;                        /* Size of PK in bytes */
  Fts5Prefix *pNext;              /* Next entry in query-time list */
  u8 *aList;
  int nList;
  int nAlloc;
};

struct Fts5Token {
  /* TODO: The first three members are redundant in some senses, since the
  ** same information is encoded in the aPrefix[]/nPrefix key. */
  int bPrefix;                    /* True for a prefix search */
  int n;                          /* Size of z[] in bytes */
  char *z;                        /* Token value */


  KVByteArray *aPrefix;           /* KV prefix to iterate through */
  KVSize nPrefix;                 /* Size of aPrefix in bytes */
  KVCursor *pCsr;                 /* Cursor to iterate thru entries for token */
  Fts5Prefix *pPrefix;            /* Head of prefix list */
};

struct Fts5Str {
  Fts5Token *aToken;
  int nToken;
  u8 *aList;
  int nList;
................................................................................
      p->iWeight = (iVal>>2);
    }
    else{
      p->iOff += (iVal>>1);
      bRet = 0;
    }
  }
  if( bRet ){
    p->aList = 0;
  }

  p->iList = i;
  return bRet;
}

static int fts5InstanceListEof(InstanceList *p){
  return (p->aList==0);
}

static void fts5InstanceListAppend(
  InstanceList *p,                /* Instance list to append to */
  int iCol,                       /* Column of new entry */
  int iWeight,                    /* Weight of new entry */
  int iOff                        /* Offset of new entry */
................................................................................
}

/*
** Return true if argument c is one of the special non-whitespace 
** characters that ends an unquoted expression token. 
*/
static int fts5IsSpecial(char c){
  return (c==':' || c=='(' || c==')' || c=='+' || c=='"' || c=='*');
}

static int fts5NextToken(
  Fts5Parser *pParse,             /* Parser context */
  Fts5ParserToken *p              /* OUT: Populate this object */
){
  const char *z = pParse->zExpr;
................................................................................
    p->eType = TOKEN_COLON;
  }

  else if( c=='+' ){
    pParse->iExpr++;
    p->eType = TOKEN_PLUS;
  }

  else if( c=='*' ){
    pParse->iExpr++;
    p->eType = TOKEN_STAR;
  }

  else if( c=='"' ){
    char *zOut = &pParse->aSpace[pParse->iSpace];
    const char *zPrimitive = zOut;
    int i = pParse->iExpr+1;

    while( z[i] ){
................................................................................
    }else{
      rc = fts5AppendTokens(pParse, pStr, zPrim, nPrim);
    }
  }

  return rc;
}

static int fts5PhraseAppendStar(
  Fts5Parser *pParse,
  Fts5Phrase *pPhrase
){
  Fts5Str *pStr = &pPhrase->aStr[pPhrase->nStr-1];
  Fts5Token *p = &pStr->aToken[pStr->nToken-1];

  if( p->bPrefix ){
    return SQLITE4_ERROR;
  }
  p->bPrefix = 1;
  p->nPrefix--;
  return SQLITE4_OK;
}

static void fts5PhraseFree(sqlite4 *db, Fts5Phrase *p){
  if( p ){
    int i;
    for(i=0; i<p->nStr; i++){
      int iTok;
      for(iTok=0; iTok<p->aStr[i].nToken; iTok++){
................................................................................

    /* Add the first Fts5Str to the new phrase object. Populate it with the
    ** results of tokenizing t.z/t.n. */
    rc = fts5PhraseNewStr(pParse, pPhrase, 0);
    if( rc==SQLITE4_OK ){
      rc = fts5PhraseAppend(pParse, pPhrase, t.z, t.n);
    }
    if( rc==SQLITE4_OK && pParse->next.eType==TOKEN_STAR ){
      fts5NextToken2(pParse, &t);
      rc = fts5PhraseAppendStar(pParse, pPhrase);
    }

    /* Add any further primitives connected by "+" or NEAR operators. */
    while( rc==SQLITE4_OK && 
        (pParse->next.eType==TOKEN_PLUS || pParse->next.eType==TOKEN_NEAR)
    ){
      rc = fts5NextToken2(pParse, &t);
      if( rc==SQLITE4_OK ){
................................................................................
        }
        rc = fts5NextToken2(pParse, &t);
        if( rc!=SQLITE4_OK ) goto token_or_phrase_out;
        if( t.eType!=TOKEN_PRIMITIVE ){
          rc = SQLITE4_ERROR;
        }else{
          rc = fts5PhraseAppend(pParse, pPhrase, t.z, t.n);
          if( rc==SQLITE4_OK && pParse->next.eType==TOKEN_STAR ){
            fts5NextToken2(pParse, &t);
            rc = fts5PhraseAppendStar(pParse, pPhrase);
          }
        }
      }
    }
  }

 token_or_phrase_out:
  if( rc!=SQLITE4_OK ){
................................................................................
  int nPK;
  HashElem *pElem;

  pStore = db->aDb[pInfo->iDb].pKV;
  sCtx.rc = SQLITE4_OK;
  sCtx.db = db;
  sCtx.nMax = 0;
  sqlite4HashInit(db->pEnv, &sCtx.hash, 1);

  pPK = (const u8 *)sqlite4_value_blob(pKey);
  nPK = sqlite4_value_bytes(pKey);
  
  nTnum = getVarint32(pPK, dummy);
  nPK -= nTnum;
  pPK += nTnum;
................................................................................
      );
    }
  }

  *piCksum = sCtx.cksum;
  return rc;
}

/*
** Obtain the primary key value from the entry cursor pToken->pCsr currently
** points to. Set *paPk to point to a buffer containing the PK, and *pnPk
** to the size of the buffer in bytes before returning.
**
** Return SQLITE4_OK if everything goes according to plan, or an error code
** if an error occurs. If an error occurs the final values of *paPk and *pnPk
** are undefined.
*/
static int fts5TokenPk(Fts5Token *p, const u8 **paPk, int *pnPk){
  int rc;

  if( p->pCsr ){
    const u8 *aKey;
    int nKey;

    rc = sqlite4KVCursorKey(p->pCsr, &aKey, &nKey);
    if( rc==SQLITE4_OK ){
      if( nKey<p->nPrefix || memcmp(p->aPrefix, aKey, p->nPrefix) ){
        rc = SQLITE4_NOTFOUND;
      }else if( p->bPrefix==0 ){
        *paPk = &aKey[p->nPrefix];
        *pnPk = nKey - p->nPrefix;
      }else{
        const u8 *z = &aKey[p->nPrefix];
        while( *(z++)!='\0' );
        *paPk = z;
        *pnPk = nKey - (z-aKey);
      }
    }
  }else{
    if( p->pPrefix ){
      *paPk = p->pPrefix->aPk;
      *pnPk = p->pPrefix->nPk;
      rc = SQLITE4_OK;
    }else{
      rc = SQLITE4_NOTFOUND;
    }
  }

  return rc;
}

static int fts5TokenAdvance(sqlite4 *db, Fts5Token *pToken){
  int rc;
  if( pToken->pCsr ){
    rc = sqlite4KVCursorNext(pToken->pCsr);
  }else if( pToken->pPrefix ){
    Fts5Prefix *pDel = pToken->pPrefix;
    pToken->pPrefix = pDel->pNext;
    sqlite4DbFree(db, pDel->aList);
    sqlite4DbFree(db, pDel);
    rc = SQLITE4_OK;
  }else{
    rc = SQLITE4_NOTFOUND;
  }
  return rc;
}

static int fts5TokenData(Fts5Token *pToken, const u8 **paData, int *pnData){
  int rc;
  if( pToken->pCsr ){
    rc = sqlite4KVCursorData(pToken->pCsr, 0, -1, paData, pnData);
  }else if( pToken->pPrefix ){
    *paData = pToken->pPrefix->aList;
    *pnData = pToken->pPrefix->nList;
    rc = SQLITE4_OK;
  }else{
    rc = SQLITE4_NOTFOUND;
  }

  return rc;
}

/*
** Compare keys (aLeft/nLeft) and (aRight/nRight) using the ordinary memcmp()
** method. Except, if either aLeft or aRight are NULL, consider them larger
** than all other values.
*/
static int fts5KeyCompare(
  const u8 *aLeft, int nLeft, 
  const u8 *aRight, int nRight
){
  int res;
  int nMin;

  res = (aLeft==0) - (aRight==0);
  if( res==0 ){
    nMin = (nLeft > nRight) ? nRight : nLeft;
    res = memcmp(aLeft, aRight, nMin);
  }
  return (res ? res : (nLeft-nRight));
}

static int fts5ListMerge(sqlite4 *db, Fts5List *p1, Fts5List *p2, int bFree){
  InstanceList in1;
  InstanceList in2;
  InstanceList out;

  memset(&out, 0, sizeof(InstanceList));
  if( p1->nData==0 && p2->nData==0 ) return SQLITE4_OK;
  out.nList = p1->nData+p2->nData;
  out.aList = sqlite4DbMallocRaw(db, out.nList);
  if( !out.aList ) return SQLITE4_NOMEM;
  fts5InstanceListInit(p1->aData, p1->nData, &in1);
  fts5InstanceListInit(p2->aData, p2->nData, &in2);

  fts5InstanceListNext(&in1);
  fts5InstanceListNext(&in2);

  while( fts5InstanceListEof(&in1)==0 || fts5InstanceListEof(&in2)==0 ){
    InstanceList *pAdv;

    if( fts5InstanceListEof(&in1) ){
      pAdv = &in2;
    }else if( fts5InstanceListEof(&in2) ){
      pAdv = &in1;
    }else if( in1.iCol==in2.iCol && in1.iOff==in2.iOff ){
      pAdv = &in1;
      fts5InstanceListNext(&in2);
    }else if( in1.iCol<in2.iCol || (in1.iCol==in2.iCol && in1.iOff<in2.iOff) ){
      pAdv = &in1;
    }else{
      pAdv = &in2;
    }

    fts5InstanceListAppend(&out, pAdv->iCol, pAdv->iWeight, pAdv->iOff);
    fts5InstanceListNext(pAdv);
  }

  if( bFree ){
    sqlite4DbFree(db, p1->aData);
    sqlite4DbFree(db, p2->aData);
  }
  memset(p2, 0, sizeof(Fts5List));
  p1->aData = out.aList;
  p1->nData = out.iList;
  return SQLITE4_OK;
}

static void fts5PrefixMerge(Fts5Prefix **pp, Fts5Prefix *p2){
  Fts5Prefix *p1 = *pp;
  Fts5Prefix *pRet = 0;
  Fts5Prefix **ppWrite = &pRet;

  while( p1 || p2 ){
    Fts5Prefix **ppAdv = 0;
    if( p1==0 ){
      ppAdv = &p2;
    }else if( p2==0 ){
      ppAdv = &p1;
    }else{
      int res = fts5KeyCompare(p1->aPk, p1->nPk, p2->aPk, p2->nPk);
      assert( res!=0 );
      if( res<0 ){
        ppAdv = &p1;
      }else{
        ppAdv = &p2;
      }
    }

    *ppWrite = *ppAdv;
    ppWrite = &((*ppWrite)->pNext);
    *ppAdv = (*ppAdv)->pNext;
    *ppWrite = 0;
  }

  *pp = pRet;
}

static int fts5FindPrefixes(sqlite4 *db, Fts5Info *pInfo, Fts5Token *pToken){
  int rc = SQLITE4_OK;
  HashElem *pElem;
  Hash hash;

  assert( pToken->bPrefix );
  assert( pToken->aPrefix[pToken->nPrefix-1]!='\0' );
  sqlite4HashInit(db->pEnv, &hash, 1);

  do {
    const u8 *aData;
    int nData;
    const u8 *aPk;
    int nPk;

    rc = fts5TokenPk(pToken, &aPk, &nPk);
    if( rc==SQLITE4_OK ){
      rc = fts5TokenData(pToken, &aData, &nData);
    }
    if( rc==SQLITE4_OK ){
      Fts5Prefix *p;

      p = (Fts5Prefix *)sqlite4HashFind(&hash, (const char *)aPk, nPk);
      if( !p ){
        p = (Fts5Prefix *)sqlite4DbMallocZero(db, sizeof(Fts5Prefix) + nPk);
        if( !p ){
          rc = SQLITE4_NOMEM;
        }else{
          void *pFree;
          p->aPk = (u8 *)&p[1];
          p->nPk = nPk;
          memcpy(p->aPk, aPk, nPk);
          pFree = sqlite4HashInsert(&hash, (const char *)p->aPk, p->nPk, p);
          if( pFree ){
            assert( pFree==(void *)p );
            rc = SQLITE4_NOMEM;
            sqlite4DbFree(db, pFree);
          }
        }
      }

      if( rc==SQLITE4_OK ){
        int nReq = nData + sqlite4VarintLen(nData);
        while( (p->nList + nReq) > p->nAlloc ){
          int nAlloc = (p->nAlloc ? p->nAlloc*2 : 64);
          p->aList = sqlite4DbReallocOrFree(db, p->aList, nAlloc);
          if( !p->aList ){
            rc = SQLITE4_NOMEM;
            break;
          }
          p->nAlloc = nAlloc;
        }
      }

      if( rc==SQLITE4_OK ){
        p->nList += putVarint32(&p->aList[p->nList], nData);
        memcpy(&p->aList[p->nList], aData, nData);
        p->nList += nData;
      }
      
      if( rc==SQLITE4_OK ){
        rc = fts5TokenAdvance(db, pToken);
      }
    }
  }while( rc==SQLITE4_OK );
  if( rc==SQLITE4_NOTFOUND ) rc = SQLITE4_OK;

  if( rc==SQLITE4_OK ){
    Fts5List *aMerge;
    aMerge = (Fts5List *)sqlite4DbMallocZero(db, sizeof(Fts5List) * 32);
    if( !aMerge ) rc = SQLITE4_NOMEM;

    for(pElem=sqliteHashFirst(&hash); pElem; pElem=sqliteHashNext(pElem)){
      Fts5Prefix *p = (Fts5Prefix *)sqliteHashData(pElem);
      Fts5List list = {0, 0};
      int i = 0;
      int iLevel;

      memset(aMerge, 0, sizeof(Fts5List)*32);
      while( i<p->nList && rc==SQLITE4_OK ){
        u32 n;
        i += getVarint32(&p->aList[i], n);
        list.aData = &p->aList[i];
        list.nData = n;
        i += n;

        for(iLevel=0; rc==SQLITE4_OK && iLevel<32; iLevel++){
          if( aMerge[iLevel].aData==0 ){
            aMerge[iLevel] = list;
            break;
          }else{
            rc = fts5ListMerge(db, &list, &aMerge[iLevel], (iLevel>0));
          }
        }
        assert( iLevel<32 );
      }

      list.aData = 0;
      list.nData = 0;
      for(iLevel=0; rc==SQLITE4_OK && iLevel<32; iLevel++){
        rc = fts5ListMerge(db, &list, &aMerge[iLevel], (iLevel>0));
      }

      if( rc==SQLITE4_OK ){
        sqlite4DbFree(db, p->aList);
        p->aList = list.aData;
        p->nAlloc = p->nList = list.nData;
      }else{
        sqlite4DbFree(db, list.aData);
      }
    }

    sqlite4DbFree(db, aMerge);
  }

  if( rc==SQLITE4_OK ){
    Fts5Prefix **aMerge;
    Fts5Prefix *pPrefix = 0;

    aMerge = (Fts5Prefix **)sqlite4DbMallocZero(db, sizeof(Fts5List) * 32);
    if( !aMerge ){
      rc = SQLITE4_NOMEM;
    }else{
      int iLevel;
      for(pElem=sqliteHashFirst(&hash); pElem; pElem=sqliteHashNext(pElem)){
        pPrefix = (Fts5Prefix *)sqliteHashData(pElem);
        for(iLevel=0; iLevel<32; iLevel++){
          if( aMerge[iLevel] ){
            fts5PrefixMerge(&pPrefix, aMerge[iLevel]);
            aMerge[iLevel] = 0;
          }else{
            aMerge[iLevel] = pPrefix;
            break;
          }
        }
        assert( iLevel<32 );
      }
      pPrefix = 0;
      for(iLevel=0; iLevel<32; iLevel++){
        fts5PrefixMerge(&pPrefix, aMerge[iLevel]);
      }
      sqlite4HashClear(&hash);
      sqlite4DbFree(db, aMerge);
    }
    pToken->pPrefix = pPrefix;
  }

  for(pElem=sqliteHashFirst(&hash); pElem; pElem=sqliteHashNext(pElem)){
    Fts5Prefix *pPrefix = (Fts5Prefix *)sqliteHashData(pElem);
    sqlite4DbFree(db, pPrefix->aList);
    sqlite4DbFree(db, pPrefix);
  }
  sqlite4KVCursorClose(pToken->pCsr);
  pToken->pCsr = 0;

  return rc;
}

static int fts5OpenExprCursors(sqlite4 *db, Fts5Info *pInfo, Fts5ExprNode *p){
  int rc = SQLITE4_OK;
  if( p ){
    if( p->eType==TOKEN_PRIMITIVE ){
      KVStore *pStore = db->aDb[pInfo->iDb].pKV;
      Fts5Phrase *pPhrase = p->pPhrase;
................................................................................

      for(iStr=0; rc==SQLITE4_OK && iStr<pPhrase->nStr; iStr++){
        Fts5Str *pStr = &pPhrase->aStr[iStr];
        int i;
        for(i=0; rc==SQLITE4_OK && i<pStr->nToken; i++){
          Fts5Token *pToken = &pStr->aToken[i];
          rc = sqlite4KVStoreOpenCursor(pStore, &pToken->pCsr);

          rc = sqlite4KVCursorSeek(
              pToken->pCsr, pToken->aPrefix, pToken->nPrefix, 1
          );
          if( rc==SQLITE4_INEXACT ) rc = SQLITE4_OK;
          if( rc==SQLITE4_OK && pToken->bPrefix ){
            rc = fts5FindPrefixes(db, pInfo, pToken);
          }
        }
      }
    }
    if( rc==SQLITE4_OK ) rc = fts5OpenExprCursors(db, pInfo, p->pLeft);
    if( rc==SQLITE4_OK ) rc = fts5OpenExprCursors(db, pInfo, p->pRight);
  }
................................................................................
  if( pCsr ){
    fts5ExpressionFree(db, pCsr->pExpr);
    sqlite4DbFree(db, pCsr->aKey);
    sqlite4DbFree(db, pCsr);
  }
}
















































static int fts5TokenAdvanceToMatch(
  InstanceList *p,
  InstanceList *pFirst,
  int iOff,
  int *pbEof
){
  int iReq = pFirst->iOff + iOff;
................................................................................
  memset(&out, 0, sizeof(InstanceList));

  aIn = (InstanceList *)sqlite4DbMallocZero(pCsr->db, nByte);
  if( !aIn ) rc = SQLITE4_NOMEM;
  for(i=0; rc==SQLITE4_OK && i<pStr->nToken; i++){
    const u8 *aData;
    int nData;
    rc = fts5TokenData(&pStr->aToken[i], &aData, &nData);
    if( rc==SQLITE4_OK ){
      fts5InstanceListInit((u8 *)aData, nData, &aIn[i]);
      fts5InstanceListNext(&aIn[i]);
    }
  }

  /* Allocate the output list */
................................................................................
static int fts5PhraseAdvanceToMatch(Fts5Cursor *pCsr, Fts5Phrase *pPhrase){
  int rc;
  do {
    int bMatch;
    Fts5Token *pAdvance = 0;
    rc = fts5PhraseIsMatch(pCsr, pPhrase, &bMatch, &pAdvance);
    if( rc!=SQLITE4_OK || bMatch ) break;
    rc = fts5TokenAdvance(pCsr->db, pAdvance);
  }while( rc==SQLITE4_OK );
  return rc;
}

static int fts5ExprAdvance(Fts5Cursor *pCsr, Fts5ExprNode *p, int bFirst){
  int rc = SQLITE4_OK;

  switch( p->eType ){
    case TOKEN_PRIMITIVE: {
      Fts5Phrase *pPhrase = p->pPhrase;
      if( bFirst==0 ){
        rc = fts5TokenAdvance(pCsr->db, &pPhrase->aStr[0].aToken[0]);
      }
      if( rc==SQLITE4_OK ) rc = fts5PhraseAdvanceToMatch(pCsr, pPhrase);
      if( rc==SQLITE4_OK ){
        rc = fts5TokenPk(&pPhrase->aStr[0].aToken[0], &p->aPk, &p->nPk);
      }else{
        p->aPk = 0;
        p->nPk = 0;
        if( rc==SQLITE4_NOTFOUND ) rc = SQLITE4_OK;
................................................................................
        if( iToken>0 ) zRet[nRet++] = '+';
        zRet[nRet++] = '"';

        for(i=0; i<n; i++){
          if( z[i]=='"' ) zRet[nRet++] = '"';
          zRet[nRet++] = z[i];
        }

        zRet[nRet++] = '"';
        if( pStr->aToken[iToken].bPrefix ){
          zRet[nRet++] = '*';
        }
        zRet[nRet++] = '\0';
      }
    }
  }else{
    fts5PrintExprNodeParen(db, azCol, pNode->pLeft, &zRet);
    switch( pNode->eType ){
      case TOKEN_AND:

Changes to src/hash.c.

10
11
12
13
14
15
16































17
18
19
20
21
22
23
24
25
26
27
28
29







30
31
32
33
34
35
36
..
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
...
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
...
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
...
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
...
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
...
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
**
*************************************************************************
** This is the implementation of generic hash-tables
** used in SQLite.
*/
#include "sqliteInt.h"
#include <assert.h>
































/* Turn bulk memory into a hash table object by initializing the
** fields of the Hash structure.
**
** "pNew" is a pointer to the hash table that is to be initialized.
*/
void sqlite4HashInit(sqlite4_env *pEnv, Hash *pNew){
  assert( pNew!=0 );
  pNew->first = 0;
  pNew->count = 0;
  pNew->htsize = 0;
  pNew->ht = 0;
  pNew->pEnv = pEnv;







}

/* Remove all entries from a hash table.  Reclaim all memory.
** Call this routine to delete a hash table or to reset a hash table
** to the empty state.
*/
void sqlite4HashClear(Hash *pH){
................................................................................
  while( elem ){
    HashElem *next_elem = elem->next;
    sqlite4_free(pH->pEnv, elem);
    elem = next_elem;
  }
  pH->count = 0;
}

/*
** The hashing function.
*/
static unsigned int strHash(const char *z, int nKey){
  int h = 0;
  assert( nKey>=0 );
  while( nKey > 0  ){
    h = (h<<3) ^ h ^ sqlite4UpperToLower[(unsigned char)*z++];
    nKey--;
  }
  return h;
}


/* Link pNew element into the hash table pH.  If pEntry!=0 then also
** insert pNew into the pEntry hash bucket.
*/
static void insertElement(
  Hash *pH,              /* The complete hash table */
  struct _ht *pEntry,    /* The entry into which pNew is inserted */
................................................................................

  if( new_ht==0 ) return 0;
  sqlite4_free(pH->pEnv, pH->ht);
  pH->ht = new_ht;
  pH->htsize = new_size = sqlite4MallocSize(pH->pEnv, new_ht)/sizeof(struct _ht);
  memset(new_ht, 0, new_size*sizeof(struct _ht));
  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
    next_elem = elem->next;
    insertElement(pH, &new_ht[h], elem);
  }
  return 1;
}

/* This function (for internal use only) locates an element in an
................................................................................
    elem = pEntry->chain;
    count = pEntry->count;
  }else{
    elem = pH->first;
    count = pH->count;
  }
  while( count-- && ALWAYS(elem) ){
    if( elem->nKey==nKey && sqlite4StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
      return elem;
    }
    elem = elem->next;
  }
  return 0;
}

................................................................................
  HashElem *elem;    /* The element that matches key */
  unsigned int h;    /* A hash on key */

  assert( pH!=0 );
  assert( pKey!=0 );
  assert( nKey>=0 );
  if( pH->ht ){
    h = strHash(pKey, nKey) % pH->htsize;
  }else{
    h = 0;
  }
  elem = findElementGivenHash(pH, pKey, nKey, h);
  return elem ? elem->data : 0;
}

................................................................................
  HashElem *elem;       /* Used to loop thru the element list */
  HashElem *new_elem;   /* New element added to the pH */

  assert( pH!=0 );
  assert( pKey!=0 );
  assert( nKey>=0 );
  if( pH->htsize ){
    h = strHash(pKey, nKey) % pH->htsize;
  }else{
    h = 0;
  }
  elem = findElementGivenHash(pH,pKey,nKey,h);
  if( elem ){
    void *old_data = elem->data;
    if( data==0 ){
................................................................................
  new_elem->pKey = pKey;
  new_elem->nKey = nKey;
  new_elem->data = data;
  pH->count++;
  if( pH->count>=10 && pH->count > 2*pH->htsize ){
    if( rehash(pH, pH->count*2) ){
      assert( pH->htsize>0 );
      h = strHash(pKey, nKey) % pH->htsize;
    }
  }
  if( pH->ht ){
    insertElement(pH, &pH->ht[h], new_elem);
  }else{
    insertElement(pH, 0, new_elem);
  }
  return 0;
}







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






|






>
>
>
>
>
>
>







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







|







 







|







 







|







 







|







 







|









10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
..
83
84
85
86
87
88
89














90
91
92
93
94
95
96
...
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
...
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
...
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
...
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
...
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
**
*************************************************************************
** This is the implementation of generic hash-tables
** used in SQLite.
*/
#include "sqliteInt.h"
#include <assert.h>

/*
** The hashing function.
*/
static unsigned int strHash(const char *z, int nKey){
  int h = 0;
  assert( nKey>=0 );
  while( nKey > 0  ){
    h = (h<<3) ^ h ^ sqlite4UpperToLower[(unsigned char)*z++];
    nKey--;
  }
  return h;
}

static int strCmp(const char *z1, const char *z2, int n){
  return sqlite4StrNICmp(z1, z2, n);
}

static unsigned int binHash(const char *z, int nKey){
  int h = 0;
  assert( nKey>=0 );
  while( nKey > 0  ){
    h = (h<<3) ^ h ^ ((unsigned char)*z++);
    nKey--;
  }
  return h;
}

static int binCmp(const char *z1, const char *z2, int n){
  return memcmp(z1, z2, n);
}

/* Turn bulk memory into a hash table object by initializing the
** fields of the Hash structure.
**
** "pNew" is a pointer to the hash table that is to be initialized.
*/
void sqlite4HashInit(sqlite4_env *pEnv, Hash *pNew, int bBin){
  assert( pNew!=0 );
  pNew->first = 0;
  pNew->count = 0;
  pNew->htsize = 0;
  pNew->ht = 0;
  pNew->pEnv = pEnv;
  if( bBin ){
    pNew->xHash = binHash;
    pNew->xCmp = binCmp;
  }else{
    pNew->xHash = strHash;
    pNew->xCmp = strCmp;
  }
}

/* Remove all entries from a hash table.  Reclaim all memory.
** Call this routine to delete a hash table or to reset a hash table
** to the empty state.
*/
void sqlite4HashClear(Hash *pH){
................................................................................
  while( elem ){
    HashElem *next_elem = elem->next;
    sqlite4_free(pH->pEnv, elem);
    elem = next_elem;
  }
  pH->count = 0;
}















/* Link pNew element into the hash table pH.  If pEntry!=0 then also
** insert pNew into the pEntry hash bucket.
*/
static void insertElement(
  Hash *pH,              /* The complete hash table */
  struct _ht *pEntry,    /* The entry into which pNew is inserted */
................................................................................

  if( new_ht==0 ) return 0;
  sqlite4_free(pH->pEnv, pH->ht);
  pH->ht = new_ht;
  pH->htsize = new_size = sqlite4MallocSize(pH->pEnv, new_ht)/sizeof(struct _ht);
  memset(new_ht, 0, new_size*sizeof(struct _ht));
  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
    unsigned int h = pH->xHash(elem->pKey, elem->nKey) % new_size;
    next_elem = elem->next;
    insertElement(pH, &new_ht[h], elem);
  }
  return 1;
}

/* This function (for internal use only) locates an element in an
................................................................................
    elem = pEntry->chain;
    count = pEntry->count;
  }else{
    elem = pH->first;
    count = pH->count;
  }
  while( count-- && ALWAYS(elem) ){
    if( elem->nKey==nKey && pH->xCmp(elem->pKey,pKey,nKey)==0 ){ 
      return elem;
    }
    elem = elem->next;
  }
  return 0;
}

................................................................................
  HashElem *elem;    /* The element that matches key */
  unsigned int h;    /* A hash on key */

  assert( pH!=0 );
  assert( pKey!=0 );
  assert( nKey>=0 );
  if( pH->ht ){
    h = pH->xHash(pKey, nKey) % pH->htsize;
  }else{
    h = 0;
  }
  elem = findElementGivenHash(pH, pKey, nKey, h);
  return elem ? elem->data : 0;
}

................................................................................
  HashElem *elem;       /* Used to loop thru the element list */
  HashElem *new_elem;   /* New element added to the pH */

  assert( pH!=0 );
  assert( pKey!=0 );
  assert( nKey>=0 );
  if( pH->htsize ){
    h = pH->xHash(pKey, nKey) % pH->htsize;
  }else{
    h = 0;
  }
  elem = findElementGivenHash(pH,pKey,nKey,h);
  if( elem ){
    void *old_data = elem->data;
    if( data==0 ){
................................................................................
  new_elem->pKey = pKey;
  new_elem->nKey = nKey;
  new_elem->data = data;
  pH->count++;
  if( pH->count>=10 && pH->count > 2*pH->htsize ){
    if( rehash(pH, pH->count*2) ){
      assert( pH->htsize>0 );
      h = pH->xHash(pKey, nKey) % pH->htsize;
    }
  }
  if( pH->ht ){
    insertElement(pH, &pH->ht[h], new_elem);
  }else{
    insertElement(pH, 0, new_elem);
  }
  return 0;
}

Changes to src/hash.h.

38
39
40
41
42
43
44


45
46
47
48
49
50
51
..
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
** by a linear search of the global list.  For small tables, the 
** Hash.ht table is never allocated because if there are few elements
** in the table, it is faster to do a linear search than to manage
** the hash table.
*/
struct Hash {
  sqlite4_env *pEnv;        /* Memory allocation environment */


  unsigned int htsize;      /* Number of buckets in the hash table */
  unsigned int count;       /* Number of entries in this table */
  HashElem *first;          /* The first element of the array */
  struct _ht {              /* the hash table */
    int count;                 /* Number of entries with this hash */
    HashElem *chain;           /* Pointer to first entry with this hash */
  } *ht;
................................................................................
  void *data;                  /* Data associated with this element */
  const char *pKey; int nKey;  /* Key associated with this element */
};

/*
** Access routines.  To delete, insert a NULL pointer.
*/
void sqlite4HashInit(sqlite4_env *pEnv, Hash*);
void *sqlite4HashInsert(Hash*, const char *pKey, int nKey, void *pData);
void *sqlite4HashFind(const Hash*, const char *pKey, int nKey);
void sqlite4HashClear(Hash*);

/*
** Macros for looping over all elements of a hash table.  The idiom is
** like this:







>
>







 







|







38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
..
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
** by a linear search of the global list.  For small tables, the 
** Hash.ht table is never allocated because if there are few elements
** in the table, it is faster to do a linear search than to manage
** the hash table.
*/
struct Hash {
  sqlite4_env *pEnv;        /* Memory allocation environment */
  unsigned int (*xHash)(const char *, int);
  int (*xCmp)(const char *, const char *, int);
  unsigned int htsize;      /* Number of buckets in the hash table */
  unsigned int count;       /* Number of entries in this table */
  HashElem *first;          /* The first element of the array */
  struct _ht {              /* the hash table */
    int count;                 /* Number of entries with this hash */
    HashElem *chain;           /* Pointer to first entry with this hash */
  } *ht;
................................................................................
  void *data;                  /* Data associated with this element */
  const char *pKey; int nKey;  /* Key associated with this element */
};

/*
** Access routines.  To delete, insert a NULL pointer.
*/
void sqlite4HashInit(sqlite4_env *pEnv, Hash*, int);
void *sqlite4HashInsert(Hash*, const char *pKey, int nKey, void *pData);
void *sqlite4HashFind(const Hash*, const char *pKey, int nKey);
void sqlite4HashClear(Hash*);

/*
** Macros for looping over all elements of a hash table.  The idiom is
** like this:

Changes to src/main.c.

1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
  db->nextAutovac = -1;
  db->nextPagesize = 0;
  db->flags |=  SQLITE4_AutoIndex
                 | SQLITE4_EnableTrigger
                 | SQLITE4_ForeignKeys
            ;

  sqlite4HashInit(pEnv, &db->aCollSeq);
#ifndef SQLITE4_OMIT_VIRTUALTABLE
  sqlite4HashInit(pEnv, &db->aModule);
#endif

  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  ** and UTF-16, so add a version for each to avoid any unnecessary
  ** conversions. The only error that can occur here is a malloc() failure.
  */
  createCollation(db, "BINARY", SQLITE4_UTF8, 0, binCollFunc, 0, 0);







|

|







1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
  db->nextAutovac = -1;
  db->nextPagesize = 0;
  db->flags |=  SQLITE4_AutoIndex
                 | SQLITE4_EnableTrigger
                 | SQLITE4_ForeignKeys
            ;

  sqlite4HashInit(pEnv, &db->aCollSeq, 0);
#ifndef SQLITE4_OMIT_VIRTUALTABLE
  sqlite4HashInit(pEnv, &db->aModule, 0);
#endif

  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  ** and UTF-16, so add a version for each to avoid any unnecessary
  ** conversions. The only error that can occur here is a malloc() failure.
  */
  createCollation(db, "BINARY", SQLITE4_UTF8, 0, binCollFunc, 0, 0);

Changes to test/fts5expr1.test.

53
54
55
56
57
58
59









60
61
62
63
64
65
}

foreach {tn expr res} {
  1 { a : abc }                  {"a":"abc"}
  2 { b : abc + def}             {"b":"abc"+"def"}
} {
  do_execsql_test 2.$tn { 









    SELECT fts5_parse_expr('simple', $expr, 't1') 
  } [list [string trim $res]]
}


finish_test







>
>
>
>
>
>
>
>
>






53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
}

foreach {tn expr res} {
  1 { a : abc }                  {"a":"abc"}
  2 { b : abc + def}             {"b":"abc"+"def"}
} {
  do_execsql_test 2.$tn { 
    SELECT fts5_parse_expr('simple', $expr, 't1') 
  } [list [string trim $res]]
}

breakpoint
foreach {tn expr res} {
  1 { abc* }                  {"abc"*}
} {
  do_execsql_test 3.$tn { 
    SELECT fts5_parse_expr('simple', $expr, 't1') 
  } [list [string trim $res]]
}


finish_test

Changes to test/fts5query1.test.

85
86
87
88
89
90
91
92
93
94
95
96

























97
98

do_execsql_test 4.0 {
  CREATE TABLE t2(docid PRIMARY KEY, a, b, c);
  CREATE INDEX i2 ON t2 USING fts5();
  INSERT INTO t2 VALUES(136895, 'qkfl my qkfl krag gw', NULL, NULL);
}

breakpoint
do_execsql_test 4.1 {
  SELECT docid FROM t2 WHERE t2 MATCH 'qkfl NEAR/2 gw';
} {136895}


























finish_test








<




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


85
86
87
88
89
90
91

92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

do_execsql_test 4.0 {
  CREATE TABLE t2(docid PRIMARY KEY, a, b, c);
  CREATE INDEX i2 ON t2 USING fts5();
  INSERT INTO t2 VALUES(136895, 'qkfl my qkfl krag gw', NULL, NULL);
}


do_execsql_test 4.1 {
  SELECT docid FROM t2 WHERE t2 MATCH 'qkfl NEAR/2 gw';
} {136895}

do_execsql_test 6.0 {
  CREATE TABLE t3(docid PRIMARY KEY, a, b, c);
  CREATE INDEX i3 ON t3 USING fts5();
  INSERT INTO t3 VALUES(123, 'fix the hash table', NULL, NULL);
}
do_execsql_test 5.1 {
  SELECT docid FROM t3 WHERE t3 MATCH 'h*';
} {123}

do_execsql_test 6.0 {

BEGIN TRANSACTION;
CREATE TABLE t4(docid PRIMARY KEY, a, b, c);
CREATE INDEX i4 ON t4 USING fts5();

INSERT INTO "t4" VALUES(34,'ndmv jk qhiv cnz kyev blu qs nxhf etm uen','uh hu as wcvo hw whgu wd zm saus jvg bmbx kyev bnyk wmbz yf uh rb yf ju blu jkb jk qkfl jk gimj uh brsu ptic ka ztc vniq uprt kyev rxcf blu bnyk mu hgjo rxcf rnxr vcy vllx mve nxhf kb iddj qpnv fal iddj ju zidh mu pvjr cu my blu ztc vllx ono ndmv ib mu qpnv ldfi jvg jvg ztc uprt qrwj ptic saus fltt uen cnz ju qrwj gfap jk krag bwsr kb csjq kn krag ono uv krag da cu bil wd sk','ib qrwj iddj cku qdye uv pnz hu wte kyev ka jvg hu mu las bwsr mu uv da szem vllx bwsr wfar blu uv ztc qpnv wwne osok qpnv');
INSERT INTO "t4" VALUES(50,'ldfi zlc cku cnz sk juhw nxhf iddj las hu qhiv bmbx nq kn uprt las jk pvjr urvy qs bwsr uyn pmh ssc fltt bmbx ldfi rnxr cnz yf rnxr ndmv wmbz fal pmh uyn sk uh szem uv ssc bnyk yle jvg zm hgjo uh blu jvg rxcf whgu ztc kyev xdza cku kyev juhw nq ldfi las uprt wwne uprt qrwj vniq fal szem fteo cnz bwsr jrx jk jpa uv pmh nq qdye gfap ldfi uen sk wgwd zidh cu gfap','wd ndmv saus pnz hgjo gimj ztc jrx krag jrx gimj qhiv saj hgjo jrx xdza gvp cku kn szem my saus bnyk saj pmh gw bnyk saj as zimg ssc kh pvjr fal etm cu jvg krag hbtv kb szem qdye uv bil aayx wmbz xdza zm ib ldfi brsu zm rnxr csjq ldfi kb vllx zidh','gw fteo ka cu ib hu fteo juhw yf pnz blu jk ka bnyk bwsr da pnz pvjr yf pmh csjq my ztc zm hbtv qrwj cnz hu mu za ldfi qpnv saj');
COMMIT;
}

breakpoint
do_execsql_test 6.1 {
  SELECT docid FROM t4 WHERE t4 MATCH 'm*' 
} {34 50}

finish_test

Changes to test/fts5rnd1.test.

340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355

356
357
358
359
360
361
362
...
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
    } [simple_phrase $term]
  }

  # This time, use the first two characters of each term as a term prefix
  # to query for. Test that querying the Tcl array produces the same results
  # as querying the FTS3 table for the prefix.
  #

puts "todo: prefix query support"
#  for {set i 0} {$i < $nRep} {incr i} {
#    set prefix [string range [random_term] 0 end-1]
#    set match "${prefix}*"
#    do_orderbydocid_test 2.$i {
#      SELECT docid FROM t1 WHERE t1 MATCH $match
#    } [simple_phrase $match]
#  }


  # Similar to the above, except for phrase queries.
  #
  for {set i 0} {$i < $nRep} {incr i} {
    set term [list [random_term] [random_term]]
    set match "\"$term\""
    do_orderbydocid_test 3.$i {
................................................................................
    do_orderbydocid_test 4.$i {
      SELECT docid FROM t1 WHERE t1 MATCH $match
    } [simple_phrase $term]
  }

  # Three word phrases made up of term-prefixes.
  #
puts "todo: prefix query support"
#  for {set i 0} {$i < $nRep} {incr i} {
#    set    query "[string range [random_term] 0 end-1]* "
#    append query "[string range [random_term] 0 end-1]* "
#    append query "[string range [random_term] 0 end-1]*"
#
#    set match "\"$query\""
#    do_orderbydocid_test 5.$i {
#      SELECT docid FROM t1 WHERE t1 MATCH $match
#    } [simple_phrase $query]
#  }


  # A NEAR query with terms as the arguments:
  #
  #     ... MATCH '$term1 NEAR $term2' ...
  #
  for {set i 0} {$i < $nRep} {incr i} {
    set terms [list [random_term] [random_term]]







<
<
|
|
|
|
|
|
<
>







 







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







340
341
342
343
344
345
346


347
348
349
350
351
352

353
354
355
356
357
358
359
360
...
370
371
372
373
374
375
376

377
378
379
380
381

382
383
384

385
386
387
388
389
390
391
392
    } [simple_phrase $term]
  }

  # This time, use the first two characters of each term as a term prefix
  # to query for. Test that querying the Tcl array produces the same results
  # as querying the FTS3 table for the prefix.
  #


  for {set i 0} {$i < $nRep} {incr i} {
    set prefix [string range [random_term] 0 end-1]
    set match "${prefix}*"
    do_orderbydocid_test 2.$i {
      SELECT docid FROM t1 WHERE t1 MATCH $match
    } [simple_phrase $match]

  }

  # Similar to the above, except for phrase queries.
  #
  for {set i 0} {$i < $nRep} {incr i} {
    set term [list [random_term] [random_term]]
    set match "\"$term\""
    do_orderbydocid_test 3.$i {
................................................................................
    do_orderbydocid_test 4.$i {
      SELECT docid FROM t1 WHERE t1 MATCH $match
    } [simple_phrase $term]
  }

  # Three word phrases made up of term-prefixes.
  #

  for {set i 0} {$i < $nRep} {incr i} {
    set    query "[string range [random_term] 0 end-1]* + "
    append query "[string range [random_term] 0 end-1]* + "
    append query "[string range [random_term] 0 end-1]*"


    do_orderbydocid_test 5.$i {
      SELECT docid FROM t1 WHERE t1 MATCH $match
    } [simple_phrase $query]

  }

  # A NEAR query with terms as the arguments:
  #
  #     ... MATCH '$term1 NEAR $term2' ...
  #
  for {set i 0} {$i < $nRep} {incr i} {
    set terms [list [random_term] [random_term]]

Changes to test/permutations.test.

135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
} -files {
  simple.test simple2.test
  log3.test 
  lsm1.test lsm2.test
  csr1.test
  ckpt1.test
  mc1.test
  fts5expr1.test

  aggerror.test
  attach.test
  autoindex1.test
  badutf.test
  between.test
  bigrow.test







|







135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
} -files {
  simple.test simple2.test
  log3.test 
  lsm1.test lsm2.test
  csr1.test
  ckpt1.test
  mc1.test
  fts5expr1.test fts5query1.test fts5rnd1.test fts5create.test

  aggerror.test
  attach.test
  autoindex1.test
  badutf.test
  between.test
  bigrow.test