interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / misc / amatch.c

1524 lines · 46527 bytes Raw Blame History
1/*
2** 2013-03-14
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12**
13** This file contains code for a demonstration virtual table that finds
14** "approximate matches" - strings from a finite set that are nearly the
15** same as a single input string. The virtual table is called "amatch".
16**
17** A amatch virtual table is created like this:
18**
19** CREATE VIRTUAL TABLE f USING approximate_match(
20** vocabulary_table=<tablename>, -- V
21** vocabulary_word=<columnname>, -- W
22** vocabulary_language=<columnname>, -- L
23** edit_distances=<edit-cost-table>
24** );
25**
26** When it is created, the new amatch table must be supplied with the
27** the name of a table V and columns V.W and V.L such that
28**
29** SELECT W FROM V WHERE L=$language
30**
31** returns the allowed vocabulary for the match. If the "vocabulary_language"
32** or L columnname is left unspecified or is an empty string, then no
33** filtering of the vocabulary by language is performed.
34**
35** For efficiency, it is essential that the vocabulary table be indexed:
36**
37** CREATE vocab_index ON V(W)
38**
39** A separate edit-cost-table provides scoring information that defines
40** what it means for one string to be "close" to another.
41**
42** The edit-cost-table must contain exactly four columns (more precisely,
43** the statement "SELECT * FROM <edit-cost-table>" must return records
44** that consist of four columns). It does not matter what the columns are
45** named.
46**
47** Each row in the edit-cost-table represents a single character
48** transformation going from user input to the vocabulary. The leftmost
49** column of the row (column 0) contains an integer identifier of the
50** language to which the transformation rule belongs (see "MULTIPLE LANGUAGES"
51** below). The second column of the row (column 1) contains the input
52** character or characters - the characters of user input. The third
53** column contains characters as they appear in the vocabulary table.
54** And the fourth column contains the integer cost of making the
55** transformation. For example:
56**
57** CREATE TABLE f_data(iLang, cFrom, cTo, Cost);
58** INSERT INTO f_data(iLang, cFrom, cTo, Cost) VALUES(0, '', 'a', 100);
59** INSERT INTO f_data(iLang, cFrom, cTo, Cost) VALUES(0, 'b', '', 87);
60** INSERT INTO f_data(iLang, cFrom, cTo, Cost) VALUES(0, 'o', 'oe', 38);
61** INSERT INTO f_data(iLang, cFrom, cTo, Cost) VALUES(0, 'oe', 'o', 40);
62**
63** The first row inserted into the edit-cost-table by the SQL script
64** above indicates that the cost of having an extra 'a' in the vocabulary
65** table that is missing in the user input 100. (All costs are integers.
66** Overall cost must not exceed 16777216.) The second INSERT statement
67** creates a rule saying that the cost of having a single letter 'b' in
68** user input which is missing in the vocabulary table is 87. The third
69** INSERT statement mean that the cost of matching an 'o' in user input
70** against an 'oe' in the vocabulary table is 38. And so forth.
71**
72** The following rules are special:
73**
74** INSERT INTO f_data(iLang, cFrom, cTo, Cost) VALUES(0, '?', '', 97);
75** INSERT INTO f_data(iLang, cFrom, cTo, Cost) VALUES(0, '', '?', 98);
76** INSERT INTO f_data(iLang, cFrom, cTo, Cost) VALUES(0, '?', '?', 99);
77**
78** The '?' to '' rule is the cost of having any single character in the input
79** that is not found in the vocabular. The '' to '?' rule is the cost of
80** having a character in the vocabulary table that is missing from input.
81** And the '?' to '?' rule is the cost of doing an arbitrary character
82** substitution. These three generic rules apply across all languages.
83** In other words, the iLang field is ignored for the generic substitution
84** rules. If more than one cost is given for a generic substitution rule,
85** then the lowest cost is used.
86**
87** Once it has been created, the amatch virtual table can be queried
88** as follows:
89**
90** SELECT word, distance FROM f
91** WHERE word MATCH 'abcdefg'
92** AND distance<200;
93**
94** This query outputs the strings contained in the T(F) field that
95** are close to "abcdefg" and in order of increasing distance. No string
96** is output more than once. If there are multiple ways to transform the
97** target string ("abcdefg") into a string in the vocabulary table then
98** the lowest cost transform is the one that is returned. In this example,
99** the search is limited to strings with a total distance of less than 200.
100**
101** For efficiency, it is important to put tight bounds on the distance.
102** The time and memory space needed to perform this query is exponential
103** in the maximum distance. A good rule of thumb is to limit the distance
104** to no more than 1.5 or 2 times the maximum cost of any rule in the
105** edit-cost-table.
106**
107** The amatch is a read-only table. Any attempt to DELETE, INSERT, or
108** UPDATE on a amatch table will throw an error.
109**
110** It is important to put some kind of a limit on the amatch output. This
111** can be either in the form of a LIMIT clause at the end of the query,
112** or better, a "distance<NNN" constraint where NNN is some number. The
113** running time and memory requirement is exponential in the value of NNN
114** so you want to make sure that NNN is not too big. A value of NNN that
115** is about twice the average transformation cost seems to give good results.
116**
117** The amatch table can be useful for tasks such as spelling correction.
118** Suppose all allowed words are in table vocabulary(w). Then one would create
119** an amatch virtual table like this:
120**
121** CREATE VIRTUAL TABLE ex1 USING amatch(
122** vocabtable=vocabulary,
123** vocabcolumn=w,
124** edit_distances=ec1
125** );
126**
127** Then given an input word $word, look up close spellings this way:
128**
129** SELECT word, distance FROM ex1
130** WHERE word MATCH $word AND distance<200;
131**
132** MULTIPLE LANGUAGES
133**
134** Normally, the "iLang" value associated with all character transformations
135** in the edit-cost-table is zero. However, if required, the amatch
136** virtual table allows multiple languages to be defined. Each query uses
137** only a single iLang value. This allows, for example, a single
138** amatch table to support multiple languages.
139**
140** By default, only the rules with iLang=0 are used. To specify an
141** alternative language, a "language = ?" expression must be added to the
142** WHERE clause of a SELECT, where ? is the integer identifier of the desired
143** language. For example:
144**
145** SELECT word, distance FROM ex1
146** WHERE word MATCH $word
147** AND distance<=200
148** AND language=1 -- Specify use language 1 instead of 0
149**
150** If no "language = ?" constraint is specified in the WHERE clause, language
151** 0 is used.
152**
153** LIMITS
154**
155** The maximum language number is 2147483647. The maximum length of either
156** of the strings in the second or third column of the amatch data table
157** is 50 bytes. The maximum cost on a rule is 1000.
158*/
159#include "sqlite3ext.h"
160SQLITE_EXTENSION_INIT1
161#include <stdlib.h>
162#include <string.h>
163#include <assert.h>
164#include <stdio.h>
165#include <ctype.h>
166
167#ifndef SQLITE_OMIT_VIRTUALTABLE
168
169/*
170** Forward declaration of objects used by this implementation
171*/
172typedef struct amatch_vtab amatch_vtab;
173typedef struct amatch_cursor amatch_cursor;
174typedef struct amatch_rule amatch_rule;
175typedef struct amatch_word amatch_word;
176typedef struct amatch_avl amatch_avl;
177
178
179/*****************************************************************************
180** AVL Tree implementation
181*/
182/*
183** Objects that want to be members of the AVL tree should embedded an
184** instance of this structure.
185*/
186struct amatch_avl {
187 amatch_word *pWord; /* Points to the object being stored in the tree */
188 char *zKey; /* Key. zero-terminated string. Must be unique */
189 amatch_avl *pBefore; /* Other elements less than zKey */
190 amatch_avl *pAfter; /* Other elements greater than zKey */
191 amatch_avl *pUp; /* Parent element */
192 int height; /* Height of this node. Leaf==1 */
193 int imbalance; /* Height difference between pBefore and pAfter */
194};
195
196/* Recompute the amatch_avl.height and amatch_avl.imbalance fields for p.
197** Assume that the children of p have correct heights.
198*/
199static void amatchAvlRecomputeHeight(amatch_avl *p){
200 int hBefore = p->pBefore ? p->pBefore->height : 0;
201 int hAfter = p->pAfter ? p->pAfter->height : 0;
202 p->imbalance = hBefore - hAfter; /* -: pAfter higher. +: pBefore higher */
203 p->height = (hBefore>hAfter ? hBefore : hAfter)+1;
204}
205
206/*
207** P B
208** / \ / \
209** B Z ==> X P
210** / \ / \
211** X Y Y Z
212**
213*/
214static amatch_avl *amatchAvlRotateBefore(amatch_avl *pP){
215 amatch_avl *pB = pP->pBefore;
216 amatch_avl *pY = pB->pAfter;
217 pB->pUp = pP->pUp;
218 pB->pAfter = pP;
219 pP->pUp = pB;
220 pP->pBefore = pY;
221 if( pY ) pY->pUp = pP;
222 amatchAvlRecomputeHeight(pP);
223 amatchAvlRecomputeHeight(pB);
224 return pB;
225}
226
227/*
228** P A
229** / \ / \
230** X A ==> P Z
231** / \ / \
232** Y Z X Y
233**
234*/
235static amatch_avl *amatchAvlRotateAfter(amatch_avl *pP){
236 amatch_avl *pA = pP->pAfter;
237 amatch_avl *pY = pA->pBefore;
238 pA->pUp = pP->pUp;
239 pA->pBefore = pP;
240 pP->pUp = pA;
241 pP->pAfter = pY;
242 if( pY ) pY->pUp = pP;
243 amatchAvlRecomputeHeight(pP);
244 amatchAvlRecomputeHeight(pA);
245 return pA;
246}
247
248/*
249** Return a pointer to the pBefore or pAfter pointer in the parent
250** of p that points to p. Or if p is the root node, return pp.
251*/
252static amatch_avl **amatchAvlFromPtr(amatch_avl *p, amatch_avl **pp){
253 amatch_avl *pUp = p->pUp;
254 if( pUp==0 ) return pp;
255 if( pUp->pAfter==p ) return &pUp->pAfter;
256 return &pUp->pBefore;
257}
258
259/*
260** Rebalance all nodes starting with p and working up to the root.
261** Return the new root.
262*/
263static amatch_avl *amatchAvlBalance(amatch_avl *p){
264 amatch_avl *pTop = p;
265 amatch_avl **pp;
266 while( p ){
267 amatchAvlRecomputeHeight(p);
268 if( p->imbalance>=2 ){
269 amatch_avl *pB = p->pBefore;
270 if( pB->imbalance<0 ) p->pBefore = amatchAvlRotateAfter(pB);
271 pp = amatchAvlFromPtr(p,&p);
272 p = *pp = amatchAvlRotateBefore(p);
273 }else if( p->imbalance<=(-2) ){
274 amatch_avl *pA = p->pAfter;
275 if( pA->imbalance>0 ) p->pAfter = amatchAvlRotateBefore(pA);
276 pp = amatchAvlFromPtr(p,&p);
277 p = *pp = amatchAvlRotateAfter(p);
278 }
279 pTop = p;
280 p = p->pUp;
281 }
282 return pTop;
283}
284
285/* Search the tree rooted at p for an entry with zKey. Return a pointer
286** to the entry or return NULL.
287*/
288static amatch_avl *amatchAvlSearch(amatch_avl *p, const char *zKey){
289 int c;
290 while( p && (c = strcmp(zKey, p->zKey))!=0 ){
291 p = (c<0) ? p->pBefore : p->pAfter;
292 }
293 return p;
294}
295
296/* Find the first node (the one with the smallest key).
297*/
298static amatch_avl *amatchAvlFirst(amatch_avl *p){
299 if( p ) while( p->pBefore ) p = p->pBefore;
300 return p;
301}
302
303#if 0 /* NOT USED */
304/* Return the node with the next larger key after p.
305*/
306static amatch_avl *amatchAvlNext(amatch_avl *p){
307 amatch_avl *pPrev = 0;
308 while( p && p->pAfter==pPrev ){
309 pPrev = p;
310 p = p->pUp;
311 }
312 if( p && pPrev==0 ){
313 p = amatchAvlFirst(p->pAfter);
314 }
315 return p;
316}
317#endif
318
319#if 0 /* NOT USED */
320/* Verify AVL tree integrity
321*/
322static int amatchAvlIntegrity(amatch_avl *pHead){
323 amatch_avl *p;
324 if( pHead==0 ) return 1;
325 if( (p = pHead->pBefore)!=0 ){
326 assert( p->pUp==pHead );
327 assert( amatchAvlIntegrity(p) );
328 assert( strcmp(p->zKey, pHead->zKey)<0 );
329 while( p->pAfter ) p = p->pAfter;
330 assert( strcmp(p->zKey, pHead->zKey)<0 );
331 }
332 if( (p = pHead->pAfter)!=0 ){
333 assert( p->pUp==pHead );
334 assert( amatchAvlIntegrity(p) );
335 assert( strcmp(p->zKey, pHead->zKey)>0 );
336 p = amatchAvlFirst(p);
337 assert( strcmp(p->zKey, pHead->zKey)>0 );
338 }
339 return 1;
340}
341static int amatchAvlIntegrity2(amatch_avl *pHead){
342 amatch_avl *p, *pNext;
343 for(p=amatchAvlFirst(pHead); p; p=pNext){
344 pNext = amatchAvlNext(p);
345 if( pNext==0 ) break;
346 assert( strcmp(p->zKey, pNext->zKey)<0 );
347 }
348 return 1;
349}
350#endif
351
352/* Insert a new node pNew. Return NULL on success. If the key is not
353** unique, then do not perform the insert but instead leave pNew unchanged
354** and return a pointer to an existing node with the same key.
355*/
356static amatch_avl *amatchAvlInsert(amatch_avl **ppHead, amatch_avl *pNew){
357 int c;
358 amatch_avl *p = *ppHead;
359 if( p==0 ){
360 p = pNew;
361 pNew->pUp = 0;
362 }else{
363 while( p ){
364 c = strcmp(pNew->zKey, p->zKey);
365 if( c<0 ){
366 if( p->pBefore ){
367 p = p->pBefore;
368 }else{
369 p->pBefore = pNew;
370 pNew->pUp = p;
371 break;
372 }
373 }else if( c>0 ){
374 if( p->pAfter ){
375 p = p->pAfter;
376 }else{
377 p->pAfter = pNew;
378 pNew->pUp = p;
379 break;
380 }
381 }else{
382 return p;
383 }
384 }
385 }
386 pNew->pBefore = 0;
387 pNew->pAfter = 0;
388 pNew->height = 1;
389 pNew->imbalance = 0;
390 *ppHead = amatchAvlBalance(p);
391 /* assert( amatchAvlIntegrity(*ppHead) ); */
392 /* assert( amatchAvlIntegrity2(*ppHead) ); */
393 return 0;
394}
395
396/* Remove node pOld from the tree. pOld must be an element of the tree or
397** the AVL tree will become corrupt.
398*/
399static void amatchAvlRemove(amatch_avl **ppHead, amatch_avl *pOld){
400 amatch_avl **ppParent;
401 amatch_avl *pBalance = 0;
402 /* assert( amatchAvlSearch(*ppHead, pOld->zKey)==pOld ); */
403 ppParent = amatchAvlFromPtr(pOld, ppHead);
404 if( pOld->pBefore==0 && pOld->pAfter==0 ){
405 *ppParent = 0;
406 pBalance = pOld->pUp;
407 }else if( pOld->pBefore && pOld->pAfter ){
408 amatch_avl *pX, *pY;
409 pX = amatchAvlFirst(pOld->pAfter);
410 *amatchAvlFromPtr(pX, 0) = pX->pAfter;
411 if( pX->pAfter ) pX->pAfter->pUp = pX->pUp;
412 pBalance = pX->pUp;
413 pX->pAfter = pOld->pAfter;
414 if( pX->pAfter ){
415 pX->pAfter->pUp = pX;
416 }else{
417 assert( pBalance==pOld );
418 pBalance = pX;
419 }
420 pX->pBefore = pY = pOld->pBefore;
421 if( pY ) pY->pUp = pX;
422 pX->pUp = pOld->pUp;
423 *ppParent = pX;
424 }else if( pOld->pBefore==0 ){
425 *ppParent = pBalance = pOld->pAfter;
426 pBalance->pUp = pOld->pUp;
427 }else if( pOld->pAfter==0 ){
428 *ppParent = pBalance = pOld->pBefore;
429 pBalance->pUp = pOld->pUp;
430 }
431 *ppHead = amatchAvlBalance(pBalance);
432 pOld->pUp = 0;
433 pOld->pBefore = 0;
434 pOld->pAfter = 0;
435 /* assert( amatchAvlIntegrity(*ppHead) ); */
436 /* assert( amatchAvlIntegrity2(*ppHead) ); */
437}
438/*
439** End of the AVL Tree implementation
440******************************************************************************/
441
442
443/*
444** Various types.
445**
446** amatch_cost is the "cost" of an edit operation.
447**
448** amatch_len is the length of a matching string.
449**
450** amatch_langid is an ruleset identifier.
451*/
452typedef int amatch_cost;
453typedef signed char amatch_len;
454typedef int amatch_langid;
455
456/*
457** Limits
458*/
459#define AMATCH_MX_LENGTH 50 /* Maximum length of a rule string */
460#define AMATCH_MX_LANGID 2147483647 /* Maximum rule ID */
461#define AMATCH_MX_COST 1000 /* Maximum single-rule cost */
462#define AMATCH_MX_WORD 1000 /* Maximum length of a word */
463
464
465/*
466** A match or partial match
467*/
468struct amatch_word {
469 amatch_word *pNext; /* Next on a list of all amatch_words */
470 amatch_avl sCost; /* Linkage of this node into the cost tree */
471 amatch_avl sWord; /* Linkage of this node into the word tree */
472 amatch_cost rCost; /* Cost of the match so far */
473 int iSeq; /* Sequence number */
474 int nMatch; /* Input characters matched */
475 char zCost[10]; /* Cost key (text rendering of rCost) */
476 char zWord[4]; /* Text of the word. Extra space appended as needed */
477};
478
479/*
480** Each transformation rule is stored as an instance of this object.
481** All rules are kept on a linked list sorted by rCost.
482*/
483struct amatch_rule {
484 amatch_rule *pNext; /* Next rule in order of increasing rCost */
485 char *zFrom; /* Transform from (a string from user input) */
486 amatch_cost rCost; /* Cost of this transformation */
487 amatch_langid iLang; /* The language to which this rule belongs */
488 amatch_len nFrom, nTo; /* Length of the zFrom and zTo strings */
489 char zTo[4]; /* Transform to V.W value (extra space appended) */
490};
491
492/*
493** A amatch virtual-table object
494*/
495struct amatch_vtab {
496 sqlite3_vtab base; /* Base class - must be first */
497 char *zClassName; /* Name of this class. Default: "amatch" */
498 char *zDb; /* Name of database. (ex: "main") */
499 char *zSelf; /* Name of this virtual table */
500 char *zCostTab; /* Name of edit-cost-table */
501 char *zVocabTab; /* Name of vocabulary table */
502 char *zVocabWord; /* Name of vocabulary table word column */
503 char *zVocabLang; /* Name of vocabulary table language column */
504 amatch_rule *pRule; /* All active rules in this amatch */
505 amatch_cost rIns; /* Generic insertion cost '' -> ? */
506 amatch_cost rDel; /* Generic deletion cost ? -> '' */
507 amatch_cost rSub; /* Generic substitution cost ? -> ? */
508 sqlite3 *db; /* The database connection */
509 sqlite3_stmt *pVCheck; /* Query to check zVocabTab */
510 int nCursor; /* Number of active cursors */
511};
512
513/* A amatch cursor object */
514struct amatch_cursor {
515 sqlite3_vtab_cursor base; /* Base class - must be first */
516 sqlite3_int64 iRowid; /* The rowid of the current word */
517 amatch_langid iLang; /* Use this language ID */
518 amatch_cost rLimit; /* Maximum cost of any term */
519 sqlite3_int64 nBuf; /* Space allocated for zBuf */
520 int oomErr; /* True following an OOM error */
521 int nWord; /* Number of amatch_word objects */
522 char *zBuf; /* Temp-use buffer space */
523 char *zInput; /* Input word to match against */
524 amatch_vtab *pVtab; /* The virtual table this cursor belongs to */
525 amatch_word *pAllWords; /* List of all amatch_word objects */
526 amatch_word *pCurrent; /* Most recent solution */
527 amatch_avl *pCost; /* amatch_word objects keyed by iCost */
528 amatch_avl *pWord; /* amatch_word objects keyed by zWord */
529};
530
531/*
532** The two input rule lists are both sorted in order of increasing
533** cost. Merge them together into a single list, sorted by cost, and
534** return a pointer to the head of that list.
535*/
536static amatch_rule *amatchMergeRules(amatch_rule *pA, amatch_rule *pB){
537 amatch_rule head;
538 amatch_rule *pTail;
539
540 pTail = &head;
541 while( pA && pB ){
542 if( pA->rCost<=pB->rCost ){
543 pTail->pNext = pA;
544 pTail = pA;
545 pA = pA->pNext;
546 }else{
547 pTail->pNext = pB;
548 pTail = pB;
549 pB = pB->pNext;
550 }
551 }
552 if( pA==0 ){
553 pTail->pNext = pB;
554 }else{
555 pTail->pNext = pA;
556 }
557 return head.pNext;
558}
559
560/*
561** Truncate an integer so that it fits in 32 bits.
562*/
563static int amatchTruncateInt(sqlite3_int64 i){
564 if( i>=-2147483647 && i<=2147483646 ){
565 return (int)i;
566 }else{
567 return i<0 ? (-1)-2147483647 : 2147483647;
568 }
569}
570
571/*
572** Statement pStmt currently points to a row in the amatch data table. This
573** function allocates and populates a amatch_rule structure according to
574** the content of the row.
575**
576** If successful, *ppRule is set to point to the new object and SQLITE_OK
577** is returned. Otherwise, *ppRule is zeroed, *pzErr may be set to point
578** to an error message and an SQLite error code returned.
579*/
580static int amatchLoadOneRule(
581 amatch_vtab *p, /* Fuzzer virtual table handle */
582 sqlite3_stmt *pStmt, /* Base rule on statements current row */
583 amatch_rule **ppRule, /* OUT: New rule object */
584 char **pzErr /* OUT: Error message */
585){
586 sqlite3_int64 iLang = sqlite3_column_int64(pStmt, 0);
587 const char *zFrom = (const char *)sqlite3_column_text(pStmt, 1);
588 const char *zTo = (const char *)sqlite3_column_text(pStmt, 2);
589 sqlite3_int64 iCost = sqlite3_column_int64(pStmt, 3);
590 amatch_cost rCost = amatchTruncateInt(iCost);
591
592 int rc = SQLITE_OK; /* Return code */
593 int nFrom; /* Size of string zFrom, in bytes */
594 int nTo; /* Size of string zTo, in bytes */
595 amatch_rule *pRule = 0; /* New rule object to return */
596
597 if( zFrom==0 ) zFrom = "";
598 if( zTo==0 ) zTo = "";
599 nFrom = (int)strlen(zFrom);
600 nTo = (int)strlen(zTo);
601
602 if( rCost<=0 || rCost>AMATCH_MX_COST ){
603 *pzErr = sqlite3_mprintf("%s: cost must be between 1 and %d",
604 p->zClassName, AMATCH_MX_COST
605 );
606 return SQLITE_ERROR;
607 }
608
609 /* Silently ignore null transformations */
610 if( strcmp(zFrom, zTo)==0 ){
611 if( zFrom[0]=='?' && zFrom[1]==0 ){
612 if( p->rSub==0 || p->rSub>rCost ) p->rSub = rCost;
613 }
614 *ppRule = 0;
615 return SQLITE_OK;
616 }
617
618 if( nFrom>AMATCH_MX_LENGTH || nTo>AMATCH_MX_LENGTH ){
619 *pzErr = sqlite3_mprintf("%s: maximum string length is %d",
620 p->zClassName, AMATCH_MX_LENGTH
621 );
622 rc = SQLITE_ERROR;
623 }else
624 if( iLang<0 || iLang>AMATCH_MX_LANGID ){
625 *pzErr = sqlite3_mprintf("%s: iLang must be between 0 and %d",
626 p->zClassName, AMATCH_MX_LANGID
627 );
628 rc = SQLITE_ERROR;
629 }else
630 if( strcmp(zFrom,"")==0 && strcmp(zTo,"?")==0 ){
631 if( p->rIns==0 || p->rIns>rCost ) p->rIns = rCost;
632 }else
633 if( strcmp(zFrom,"?")==0 && strcmp(zTo,"")==0 ){
634 if( p->rDel==0 || p->rDel>rCost ) p->rDel = rCost;
635 }else
636 {
637 pRule = sqlite3_malloc64( sizeof(*pRule) + nFrom + nTo );
638 if( pRule==0 ){
639 rc = SQLITE_NOMEM;
640 }else{
641 memset(pRule, 0, sizeof(*pRule));
642 pRule->zFrom = &pRule->zTo[nTo+1];
643 pRule->nFrom = (amatch_len)nFrom;
644 memcpy(pRule->zFrom, zFrom, nFrom+1);
645 memcpy(pRule->zTo, zTo, nTo+1);
646 pRule->nTo = (amatch_len)nTo;
647 pRule->rCost = rCost;
648 pRule->iLang = (int)iLang;
649 }
650 }
651
652 *ppRule = pRule;
653 return rc;
654}
655
656/*
657** Free all the content in the edit-cost-table
658*/
659static void amatchFreeRules(amatch_vtab *p){
660 while( p->pRule ){
661 amatch_rule *pRule = p->pRule;
662 p->pRule = pRule->pNext;
663 sqlite3_free(pRule);
664 }
665 p->pRule = 0;
666}
667
668/*
669** Load the content of the amatch data table into memory.
670*/
671static int amatchLoadRules(
672 sqlite3 *db, /* Database handle */
673 amatch_vtab *p, /* Virtual amatch table to configure */
674 char **pzErr /* OUT: Error message */
675){
676 int rc = SQLITE_OK; /* Return code */
677 char *zSql; /* SELECT used to read from rules table */
678 amatch_rule *pHead = 0;
679
680 zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", p->zDb, p->zCostTab);
681 if( zSql==0 ){
682 rc = SQLITE_NOMEM;
683 }else{
684 int rc2; /* finalize() return code */
685 sqlite3_stmt *pStmt = 0;
686 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
687 if( rc!=SQLITE_OK ){
688 *pzErr = sqlite3_mprintf("%s: %s", p->zClassName, sqlite3_errmsg(db));
689 }else if( sqlite3_column_count(pStmt)!=4 ){
690 *pzErr = sqlite3_mprintf("%s: %s has %d columns, expected 4",
691 p->zClassName, p->zCostTab, sqlite3_column_count(pStmt)
692 );
693 rc = SQLITE_ERROR;
694 }else{
695 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
696 amatch_rule *pRule = 0;
697 rc = amatchLoadOneRule(p, pStmt, &pRule, pzErr);
698 if( pRule ){
699 pRule->pNext = pHead;
700 pHead = pRule;
701 }
702 }
703 }
704 rc2 = sqlite3_finalize(pStmt);
705 if( rc==SQLITE_OK ) rc = rc2;
706 }
707 sqlite3_free(zSql);
708
709 /* All rules are now in a singly linked list starting at pHead. This
710 ** block sorts them by cost and then sets amatch_vtab.pRule to point to
711 ** point to the head of the sorted list.
712 */
713 if( rc==SQLITE_OK ){
714 unsigned int i;
715 amatch_rule *pX;
716 amatch_rule *a[15];
717 for(i=0; i<sizeof(a)/sizeof(a[0]); i++) a[i] = 0;
718 while( (pX = pHead)!=0 ){
719 pHead = pX->pNext;
720 pX->pNext = 0;
721 for(i=0; a[i] && i<sizeof(a)/sizeof(a[0])-1; i++){
722 pX = amatchMergeRules(a[i], pX);
723 a[i] = 0;
724 }
725 a[i] = amatchMergeRules(a[i], pX);
726 }
727 for(pX=a[0], i=1; i<sizeof(a)/sizeof(a[0]); i++){
728 pX = amatchMergeRules(a[i], pX);
729 }
730 p->pRule = amatchMergeRules(p->pRule, pX);
731 }else{
732 /* An error has occurred. Setting p->pRule to point to the head of the
733 ** allocated list ensures that the list will be cleaned up in this case.
734 */
735 assert( p->pRule==0 );
736 p->pRule = pHead;
737 }
738
739 return rc;
740}
741
742/*
743** This function converts an SQL quoted string into an unquoted string
744** and returns a pointer to a buffer allocated using sqlite3_malloc()
745** containing the result. The caller should eventually free this buffer
746** using sqlite3_free.
747**
748** Examples:
749**
750** "abc" becomes abc
751** 'xyz' becomes xyz
752** [pqr] becomes pqr
753** `mno` becomes mno
754*/
755static char *amatchDequote(const char *zIn){
756 sqlite3_int64 nIn; /* Size of input string, in bytes */
757 char *zOut; /* Output (dequoted) string */
758
759 nIn = strlen(zIn);
760 zOut = sqlite3_malloc64(nIn+1);
761 if( zOut ){
762 char q = zIn[0]; /* Quote character (if any ) */
763
764 if( q!='[' && q!= '\'' && q!='"' && q!='`' ){
765 memcpy(zOut, zIn, (size_t)(nIn+1));
766 }else{
767 int iOut = 0; /* Index of next byte to write to output */
768 int iIn; /* Index of next byte to read from input */
769
770 if( q=='[' ) q = ']';
771 for(iIn=1; iIn<nIn; iIn++){
772 if( zIn[iIn]==q ) iIn++;
773 zOut[iOut++] = zIn[iIn];
774 }
775 }
776 assert( (int)strlen(zOut)<=nIn );
777 }
778 return zOut;
779}
780
781/*
782** Deallocate the pVCheck prepared statement.
783*/
784static void amatchVCheckClear(amatch_vtab *p){
785 if( p->pVCheck ){
786 sqlite3_finalize(p->pVCheck);
787 p->pVCheck = 0;
788 }
789}
790
791/*
792** Deallocate an amatch_vtab object
793*/
794static void amatchFree(amatch_vtab *p){
795 if( p ){
796 amatchFreeRules(p);
797 amatchVCheckClear(p);
798 sqlite3_free(p->zClassName);
799 sqlite3_free(p->zDb);
800 sqlite3_free(p->zCostTab);
801 sqlite3_free(p->zVocabTab);
802 sqlite3_free(p->zVocabWord);
803 sqlite3_free(p->zVocabLang);
804 sqlite3_free(p->zSelf);
805 memset(p, 0, sizeof(*p));
806 sqlite3_free(p);
807 }
808}
809
810/*
811** xDisconnect/xDestroy method for the amatch module.
812*/
813static int amatchDisconnect(sqlite3_vtab *pVtab){
814 amatch_vtab *p = (amatch_vtab*)pVtab;
815 assert( p->nCursor==0 );
816 amatchFree(p);
817 return SQLITE_OK;
818}
819
820/*
821** Check to see if the argument is of the form:
822**
823** KEY = VALUE
824**
825** If it is, return a pointer to the first character of VALUE.
826** If not, return NULL. Spaces around the = are ignored.
827*/
828static const char *amatchValueOfKey(const char *zKey, const char *zStr){
829 int nKey = (int)strlen(zKey);
830 int nStr = (int)strlen(zStr);
831 int i;
832 if( nStr<nKey+1 ) return 0;
833 if( memcmp(zStr, zKey, nKey)!=0 ) return 0;
834 for(i=nKey; isspace((unsigned char)zStr[i]); i++){}
835 if( zStr[i]!='=' ) return 0;
836 i++;
837 while( isspace((unsigned char)zStr[i]) ){ i++; }
838 return zStr+i;
839}
840
841/*
842** xConnect/xCreate method for the amatch module. Arguments are:
843**
844** argv[0] -> module name ("approximate_match")
845** argv[1] -> database name
846** argv[2] -> table name
847** argv[3...] -> arguments
848*/
849static int amatchConnect(
850 sqlite3 *db,
851 void *pAux,
852 int argc, const char *const*argv,
853 sqlite3_vtab **ppVtab,
854 char **pzErr
855){
856 int rc = SQLITE_OK; /* Return code */
857 amatch_vtab *pNew = 0; /* New virtual table */
858 const char *zModule = argv[0];
859 const char *zDb = argv[1];
860 const char *zVal;
861 int i;
862
863 (void)pAux;
864 *ppVtab = 0;
865 pNew = sqlite3_malloc64( sizeof(*pNew) );
866 if( pNew==0 ) return SQLITE_NOMEM;
867 rc = SQLITE_NOMEM;
868 memset(pNew, 0, sizeof(*pNew));
869 pNew->db = db;
870 pNew->zClassName = sqlite3_mprintf("%s", zModule);
871 if( pNew->zClassName==0 ) goto amatchConnectError;
872 pNew->zDb = sqlite3_mprintf("%s", zDb);
873 if( pNew->zDb==0 ) goto amatchConnectError;
874 pNew->zSelf = sqlite3_mprintf("%s", argv[2]);
875 if( pNew->zSelf==0 ) goto amatchConnectError;
876 for(i=3; i<argc; i++){
877 zVal = amatchValueOfKey("vocabulary_table", argv[i]);
878 if( zVal ){
879 sqlite3_free(pNew->zVocabTab);
880 pNew->zVocabTab = amatchDequote(zVal);
881 if( pNew->zVocabTab==0 ) goto amatchConnectError;
882 continue;
883 }
884 zVal = amatchValueOfKey("vocabulary_word", argv[i]);
885 if( zVal ){
886 sqlite3_free(pNew->zVocabWord);
887 pNew->zVocabWord = amatchDequote(zVal);
888 if( pNew->zVocabWord==0 ) goto amatchConnectError;
889 continue;
890 }
891 zVal = amatchValueOfKey("vocabulary_language", argv[i]);
892 if( zVal ){
893 sqlite3_free(pNew->zVocabLang);
894 pNew->zVocabLang = amatchDequote(zVal);
895 if( pNew->zVocabLang==0 ) goto amatchConnectError;
896 continue;
897 }
898 zVal = amatchValueOfKey("edit_distances", argv[i]);
899 if( zVal ){
900 sqlite3_free(pNew->zCostTab);
901 pNew->zCostTab = amatchDequote(zVal);
902 if( pNew->zCostTab==0 ) goto amatchConnectError;
903 continue;
904 }
905 *pzErr = sqlite3_mprintf("unrecognized argument: [%s]\n", argv[i]);
906 amatchFree(pNew);
907 *ppVtab = 0;
908 return SQLITE_ERROR;
909 }
910 rc = SQLITE_OK;
911 if( pNew->zCostTab==0 ){
912 *pzErr = sqlite3_mprintf("no edit_distances table specified");
913 rc = SQLITE_ERROR;
914 }else{
915 rc = amatchLoadRules(db, pNew, pzErr);
916 }
917 if( rc==SQLITE_OK ){
918 sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
919 rc = sqlite3_declare_vtab(db,
920 "CREATE TABLE x(word,distance,language,"
921 "command HIDDEN,nword HIDDEN)"
922 );
923#define AMATCH_COL_WORD 0
924#define AMATCH_COL_DISTANCE 1
925#define AMATCH_COL_LANGUAGE 2
926#define AMATCH_COL_COMMAND 3
927#define AMATCH_COL_NWORD 4
928 }
929 if( rc!=SQLITE_OK ){
930 amatchFree(pNew);
931 }
932 *ppVtab = &pNew->base;
933 return rc;
934
935amatchConnectError:
936 amatchFree(pNew);
937 return rc;
938}
939
940/*
941** Open a new amatch cursor.
942*/
943static int amatchOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
944 amatch_vtab *p = (amatch_vtab*)pVTab;
945 amatch_cursor *pCur;
946 pCur = sqlite3_malloc64( sizeof(*pCur) );
947 if( pCur==0 ) return SQLITE_NOMEM;
948 memset(pCur, 0, sizeof(*pCur));
949 pCur->pVtab = p;
950 *ppCursor = &pCur->base;
951 p->nCursor++;
952 return SQLITE_OK;
953}
954
955/*
956** Free up all the memory allocated by a cursor. Set it rLimit to 0
957** to indicate that it is at EOF.
958*/
959static void amatchClearCursor(amatch_cursor *pCur){
960 amatch_word *pWord, *pNextWord;
961 for(pWord=pCur->pAllWords; pWord; pWord=pNextWord){
962 pNextWord = pWord->pNext;
963 sqlite3_free(pWord);
964 }
965 pCur->pAllWords = 0;
966 sqlite3_free(pCur->zInput);
967 pCur->zInput = 0;
968 sqlite3_free(pCur->zBuf);
969 pCur->zBuf = 0;
970 pCur->nBuf = 0;
971 pCur->pCost = 0;
972 pCur->pWord = 0;
973 pCur->pCurrent = 0;
974 pCur->rLimit = 1000000;
975 pCur->iLang = 0;
976 pCur->nWord = 0;
977}
978
979/*
980** Close a amatch cursor.
981*/
982static int amatchClose(sqlite3_vtab_cursor *cur){
983 amatch_cursor *pCur = (amatch_cursor *)cur;
984 amatchClearCursor(pCur);
985 pCur->pVtab->nCursor--;
986 sqlite3_free(pCur);
987 return SQLITE_OK;
988}
989
990/*
991** Render a 24-bit unsigned integer as a 4-byte base-64 number.
992*/
993static void amatchEncodeInt(int x, char *z){
994 static const char a[] =
995 "0123456789"
996 "ABCDEFGHIJ"
997 "KLMNOPQRST"
998 "UVWXYZ^abc"
999 "defghijklm"
1000 "nopqrstuvw"
1001 "xyz~";
1002 z[0] = a[(x>>18)&0x3f];
1003 z[1] = a[(x>>12)&0x3f];
1004 z[2] = a[(x>>6)&0x3f];
1005 z[3] = a[x&0x3f];
1006}
1007
1008/*
1009** Write the zCost[] field for a amatch_word object
1010*/
1011static void amatchWriteCost(amatch_word *pWord){
1012 amatchEncodeInt(pWord->rCost, pWord->zCost);
1013 amatchEncodeInt(pWord->iSeq, pWord->zCost+4);
1014 pWord->zCost[8] = 0;
1015}
1016
1017/* Circumvent compiler warnings about the use of strcpy() by supplying
1018** our own implementation.
1019*/
1020static void amatchStrcpy(char *dest, const char *src){
1021 while( (*(dest++) = *(src++))!=0 ){}
1022}
1023static void amatchStrcat(char *dest, const char *src){
1024 while( *dest ) dest++;
1025 amatchStrcpy(dest, src);
1026}
1027
1028/*
1029** Add a new amatch_word object to the queue.
1030**
1031** If a prior amatch_word object with the same zWord, and nMatch
1032** already exists, update its rCost (if the new rCost is less) but
1033** otherwise leave it unchanged. Do not add a duplicate.
1034**
1035** Do nothing if the cost exceeds threshold.
1036*/
1037static void amatchAddWord(
1038 amatch_cursor *pCur,
1039 amatch_cost rCost,
1040 int nMatch,
1041 const char *zWordBase,
1042 const char *zWordTail
1043){
1044 amatch_word *pWord;
1045 amatch_avl *pNode;
1046 amatch_avl *pOther;
1047 int nBase, nTail;
1048 char zBuf[4];
1049
1050 if( rCost>pCur->rLimit ){
1051 return;
1052 }
1053 nBase = (int)strlen(zWordBase);
1054 nTail = (int)strlen(zWordTail);
1055 if( nBase+nTail+3>pCur->nBuf ){
1056 pCur->nBuf = nBase+nTail+100;
1057 pCur->zBuf = sqlite3_realloc64(pCur->zBuf, pCur->nBuf);
1058 if( pCur->zBuf==0 ){
1059 pCur->nBuf = 0;
1060 return;
1061 }
1062 }
1063 amatchEncodeInt(nMatch, zBuf);
1064 memcpy(pCur->zBuf, zBuf+2, 2);
1065 memcpy(pCur->zBuf+2, zWordBase, nBase);
1066 memcpy(pCur->zBuf+2+nBase, zWordTail, nTail+1);
1067 pNode = amatchAvlSearch(pCur->pWord, pCur->zBuf);
1068 if( pNode ){
1069 pWord = pNode->pWord;
1070 if( pWord->rCost>rCost ){
1071#ifdef AMATCH_TRACE_1
1072 printf("UPDATE [%s][%.*s^%s] %d (\"%s\" \"%s\")\n",
1073 pWord->zWord+2, pWord->nMatch, pCur->zInput, pCur->zInput,
1074 pWord->rCost, pWord->zWord, pWord->zCost);
1075#endif
1076 amatchAvlRemove(&pCur->pCost, &pWord->sCost);
1077 pWord->rCost = rCost;
1078 amatchWriteCost(pWord);
1079#ifdef AMATCH_TRACE_1
1080 printf(" ---> %d (\"%s\" \"%s\")\n",
1081 pWord->rCost, pWord->zWord, pWord->zCost);
1082#endif
1083 pOther = amatchAvlInsert(&pCur->pCost, &pWord->sCost);
1084 assert( pOther==0 ); (void)pOther;
1085 }
1086 return;
1087 }
1088 pWord = sqlite3_malloc64( sizeof(*pWord) + nBase + nTail );
1089 if( pWord==0 ) return;
1090 memset(pWord, 0, sizeof(*pWord));
1091 pWord->rCost = rCost;
1092 pWord->iSeq = pCur->nWord++;
1093 amatchWriteCost(pWord);
1094 pWord->nMatch = nMatch;
1095 pWord->pNext = pCur->pAllWords;
1096 pCur->pAllWords = pWord;
1097 pWord->sCost.zKey = pWord->zCost;
1098 pWord->sCost.pWord = pWord;
1099 pOther = amatchAvlInsert(&pCur->pCost, &pWord->sCost);
1100 assert( pOther==0 ); (void)pOther;
1101 pWord->sWord.zKey = pWord->zWord;
1102 pWord->sWord.pWord = pWord;
1103 amatchStrcpy(pWord->zWord, pCur->zBuf);
1104 pOther = amatchAvlInsert(&pCur->pWord, &pWord->sWord);
1105 assert( pOther==0 ); (void)pOther;
1106#ifdef AMATCH_TRACE_1
1107 printf("INSERT [%s][%.*s^%s] %d (\"%s\" \"%s\")\n", pWord->zWord+2,
1108 pWord->nMatch, pCur->zInput, pCur->zInput+pWord->nMatch, rCost,
1109 pWord->zWord, pWord->zCost);
1110#endif
1111}
1112
1113
1114/*
1115** Advance a cursor to its next row of output
1116*/
1117static int amatchNext(sqlite3_vtab_cursor *cur){
1118 amatch_cursor *pCur = (amatch_cursor*)cur;
1119 amatch_word *pWord = 0;
1120 amatch_avl *pNode;
1121 int isMatch = 0;
1122 amatch_vtab *p = pCur->pVtab;
1123 sqlite3_int64 nWord;
1124 int rc;
1125 int i;
1126 const char *zW;
1127 amatch_rule *pRule;
1128 char *zBuf = 0;
1129 sqlite3_int64 nBuf = 0;
1130 char zNext[8];
1131 char zNextIn[8];
1132 int nNextIn;
1133
1134 if( p->pVCheck==0 ){
1135 char *zSql;
1136 if( p->zVocabLang && p->zVocabLang[0] ){
1137 zSql = sqlite3_mprintf(
1138 "SELECT \"%w\" FROM \"%w\"",
1139 " WHERE \"%w\">=?1 AND \"%w\"=?2"
1140 " ORDER BY 1",
1141 p->zVocabWord, p->zVocabTab,
1142 p->zVocabWord, p->zVocabLang
1143 );
1144 }else{
1145 zSql = sqlite3_mprintf(
1146 "SELECT \"%w\" FROM \"%w\""
1147 " WHERE \"%w\">=?1"
1148 " ORDER BY 1",
1149 p->zVocabWord, p->zVocabTab,
1150 p->zVocabWord
1151 );
1152 }
1153 rc = sqlite3_prepare_v2(p->db, zSql, -1, &p->pVCheck, 0);
1154 sqlite3_free(zSql);
1155 if( rc ) return rc;
1156 }
1157 sqlite3_bind_int(p->pVCheck, 2, pCur->iLang);
1158
1159 do{
1160 pNode = amatchAvlFirst(pCur->pCost);
1161 if( pNode==0 ){
1162 pWord = 0;
1163 break;
1164 }
1165 pWord = pNode->pWord;
1166 amatchAvlRemove(&pCur->pCost, &pWord->sCost);
1167
1168#ifdef AMATCH_TRACE_1
1169 printf("PROCESS [%s][%.*s^%s] %d (\"%s\" \"%s\")\n",
1170 pWord->zWord+2, pWord->nMatch, pCur->zInput, pCur->zInput+pWord->nMatch,
1171 pWord->rCost, pWord->zWord, pWord->zCost);
1172#endif
1173 nWord = (int)strlen(pWord->zWord+2);
1174 if( nWord+20>nBuf ){
1175 nBuf = nWord+100;
1176 zBuf = sqlite3_realloc64(zBuf, nBuf);
1177 if( zBuf==0 ) return SQLITE_NOMEM;
1178 }
1179 amatchStrcpy(zBuf, pWord->zWord+2);
1180 zNext[0] = 0;
1181 zNextIn[0] = pCur->zInput[pWord->nMatch];
1182 if( zNextIn[0] ){
1183 for(i=1; i<=4 && (pCur->zInput[pWord->nMatch+i]&0xc0)==0x80; i++){
1184 zNextIn[i] = pCur->zInput[pWord->nMatch+i];
1185 }
1186 zNextIn[i] = 0;
1187 nNextIn = i;
1188 }else{
1189 nNextIn = 0;
1190 }
1191
1192 if( zNextIn[0] && zNextIn[0]!='*' ){
1193 sqlite3_reset(p->pVCheck);
1194 amatchStrcat(zBuf, zNextIn);
1195 sqlite3_bind_text(p->pVCheck, 1, zBuf, nWord+nNextIn, SQLITE_STATIC);
1196 rc = sqlite3_step(p->pVCheck);
1197 if( rc==SQLITE_ROW ){
1198 zW = (const char*)sqlite3_column_text(p->pVCheck, 0);
1199 if( zW!=0 && strncmp(zBuf, zW, nWord+nNextIn)==0 ){
1200 amatchAddWord(pCur, pWord->rCost, pWord->nMatch+nNextIn, zBuf, "");
1201 }
1202 }
1203 zBuf[nWord] = 0;
1204 }
1205
1206 while( 1 ){
1207 amatchStrcpy(zBuf+nWord, zNext);
1208 sqlite3_reset(p->pVCheck);
1209 sqlite3_bind_text(p->pVCheck, 1, zBuf, -1, SQLITE_TRANSIENT);
1210 rc = sqlite3_step(p->pVCheck);
1211 if( rc!=SQLITE_ROW ) break;
1212 zW = (const char*)sqlite3_column_text(p->pVCheck, 0);
1213 amatchStrcpy(zBuf+nWord, zNext);
1214 if( zW==0 || strncmp(zW, zBuf, nWord)!=0 ) break;
1215 if( (zNextIn[0]=='*' && zNextIn[1]==0)
1216 || (zNextIn[0]==0 && zW[nWord]==0)
1217 ){
1218 isMatch = 1;
1219 zNextIn[0] = 0;
1220 nNextIn = 0;
1221 break;
1222 }
1223 zNext[0] = zW[nWord];
1224 for(i=1; i<=4 && (zW[nWord+i]&0xc0)==0x80; i++){
1225 zNext[i] = zW[nWord+i];
1226 }
1227 zNext[i] = 0;
1228 zBuf[nWord] = 0;
1229 if( p->rIns>0 ){
1230 amatchAddWord(pCur, pWord->rCost+p->rIns, pWord->nMatch,
1231 zBuf, zNext);
1232 }
1233 if( p->rSub>0 ){
1234 amatchAddWord(pCur, pWord->rCost+p->rSub, pWord->nMatch+nNextIn,
1235 zBuf, zNext);
1236 }
1237 if( p->rIns<0 && p->rSub<0 ) break;
1238 zNext[i-1]++; /* FIX ME */
1239 }
1240 sqlite3_reset(p->pVCheck);
1241
1242 if( p->rDel>0 ){
1243 zBuf[nWord] = 0;
1244 amatchAddWord(pCur, pWord->rCost+p->rDel, pWord->nMatch+nNextIn,
1245 zBuf, "");
1246 }
1247
1248 for(pRule=p->pRule; pRule; pRule=pRule->pNext){
1249 if( pRule->iLang!=pCur->iLang ) continue;
1250 if( strncmp(pRule->zFrom, pCur->zInput+pWord->nMatch, pRule->nFrom)==0 ){
1251 amatchAddWord(pCur, pWord->rCost+pRule->rCost,
1252 pWord->nMatch+pRule->nFrom, pWord->zWord+2, pRule->zTo);
1253 }
1254 }
1255 }while( !isMatch );
1256 pCur->pCurrent = pWord;
1257 sqlite3_free(zBuf);
1258 return SQLITE_OK;
1259}
1260
1261/*
1262** Called to "rewind" a cursor back to the beginning so that
1263** it starts its output over again. Always called at least once
1264** prior to any amatchColumn, amatchRowid, or amatchEof call.
1265*/
1266static int amatchFilter(
1267 sqlite3_vtab_cursor *pVtabCursor,
1268 int idxNum, const char *idxStr,
1269 int argc, sqlite3_value **argv
1270){
1271 amatch_cursor *pCur = (amatch_cursor *)pVtabCursor;
1272 const char *zWord = "*";
1273 int idx;
1274 int rc = SQLITE_OK;
1275
1276 amatchClearCursor(pCur);
1277 idx = 0;
1278 if( idxNum & 1 ){
1279 zWord = (const char*)sqlite3_value_text(argv[0]);
1280 if( zWord==0 ) zWord = "";
1281 idx++;
1282 }
1283 if( idxNum & 2 ){
1284 sqlite3_int64 ii = sqlite3_value_int64(argv[idx]);
1285 pCur->rLimit = (amatch_cost)amatchTruncateInt(ii);
1286 idx++;
1287 }
1288 if( idxNum & 4 ){
1289 sqlite3_int64 ii = sqlite3_value_int64(argv[idx]);
1290 pCur->iLang = (amatch_cost)amatchTruncateInt(ii);
1291 idx++;
1292 }
1293 pCur->zInput = sqlite3_mprintf("%s", zWord);
1294 if( pCur->zInput==0 ) return SQLITE_NOMEM;
1295 if( strlen(pCur->zInput)>AMATCH_MX_WORD ){
1296 pCur->zInput[AMATCH_MX_WORD] = 0;
1297 rc = SQLITE_TOOBIG;
1298 }
1299 amatchAddWord(pCur, 0, 0, "", "");
1300 amatchNext(pVtabCursor);
1301 return rc;
1302}
1303
1304/*
1305** Only the word and distance columns have values. All other columns
1306** return NULL
1307*/
1308static int amatchColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
1309 amatch_cursor *pCur = (amatch_cursor*)cur;
1310 switch( i ){
1311 case AMATCH_COL_WORD: {
1312 sqlite3_result_text(ctx, pCur->pCurrent->zWord+2, -1, SQLITE_STATIC);
1313 break;
1314 }
1315 case AMATCH_COL_DISTANCE: {
1316 sqlite3_result_int(ctx, pCur->pCurrent->rCost);
1317 break;
1318 }
1319 case AMATCH_COL_LANGUAGE: {
1320 sqlite3_result_int(ctx, pCur->iLang);
1321 break;
1322 }
1323 case AMATCH_COL_NWORD: {
1324 sqlite3_result_int(ctx, pCur->nWord);
1325 break;
1326 }
1327 default: {
1328 sqlite3_result_null(ctx);
1329 break;
1330 }
1331 }
1332 return SQLITE_OK;
1333}
1334
1335/*
1336** The rowid.
1337*/
1338static int amatchRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
1339 amatch_cursor *pCur = (amatch_cursor*)cur;
1340 *pRowid = pCur->iRowid;
1341 return SQLITE_OK;
1342}
1343
1344/*
1345** EOF indicator
1346*/
1347static int amatchEof(sqlite3_vtab_cursor *cur){
1348 amatch_cursor *pCur = (amatch_cursor*)cur;
1349 return pCur->pCurrent==0;
1350}
1351
1352/*
1353** Search for terms of these forms:
1354**
1355** (A) word MATCH $str
1356** (B1) distance < $value
1357** (B2) distance <= $value
1358** (C) language == $language
1359**
1360** The distance< and distance<= are both treated as distance<=.
1361** The query plan number is a bit vector:
1362**
1363** bit 1: Term of the form (A) found
1364** bit 2: Term like (B1) or (B2) found
1365** bit 3: Term like (C) found
1366**
1367** If bit-1 is set, $str is always in filter.argv[0]. If bit-2 is set
1368** then $value is in filter.argv[0] if bit-1 is clear and is in
1369** filter.argv[1] if bit-1 is set. If bit-3 is set, then $ruleid is
1370** in filter.argv[0] if bit-1 and bit-2 are both zero, is in
1371** filter.argv[1] if exactly one of bit-1 and bit-2 are set, and is in
1372** filter.argv[2] if both bit-1 and bit-2 are set.
1373*/
1374static int amatchBestIndex(
1375 sqlite3_vtab *tab,
1376 sqlite3_index_info *pIdxInfo
1377){
1378 int iPlan = 0;
1379 int iDistTerm = -1;
1380 int iLangTerm = -1;
1381 int i;
1382 const struct sqlite3_index_constraint *pConstraint;
1383
1384 (void)tab;
1385 pConstraint = pIdxInfo->aConstraint;
1386 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
1387 if( pConstraint->usable==0 ) continue;
1388 if( (iPlan & 1)==0
1389 && pConstraint->iColumn==0
1390 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH
1391 ){
1392 iPlan |= 1;
1393 pIdxInfo->aConstraintUsage[i].argvIndex = 1;
1394 pIdxInfo->aConstraintUsage[i].omit = 1;
1395 }
1396 if( (iPlan & 2)==0
1397 && pConstraint->iColumn==1
1398 && (pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT
1399 || pConstraint->op==SQLITE_INDEX_CONSTRAINT_LE)
1400 ){
1401 iPlan |= 2;
1402 iDistTerm = i;
1403 }
1404 if( (iPlan & 4)==0
1405 && pConstraint->iColumn==2
1406 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ
1407 ){
1408 iPlan |= 4;
1409 pIdxInfo->aConstraintUsage[i].omit = 1;
1410 iLangTerm = i;
1411 }
1412 }
1413 if( iPlan & 2 ){
1414 pIdxInfo->aConstraintUsage[iDistTerm].argvIndex = 1+((iPlan&1)!=0);
1415 }
1416 if( iPlan & 4 ){
1417 int idx = 1;
1418 if( iPlan & 1 ) idx++;
1419 if( iPlan & 2 ) idx++;
1420 pIdxInfo->aConstraintUsage[iLangTerm].argvIndex = idx;
1421 }
1422 pIdxInfo->idxNum = iPlan;
1423 if( pIdxInfo->nOrderBy==1
1424 && pIdxInfo->aOrderBy[0].iColumn==1
1425 && pIdxInfo->aOrderBy[0].desc==0
1426 ){
1427 pIdxInfo->orderByConsumed = 1;
1428 }
1429 pIdxInfo->estimatedCost = (double)10000;
1430
1431 return SQLITE_OK;
1432}
1433
1434/*
1435** The xUpdate() method.
1436**
1437** This implementation disallows DELETE and UPDATE. The only thing
1438** allowed is INSERT into the "command" column.
1439*/
1440static int amatchUpdate(
1441 sqlite3_vtab *pVTab,
1442 int argc,
1443 sqlite3_value **argv,
1444 sqlite_int64 *pRowid
1445){
1446 amatch_vtab *p = (amatch_vtab*)pVTab;
1447 const unsigned char *zCmd;
1448 (void)pRowid;
1449 if( argc==1 ){
1450 pVTab->zErrMsg = sqlite3_mprintf("DELETE from %s is not allowed",
1451 p->zSelf);
1452 return SQLITE_ERROR;
1453 }
1454 if( sqlite3_value_type(argv[0])!=SQLITE_NULL ){
1455 pVTab->zErrMsg = sqlite3_mprintf("UPDATE of %s is not allowed",
1456 p->zSelf);
1457 return SQLITE_ERROR;
1458 }
1459 if( sqlite3_value_type(argv[2+AMATCH_COL_WORD])!=SQLITE_NULL
1460 || sqlite3_value_type(argv[2+AMATCH_COL_DISTANCE])!=SQLITE_NULL
1461 || sqlite3_value_type(argv[2+AMATCH_COL_LANGUAGE])!=SQLITE_NULL
1462 ){
1463 pVTab->zErrMsg = sqlite3_mprintf(
1464 "INSERT INTO %s allowed for column [command] only", p->zSelf);
1465 return SQLITE_ERROR;
1466 }
1467 zCmd = sqlite3_value_text(argv[2+AMATCH_COL_COMMAND]);
1468 if( zCmd==0 ) return SQLITE_OK;
1469
1470 return SQLITE_OK;
1471}
1472
1473/*
1474** A virtual table module that implements the "approximate_match".
1475*/
1476static sqlite3_module amatchModule = {
1477 0, /* iVersion */
1478 amatchConnect, /* xCreate */
1479 amatchConnect, /* xConnect */
1480 amatchBestIndex, /* xBestIndex */
1481 amatchDisconnect, /* xDisconnect */
1482 amatchDisconnect, /* xDestroy */
1483 amatchOpen, /* xOpen - open a cursor */
1484 amatchClose, /* xClose - close a cursor */
1485 amatchFilter, /* xFilter - configure scan constraints */
1486 amatchNext, /* xNext - advance a cursor */
1487 amatchEof, /* xEof - check for end of scan */
1488 amatchColumn, /* xColumn - read data */
1489 amatchRowid, /* xRowid - read data */
1490 amatchUpdate, /* xUpdate */
1491 0, /* xBegin */
1492 0, /* xSync */
1493 0, /* xCommit */
1494 0, /* xRollback */
1495 0, /* xFindMethod */
1496 0, /* xRename */
1497 0, /* xSavepoint */
1498 0, /* xRelease */
1499 0, /* xRollbackTo */
1500 0, /* xShadowName */
1501 0 /* xIntegrity */
1502};
1503
1504#endif /* SQLITE_OMIT_VIRTUALTABLE */
1505
1506/*
1507** Register the amatch virtual table
1508*/
1509#ifdef _WIN32
1510__declspec(dllexport)
1511#endif
1512int sqlite3_amatch_init(
1513 sqlite3 *db,
1514 char **pzErrMsg,
1515 const sqlite3_api_routines *pApi
1516){
1517 int rc = SQLITE_OK;
1518 SQLITE_EXTENSION_INIT2(pApi);
1519 (void)pzErrMsg; /* Not used */
1520#ifndef SQLITE_OMIT_VIRTUALTABLE
1521 rc = sqlite3_create_module(db, "approximate_match", &amatchModule, 0);
1522#endif /* SQLITE_OMIT_VIRTUALTABLE */
1523 return rc;
1524}