spellfix.c 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844
  1. /*
  2. ** 2012 April 10
  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 module implements the spellfix1 VIRTUAL TABLE that can be used
  14. ** to search a large vocabulary for close matches. See separate
  15. ** documentation (http://www.sqlite.org/spellfix1.html) for details.
  16. */
  17. #include "sqlite3ext.h"
  18. SQLITE_EXTENSION_INIT1
  19. #ifndef SQLITE_AMALGAMATION
  20. # include <string.h>
  21. # include <stdio.h>
  22. # include <stdlib.h>
  23. # include <assert.h>
  24. # define ALWAYS(X) 1
  25. # define NEVER(X) 0
  26. typedef unsigned char u8;
  27. typedef unsigned short u16;
  28. # include <ctype.h>
  29. #endif
  30. #ifndef SQLITE_OMIT_VIRTUALTABLE
  31. /*
  32. ** Character classes for ASCII characters:
  33. **
  34. ** 0 '' Silent letters: H W
  35. ** 1 'A' Any vowel: A E I O U (Y)
  36. ** 2 'B' A bilabeal stop or fricative: B F P V W
  37. ** 3 'C' Other fricatives or back stops: C G J K Q S X Z
  38. ** 4 'D' Alveolar stops: D T
  39. ** 5 'H' Letter H at the beginning of a word
  40. ** 6 'L' Glide: L
  41. ** 7 'R' Semivowel: R
  42. ** 8 'M' Nasals: M N
  43. ** 9 'Y' Letter Y at the beginning of a word.
  44. ** 10 '9' Digits: 0 1 2 3 4 5 6 7 8 9
  45. ** 11 ' ' White space
  46. ** 12 '?' Other.
  47. */
  48. #define CCLASS_SILENT 0
  49. #define CCLASS_VOWEL 1
  50. #define CCLASS_B 2
  51. #define CCLASS_C 3
  52. #define CCLASS_D 4
  53. #define CCLASS_H 5
  54. #define CCLASS_L 6
  55. #define CCLASS_R 7
  56. #define CCLASS_M 8
  57. #define CCLASS_Y 9
  58. #define CCLASS_DIGIT 10
  59. #define CCLASS_SPACE 11
  60. #define CCLASS_OTHER 12
  61. /*
  62. ** The following table gives the character class for non-initial ASCII
  63. ** characters.
  64. */
  65. static const unsigned char midClass[] = {
  66. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  67. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  68. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  69. /* */ CCLASS_SPACE, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  70. /* */ CCLASS_SPACE, /* */ CCLASS_SPACE, /* */ CCLASS_OTHER,
  71. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  72. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  73. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  74. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  75. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  76. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_SPACE,
  77. /* ! */ CCLASS_OTHER, /* " */ CCLASS_OTHER, /* # */ CCLASS_OTHER,
  78. /* $ */ CCLASS_OTHER, /* % */ CCLASS_OTHER, /* & */ CCLASS_OTHER,
  79. /* ' */ CCLASS_SILENT, /* ( */ CCLASS_OTHER, /* ) */ CCLASS_OTHER,
  80. /* * */ CCLASS_OTHER, /* + */ CCLASS_OTHER, /* , */ CCLASS_OTHER,
  81. /* - */ CCLASS_OTHER, /* . */ CCLASS_OTHER, /* / */ CCLASS_OTHER,
  82. /* 0 */ CCLASS_DIGIT, /* 1 */ CCLASS_DIGIT, /* 2 */ CCLASS_DIGIT,
  83. /* 3 */ CCLASS_DIGIT, /* 4 */ CCLASS_DIGIT, /* 5 */ CCLASS_DIGIT,
  84. /* 6 */ CCLASS_DIGIT, /* 7 */ CCLASS_DIGIT, /* 8 */ CCLASS_DIGIT,
  85. /* 9 */ CCLASS_DIGIT, /* : */ CCLASS_OTHER, /* ; */ CCLASS_OTHER,
  86. /* < */ CCLASS_OTHER, /* = */ CCLASS_OTHER, /* > */ CCLASS_OTHER,
  87. /* ? */ CCLASS_OTHER, /* @ */ CCLASS_OTHER, /* A */ CCLASS_VOWEL,
  88. /* B */ CCLASS_B, /* C */ CCLASS_C, /* D */ CCLASS_D,
  89. /* E */ CCLASS_VOWEL, /* F */ CCLASS_B, /* G */ CCLASS_C,
  90. /* H */ CCLASS_SILENT, /* I */ CCLASS_VOWEL, /* J */ CCLASS_C,
  91. /* K */ CCLASS_C, /* L */ CCLASS_L, /* M */ CCLASS_M,
  92. /* N */ CCLASS_M, /* O */ CCLASS_VOWEL, /* P */ CCLASS_B,
  93. /* Q */ CCLASS_C, /* R */ CCLASS_R, /* S */ CCLASS_C,
  94. /* T */ CCLASS_D, /* U */ CCLASS_VOWEL, /* V */ CCLASS_B,
  95. /* W */ CCLASS_B, /* X */ CCLASS_C, /* Y */ CCLASS_VOWEL,
  96. /* Z */ CCLASS_C, /* [ */ CCLASS_OTHER, /* \ */ CCLASS_OTHER,
  97. /* ] */ CCLASS_OTHER, /* ^ */ CCLASS_OTHER, /* _ */ CCLASS_OTHER,
  98. /* ` */ CCLASS_OTHER, /* a */ CCLASS_VOWEL, /* b */ CCLASS_B,
  99. /* c */ CCLASS_C, /* d */ CCLASS_D, /* e */ CCLASS_VOWEL,
  100. /* f */ CCLASS_B, /* g */ CCLASS_C, /* h */ CCLASS_SILENT,
  101. /* i */ CCLASS_VOWEL, /* j */ CCLASS_C, /* k */ CCLASS_C,
  102. /* l */ CCLASS_L, /* m */ CCLASS_M, /* n */ CCLASS_M,
  103. /* o */ CCLASS_VOWEL, /* p */ CCLASS_B, /* q */ CCLASS_C,
  104. /* r */ CCLASS_R, /* s */ CCLASS_C, /* t */ CCLASS_D,
  105. /* u */ CCLASS_VOWEL, /* v */ CCLASS_B, /* w */ CCLASS_B,
  106. /* x */ CCLASS_C, /* y */ CCLASS_VOWEL, /* z */ CCLASS_C,
  107. /* { */ CCLASS_OTHER, /* | */ CCLASS_OTHER, /* } */ CCLASS_OTHER,
  108. /* ~ */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  109. };
  110. /*
  111. ** This tables gives the character class for ASCII characters that form the
  112. ** initial character of a word. The only difference from midClass is with
  113. ** the letters H, W, and Y.
  114. */
  115. static const unsigned char initClass[] = {
  116. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  117. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  118. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  119. /* */ CCLASS_SPACE, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  120. /* */ CCLASS_SPACE, /* */ CCLASS_SPACE, /* */ CCLASS_OTHER,
  121. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  122. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  123. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  124. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  125. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  126. /* */ CCLASS_OTHER, /* */ CCLASS_OTHER, /* */ CCLASS_SPACE,
  127. /* ! */ CCLASS_OTHER, /* " */ CCLASS_OTHER, /* # */ CCLASS_OTHER,
  128. /* $ */ CCLASS_OTHER, /* % */ CCLASS_OTHER, /* & */ CCLASS_OTHER,
  129. /* ' */ CCLASS_OTHER, /* ( */ CCLASS_OTHER, /* ) */ CCLASS_OTHER,
  130. /* * */ CCLASS_OTHER, /* + */ CCLASS_OTHER, /* , */ CCLASS_OTHER,
  131. /* - */ CCLASS_OTHER, /* . */ CCLASS_OTHER, /* / */ CCLASS_OTHER,
  132. /* 0 */ CCLASS_DIGIT, /* 1 */ CCLASS_DIGIT, /* 2 */ CCLASS_DIGIT,
  133. /* 3 */ CCLASS_DIGIT, /* 4 */ CCLASS_DIGIT, /* 5 */ CCLASS_DIGIT,
  134. /* 6 */ CCLASS_DIGIT, /* 7 */ CCLASS_DIGIT, /* 8 */ CCLASS_DIGIT,
  135. /* 9 */ CCLASS_DIGIT, /* : */ CCLASS_OTHER, /* ; */ CCLASS_OTHER,
  136. /* < */ CCLASS_OTHER, /* = */ CCLASS_OTHER, /* > */ CCLASS_OTHER,
  137. /* ? */ CCLASS_OTHER, /* @ */ CCLASS_OTHER, /* A */ CCLASS_VOWEL,
  138. /* B */ CCLASS_B, /* C */ CCLASS_C, /* D */ CCLASS_D,
  139. /* E */ CCLASS_VOWEL, /* F */ CCLASS_B, /* G */ CCLASS_C,
  140. /* H */ CCLASS_SILENT, /* I */ CCLASS_VOWEL, /* J */ CCLASS_C,
  141. /* K */ CCLASS_C, /* L */ CCLASS_L, /* M */ CCLASS_M,
  142. /* N */ CCLASS_M, /* O */ CCLASS_VOWEL, /* P */ CCLASS_B,
  143. /* Q */ CCLASS_C, /* R */ CCLASS_R, /* S */ CCLASS_C,
  144. /* T */ CCLASS_D, /* U */ CCLASS_VOWEL, /* V */ CCLASS_B,
  145. /* W */ CCLASS_B, /* X */ CCLASS_C, /* Y */ CCLASS_Y,
  146. /* Z */ CCLASS_C, /* [ */ CCLASS_OTHER, /* \ */ CCLASS_OTHER,
  147. /* ] */ CCLASS_OTHER, /* ^ */ CCLASS_OTHER, /* _ */ CCLASS_OTHER,
  148. /* ` */ CCLASS_OTHER, /* a */ CCLASS_VOWEL, /* b */ CCLASS_B,
  149. /* c */ CCLASS_C, /* d */ CCLASS_D, /* e */ CCLASS_VOWEL,
  150. /* f */ CCLASS_B, /* g */ CCLASS_C, /* h */ CCLASS_SILENT,
  151. /* i */ CCLASS_VOWEL, /* j */ CCLASS_C, /* k */ CCLASS_C,
  152. /* l */ CCLASS_L, /* m */ CCLASS_M, /* n */ CCLASS_M,
  153. /* o */ CCLASS_VOWEL, /* p */ CCLASS_B, /* q */ CCLASS_C,
  154. /* r */ CCLASS_R, /* s */ CCLASS_C, /* t */ CCLASS_D,
  155. /* u */ CCLASS_VOWEL, /* v */ CCLASS_B, /* w */ CCLASS_B,
  156. /* x */ CCLASS_C, /* y */ CCLASS_Y, /* z */ CCLASS_C,
  157. /* { */ CCLASS_OTHER, /* | */ CCLASS_OTHER, /* } */ CCLASS_OTHER,
  158. /* ~ */ CCLASS_OTHER, /* */ CCLASS_OTHER,
  159. };
  160. /*
  161. ** Mapping from the character class number (0-13) to a symbol for each
  162. ** character class. Note that initClass[] can be used to map the class
  163. ** symbol back into the class number.
  164. */
  165. static const unsigned char className[] = ".ABCDHLRMY9 ?";
  166. /*
  167. ** Generate a "phonetic hash" from a string of ASCII characters
  168. ** in zIn[0..nIn-1].
  169. **
  170. ** * Map characters by character class as defined above.
  171. ** * Omit double-letters
  172. ** * Omit vowels beside R and L
  173. ** * Omit T when followed by CH
  174. ** * Omit W when followed by R
  175. ** * Omit D when followed by J or G
  176. ** * Omit K in KN or G in GN at the beginning of a word
  177. **
  178. ** Space to hold the result is obtained from sqlite3_malloc()
  179. **
  180. ** Return NULL if memory allocation fails.
  181. */
  182. static unsigned char *phoneticHash(const unsigned char *zIn, int nIn){
  183. unsigned char *zOut = sqlite3_malloc( nIn + 1 );
  184. int i;
  185. int nOut = 0;
  186. char cPrev = 0x77;
  187. char cPrevX = 0x77;
  188. const unsigned char *aClass = initClass;
  189. if( zOut==0 ) return 0;
  190. if( nIn>2 ){
  191. switch( zIn[0] ){
  192. case 'g':
  193. case 'k': {
  194. if( zIn[1]=='n' ){ zIn++; nIn--; }
  195. break;
  196. }
  197. }
  198. }
  199. for(i=0; i<nIn; i++){
  200. unsigned char c = zIn[i];
  201. if( i+1<nIn ){
  202. if( c=='w' && zIn[i+1]=='r' ) continue;
  203. if( c=='d' && (zIn[i+1]=='j' || zIn[i+1]=='g') ) continue;
  204. if( i+2<nIn ){
  205. if( c=='t' && zIn[i+1]=='c' && zIn[i+2]=='h' ) continue;
  206. }
  207. }
  208. c = aClass[c&0x7f];
  209. if( c==CCLASS_SPACE ) continue;
  210. if( c==CCLASS_OTHER && cPrev!=CCLASS_DIGIT ) continue;
  211. aClass = midClass;
  212. if( c==CCLASS_VOWEL && (cPrevX==CCLASS_R || cPrevX==CCLASS_L) ){
  213. continue; /* No vowels beside L or R */
  214. }
  215. if( (c==CCLASS_R || c==CCLASS_L) && cPrevX==CCLASS_VOWEL ){
  216. nOut--; /* No vowels beside L or R */
  217. }
  218. cPrev = c;
  219. if( c==CCLASS_SILENT ) continue;
  220. cPrevX = c;
  221. c = className[c];
  222. assert( nOut>=0 );
  223. if( nOut==0 || c!=zOut[nOut-1] ) zOut[nOut++] = c;
  224. }
  225. zOut[nOut] = 0;
  226. return zOut;
  227. }
  228. /*
  229. ** This is an SQL function wrapper around phoneticHash(). See
  230. ** the description of phoneticHash() for additional information.
  231. */
  232. static void phoneticHashSqlFunc(
  233. sqlite3_context *context,
  234. int argc,
  235. sqlite3_value **argv
  236. ){
  237. const unsigned char *zIn;
  238. unsigned char *zOut;
  239. zIn = sqlite3_value_text(argv[0]);
  240. if( zIn==0 ) return;
  241. zOut = phoneticHash(zIn, sqlite3_value_bytes(argv[0]));
  242. if( zOut==0 ){
  243. sqlite3_result_error_nomem(context);
  244. }else{
  245. sqlite3_result_text(context, (char*)zOut, -1, sqlite3_free);
  246. }
  247. }
  248. /*
  249. ** Return the character class number for a character given its
  250. ** context.
  251. */
  252. static char characterClass(char cPrev, char c){
  253. return cPrev==0 ? initClass[c&0x7f] : midClass[c&0x7f];
  254. }
  255. /*
  256. ** Return the cost of inserting or deleting character c immediately
  257. ** following character cPrev. If cPrev==0, that means c is the first
  258. ** character of the word.
  259. */
  260. static int insertOrDeleteCost(char cPrev, char c, char cNext){
  261. char classC = characterClass(cPrev, c);
  262. char classCprev;
  263. if( classC==CCLASS_SILENT ){
  264. /* Insert or delete "silent" characters such as H or W */
  265. return 1;
  266. }
  267. if( cPrev==c ){
  268. /* Repeated characters, or miss a repeat */
  269. return 10;
  270. }
  271. if( classC==CCLASS_VOWEL && (cPrev=='r' || cNext=='r') ){
  272. return 20; /* Insert a vowel before or after 'r' */
  273. }
  274. classCprev = characterClass(cPrev, cPrev);
  275. if( classC==classCprev ){
  276. if( classC==CCLASS_VOWEL ){
  277. /* Remove or add a new vowel to a vowel cluster */
  278. return 15;
  279. }else{
  280. /* Remove or add a consonant not in the same class */
  281. return 50;
  282. }
  283. }
  284. /* any other character insertion or deletion */
  285. return 100;
  286. }
  287. /*
  288. ** Divide the insertion cost by this factor when appending to the
  289. ** end of the word.
  290. */
  291. #define FINAL_INS_COST_DIV 4
  292. /*
  293. ** Return the cost of substituting cTo in place of cFrom assuming
  294. ** the previous character is cPrev. If cPrev==0 then cTo is the first
  295. ** character of the word.
  296. */
  297. static int substituteCost(char cPrev, char cFrom, char cTo){
  298. char classFrom, classTo;
  299. if( cFrom==cTo ){
  300. /* Exact match */
  301. return 0;
  302. }
  303. if( cFrom==(cTo^0x20) && ((cTo>='A' && cTo<='Z') || (cTo>='a' && cTo<='z')) ){
  304. /* differ only in case */
  305. return 0;
  306. }
  307. classFrom = characterClass(cPrev, cFrom);
  308. classTo = characterClass(cPrev, cTo);
  309. if( classFrom==classTo ){
  310. /* Same character class */
  311. return 40;
  312. }
  313. if( classFrom>=CCLASS_B && classFrom<=CCLASS_Y
  314. && classTo>=CCLASS_B && classTo<=CCLASS_Y ){
  315. /* Convert from one consonant to another, but in a different class */
  316. return 75;
  317. }
  318. /* Any other subsitution */
  319. return 100;
  320. }
  321. /*
  322. ** Given two strings zA and zB which are pure ASCII, return the cost
  323. ** of transforming zA into zB. If zA ends with '*' assume that it is
  324. ** a prefix of zB and give only minimal penalty for extra characters
  325. ** on the end of zB.
  326. **
  327. ** Smaller numbers mean a closer match.
  328. **
  329. ** Negative values indicate an error:
  330. ** -1 One of the inputs is NULL
  331. ** -2 Non-ASCII characters on input
  332. ** -3 Unable to allocate memory
  333. **
  334. ** If pnMatch is not NULL, then *pnMatch is set to the number of bytes
  335. ** of zB that matched the pattern in zA. If zA does not end with a '*',
  336. ** then this value is always the number of bytes in zB (i.e. strlen(zB)).
  337. ** If zA does end in a '*', then it is the number of bytes in the prefix
  338. ** of zB that was deemed to match zA.
  339. */
  340. static int editdist1(const char *zA, const char *zB, int *pnMatch){
  341. int nA, nB; /* Number of characters in zA[] and zB[] */
  342. int xA, xB; /* Loop counters for zA[] and zB[] */
  343. char cA, cB; /* Current character of zA and zB */
  344. char cAprev, cBprev; /* Previous character of zA and zB */
  345. char cAnext, cBnext; /* Next character in zA and zB */
  346. int d; /* North-west cost value */
  347. int dc = 0; /* North-west character value */
  348. int res; /* Final result */
  349. int *m; /* The cost matrix */
  350. char *cx; /* Corresponding character values */
  351. int *toFree = 0; /* Malloced space */
  352. int mStack[60+15]; /* Stack space to use if not too much is needed */
  353. int nMatch = 0;
  354. /* Early out if either input is NULL */
  355. if( zA==0 || zB==0 ) return -1;
  356. /* Skip any common prefix */
  357. while( zA[0] && zA[0]==zB[0] ){ dc = zA[0]; zA++; zB++; nMatch++; }
  358. if( pnMatch ) *pnMatch = nMatch;
  359. if( zA[0]==0 && zB[0]==0 ) return 0;
  360. #if 0
  361. printf("A=\"%s\" B=\"%s\" dc=%c\n", zA, zB, dc?dc:' ');
  362. #endif
  363. /* Verify input strings and measure their lengths */
  364. for(nA=0; zA[nA]; nA++){
  365. if( zA[nA]&0x80 ) return -2;
  366. }
  367. for(nB=0; zB[nB]; nB++){
  368. if( zB[nB]&0x80 ) return -2;
  369. }
  370. /* Special processing if either string is empty */
  371. if( nA==0 ){
  372. cBprev = dc;
  373. for(xB=res=0; (cB = zB[xB])!=0; xB++){
  374. res += insertOrDeleteCost(cBprev, cB, zB[xB+1])/FINAL_INS_COST_DIV;
  375. cBprev = cB;
  376. }
  377. return res;
  378. }
  379. if( nB==0 ){
  380. cAprev = dc;
  381. for(xA=res=0; (cA = zA[xA])!=0; xA++){
  382. res += insertOrDeleteCost(cAprev, cA, zA[xA+1]);
  383. cAprev = cA;
  384. }
  385. return res;
  386. }
  387. /* A is a prefix of B */
  388. if( zA[0]=='*' && zA[1]==0 ) return 0;
  389. /* Allocate and initialize the Wagner matrix */
  390. if( nB<(sizeof(mStack)*4)/(sizeof(mStack[0])*5) ){
  391. m = mStack;
  392. }else{
  393. m = toFree = sqlite3_malloc( (nB+1)*5*sizeof(m[0])/4 );
  394. if( m==0 ) return -3;
  395. }
  396. cx = (char*)&m[nB+1];
  397. /* Compute the Wagner edit distance */
  398. m[0] = 0;
  399. cx[0] = dc;
  400. cBprev = dc;
  401. for(xB=1; xB<=nB; xB++){
  402. cBnext = zB[xB];
  403. cB = zB[xB-1];
  404. cx[xB] = cB;
  405. m[xB] = m[xB-1] + insertOrDeleteCost(cBprev, cB, cBnext);
  406. cBprev = cB;
  407. }
  408. cAprev = dc;
  409. for(xA=1; xA<=nA; xA++){
  410. int lastA = (xA==nA);
  411. cA = zA[xA-1];
  412. cAnext = zA[xA];
  413. if( cA=='*' && lastA ) break;
  414. d = m[0];
  415. dc = cx[0];
  416. m[0] = d + insertOrDeleteCost(cAprev, cA, cAnext);
  417. cBprev = 0;
  418. for(xB=1; xB<=nB; xB++){
  419. int totalCost, insCost, delCost, subCost, ncx;
  420. cB = zB[xB-1];
  421. cBnext = zB[xB];
  422. /* Cost to insert cB */
  423. insCost = insertOrDeleteCost(cx[xB-1], cB, cBnext);
  424. if( lastA ) insCost /= FINAL_INS_COST_DIV;
  425. /* Cost to delete cA */
  426. delCost = insertOrDeleteCost(cx[xB], cA, cBnext);
  427. /* Cost to substitute cA->cB */
  428. subCost = substituteCost(cx[xB-1], cA, cB);
  429. /* Best cost */
  430. totalCost = insCost + m[xB-1];
  431. ncx = cB;
  432. if( (delCost + m[xB])<totalCost ){
  433. totalCost = delCost + m[xB];
  434. ncx = cA;
  435. }
  436. if( (subCost + d)<totalCost ){
  437. totalCost = subCost + d;
  438. }
  439. #if 0
  440. printf("%d,%d d=%4d u=%4d r=%4d dc=%c cA=%c cB=%c"
  441. " ins=%4d del=%4d sub=%4d t=%4d ncx=%c\n",
  442. xA, xB, d, m[xB], m[xB-1], dc?dc:' ', cA, cB,
  443. insCost, delCost, subCost, totalCost, ncx?ncx:' ');
  444. #endif
  445. /* Update the matrix */
  446. d = m[xB];
  447. dc = cx[xB];
  448. m[xB] = totalCost;
  449. cx[xB] = ncx;
  450. cBprev = cB;
  451. }
  452. cAprev = cA;
  453. }
  454. /* Free the wagner matrix and return the result */
  455. if( cA=='*' ){
  456. res = m[1];
  457. for(xB=1; xB<=nB; xB++){
  458. if( m[xB]<res ){
  459. res = m[xB];
  460. if( pnMatch ) *pnMatch = xB+nMatch;
  461. }
  462. }
  463. }else{
  464. res = m[nB];
  465. /* In the current implementation, pnMatch is always NULL if zA does
  466. ** not end in "*" */
  467. assert( pnMatch==0 );
  468. }
  469. sqlite3_free(toFree);
  470. return res;
  471. }
  472. /*
  473. ** Function: editdist(A,B)
  474. **
  475. ** Return the cost of transforming string A into string B. Both strings
  476. ** must be pure ASCII text. If A ends with '*' then it is assumed to be
  477. ** a prefix of B and extra characters on the end of B have minimal additional
  478. ** cost.
  479. */
  480. static void editdistSqlFunc(
  481. sqlite3_context *context,
  482. int argc,
  483. sqlite3_value **argv
  484. ){
  485. int res = editdist1(
  486. (const char*)sqlite3_value_text(argv[0]),
  487. (const char*)sqlite3_value_text(argv[1]),
  488. 0);
  489. if( res<0 ){
  490. if( res==(-3) ){
  491. sqlite3_result_error_nomem(context);
  492. }else if( res==(-2) ){
  493. sqlite3_result_error(context, "non-ASCII input to editdist()", -1);
  494. }else{
  495. sqlite3_result_error(context, "NULL input to editdist()", -1);
  496. }
  497. }else{
  498. sqlite3_result_int(context, res);
  499. }
  500. }
  501. /* End of the fixed-cost edit distance implementation
  502. ******************************************************************************
  503. *****************************************************************************
  504. ** Begin: Configurable cost unicode edit distance routines
  505. */
  506. /* Forward declaration of structures */
  507. typedef struct EditDist3Cost EditDist3Cost;
  508. typedef struct EditDist3Config EditDist3Config;
  509. typedef struct EditDist3Point EditDist3Point;
  510. typedef struct EditDist3From EditDist3From;
  511. typedef struct EditDist3FromString EditDist3FromString;
  512. typedef struct EditDist3To EditDist3To;
  513. typedef struct EditDist3ToString EditDist3ToString;
  514. typedef struct EditDist3Lang EditDist3Lang;
  515. /*
  516. ** An entry in the edit cost table
  517. */
  518. struct EditDist3Cost {
  519. EditDist3Cost *pNext; /* Next cost element */
  520. u8 nFrom; /* Number of bytes in aFrom */
  521. u8 nTo; /* Number of bytes in aTo */
  522. u16 iCost; /* Cost of this transformation */
  523. char a[4] ; /* FROM string followed by TO string */
  524. /* Additional TO and FROM string bytes appended as necessary */
  525. };
  526. /*
  527. ** Edit costs for a particular language ID
  528. */
  529. struct EditDist3Lang {
  530. int iLang; /* Language ID */
  531. int iInsCost; /* Default insertion cost */
  532. int iDelCost; /* Default deletion cost */
  533. int iSubCost; /* Default substitution cost */
  534. EditDist3Cost *pCost; /* Costs */
  535. };
  536. /*
  537. ** The default EditDist3Lang object, with default costs.
  538. */
  539. static const EditDist3Lang editDist3Lang = { 0, 100, 100, 150, 0 };
  540. /*
  541. ** Complete configuration
  542. */
  543. struct EditDist3Config {
  544. int nLang; /* Number of language IDs. Size of a[] */
  545. EditDist3Lang *a; /* One for each distinct language ID */
  546. };
  547. /*
  548. ** Extra information about each character in the FROM string.
  549. */
  550. struct EditDist3From {
  551. int nSubst; /* Number of substitution cost entries */
  552. int nDel; /* Number of deletion cost entries */
  553. int nByte; /* Number of bytes in this character */
  554. EditDist3Cost **apSubst; /* Array of substitution costs for this element */
  555. EditDist3Cost **apDel; /* Array of deletion cost entries */
  556. };
  557. /*
  558. ** A precompiled FROM string.
  559. *
  560. ** In the common case we expect the FROM string to be reused multiple times.
  561. ** In other words, the common case will be to measure the edit distance
  562. ** from a single origin string to multiple target strings.
  563. */
  564. struct EditDist3FromString {
  565. char *z; /* The complete text of the FROM string */
  566. int n; /* Number of characters in the FROM string */
  567. int isPrefix; /* True if ends with '*' character */
  568. EditDist3From *a; /* Extra info about each char of the FROM string */
  569. };
  570. /*
  571. ** Extra information about each character in the TO string.
  572. */
  573. struct EditDist3To {
  574. int nIns; /* Number of insertion cost entries */
  575. int nByte; /* Number of bytes in this character */
  576. EditDist3Cost **apIns; /* Array of deletion cost entries */
  577. };
  578. /*
  579. ** A precompiled FROM string
  580. */
  581. struct EditDist3ToString {
  582. char *z; /* The complete text of the TO string */
  583. int n; /* Number of characters in the TO string */
  584. EditDist3To *a; /* Extra info about each char of the TO string */
  585. };
  586. /*
  587. ** Clear or delete an instance of the object that records all edit-distance
  588. ** weights.
  589. */
  590. static void editDist3ConfigClear(EditDist3Config *p){
  591. int i;
  592. if( p==0 ) return;
  593. for(i=0; i<p->nLang; i++){
  594. EditDist3Cost *pCost, *pNext;
  595. pCost = p->a[i].pCost;
  596. while( pCost ){
  597. pNext = pCost->pNext;
  598. sqlite3_free(pCost);
  599. pCost = pNext;
  600. }
  601. }
  602. sqlite3_free(p->a);
  603. memset(p, 0, sizeof(*p));
  604. }
  605. static void editDist3ConfigDelete(void *pIn){
  606. EditDist3Config *p = (EditDist3Config*)pIn;
  607. editDist3ConfigClear(p);
  608. sqlite3_free(p);
  609. }
  610. /*
  611. ** Load all edit-distance weights from a table.
  612. */
  613. static int editDist3ConfigLoad(
  614. EditDist3Config *p, /* The edit distance configuration to load */
  615. sqlite3 *db, /* Load from this database */
  616. const char *zTable /* Name of the table from which to load */
  617. ){
  618. sqlite3_stmt *pStmt;
  619. int rc, rc2;
  620. char *zSql;
  621. int iLangPrev = -9999;
  622. EditDist3Lang *pLang = 0;
  623. zSql = sqlite3_mprintf("SELECT iLang, cFrom, cTo, iCost"
  624. " FROM \"%w\" WHERE iLang>=0 ORDER BY iLang", zTable);
  625. if( zSql==0 ) return SQLITE_NOMEM;
  626. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  627. sqlite3_free(zSql);
  628. if( rc ) return rc;
  629. editDist3ConfigClear(p);
  630. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  631. int iLang = sqlite3_column_int(pStmt, 0);
  632. const char *zFrom = (const char*)sqlite3_column_text(pStmt, 1);
  633. int nFrom = zFrom ? sqlite3_column_bytes(pStmt, 1) : 0;
  634. const char *zTo = (const char*)sqlite3_column_text(pStmt, 2);
  635. int nTo = zTo ? sqlite3_column_bytes(pStmt, 2) : 0;
  636. int iCost = sqlite3_column_int(pStmt, 3);
  637. assert( zFrom!=0 || nFrom==0 );
  638. assert( zTo!=0 || nTo==0 );
  639. if( nFrom>100 || nTo>100 ) continue;
  640. if( iCost<0 ) continue;
  641. if( pLang==0 || iLang!=iLangPrev ){
  642. EditDist3Lang *pNew;
  643. pNew = sqlite3_realloc(p->a, (p->nLang+1)*sizeof(p->a[0]));
  644. if( pNew==0 ){ rc = SQLITE_NOMEM; break; }
  645. p->a = pNew;
  646. pLang = &p->a[p->nLang];
  647. p->nLang++;
  648. pLang->iLang = iLang;
  649. pLang->iInsCost = 100;
  650. pLang->iDelCost = 100;
  651. pLang->iSubCost = 150;
  652. pLang->pCost = 0;
  653. iLangPrev = iLang;
  654. }
  655. if( nFrom==1 && zFrom[0]=='?' && nTo==0 ){
  656. pLang->iDelCost = iCost;
  657. }else if( nFrom==0 && nTo==1 && zTo[0]=='?' ){
  658. pLang->iInsCost = iCost;
  659. }else if( nFrom==1 && nTo==1 && zFrom[0]=='?' && zTo[0]=='?' ){
  660. pLang->iSubCost = iCost;
  661. }else{
  662. EditDist3Cost *pCost;
  663. int nExtra = nFrom + nTo - 4;
  664. if( nExtra<0 ) nExtra = 0;
  665. pCost = sqlite3_malloc( sizeof(*pCost) + nExtra );
  666. if( pCost==0 ){ rc = SQLITE_NOMEM; break; }
  667. pCost->nFrom = nFrom;
  668. pCost->nTo = nTo;
  669. pCost->iCost = iCost;
  670. memcpy(pCost->a, zFrom, nFrom);
  671. memcpy(pCost->a + nFrom, zTo, nTo);
  672. pCost->pNext = pLang->pCost;
  673. pLang->pCost = pCost;
  674. }
  675. }
  676. rc2 = sqlite3_finalize(pStmt);
  677. if( rc==SQLITE_OK ) rc = rc2;
  678. return rc;
  679. }
  680. /*
  681. ** Return the length (in bytes) of a utf-8 character. Or return a maximum
  682. ** of N.
  683. */
  684. static int utf8Len(unsigned char c, int N){
  685. int len = 1;
  686. if( c>0x7f ){
  687. if( (c&0xe0)==0xc0 ){
  688. len = 2;
  689. }else if( (c&0xf0)==0xe0 ){
  690. len = 3;
  691. }else{
  692. len = 4;
  693. }
  694. }
  695. if( len>N ) len = N;
  696. return len;
  697. }
  698. /*
  699. ** Return TRUE (non-zero) if the To side of the given cost matches
  700. ** the given string.
  701. */
  702. static int matchTo(EditDist3Cost *p, const char *z, int n){
  703. if( p->nTo>n ) return 0;
  704. if( strncmp(p->a+p->nFrom, z, p->nTo)!=0 ) return 0;
  705. return 1;
  706. }
  707. /*
  708. ** Return TRUE (non-zero) if the From side of the given cost matches
  709. ** the given string.
  710. */
  711. static int matchFrom(EditDist3Cost *p, const char *z, int n){
  712. assert( p->nFrom<=n );
  713. if( strncmp(p->a, z, p->nFrom)!=0 ) return 0;
  714. return 1;
  715. }
  716. /*
  717. ** Return TRUE (non-zero) of the next FROM character and the next TO
  718. ** character are the same.
  719. */
  720. static int matchFromTo(
  721. EditDist3FromString *pStr, /* Left hand string */
  722. int n1, /* Index of comparison character on the left */
  723. const char *z2, /* Right-handl comparison character */
  724. int n2 /* Bytes remaining in z2[] */
  725. ){
  726. int b1 = pStr->a[n1].nByte;
  727. if( b1>n2 ) return 0;
  728. if( memcmp(pStr->z+n1, z2, b1)!=0 ) return 0;
  729. return 1;
  730. }
  731. /*
  732. ** Delete an EditDist3FromString objecct
  733. */
  734. static void editDist3FromStringDelete(EditDist3FromString *p){
  735. int i;
  736. if( p ){
  737. for(i=0; i<p->n; i++){
  738. sqlite3_free(p->a[i].apDel);
  739. sqlite3_free(p->a[i].apSubst);
  740. }
  741. sqlite3_free(p);
  742. }
  743. }
  744. /*
  745. ** Create a EditDist3FromString object.
  746. */
  747. static EditDist3FromString *editDist3FromStringNew(
  748. const EditDist3Lang *pLang,
  749. const char *z,
  750. int n
  751. ){
  752. EditDist3FromString *pStr;
  753. EditDist3Cost *p;
  754. int i;
  755. if( z==0 ) return 0;
  756. if( n<0 ) n = (int)strlen(z);
  757. pStr = sqlite3_malloc( sizeof(*pStr) + sizeof(pStr->a[0])*n + n + 1 );
  758. if( pStr==0 ) return 0;
  759. pStr->a = (EditDist3From*)&pStr[1];
  760. memset(pStr->a, 0, sizeof(pStr->a[0])*n);
  761. pStr->n = n;
  762. pStr->z = (char*)&pStr->a[n];
  763. memcpy(pStr->z, z, n+1);
  764. if( n && z[n-1]=='*' ){
  765. pStr->isPrefix = 1;
  766. n--;
  767. pStr->n--;
  768. pStr->z[n] = 0;
  769. }else{
  770. pStr->isPrefix = 0;
  771. }
  772. for(i=0; i<n; i++){
  773. EditDist3From *pFrom = &pStr->a[i];
  774. memset(pFrom, 0, sizeof(*pFrom));
  775. pFrom->nByte = utf8Len((unsigned char)z[i], n-i);
  776. for(p=pLang->pCost; p; p=p->pNext){
  777. EditDist3Cost **apNew;
  778. if( i+p->nFrom>n ) continue;
  779. if( matchFrom(p, z+i, n-i)==0 ) continue;
  780. if( p->nTo==0 ){
  781. apNew = sqlite3_realloc(pFrom->apDel,
  782. sizeof(*apNew)*(pFrom->nDel+1));
  783. if( apNew==0 ) break;
  784. pFrom->apDel = apNew;
  785. apNew[pFrom->nDel++] = p;
  786. }else{
  787. apNew = sqlite3_realloc(pFrom->apSubst,
  788. sizeof(*apNew)*(pFrom->nSubst+1));
  789. if( apNew==0 ) break;
  790. pFrom->apSubst = apNew;
  791. apNew[pFrom->nSubst++] = p;
  792. }
  793. }
  794. if( p ){
  795. editDist3FromStringDelete(pStr);
  796. pStr = 0;
  797. break;
  798. }
  799. }
  800. return pStr;
  801. }
  802. /*
  803. ** Update entry m[i] such that it is the minimum of its current value
  804. ** and m[j]+iCost.
  805. **
  806. ** If the iCost is 1,000,000 or greater, then consider the cost to be
  807. ** infinite and skip the update.
  808. */
  809. static void updateCost(
  810. unsigned int *m,
  811. int i,
  812. int j,
  813. int iCost
  814. ){
  815. assert( iCost>=0 );
  816. if( iCost<10000 ){
  817. unsigned int b = m[j] + iCost;
  818. if( b<m[i] ) m[i] = b;
  819. }
  820. }
  821. /* Compute the edit distance between two strings.
  822. **
  823. ** If an error occurs, return a negative number which is the error code.
  824. **
  825. ** If pnMatch is not NULL, then *pnMatch is set to the number of characters
  826. ** (not bytes) in z2 that matched the search pattern in *pFrom. If pFrom does
  827. ** not contain the pattern for a prefix-search, then this is always the number
  828. ** of characters in z2. If pFrom does contain a prefix search pattern, then
  829. ** it is the number of characters in the prefix of z2 that was deemed to
  830. ** match pFrom.
  831. */
  832. static int editDist3Core(
  833. EditDist3FromString *pFrom, /* The FROM string */
  834. const char *z2, /* The TO string */
  835. int n2, /* Length of the TO string */
  836. const EditDist3Lang *pLang, /* Edit weights for a particular language ID */
  837. int *pnMatch /* OUT: Characters in matched prefix */
  838. ){
  839. int k, n;
  840. int i1, b1;
  841. int i2, b2;
  842. EditDist3FromString f = *pFrom;
  843. EditDist3To *a2;
  844. unsigned int *m;
  845. int szRow;
  846. EditDist3Cost *p;
  847. int res;
  848. /* allocate the Wagner matrix and the aTo[] array for the TO string */
  849. n = (f.n+1)*(n2+1);
  850. n = (n+1)&~1;
  851. m = sqlite3_malloc( n*sizeof(m[0]) + sizeof(a2[0])*n2 );
  852. if( m==0 ) return -1; /* Out of memory */
  853. a2 = (EditDist3To*)&m[n];
  854. memset(a2, 0, sizeof(a2[0])*n2);
  855. /* Fill in the a1[] matrix for all characters of the TO string */
  856. for(i2=0; i2<n2; i2++){
  857. a2[i2].nByte = utf8Len((unsigned char)z2[i2], n2-i2);
  858. for(p=pLang->pCost; p; p=p->pNext){
  859. EditDist3Cost **apNew;
  860. if( p->nFrom>0 ) continue;
  861. if( i2+p->nTo>n2 ) continue;
  862. if( matchTo(p, z2+i2, n2-i2)==0 ) continue;
  863. a2[i2].nIns++;
  864. apNew = sqlite3_realloc(a2[i2].apIns, sizeof(*apNew)*a2[i2].nIns);
  865. if( apNew==0 ){
  866. res = -1; /* Out of memory */
  867. goto editDist3Abort;
  868. }
  869. a2[i2].apIns = apNew;
  870. a2[i2].apIns[a2[i2].nIns-1] = p;
  871. }
  872. }
  873. /* Prepare to compute the minimum edit distance */
  874. szRow = f.n+1;
  875. memset(m, 0x01, (n2+1)*szRow*sizeof(m[0]));
  876. m[0] = 0;
  877. /* First fill in the top-row of the matrix with FROM deletion costs */
  878. for(i1=0; i1<f.n; i1 += b1){
  879. b1 = f.a[i1].nByte;
  880. updateCost(m, i1+b1, i1, pLang->iDelCost);
  881. for(k=0; k<f.a[i1].nDel; k++){
  882. p = f.a[i1].apDel[k];
  883. updateCost(m, i1+p->nFrom, i1, p->iCost);
  884. }
  885. }
  886. /* Fill in all subsequent rows, top-to-bottom, left-to-right */
  887. for(i2=0; i2<n2; i2 += b2){
  888. int rx; /* Starting index for current row */
  889. int rxp; /* Starting index for previous row */
  890. b2 = a2[i2].nByte;
  891. rx = szRow*(i2+b2);
  892. rxp = szRow*i2;
  893. updateCost(m, rx, rxp, pLang->iInsCost);
  894. for(k=0; k<a2[i2].nIns; k++){
  895. p = a2[i2].apIns[k];
  896. updateCost(m, szRow*(i2+p->nTo), rxp, p->iCost);
  897. }
  898. for(i1=0; i1<f.n; i1+=b1){
  899. int cx; /* Index of current cell */
  900. int cxp; /* Index of cell immediately to the left */
  901. int cxd; /* Index of cell to the left and one row above */
  902. int cxu; /* Index of cell immediately above */
  903. b1 = f.a[i1].nByte;
  904. cxp = rx + i1;
  905. cx = cxp + b1;
  906. cxd = rxp + i1;
  907. cxu = cxd + b1;
  908. updateCost(m, cx, cxp, pLang->iDelCost);
  909. for(k=0; k<f.a[i1].nDel; k++){
  910. p = f.a[i1].apDel[k];
  911. updateCost(m, cxp+p->nFrom, cxp, p->iCost);
  912. }
  913. updateCost(m, cx, cxu, pLang->iInsCost);
  914. if( matchFromTo(&f, i1, z2+i2, n2-i2) ){
  915. updateCost(m, cx, cxd, 0);
  916. }
  917. updateCost(m, cx, cxd, pLang->iSubCost);
  918. for(k=0; k<f.a[i1].nSubst; k++){
  919. p = f.a[i1].apSubst[k];
  920. if( matchTo(p, z2+i2, n2-i2) ){
  921. updateCost(m, cxd+p->nFrom+szRow*p->nTo, cxd, p->iCost);
  922. }
  923. }
  924. }
  925. }
  926. #if 0 /* Enable for debugging */
  927. printf(" ^");
  928. for(i1=0; i1<f.n; i1++) printf(" %c-%2x", f.z[i1], f.z[i1]&0xff);
  929. printf("\n ^:");
  930. for(i1=0; i1<szRow; i1++){
  931. int v = m[i1];
  932. if( v>9999 ) printf(" ****");
  933. else printf(" %4d", v);
  934. }
  935. printf("\n");
  936. for(i2=0; i2<n2; i2++){
  937. printf("%c-%02x:", z2[i2], z2[i2]&0xff);
  938. for(i1=0; i1<szRow; i1++){
  939. int v = m[(i2+1)*szRow+i1];
  940. if( v>9999 ) printf(" ****");
  941. else printf(" %4d", v);
  942. }
  943. printf("\n");
  944. }
  945. #endif
  946. /* Free memory allocations and return the result */
  947. res = (int)m[szRow*(n2+1)-1];
  948. n = n2;
  949. if( f.isPrefix ){
  950. for(i2=1; i2<=n2; i2++){
  951. int b = m[szRow*i2-1];
  952. if( b<=res ){
  953. res = b;
  954. n = i2 - 1;
  955. }
  956. }
  957. }
  958. if( pnMatch ){
  959. int nExtra = 0;
  960. for(k=0; k<n; k++){
  961. if( (z2[k] & 0xc0)==0x80 ) nExtra++;
  962. }
  963. *pnMatch = n - nExtra;
  964. }
  965. editDist3Abort:
  966. for(i2=0; i2<n2; i2++) sqlite3_free(a2[i2].apIns);
  967. sqlite3_free(m);
  968. return res;
  969. }
  970. /*
  971. ** Get an appropriate EditDist3Lang object.
  972. */
  973. static const EditDist3Lang *editDist3FindLang(
  974. EditDist3Config *pConfig,
  975. int iLang
  976. ){
  977. int i;
  978. for(i=0; i<pConfig->nLang; i++){
  979. if( pConfig->a[i].iLang==iLang ) return &pConfig->a[i];
  980. }
  981. return &editDist3Lang;
  982. }
  983. /*
  984. ** Function: editdist3(A,B,iLang)
  985. ** editdist3(tablename)
  986. **
  987. ** Return the cost of transforming string A into string B using edit
  988. ** weights for iLang.
  989. **
  990. ** The second form loads edit weights into memory from a table.
  991. */
  992. static void editDist3SqlFunc(
  993. sqlite3_context *context,
  994. int argc,
  995. sqlite3_value **argv
  996. ){
  997. EditDist3Config *pConfig = (EditDist3Config*)sqlite3_user_data(context);
  998. sqlite3 *db = sqlite3_context_db_handle(context);
  999. int rc;
  1000. if( argc==1 ){
  1001. const char *zTable = (const char*)sqlite3_value_text(argv[0]);
  1002. rc = editDist3ConfigLoad(pConfig, db, zTable);
  1003. if( rc ) sqlite3_result_error_code(context, rc);
  1004. }else{
  1005. const char *zA = (const char*)sqlite3_value_text(argv[0]);
  1006. const char *zB = (const char*)sqlite3_value_text(argv[1]);
  1007. int nA = sqlite3_value_bytes(argv[0]);
  1008. int nB = sqlite3_value_bytes(argv[1]);
  1009. int iLang = argc==3 ? sqlite3_value_int(argv[2]) : 0;
  1010. const EditDist3Lang *pLang = editDist3FindLang(pConfig, iLang);
  1011. EditDist3FromString *pFrom;
  1012. int dist;
  1013. pFrom = editDist3FromStringNew(pLang, zA, nA);
  1014. if( pFrom==0 ){
  1015. sqlite3_result_error_nomem(context);
  1016. return;
  1017. }
  1018. dist = editDist3Core(pFrom, zB, nB, pLang, 0);
  1019. editDist3FromStringDelete(pFrom);
  1020. if( dist==(-1) ){
  1021. sqlite3_result_error_nomem(context);
  1022. }else{
  1023. sqlite3_result_int(context, dist);
  1024. }
  1025. }
  1026. }
  1027. /*
  1028. ** Register the editDist3 function with SQLite
  1029. */
  1030. static int editDist3Install(sqlite3 *db){
  1031. int rc;
  1032. EditDist3Config *pConfig = sqlite3_malloc( sizeof(*pConfig) );
  1033. if( pConfig==0 ) return SQLITE_NOMEM;
  1034. memset(pConfig, 0, sizeof(*pConfig));
  1035. rc = sqlite3_create_function_v2(db, "editdist3",
  1036. 2, SQLITE_UTF8, pConfig, editDist3SqlFunc, 0, 0, 0);
  1037. if( rc==SQLITE_OK ){
  1038. rc = sqlite3_create_function_v2(db, "editdist3",
  1039. 3, SQLITE_UTF8, pConfig, editDist3SqlFunc, 0, 0, 0);
  1040. }
  1041. if( rc==SQLITE_OK ){
  1042. rc = sqlite3_create_function_v2(db, "editdist3",
  1043. 1, SQLITE_UTF8, pConfig, editDist3SqlFunc, 0, 0,
  1044. editDist3ConfigDelete);
  1045. }else{
  1046. sqlite3_free(pConfig);
  1047. }
  1048. return rc;
  1049. }
  1050. /* End configurable cost unicode edit distance routines
  1051. ******************************************************************************
  1052. ******************************************************************************
  1053. ** Begin transliterate unicode-to-ascii implementation
  1054. */
  1055. #if !SQLITE_AMALGAMATION
  1056. /*
  1057. ** This lookup table is used to help decode the first byte of
  1058. ** a multi-byte UTF8 character.
  1059. */
  1060. static const unsigned char sqlite3Utf8Trans1[] = {
  1061. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  1062. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  1063. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  1064. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  1065. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  1066. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  1067. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  1068. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  1069. };
  1070. #endif
  1071. /*
  1072. ** Return the value of the first UTF-8 character in the string.
  1073. */
  1074. static int utf8Read(const unsigned char *z, int n, int *pSize){
  1075. int c, i;
  1076. /* All callers to this routine (in the current implementation)
  1077. ** always have n>0. */
  1078. if( NEVER(n==0) ){
  1079. c = i = 0;
  1080. }else{
  1081. c = z[0];
  1082. i = 1;
  1083. if( c>=0xc0 ){
  1084. c = sqlite3Utf8Trans1[c-0xc0];
  1085. while( i<n && (z[i] & 0xc0)==0x80 ){
  1086. c = (c<<6) + (0x3f & z[i++]);
  1087. }
  1088. }
  1089. }
  1090. *pSize = i;
  1091. return c;
  1092. }
  1093. /*
  1094. ** Return the number of characters in the utf-8 string in the nIn byte
  1095. ** buffer pointed to by zIn.
  1096. */
  1097. static int utf8Charlen(const char *zIn, int nIn){
  1098. int i;
  1099. int nChar = 0;
  1100. for(i=0; i<nIn; nChar++){
  1101. int sz;
  1102. utf8Read((const unsigned char *)&zIn[i], nIn-i, &sz);
  1103. i += sz;
  1104. }
  1105. return nChar;
  1106. }
  1107. /*
  1108. ** Table of translations from unicode characters into ASCII.
  1109. */
  1110. static const struct {
  1111. unsigned short int cFrom;
  1112. unsigned char cTo0, cTo1;
  1113. } translit[] = {
  1114. { 0x00A0, 0x20, 0x00 }, /*   to */
  1115. { 0x00B5, 0x75, 0x00 }, /* µ to u */
  1116. { 0x00C0, 0x41, 0x00 }, /* À to A */
  1117. { 0x00C1, 0x41, 0x00 }, /* Á to A */
  1118. { 0x00C2, 0x41, 0x00 }, /* Â to A */
  1119. { 0x00C3, 0x41, 0x00 }, /* Ã to A */
  1120. { 0x00C4, 0x41, 0x65 }, /* Ä to Ae */
  1121. { 0x00C5, 0x41, 0x61 }, /* Å to Aa */
  1122. { 0x00C6, 0x41, 0x45 }, /* Æ to AE */
  1123. { 0x00C7, 0x43, 0x00 }, /* Ç to C */
  1124. { 0x00C8, 0x45, 0x00 }, /* È to E */
  1125. { 0x00C9, 0x45, 0x00 }, /* É to E */
  1126. { 0x00CA, 0x45, 0x00 }, /* Ê to E */
  1127. { 0x00CB, 0x45, 0x00 }, /* Ë to E */
  1128. { 0x00CC, 0x49, 0x00 }, /* Ì to I */
  1129. { 0x00CD, 0x49, 0x00 }, /* Í to I */
  1130. { 0x00CE, 0x49, 0x00 }, /* Î to I */
  1131. { 0x00CF, 0x49, 0x00 }, /* Ï to I */
  1132. { 0x00D0, 0x44, 0x00 }, /* Ð to D */
  1133. { 0x00D1, 0x4E, 0x00 }, /* Ñ to N */
  1134. { 0x00D2, 0x4F, 0x00 }, /* Ò to O */
  1135. { 0x00D3, 0x4F, 0x00 }, /* Ó to O */
  1136. { 0x00D4, 0x4F, 0x00 }, /* Ô to O */
  1137. { 0x00D5, 0x4F, 0x00 }, /* Õ to O */
  1138. { 0x00D6, 0x4F, 0x65 }, /* Ö to Oe */
  1139. { 0x00D7, 0x78, 0x00 }, /* × to x */
  1140. { 0x00D8, 0x4F, 0x00 }, /* Ø to O */
  1141. { 0x00D9, 0x55, 0x00 }, /* Ù to U */
  1142. { 0x00DA, 0x55, 0x00 }, /* Ú to U */
  1143. { 0x00DB, 0x55, 0x00 }, /* Û to U */
  1144. { 0x00DC, 0x55, 0x65 }, /* Ü to Ue */
  1145. { 0x00DD, 0x59, 0x00 }, /* Ý to Y */
  1146. { 0x00DE, 0x54, 0x68 }, /* Þ to Th */
  1147. { 0x00DF, 0x73, 0x73 }, /* ß to ss */
  1148. { 0x00E0, 0x61, 0x00 }, /* à to a */
  1149. { 0x00E1, 0x61, 0x00 }, /* á to a */
  1150. { 0x00E2, 0x61, 0x00 }, /* â to a */
  1151. { 0x00E3, 0x61, 0x00 }, /* ã to a */
  1152. { 0x00E4, 0x61, 0x65 }, /* ä to ae */
  1153. { 0x00E5, 0x61, 0x61 }, /* å to aa */
  1154. { 0x00E6, 0x61, 0x65 }, /* æ to ae */
  1155. { 0x00E7, 0x63, 0x00 }, /* ç to c */
  1156. { 0x00E8, 0x65, 0x00 }, /* è to e */
  1157. { 0x00E9, 0x65, 0x00 }, /* é to e */
  1158. { 0x00EA, 0x65, 0x00 }, /* ê to e */
  1159. { 0x00EB, 0x65, 0x00 }, /* ë to e */
  1160. { 0x00EC, 0x69, 0x00 }, /* ì to i */
  1161. { 0x00ED, 0x69, 0x00 }, /* í to i */
  1162. { 0x00EE, 0x69, 0x00 }, /* î to i */
  1163. { 0x00EF, 0x69, 0x00 }, /* ï to i */
  1164. { 0x00F0, 0x64, 0x00 }, /* ð to d */
  1165. { 0x00F1, 0x6E, 0x00 }, /* ñ to n */
  1166. { 0x00F2, 0x6F, 0x00 }, /* ò to o */
  1167. { 0x00F3, 0x6F, 0x00 }, /* ó to o */
  1168. { 0x00F4, 0x6F, 0x00 }, /* ô to o */
  1169. { 0x00F5, 0x6F, 0x00 }, /* õ to o */
  1170. { 0x00F6, 0x6F, 0x65 }, /* ö to oe */
  1171. { 0x00F7, 0x3A, 0x00 }, /* ÷ to : */
  1172. { 0x00F8, 0x6F, 0x00 }, /* ø to o */
  1173. { 0x00F9, 0x75, 0x00 }, /* ù to u */
  1174. { 0x00FA, 0x75, 0x00 }, /* ú to u */
  1175. { 0x00FB, 0x75, 0x00 }, /* û to u */
  1176. { 0x00FC, 0x75, 0x65 }, /* ü to ue */
  1177. { 0x00FD, 0x79, 0x00 }, /* ý to y */
  1178. { 0x00FE, 0x74, 0x68 }, /* þ to th */
  1179. { 0x00FF, 0x79, 0x00 }, /* ÿ to y */
  1180. { 0x0100, 0x41, 0x00 }, /* Ā to A */
  1181. { 0x0101, 0x61, 0x00 }, /* ā to a */
  1182. { 0x0102, 0x41, 0x00 }, /* Ă to A */
  1183. { 0x0103, 0x61, 0x00 }, /* ă to a */
  1184. { 0x0104, 0x41, 0x00 }, /* Ą to A */
  1185. { 0x0105, 0x61, 0x00 }, /* ą to a */
  1186. { 0x0106, 0x43, 0x00 }, /* Ć to C */
  1187. { 0x0107, 0x63, 0x00 }, /* ć to c */
  1188. { 0x0108, 0x43, 0x68 }, /* Ĉ to Ch */
  1189. { 0x0109, 0x63, 0x68 }, /* ĉ to ch */
  1190. { 0x010A, 0x43, 0x00 }, /* Ċ to C */
  1191. { 0x010B, 0x63, 0x00 }, /* ċ to c */
  1192. { 0x010C, 0x43, 0x00 }, /* Č to C */
  1193. { 0x010D, 0x63, 0x00 }, /* č to c */
  1194. { 0x010E, 0x44, 0x00 }, /* Ď to D */
  1195. { 0x010F, 0x64, 0x00 }, /* ď to d */
  1196. { 0x0110, 0x44, 0x00 }, /* Đ to D */
  1197. { 0x0111, 0x64, 0x00 }, /* đ to d */
  1198. { 0x0112, 0x45, 0x00 }, /* Ē to E */
  1199. { 0x0113, 0x65, 0x00 }, /* ē to e */
  1200. { 0x0114, 0x45, 0x00 }, /* Ĕ to E */
  1201. { 0x0115, 0x65, 0x00 }, /* ĕ to e */
  1202. { 0x0116, 0x45, 0x00 }, /* Ė to E */
  1203. { 0x0117, 0x65, 0x00 }, /* ė to e */
  1204. { 0x0118, 0x45, 0x00 }, /* Ę to E */
  1205. { 0x0119, 0x65, 0x00 }, /* ę to e */
  1206. { 0x011A, 0x45, 0x00 }, /* Ě to E */
  1207. { 0x011B, 0x65, 0x00 }, /* ě to e */
  1208. { 0x011C, 0x47, 0x68 }, /* Ĝ to Gh */
  1209. { 0x011D, 0x67, 0x68 }, /* ĝ to gh */
  1210. { 0x011E, 0x47, 0x00 }, /* Ğ to G */
  1211. { 0x011F, 0x67, 0x00 }, /* ğ to g */
  1212. { 0x0120, 0x47, 0x00 }, /* Ġ to G */
  1213. { 0x0121, 0x67, 0x00 }, /* ġ to g */
  1214. { 0x0122, 0x47, 0x00 }, /* Ģ to G */
  1215. { 0x0123, 0x67, 0x00 }, /* ģ to g */
  1216. { 0x0124, 0x48, 0x68 }, /* Ĥ to Hh */
  1217. { 0x0125, 0x68, 0x68 }, /* ĥ to hh */
  1218. { 0x0126, 0x48, 0x00 }, /* Ħ to H */
  1219. { 0x0127, 0x68, 0x00 }, /* ħ to h */
  1220. { 0x0128, 0x49, 0x00 }, /* Ĩ to I */
  1221. { 0x0129, 0x69, 0x00 }, /* ĩ to i */
  1222. { 0x012A, 0x49, 0x00 }, /* Ī to I */
  1223. { 0x012B, 0x69, 0x00 }, /* ī to i */
  1224. { 0x012C, 0x49, 0x00 }, /* Ĭ to I */
  1225. { 0x012D, 0x69, 0x00 }, /* ĭ to i */
  1226. { 0x012E, 0x49, 0x00 }, /* Į to I */
  1227. { 0x012F, 0x69, 0x00 }, /* į to i */
  1228. { 0x0130, 0x49, 0x00 }, /* İ to I */
  1229. { 0x0131, 0x69, 0x00 }, /* ı to i */
  1230. { 0x0132, 0x49, 0x4A }, /* IJ to IJ */
  1231. { 0x0133, 0x69, 0x6A }, /* ij to ij */
  1232. { 0x0134, 0x4A, 0x68 }, /* Ĵ to Jh */
  1233. { 0x0135, 0x6A, 0x68 }, /* ĵ to jh */
  1234. { 0x0136, 0x4B, 0x00 }, /* Ķ to K */
  1235. { 0x0137, 0x6B, 0x00 }, /* ķ to k */
  1236. { 0x0138, 0x6B, 0x00 }, /* ĸ to k */
  1237. { 0x0139, 0x4C, 0x00 }, /* Ĺ to L */
  1238. { 0x013A, 0x6C, 0x00 }, /* ĺ to l */
  1239. { 0x013B, 0x4C, 0x00 }, /* Ļ to L */
  1240. { 0x013C, 0x6C, 0x00 }, /* ļ to l */
  1241. { 0x013D, 0x4C, 0x00 }, /* Ľ to L */
  1242. { 0x013E, 0x6C, 0x00 }, /* ľ to l */
  1243. { 0x013F, 0x4C, 0x2E }, /* Ŀ to L. */
  1244. { 0x0140, 0x6C, 0x2E }, /* ŀ to l. */
  1245. { 0x0141, 0x4C, 0x00 }, /* Ł to L */
  1246. { 0x0142, 0x6C, 0x00 }, /* ł to l */
  1247. { 0x0143, 0x4E, 0x00 }, /* Ń to N */
  1248. { 0x0144, 0x6E, 0x00 }, /* ń to n */
  1249. { 0x0145, 0x4E, 0x00 }, /* Ņ to N */
  1250. { 0x0146, 0x6E, 0x00 }, /* ņ to n */
  1251. { 0x0147, 0x4E, 0x00 }, /* Ň to N */
  1252. { 0x0148, 0x6E, 0x00 }, /* ň to n */
  1253. { 0x0149, 0x27, 0x6E }, /* ʼn to 'n */
  1254. { 0x014A, 0x4E, 0x47 }, /* Ŋ to NG */
  1255. { 0x014B, 0x6E, 0x67 }, /* ŋ to ng */
  1256. { 0x014C, 0x4F, 0x00 }, /* Ō to O */
  1257. { 0x014D, 0x6F, 0x00 }, /* ō to o */
  1258. { 0x014E, 0x4F, 0x00 }, /* Ŏ to O */
  1259. { 0x014F, 0x6F, 0x00 }, /* ŏ to o */
  1260. { 0x0150, 0x4F, 0x00 }, /* Ő to O */
  1261. { 0x0151, 0x6F, 0x00 }, /* ő to o */
  1262. { 0x0152, 0x4F, 0x45 }, /* Œ to OE */
  1263. { 0x0153, 0x6F, 0x65 }, /* œ to oe */
  1264. { 0x0154, 0x52, 0x00 }, /* Ŕ to R */
  1265. { 0x0155, 0x72, 0x00 }, /* ŕ to r */
  1266. { 0x0156, 0x52, 0x00 }, /* Ŗ to R */
  1267. { 0x0157, 0x72, 0x00 }, /* ŗ to r */
  1268. { 0x0158, 0x52, 0x00 }, /* Ř to R */
  1269. { 0x0159, 0x72, 0x00 }, /* ř to r */
  1270. { 0x015A, 0x53, 0x00 }, /* Ś to S */
  1271. { 0x015B, 0x73, 0x00 }, /* ś to s */
  1272. { 0x015C, 0x53, 0x68 }, /* Ŝ to Sh */
  1273. { 0x015D, 0x73, 0x68 }, /* ŝ to sh */
  1274. { 0x015E, 0x53, 0x00 }, /* Ş to S */
  1275. { 0x015F, 0x73, 0x00 }, /* ş to s */
  1276. { 0x0160, 0x53, 0x00 }, /* Š to S */
  1277. { 0x0161, 0x73, 0x00 }, /* š to s */
  1278. { 0x0162, 0x54, 0x00 }, /* Ţ to T */
  1279. { 0x0163, 0x74, 0x00 }, /* ţ to t */
  1280. { 0x0164, 0x54, 0x00 }, /* Ť to T */
  1281. { 0x0165, 0x74, 0x00 }, /* ť to t */
  1282. { 0x0166, 0x54, 0x00 }, /* Ŧ to T */
  1283. { 0x0167, 0x74, 0x00 }, /* ŧ to t */
  1284. { 0x0168, 0x55, 0x00 }, /* Ũ to U */
  1285. { 0x0169, 0x75, 0x00 }, /* ũ to u */
  1286. { 0x016A, 0x55, 0x00 }, /* Ū to U */
  1287. { 0x016B, 0x75, 0x00 }, /* ū to u */
  1288. { 0x016C, 0x55, 0x00 }, /* Ŭ to U */
  1289. { 0x016D, 0x75, 0x00 }, /* ŭ to u */
  1290. { 0x016E, 0x55, 0x00 }, /* Ů to U */
  1291. { 0x016F, 0x75, 0x00 }, /* ů to u */
  1292. { 0x0170, 0x55, 0x00 }, /* Ű to U */
  1293. { 0x0171, 0x75, 0x00 }, /* ű to u */
  1294. { 0x0172, 0x55, 0x00 }, /* Ų to U */
  1295. { 0x0173, 0x75, 0x00 }, /* ų to u */
  1296. { 0x0174, 0x57, 0x00 }, /* Ŵ to W */
  1297. { 0x0175, 0x77, 0x00 }, /* ŵ to w */
  1298. { 0x0176, 0x59, 0x00 }, /* Ŷ to Y */
  1299. { 0x0177, 0x79, 0x00 }, /* ŷ to y */
  1300. { 0x0178, 0x59, 0x00 }, /* Ÿ to Y */
  1301. { 0x0179, 0x5A, 0x00 }, /* Ź to Z */
  1302. { 0x017A, 0x7A, 0x00 }, /* ź to z */
  1303. { 0x017B, 0x5A, 0x00 }, /* Ż to Z */
  1304. { 0x017C, 0x7A, 0x00 }, /* ż to z */
  1305. { 0x017D, 0x5A, 0x00 }, /* Ž to Z */
  1306. { 0x017E, 0x7A, 0x00 }, /* ž to z */
  1307. { 0x017F, 0x73, 0x00 }, /* ſ to s */
  1308. { 0x0192, 0x66, 0x00 }, /* ƒ to f */
  1309. { 0x0218, 0x53, 0x00 }, /* Ș to S */
  1310. { 0x0219, 0x73, 0x00 }, /* ș to s */
  1311. { 0x021A, 0x54, 0x00 }, /* Ț to T */
  1312. { 0x021B, 0x74, 0x00 }, /* ț to t */
  1313. { 0x0386, 0x41, 0x00 }, /* Ά to A */
  1314. { 0x0388, 0x45, 0x00 }, /* Έ to E */
  1315. { 0x0389, 0x49, 0x00 }, /* Ή to I */
  1316. { 0x038A, 0x49, 0x00 }, /* Ί to I */
  1317. { 0x038C, 0x4f, 0x00 }, /* Ό to O */
  1318. { 0x038E, 0x59, 0x00 }, /* Ύ to Y */
  1319. { 0x038F, 0x4f, 0x00 }, /* Ώ to O */
  1320. { 0x0390, 0x69, 0x00 }, /* ΐ to i */
  1321. { 0x0391, 0x41, 0x00 }, /* Α to A */
  1322. { 0x0392, 0x42, 0x00 }, /* Β to B */
  1323. { 0x0393, 0x47, 0x00 }, /* Γ to G */
  1324. { 0x0394, 0x44, 0x00 }, /* Δ to D */
  1325. { 0x0395, 0x45, 0x00 }, /* Ε to E */
  1326. { 0x0396, 0x5a, 0x00 }, /* Ζ to Z */
  1327. { 0x0397, 0x49, 0x00 }, /* Η to I */
  1328. { 0x0398, 0x54, 0x68 }, /* Θ to Th */
  1329. { 0x0399, 0x49, 0x00 }, /* Ι to I */
  1330. { 0x039A, 0x4b, 0x00 }, /* Κ to K */
  1331. { 0x039B, 0x4c, 0x00 }, /* Λ to L */
  1332. { 0x039C, 0x4d, 0x00 }, /* Μ to M */
  1333. { 0x039D, 0x4e, 0x00 }, /* Ν to N */
  1334. { 0x039E, 0x58, 0x00 }, /* Ξ to X */
  1335. { 0x039F, 0x4f, 0x00 }, /* Ο to O */
  1336. { 0x03A0, 0x50, 0x00 }, /* Π to P */
  1337. { 0x03A1, 0x52, 0x00 }, /* Ρ to R */
  1338. { 0x03A3, 0x53, 0x00 }, /* Σ to S */
  1339. { 0x03A4, 0x54, 0x00 }, /* Τ to T */
  1340. { 0x03A5, 0x59, 0x00 }, /* Υ to Y */
  1341. { 0x03A6, 0x46, 0x00 }, /* Φ to F */
  1342. { 0x03A7, 0x43, 0x68 }, /* Χ to Ch */
  1343. { 0x03A8, 0x50, 0x73 }, /* Ψ to Ps */
  1344. { 0x03A9, 0x4f, 0x00 }, /* Ω to O */
  1345. { 0x03AA, 0x49, 0x00 }, /* Ϊ to I */
  1346. { 0x03AB, 0x59, 0x00 }, /* Ϋ to Y */
  1347. { 0x03AC, 0x61, 0x00 }, /* ά to a */
  1348. { 0x03AD, 0x65, 0x00 }, /* έ to e */
  1349. { 0x03AE, 0x69, 0x00 }, /* ή to i */
  1350. { 0x03AF, 0x69, 0x00 }, /* ί to i */
  1351. { 0x03B1, 0x61, 0x00 }, /* α to a */
  1352. { 0x03B2, 0x62, 0x00 }, /* β to b */
  1353. { 0x03B3, 0x67, 0x00 }, /* γ to g */
  1354. { 0x03B4, 0x64, 0x00 }, /* δ to d */
  1355. { 0x03B5, 0x65, 0x00 }, /* ε to e */
  1356. { 0x03B6, 0x7a, 0x00 }, /* ζ to z */
  1357. { 0x03B7, 0x69, 0x00 }, /* η to i */
  1358. { 0x03B8, 0x74, 0x68 }, /* θ to th */
  1359. { 0x03B9, 0x69, 0x00 }, /* ι to i */
  1360. { 0x03BA, 0x6b, 0x00 }, /* κ to k */
  1361. { 0x03BB, 0x6c, 0x00 }, /* λ to l */
  1362. { 0x03BC, 0x6d, 0x00 }, /* μ to m */
  1363. { 0x03BD, 0x6e, 0x00 }, /* ν to n */
  1364. { 0x03BE, 0x78, 0x00 }, /* ξ to x */
  1365. { 0x03BF, 0x6f, 0x00 }, /* ο to o */
  1366. { 0x03C0, 0x70, 0x00 }, /* π to p */
  1367. { 0x03C1, 0x72, 0x00 }, /* ρ to r */
  1368. { 0x03C3, 0x73, 0x00 }, /* σ to s */
  1369. { 0x03C4, 0x74, 0x00 }, /* τ to t */
  1370. { 0x03C5, 0x79, 0x00 }, /* υ to y */
  1371. { 0x03C6, 0x66, 0x00 }, /* φ to f */
  1372. { 0x03C7, 0x63, 0x68 }, /* χ to ch */
  1373. { 0x03C8, 0x70, 0x73 }, /* ψ to ps */
  1374. { 0x03C9, 0x6f, 0x00 }, /* ω to o */
  1375. { 0x03CA, 0x69, 0x00 }, /* ϊ to i */
  1376. { 0x03CB, 0x79, 0x00 }, /* ϋ to y */
  1377. { 0x03CC, 0x6f, 0x00 }, /* ό to o */
  1378. { 0x03CD, 0x79, 0x00 }, /* ύ to y */
  1379. { 0x03CE, 0x69, 0x00 }, /* ώ to i */
  1380. { 0x0400, 0x45, 0x00 }, /* Ѐ to E */
  1381. { 0x0401, 0x45, 0x00 }, /* Ё to E */
  1382. { 0x0402, 0x44, 0x00 }, /* Ђ to D */
  1383. { 0x0403, 0x47, 0x00 }, /* Ѓ to G */
  1384. { 0x0404, 0x45, 0x00 }, /* Є to E */
  1385. { 0x0405, 0x5a, 0x00 }, /* Ѕ to Z */
  1386. { 0x0406, 0x49, 0x00 }, /* І to I */
  1387. { 0x0407, 0x49, 0x00 }, /* Ї to I */
  1388. { 0x0408, 0x4a, 0x00 }, /* Ј to J */
  1389. { 0x0409, 0x49, 0x00 }, /* Љ to I */
  1390. { 0x040A, 0x4e, 0x00 }, /* Њ to N */
  1391. { 0x040B, 0x44, 0x00 }, /* Ћ to D */
  1392. { 0x040C, 0x4b, 0x00 }, /* Ќ to K */
  1393. { 0x040D, 0x49, 0x00 }, /* Ѝ to I */
  1394. { 0x040E, 0x55, 0x00 }, /* Ў to U */
  1395. { 0x040F, 0x44, 0x00 }, /* Џ to D */
  1396. { 0x0410, 0x41, 0x00 }, /* А to A */
  1397. { 0x0411, 0x42, 0x00 }, /* Б to B */
  1398. { 0x0412, 0x56, 0x00 }, /* В to V */
  1399. { 0x0413, 0x47, 0x00 }, /* Г to G */
  1400. { 0x0414, 0x44, 0x00 }, /* Д to D */
  1401. { 0x0415, 0x45, 0x00 }, /* Е to E */
  1402. { 0x0416, 0x5a, 0x68 }, /* Ж to Zh */
  1403. { 0x0417, 0x5a, 0x00 }, /* З to Z */
  1404. { 0x0418, 0x49, 0x00 }, /* И to I */
  1405. { 0x0419, 0x49, 0x00 }, /* Й to I */
  1406. { 0x041A, 0x4b, 0x00 }, /* К to K */
  1407. { 0x041B, 0x4c, 0x00 }, /* Л to L */
  1408. { 0x041C, 0x4d, 0x00 }, /* М to M */
  1409. { 0x041D, 0x4e, 0x00 }, /* Н to N */
  1410. { 0x041E, 0x4f, 0x00 }, /* О to O */
  1411. { 0x041F, 0x50, 0x00 }, /* П to P */
  1412. { 0x0420, 0x52, 0x00 }, /* Р to R */
  1413. { 0x0421, 0x53, 0x00 }, /* С to S */
  1414. { 0x0422, 0x54, 0x00 }, /* Т to T */
  1415. { 0x0423, 0x55, 0x00 }, /* У to U */
  1416. { 0x0424, 0x46, 0x00 }, /* Ф to F */
  1417. { 0x0425, 0x4b, 0x68 }, /* Х to Kh */
  1418. { 0x0426, 0x54, 0x63 }, /* Ц to Tc */
  1419. { 0x0427, 0x43, 0x68 }, /* Ч to Ch */
  1420. { 0x0428, 0x53, 0x68 }, /* Ш to Sh */
  1421. { 0x0429, 0x53, 0x68 }, /* Щ to Shch */
  1422. { 0x042A, 0x61, 0x00 }, /* to A */
  1423. { 0x042B, 0x59, 0x00 }, /* Ы to Y */
  1424. { 0x042C, 0x59, 0x00 }, /* to Y */
  1425. { 0x042D, 0x45, 0x00 }, /* Э to E */
  1426. { 0x042E, 0x49, 0x75 }, /* Ю to Iu */
  1427. { 0x042F, 0x49, 0x61 }, /* Я to Ia */
  1428. { 0x0430, 0x61, 0x00 }, /* а to a */
  1429. { 0x0431, 0x62, 0x00 }, /* б to b */
  1430. { 0x0432, 0x76, 0x00 }, /* в to v */
  1431. { 0x0433, 0x67, 0x00 }, /* г to g */
  1432. { 0x0434, 0x64, 0x00 }, /* д to d */
  1433. { 0x0435, 0x65, 0x00 }, /* е to e */
  1434. { 0x0436, 0x7a, 0x68 }, /* ж to zh */
  1435. { 0x0437, 0x7a, 0x00 }, /* з to z */
  1436. { 0x0438, 0x69, 0x00 }, /* и to i */
  1437. { 0x0439, 0x69, 0x00 }, /* й to i */
  1438. { 0x043A, 0x6b, 0x00 }, /* к to k */
  1439. { 0x043B, 0x6c, 0x00 }, /* л to l */
  1440. { 0x043C, 0x6d, 0x00 }, /* м to m */
  1441. { 0x043D, 0x6e, 0x00 }, /* н to n */
  1442. { 0x043E, 0x6f, 0x00 }, /* о to o */
  1443. { 0x043F, 0x70, 0x00 }, /* п to p */
  1444. { 0x0440, 0x72, 0x00 }, /* р to r */
  1445. { 0x0441, 0x73, 0x00 }, /* с to s */
  1446. { 0x0442, 0x74, 0x00 }, /* т to t */
  1447. { 0x0443, 0x75, 0x00 }, /* у to u */
  1448. { 0x0444, 0x66, 0x00 }, /* ф to f */
  1449. { 0x0445, 0x6b, 0x68 }, /* х to kh */
  1450. { 0x0446, 0x74, 0x63 }, /* ц to tc */
  1451. { 0x0447, 0x63, 0x68 }, /* ч to ch */
  1452. { 0x0448, 0x73, 0x68 }, /* ш to sh */
  1453. { 0x0449, 0x73, 0x68 }, /* щ to shch */
  1454. { 0x044A, 0x61, 0x00 }, /* to a */
  1455. { 0x044B, 0x79, 0x00 }, /* ы to y */
  1456. { 0x044C, 0x79, 0x00 }, /* to y */
  1457. { 0x044D, 0x65, 0x00 }, /* э to e */
  1458. { 0x044E, 0x69, 0x75 }, /* ю to iu */
  1459. { 0x044F, 0x69, 0x61 }, /* я to ia */
  1460. { 0x0450, 0x65, 0x00 }, /* ѐ to e */
  1461. { 0x0451, 0x65, 0x00 }, /* ё to e */
  1462. { 0x0452, 0x64, 0x00 }, /* ђ to d */
  1463. { 0x0453, 0x67, 0x00 }, /* ѓ to g */
  1464. { 0x0454, 0x65, 0x00 }, /* є to e */
  1465. { 0x0455, 0x7a, 0x00 }, /* ѕ to z */
  1466. { 0x0456, 0x69, 0x00 }, /* і to i */
  1467. { 0x0457, 0x69, 0x00 }, /* ї to i */
  1468. { 0x0458, 0x6a, 0x00 }, /* ј to j */
  1469. { 0x0459, 0x69, 0x00 }, /* љ to i */
  1470. { 0x045A, 0x6e, 0x00 }, /* њ to n */
  1471. { 0x045B, 0x64, 0x00 }, /* ћ to d */
  1472. { 0x045C, 0x6b, 0x00 }, /* ќ to k */
  1473. { 0x045D, 0x69, 0x00 }, /* ѝ to i */
  1474. { 0x045E, 0x75, 0x00 }, /* ў to u */
  1475. { 0x045F, 0x64, 0x00 }, /* џ to d */
  1476. { 0x1E02, 0x42, 0x00 }, /* Ḃ to B */
  1477. { 0x1E03, 0x62, 0x00 }, /* ḃ to b */
  1478. { 0x1E0A, 0x44, 0x00 }, /* Ḋ to D */
  1479. { 0x1E0B, 0x64, 0x00 }, /* ḋ to d */
  1480. { 0x1E1E, 0x46, 0x00 }, /* Ḟ to F */
  1481. { 0x1E1F, 0x66, 0x00 }, /* ḟ to f */
  1482. { 0x1E40, 0x4D, 0x00 }, /* Ṁ to M */
  1483. { 0x1E41, 0x6D, 0x00 }, /* ṁ to m */
  1484. { 0x1E56, 0x50, 0x00 }, /* Ṗ to P */
  1485. { 0x1E57, 0x70, 0x00 }, /* ṗ to p */
  1486. { 0x1E60, 0x53, 0x00 }, /* Ṡ to S */
  1487. { 0x1E61, 0x73, 0x00 }, /* ṡ to s */
  1488. { 0x1E6A, 0x54, 0x00 }, /* Ṫ to T */
  1489. { 0x1E6B, 0x74, 0x00 }, /* ṫ to t */
  1490. { 0x1E80, 0x57, 0x00 }, /* Ẁ to W */
  1491. { 0x1E81, 0x77, 0x00 }, /* ẁ to w */
  1492. { 0x1E82, 0x57, 0x00 }, /* Ẃ to W */
  1493. { 0x1E83, 0x77, 0x00 }, /* ẃ to w */
  1494. { 0x1E84, 0x57, 0x00 }, /* Ẅ to W */
  1495. { 0x1E85, 0x77, 0x00 }, /* ẅ to w */
  1496. { 0x1EF2, 0x59, 0x00 }, /* Ỳ to Y */
  1497. { 0x1EF3, 0x79, 0x00 }, /* ỳ to y */
  1498. { 0xFB00, 0x66, 0x66 }, /* ff to ff */
  1499. { 0xFB01, 0x66, 0x69 }, /* fi to fi */
  1500. { 0xFB02, 0x66, 0x6C }, /* fl to fl */
  1501. { 0xFB05, 0x73, 0x74 }, /* ſt to st */
  1502. { 0xFB06, 0x73, 0x74 }, /* st to st */
  1503. };
  1504. /*
  1505. ** Convert the input string from UTF-8 into pure ASCII by converting
  1506. ** all non-ASCII characters to some combination of characters in the
  1507. ** ASCII subset.
  1508. **
  1509. ** The returned string might contain more characters than the input.
  1510. **
  1511. ** Space to hold the returned string comes from sqlite3_malloc() and
  1512. ** should be freed by the caller.
  1513. */
  1514. static unsigned char *transliterate(const unsigned char *zIn, int nIn){
  1515. unsigned char *zOut = sqlite3_malloc( nIn*4 + 1 );
  1516. int c, sz, nOut;
  1517. if( zOut==0 ) return 0;
  1518. nOut = 0;
  1519. while( nIn>0 ){
  1520. c = utf8Read(zIn, nIn, &sz);
  1521. zIn += sz;
  1522. nIn -= sz;
  1523. if( c<=127 ){
  1524. zOut[nOut++] = c;
  1525. }else{
  1526. int xTop, xBtm, x;
  1527. xTop = sizeof(translit)/sizeof(translit[0]) - 1;
  1528. xBtm = 0;
  1529. while( xTop>=xBtm ){
  1530. x = (xTop + xBtm)/2;
  1531. if( translit[x].cFrom==c ){
  1532. zOut[nOut++] = translit[x].cTo0;
  1533. if( translit[x].cTo1 ){
  1534. zOut[nOut++] = translit[x].cTo1;
  1535. /* Add an extra "ch" after the "sh" for Щ and щ */
  1536. if( c==0x0429 || c== 0x0449 ){
  1537. zOut[nOut++] = 'c';
  1538. zOut[nOut++] = 'h';
  1539. }
  1540. }
  1541. c = 0;
  1542. break;
  1543. }else if( translit[x].cFrom>c ){
  1544. xTop = x-1;
  1545. }else{
  1546. xBtm = x+1;
  1547. }
  1548. }
  1549. if( c ) zOut[nOut++] = '?';
  1550. }
  1551. }
  1552. zOut[nOut] = 0;
  1553. return zOut;
  1554. }
  1555. /*
  1556. ** Return the number of characters in the shortest prefix of the input
  1557. ** string that transliterates to an ASCII string nTrans bytes or longer.
  1558. ** Or, if the transliteration of the input string is less than nTrans
  1559. ** bytes in size, return the number of characters in the input string.
  1560. */
  1561. static int translen_to_charlen(const char *zIn, int nIn, int nTrans){
  1562. int i, c, sz, nOut;
  1563. int nChar;
  1564. i = nOut = 0;
  1565. for(nChar=0; i<nIn && nOut<nTrans; nChar++){
  1566. c = utf8Read((const unsigned char *)&zIn[i], nIn-i, &sz);
  1567. i += sz;
  1568. nOut++;
  1569. if( c>=128 ){
  1570. int xTop, xBtm, x;
  1571. xTop = sizeof(translit)/sizeof(translit[0]) - 1;
  1572. xBtm = 0;
  1573. while( xTop>=xBtm ){
  1574. x = (xTop + xBtm)/2;
  1575. if( translit[x].cFrom==c ){
  1576. if( translit[x].cTo1 ) nOut++;
  1577. if( c==0x0429 || c== 0x0449 ) nOut += 2;
  1578. break;
  1579. }else if( translit[x].cFrom>c ){
  1580. xTop = x-1;
  1581. }else{
  1582. xBtm = x+1;
  1583. }
  1584. }
  1585. }
  1586. }
  1587. return nChar;
  1588. }
  1589. /*
  1590. ** spellfix1_translit(X)
  1591. **
  1592. ** Convert a string that contains non-ASCII Roman characters into
  1593. ** pure ASCII.
  1594. */
  1595. static void transliterateSqlFunc(
  1596. sqlite3_context *context,
  1597. int argc,
  1598. sqlite3_value **argv
  1599. ){
  1600. const unsigned char *zIn = sqlite3_value_text(argv[0]);
  1601. int nIn = sqlite3_value_bytes(argv[0]);
  1602. unsigned char *zOut = transliterate(zIn, nIn);
  1603. if( zOut==0 ){
  1604. sqlite3_result_error_nomem(context);
  1605. }else{
  1606. sqlite3_result_text(context, (char*)zOut, -1, sqlite3_free);
  1607. }
  1608. }
  1609. /*
  1610. ** spellfix1_scriptcode(X)
  1611. **
  1612. ** Try to determine the dominant script used by the word X and return
  1613. ** its ISO 15924 numeric code.
  1614. **
  1615. ** The current implementation only understands the following scripts:
  1616. **
  1617. ** 215 (Latin)
  1618. ** 220 (Cyrillic)
  1619. ** 200 (Greek)
  1620. **
  1621. ** This routine will return 998 if the input X contains characters from
  1622. ** two or more of the above scripts or 999 if X contains no characters
  1623. ** from any of the above scripts.
  1624. */
  1625. static void scriptCodeSqlFunc(
  1626. sqlite3_context *context,
  1627. int argc,
  1628. sqlite3_value **argv
  1629. ){
  1630. const unsigned char *zIn = sqlite3_value_text(argv[0]);
  1631. int nIn = sqlite3_value_bytes(argv[0]);
  1632. int c, sz;
  1633. int scriptMask = 0;
  1634. int res;
  1635. # define SCRIPT_LATIN 0x0001
  1636. # define SCRIPT_CYRILLIC 0x0002
  1637. # define SCRIPT_GREEK 0x0004
  1638. while( nIn>0 ){
  1639. c = utf8Read(zIn, nIn, &sz);
  1640. zIn += sz;
  1641. nIn -= sz;
  1642. if( c<0x02af ){
  1643. scriptMask |= SCRIPT_LATIN;
  1644. }else if( c>=0x0400 && c<=0x04ff ){
  1645. scriptMask |= SCRIPT_CYRILLIC;
  1646. }else if( c>=0x0386 && c<=0x03ce ){
  1647. scriptMask |= SCRIPT_GREEK;
  1648. }
  1649. }
  1650. switch( scriptMask ){
  1651. case 0: res = 999; break;
  1652. case SCRIPT_LATIN: res = 215; break;
  1653. case SCRIPT_CYRILLIC: res = 220; break;
  1654. case SCRIPT_GREEK: res = 200; break;
  1655. default: res = 998; break;
  1656. }
  1657. sqlite3_result_int(context, res);
  1658. }
  1659. /* End transliterate
  1660. ******************************************************************************
  1661. ******************************************************************************
  1662. ** Begin spellfix1 virtual table.
  1663. */
  1664. /* Maximum length of a phonehash used for querying the shadow table */
  1665. #define SPELLFIX_MX_HASH 8
  1666. /* Maximum number of hash strings to examine per query */
  1667. #define SPELLFIX_MX_RUN 1
  1668. typedef struct spellfix1_vtab spellfix1_vtab;
  1669. typedef struct spellfix1_cursor spellfix1_cursor;
  1670. /* Fuzzy-search virtual table object */
  1671. struct spellfix1_vtab {
  1672. sqlite3_vtab base; /* Base class - must be first */
  1673. sqlite3 *db; /* Database connection */
  1674. char *zDbName; /* Name of database holding this table */
  1675. char *zTableName; /* Name of the virtual table */
  1676. char *zCostTable; /* Table holding edit-distance cost numbers */
  1677. EditDist3Config *pConfig3; /* Parsed edit distance costs */
  1678. };
  1679. /* Fuzzy-search cursor object */
  1680. struct spellfix1_cursor {
  1681. sqlite3_vtab_cursor base; /* Base class - must be first */
  1682. spellfix1_vtab *pVTab; /* The table to which this cursor belongs */
  1683. char *zPattern; /* rhs of MATCH clause */
  1684. int nRow; /* Number of rows of content */
  1685. int nAlloc; /* Number of allocated rows */
  1686. int iRow; /* Current row of content */
  1687. int iLang; /* Value of the langid= constraint */
  1688. int iTop; /* Value of the top= constraint */
  1689. int iScope; /* Value of the scope= constraint */
  1690. int nSearch; /* Number of vocabulary items checked */
  1691. sqlite3_stmt *pFullScan; /* Shadow query for a full table scan */
  1692. struct spellfix1_row { /* For each row of content */
  1693. sqlite3_int64 iRowid; /* Rowid for this row */
  1694. char *zWord; /* Text for this row */
  1695. int iRank; /* Rank for this row */
  1696. int iDistance; /* Distance from pattern for this row */
  1697. int iScore; /* Score for sorting */
  1698. int iMatchlen; /* Value of matchlen column (or -1) */
  1699. char zHash[SPELLFIX_MX_HASH]; /* the phonehash used for this match */
  1700. } *a;
  1701. };
  1702. /*
  1703. ** Construct one or more SQL statements from the format string given
  1704. ** and then evaluate those statements. The success code is written
  1705. ** into *pRc.
  1706. **
  1707. ** If *pRc is initially non-zero then this routine is a no-op.
  1708. */
  1709. static void spellfix1DbExec(
  1710. int *pRc, /* Success code */
  1711. sqlite3 *db, /* Database in which to run SQL */
  1712. const char *zFormat, /* Format string for SQL */
  1713. ... /* Arguments to the format string */
  1714. ){
  1715. va_list ap;
  1716. char *zSql;
  1717. if( *pRc ) return;
  1718. va_start(ap, zFormat);
  1719. zSql = sqlite3_vmprintf(zFormat, ap);
  1720. va_end(ap);
  1721. if( zSql==0 ){
  1722. *pRc = SQLITE_NOMEM;
  1723. }else{
  1724. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  1725. sqlite3_free(zSql);
  1726. }
  1727. }
  1728. /*
  1729. ** xDisconnect/xDestroy method for the fuzzy-search module.
  1730. */
  1731. static int spellfix1Uninit(int isDestroy, sqlite3_vtab *pVTab){
  1732. spellfix1_vtab *p = (spellfix1_vtab*)pVTab;
  1733. int rc = SQLITE_OK;
  1734. if( isDestroy ){
  1735. sqlite3 *db = p->db;
  1736. spellfix1DbExec(&rc, db, "DROP TABLE IF EXISTS \"%w\".\"%w_vocab\"",
  1737. p->zDbName, p->zTableName);
  1738. }
  1739. if( rc==SQLITE_OK ){
  1740. sqlite3_free(p->zTableName);
  1741. editDist3ConfigDelete(p->pConfig3);
  1742. sqlite3_free(p->zCostTable);
  1743. sqlite3_free(p);
  1744. }
  1745. return rc;
  1746. }
  1747. static int spellfix1Disconnect(sqlite3_vtab *pVTab){
  1748. return spellfix1Uninit(0, pVTab);
  1749. }
  1750. static int spellfix1Destroy(sqlite3_vtab *pVTab){
  1751. return spellfix1Uninit(1, pVTab);
  1752. }
  1753. /*
  1754. ** Make a copy of a string. Remove leading and trailing whitespace
  1755. ** and dequote it.
  1756. */
  1757. static char *spellfix1Dequote(const char *zIn){
  1758. char *zOut;
  1759. int i, j;
  1760. char c;
  1761. while( isspace(zIn[0]) ) zIn++;
  1762. zOut = sqlite3_mprintf("%s", zIn);
  1763. if( zOut==0 ) return 0;
  1764. i = (int)strlen(zOut);
  1765. #if 0 /* The parser will never leave spaces at the end */
  1766. while( i>0 && isspace(zOut[i-1]) ){ i--; }
  1767. #endif
  1768. zOut[i] = 0;
  1769. c = zOut[0];
  1770. if( c=='\'' || c=='"' ){
  1771. for(i=1, j=0; ALWAYS(zOut[i]); i++){
  1772. zOut[j++] = zOut[i];
  1773. if( zOut[i]==c ){
  1774. if( zOut[i+1]==c ){
  1775. i++;
  1776. }else{
  1777. zOut[j-1] = 0;
  1778. break;
  1779. }
  1780. }
  1781. }
  1782. }
  1783. return zOut;
  1784. }
  1785. /*
  1786. ** xConnect/xCreate method for the spellfix1 module. Arguments are:
  1787. **
  1788. ** argv[0] -> module name ("spellfix1")
  1789. ** argv[1] -> database name
  1790. ** argv[2] -> table name
  1791. ** argv[3].. -> optional arguments (i.e. "edit_cost_table" parameter)
  1792. */
  1793. static int spellfix1Init(
  1794. int isCreate,
  1795. sqlite3 *db,
  1796. void *pAux,
  1797. int argc, const char *const*argv,
  1798. sqlite3_vtab **ppVTab,
  1799. char **pzErr
  1800. ){
  1801. spellfix1_vtab *pNew = 0;
  1802. const char *zModule = argv[0];
  1803. const char *zDbName = argv[1];
  1804. const char *zTableName = argv[2];
  1805. int nDbName;
  1806. int rc = SQLITE_OK;
  1807. int i;
  1808. nDbName = (int)strlen(zDbName);
  1809. pNew = sqlite3_malloc( sizeof(*pNew) + nDbName + 1);
  1810. if( pNew==0 ){
  1811. rc = SQLITE_NOMEM;
  1812. }else{
  1813. memset(pNew, 0, sizeof(*pNew));
  1814. pNew->zDbName = (char*)&pNew[1];
  1815. memcpy(pNew->zDbName, zDbName, nDbName+1);
  1816. pNew->zTableName = sqlite3_mprintf("%s", zTableName);
  1817. pNew->db = db;
  1818. if( pNew->zTableName==0 ){
  1819. rc = SQLITE_NOMEM;
  1820. }else{
  1821. rc = sqlite3_declare_vtab(db,
  1822. "CREATE TABLE x(word,rank,distance,langid, "
  1823. "score, matchlen, phonehash HIDDEN, "
  1824. "top HIDDEN, scope HIDDEN, srchcnt HIDDEN, "
  1825. "soundslike HIDDEN, command HIDDEN)"
  1826. );
  1827. #define SPELLFIX_COL_WORD 0
  1828. #define SPELLFIX_COL_RANK 1
  1829. #define SPELLFIX_COL_DISTANCE 2
  1830. #define SPELLFIX_COL_LANGID 3
  1831. #define SPELLFIX_COL_SCORE 4
  1832. #define SPELLFIX_COL_MATCHLEN 5
  1833. #define SPELLFIX_COL_PHONEHASH 6
  1834. #define SPELLFIX_COL_TOP 7
  1835. #define SPELLFIX_COL_SCOPE 8
  1836. #define SPELLFIX_COL_SRCHCNT 9
  1837. #define SPELLFIX_COL_SOUNDSLIKE 10
  1838. #define SPELLFIX_COL_COMMAND 11
  1839. }
  1840. if( rc==SQLITE_OK && isCreate ){
  1841. sqlite3_uint64 r;
  1842. spellfix1DbExec(&rc, db,
  1843. "CREATE TABLE IF NOT EXISTS \"%w\".\"%w_vocab\"(\n"
  1844. " id INTEGER PRIMARY KEY,\n"
  1845. " rank INT,\n"
  1846. " langid INT,\n"
  1847. " word TEXT,\n"
  1848. " k1 TEXT,\n"
  1849. " k2 TEXT\n"
  1850. ");\n",
  1851. zDbName, zTableName
  1852. );
  1853. sqlite3_randomness(sizeof(r), &r);
  1854. spellfix1DbExec(&rc, db,
  1855. "CREATE INDEX IF NOT EXISTS \"%w\".\"%w_index_%llx\" "
  1856. "ON \"%w_vocab\"(langid,k2);",
  1857. zDbName, zModule, r, zTableName
  1858. );
  1859. }
  1860. for(i=3; rc==SQLITE_OK && i<argc; i++){
  1861. if( strncmp(argv[i],"edit_cost_table=",16)==0 && pNew->zCostTable==0 ){
  1862. pNew->zCostTable = spellfix1Dequote(&argv[i][16]);
  1863. if( pNew->zCostTable==0 ) rc = SQLITE_NOMEM;
  1864. continue;
  1865. }
  1866. *pzErr = sqlite3_mprintf("bad argument to spellfix1(): \"%s\"", argv[i]);
  1867. rc = SQLITE_ERROR;
  1868. }
  1869. }
  1870. if( rc && pNew ){
  1871. *ppVTab = 0;
  1872. spellfix1Uninit(0, &pNew->base);
  1873. }else{
  1874. *ppVTab = (sqlite3_vtab *)pNew;
  1875. }
  1876. return rc;
  1877. }
  1878. /*
  1879. ** The xConnect and xCreate methods
  1880. */
  1881. static int spellfix1Connect(
  1882. sqlite3 *db,
  1883. void *pAux,
  1884. int argc, const char *const*argv,
  1885. sqlite3_vtab **ppVTab,
  1886. char **pzErr
  1887. ){
  1888. return spellfix1Init(0, db, pAux, argc, argv, ppVTab, pzErr);
  1889. }
  1890. static int spellfix1Create(
  1891. sqlite3 *db,
  1892. void *pAux,
  1893. int argc, const char *const*argv,
  1894. sqlite3_vtab **ppVTab,
  1895. char **pzErr
  1896. ){
  1897. return spellfix1Init(1, db, pAux, argc, argv, ppVTab, pzErr);
  1898. }
  1899. /*
  1900. ** Clear all of the content from a cursor.
  1901. */
  1902. static void spellfix1ResetCursor(spellfix1_cursor *pCur){
  1903. int i;
  1904. for(i=0; i<pCur->nRow; i++){
  1905. sqlite3_free(pCur->a[i].zWord);
  1906. }
  1907. pCur->nRow = 0;
  1908. pCur->iRow = 0;
  1909. pCur->nSearch = 0;
  1910. if( pCur->pFullScan ){
  1911. sqlite3_finalize(pCur->pFullScan);
  1912. pCur->pFullScan = 0;
  1913. }
  1914. }
  1915. /*
  1916. ** Resize the cursor to hold up to N rows of content
  1917. */
  1918. static void spellfix1ResizeCursor(spellfix1_cursor *pCur, int N){
  1919. struct spellfix1_row *aNew;
  1920. assert( N>=pCur->nRow );
  1921. aNew = sqlite3_realloc(pCur->a, sizeof(pCur->a[0])*N);
  1922. if( aNew==0 && N>0 ){
  1923. spellfix1ResetCursor(pCur);
  1924. sqlite3_free(pCur->a);
  1925. pCur->nAlloc = 0;
  1926. pCur->a = 0;
  1927. }else{
  1928. pCur->nAlloc = N;
  1929. pCur->a = aNew;
  1930. }
  1931. }
  1932. /*
  1933. ** Close a fuzzy-search cursor.
  1934. */
  1935. static int spellfix1Close(sqlite3_vtab_cursor *cur){
  1936. spellfix1_cursor *pCur = (spellfix1_cursor *)cur;
  1937. spellfix1ResetCursor(pCur);
  1938. spellfix1ResizeCursor(pCur, 0);
  1939. sqlite3_free(pCur->zPattern);
  1940. sqlite3_free(pCur);
  1941. return SQLITE_OK;
  1942. }
  1943. /*
  1944. ** Search for terms of these forms:
  1945. **
  1946. ** (A) word MATCH $str
  1947. ** (B) langid == $langid
  1948. ** (C) top = $top
  1949. ** (D) scope = $scope
  1950. ** (E) distance < $distance
  1951. ** (F) distance <= $distance
  1952. **
  1953. ** The plan number is a bit mask formed with these bits:
  1954. **
  1955. ** 0x01 (A) is found
  1956. ** 0x02 (B) is found
  1957. ** 0x04 (C) is found
  1958. ** 0x08 (D) is found
  1959. ** 0x10 (E) is found
  1960. ** 0x20 (F) is found
  1961. **
  1962. ** filter.argv[*] values contains $str, $langid, $top, and $scope,
  1963. ** if specified and in that order.
  1964. */
  1965. static int spellfix1BestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  1966. int iPlan = 0;
  1967. int iLangTerm = -1;
  1968. int iTopTerm = -1;
  1969. int iScopeTerm = -1;
  1970. int iDistTerm = -1;
  1971. int i;
  1972. const struct sqlite3_index_constraint *pConstraint;
  1973. pConstraint = pIdxInfo->aConstraint;
  1974. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  1975. if( pConstraint->usable==0 ) continue;
  1976. /* Terms of the form: word MATCH $str */
  1977. if( (iPlan & 1)==0
  1978. && pConstraint->iColumn==SPELLFIX_COL_WORD
  1979. && pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH
  1980. ){
  1981. iPlan |= 1;
  1982. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  1983. pIdxInfo->aConstraintUsage[i].omit = 1;
  1984. }
  1985. /* Terms of the form: langid = $langid */
  1986. if( (iPlan & 2)==0
  1987. && pConstraint->iColumn==SPELLFIX_COL_LANGID
  1988. && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ
  1989. ){
  1990. iPlan |= 2;
  1991. iLangTerm = i;
  1992. }
  1993. /* Terms of the form: top = $top */
  1994. if( (iPlan & 4)==0
  1995. && pConstraint->iColumn==SPELLFIX_COL_TOP
  1996. && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ
  1997. ){
  1998. iPlan |= 4;
  1999. iTopTerm = i;
  2000. }
  2001. /* Terms of the form: scope = $scope */
  2002. if( (iPlan & 8)==0
  2003. && pConstraint->iColumn==SPELLFIX_COL_SCOPE
  2004. && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ
  2005. ){
  2006. iPlan |= 8;
  2007. iScopeTerm = i;
  2008. }
  2009. /* Terms of the form: distance < $dist or distance <= $dist */
  2010. if( (iPlan & (16|32))==0
  2011. && pConstraint->iColumn==SPELLFIX_COL_DISTANCE
  2012. && (pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT
  2013. || pConstraint->op==SQLITE_INDEX_CONSTRAINT_LE)
  2014. ){
  2015. iPlan |= pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT ? 16 : 32;
  2016. iDistTerm = i;
  2017. }
  2018. }
  2019. if( iPlan&1 ){
  2020. int idx = 2;
  2021. pIdxInfo->idxNum = iPlan;
  2022. if( pIdxInfo->nOrderBy==1
  2023. && pIdxInfo->aOrderBy[0].iColumn==SPELLFIX_COL_SCORE
  2024. && pIdxInfo->aOrderBy[0].desc==0
  2025. ){
  2026. pIdxInfo->orderByConsumed = 1; /* Default order by iScore */
  2027. }
  2028. if( iPlan&2 ){
  2029. pIdxInfo->aConstraintUsage[iLangTerm].argvIndex = idx++;
  2030. pIdxInfo->aConstraintUsage[iLangTerm].omit = 1;
  2031. }
  2032. if( iPlan&4 ){
  2033. pIdxInfo->aConstraintUsage[iTopTerm].argvIndex = idx++;
  2034. pIdxInfo->aConstraintUsage[iTopTerm].omit = 1;
  2035. }
  2036. if( iPlan&8 ){
  2037. pIdxInfo->aConstraintUsage[iScopeTerm].argvIndex = idx++;
  2038. pIdxInfo->aConstraintUsage[iScopeTerm].omit = 1;
  2039. }
  2040. if( iPlan&(16|32) ){
  2041. pIdxInfo->aConstraintUsage[iDistTerm].argvIndex = idx++;
  2042. pIdxInfo->aConstraintUsage[iDistTerm].omit = 1;
  2043. }
  2044. pIdxInfo->estimatedCost = 1e5;
  2045. }else{
  2046. pIdxInfo->idxNum = 0;
  2047. pIdxInfo->estimatedCost = 1e50;
  2048. }
  2049. return SQLITE_OK;
  2050. }
  2051. /*
  2052. ** Open a new fuzzy-search cursor.
  2053. */
  2054. static int spellfix1Open(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  2055. spellfix1_vtab *p = (spellfix1_vtab*)pVTab;
  2056. spellfix1_cursor *pCur;
  2057. pCur = sqlite3_malloc( sizeof(*pCur) );
  2058. if( pCur==0 ) return SQLITE_NOMEM;
  2059. memset(pCur, 0, sizeof(*pCur));
  2060. pCur->pVTab = p;
  2061. *ppCursor = &pCur->base;
  2062. return SQLITE_OK;
  2063. }
  2064. /*
  2065. ** Adjust a distance measurement by the words rank in order to show
  2066. ** preference to common words.
  2067. */
  2068. static int spellfix1Score(int iDistance, int iRank){
  2069. int iLog2;
  2070. for(iLog2=0; iRank>0; iLog2++, iRank>>=1){}
  2071. return iDistance + 32 - iLog2;
  2072. }
  2073. /*
  2074. ** Compare two spellfix1_row objects for sorting purposes in qsort() such
  2075. ** that they sort in order of increasing distance.
  2076. */
  2077. static int spellfix1RowCompare(const void *A, const void *B){
  2078. const struct spellfix1_row *a = (const struct spellfix1_row*)A;
  2079. const struct spellfix1_row *b = (const struct spellfix1_row*)B;
  2080. return a->iScore - b->iScore;
  2081. }
  2082. /*
  2083. ** A structure used to pass information from spellfix1FilterForMatch()
  2084. ** into spellfix1RunQuery().
  2085. */
  2086. typedef struct MatchQuery {
  2087. spellfix1_cursor *pCur; /* The cursor being queried */
  2088. sqlite3_stmt *pStmt; /* shadow table query statment */
  2089. char zHash[SPELLFIX_MX_HASH]; /* The current phonehash for zPattern */
  2090. const char *zPattern; /* Transliterated input string */
  2091. int nPattern; /* Length of zPattern */
  2092. EditDist3FromString *pMatchStr3; /* Original unicode string */
  2093. EditDist3Config *pConfig3; /* Edit-distance cost coefficients */
  2094. const EditDist3Lang *pLang; /* The selected language coefficients */
  2095. int iLang; /* The language id */
  2096. int iScope; /* Default scope */
  2097. int iMaxDist; /* Maximum allowed edit distance, or -1 */
  2098. int rc; /* Error code */
  2099. int nRun; /* Number of prior runs for the same zPattern */
  2100. char azPrior[SPELLFIX_MX_RUN][SPELLFIX_MX_HASH]; /* Prior hashes */
  2101. } MatchQuery;
  2102. /*
  2103. ** Run a query looking for the best matches against zPattern using
  2104. ** zHash as the character class seed hash.
  2105. */
  2106. static void spellfix1RunQuery(MatchQuery *p, const char *zQuery, int nQuery){
  2107. const char *zK1;
  2108. const char *zWord;
  2109. int iDist;
  2110. int iRank;
  2111. int iScore;
  2112. int iWorst = 0;
  2113. int idx;
  2114. int idxWorst = -1;
  2115. int i;
  2116. int iScope = p->iScope;
  2117. spellfix1_cursor *pCur = p->pCur;
  2118. sqlite3_stmt *pStmt = p->pStmt;
  2119. char zHash1[SPELLFIX_MX_HASH];
  2120. char zHash2[SPELLFIX_MX_HASH];
  2121. char *zClass;
  2122. int nClass;
  2123. int rc;
  2124. if( pCur->a==0 || p->rc ) return; /* Prior memory allocation failure */
  2125. zClass = (char*)phoneticHash((unsigned char*)zQuery, nQuery);
  2126. if( zClass==0 ){
  2127. p->rc = SQLITE_NOMEM;
  2128. return;
  2129. }
  2130. nClass = (int)strlen(zClass);
  2131. if( nClass>SPELLFIX_MX_HASH-2 ){
  2132. nClass = SPELLFIX_MX_HASH-2;
  2133. zClass[nClass] = 0;
  2134. }
  2135. if( nClass<=iScope ){
  2136. if( nClass>2 ){
  2137. iScope = nClass-1;
  2138. }else{
  2139. iScope = nClass;
  2140. }
  2141. }
  2142. memcpy(zHash1, zClass, iScope);
  2143. sqlite3_free(zClass);
  2144. zHash1[iScope] = 0;
  2145. memcpy(zHash2, zHash1, iScope);
  2146. zHash2[iScope] = 'Z';
  2147. zHash2[iScope+1] = 0;
  2148. #if SPELLFIX_MX_RUN>1
  2149. for(i=0; i<p->nRun; i++){
  2150. if( strcmp(p->azPrior[i], zHash1)==0 ) return;
  2151. }
  2152. #endif
  2153. assert( p->nRun<SPELLFIX_MX_RUN );
  2154. memcpy(p->azPrior[p->nRun++], zHash1, iScope+1);
  2155. if( sqlite3_bind_text(pStmt, 1, zHash1, -1, SQLITE_STATIC)==SQLITE_NOMEM
  2156. || sqlite3_bind_text(pStmt, 2, zHash2, -1, SQLITE_STATIC)==SQLITE_NOMEM
  2157. ){
  2158. p->rc = SQLITE_NOMEM;
  2159. return;
  2160. }
  2161. #if SPELLFIX_MX_RUN>1
  2162. for(i=0; i<pCur->nRow; i++){
  2163. if( pCur->a[i].iScore>iWorst ){
  2164. iWorst = pCur->a[i].iScore;
  2165. idxWorst = i;
  2166. }
  2167. }
  2168. #endif
  2169. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  2170. int iMatchlen = -1;
  2171. iRank = sqlite3_column_int(pStmt, 2);
  2172. if( p->pMatchStr3 ){
  2173. int nWord = sqlite3_column_bytes(pStmt, 1);
  2174. zWord = (const char*)sqlite3_column_text(pStmt, 1);
  2175. iDist = editDist3Core(p->pMatchStr3, zWord, nWord, p->pLang, &iMatchlen);
  2176. }else{
  2177. zK1 = (const char*)sqlite3_column_text(pStmt, 3);
  2178. if( zK1==0 ) continue;
  2179. iDist = editdist1(p->zPattern, zK1, 0);
  2180. }
  2181. if( iDist<0 ){
  2182. p->rc = SQLITE_NOMEM;
  2183. break;
  2184. }
  2185. pCur->nSearch++;
  2186. iScore = spellfix1Score(iDist,iRank);
  2187. if( p->iMaxDist>=0 ){
  2188. if( iDist>p->iMaxDist ) continue;
  2189. if( pCur->nRow>=pCur->nAlloc-1 ){
  2190. spellfix1ResizeCursor(pCur, pCur->nAlloc*2 + 10);
  2191. if( pCur->a==0 ) break;
  2192. }
  2193. idx = pCur->nRow;
  2194. }else if( pCur->nRow<pCur->nAlloc ){
  2195. idx = pCur->nRow;
  2196. }else if( iScore<iWorst ){
  2197. idx = idxWorst;
  2198. sqlite3_free(pCur->a[idx].zWord);
  2199. }else{
  2200. continue;
  2201. }
  2202. pCur->a[idx].zWord = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
  2203. if( pCur->a[idx].zWord==0 ){
  2204. p->rc = SQLITE_NOMEM;
  2205. break;
  2206. }
  2207. pCur->a[idx].iRowid = sqlite3_column_int64(pStmt, 0);
  2208. pCur->a[idx].iRank = iRank;
  2209. pCur->a[idx].iDistance = iDist;
  2210. pCur->a[idx].iScore = iScore;
  2211. pCur->a[idx].iMatchlen = iMatchlen;
  2212. memcpy(pCur->a[idx].zHash, zHash1, iScope+1);
  2213. if( pCur->nRow<pCur->nAlloc ) pCur->nRow++;
  2214. if( pCur->nRow==pCur->nAlloc ){
  2215. iWorst = pCur->a[0].iScore;
  2216. idxWorst = 0;
  2217. for(i=1; i<pCur->nRow; i++){
  2218. iScore = pCur->a[i].iScore;
  2219. if( iWorst<iScore ){
  2220. iWorst = iScore;
  2221. idxWorst = i;
  2222. }
  2223. }
  2224. }
  2225. }
  2226. rc = sqlite3_reset(pStmt);
  2227. if( rc ) p->rc = rc;
  2228. }
  2229. /*
  2230. ** This version of the xFilter method work if the MATCH term is present
  2231. ** and we are doing a scan.
  2232. */
  2233. static int spellfix1FilterForMatch(
  2234. spellfix1_cursor *pCur,
  2235. int idxNum,
  2236. int argc,
  2237. sqlite3_value **argv
  2238. ){
  2239. const unsigned char *zMatchThis; /* RHS of the MATCH operator */
  2240. EditDist3FromString *pMatchStr3 = 0; /* zMatchThis as an editdist string */
  2241. char *zPattern; /* Transliteration of zMatchThis */
  2242. int nPattern; /* Length of zPattern */
  2243. int iLimit = 20; /* Max number of rows of output */
  2244. int iScope = 3; /* Use this many characters of zClass */
  2245. int iLang = 0; /* Language code */
  2246. char *zSql; /* SQL of shadow table query */
  2247. sqlite3_stmt *pStmt = 0; /* Shadow table query */
  2248. int rc; /* Result code */
  2249. int idx = 1; /* Next available filter parameter */
  2250. spellfix1_vtab *p = pCur->pVTab; /* The virtual table that owns pCur */
  2251. MatchQuery x; /* For passing info to RunQuery() */
  2252. /* Load the cost table if we have not already done so */
  2253. if( p->zCostTable!=0 && p->pConfig3==0 ){
  2254. p->pConfig3 = sqlite3_malloc( sizeof(p->pConfig3[0]) );
  2255. if( p->pConfig3==0 ) return SQLITE_NOMEM;
  2256. memset(p->pConfig3, 0, sizeof(p->pConfig3[0]));
  2257. rc = editDist3ConfigLoad(p->pConfig3, p->db, p->zCostTable);
  2258. if( rc ) return rc;
  2259. }
  2260. memset(&x, 0, sizeof(x));
  2261. x.iScope = 3; /* Default scope if none specified by "WHERE scope=N" */
  2262. x.iMaxDist = -1; /* Maximum allowed edit distance */
  2263. if( idxNum&2 ){
  2264. iLang = sqlite3_value_int(argv[idx++]);
  2265. }
  2266. if( idxNum&4 ){
  2267. iLimit = sqlite3_value_int(argv[idx++]);
  2268. if( iLimit<1 ) iLimit = 1;
  2269. }
  2270. if( idxNum&8 ){
  2271. x.iScope = sqlite3_value_int(argv[idx++]);
  2272. if( x.iScope<1 ) x.iScope = 1;
  2273. if( x.iScope>SPELLFIX_MX_HASH-2 ) x.iScope = SPELLFIX_MX_HASH-2;
  2274. }
  2275. if( idxNum&(16|32) ){
  2276. x.iMaxDist = sqlite3_value_int(argv[idx++]);
  2277. if( idxNum&16 ) x.iMaxDist--;
  2278. if( x.iMaxDist<0 ) x.iMaxDist = 0;
  2279. }
  2280. spellfix1ResetCursor(pCur);
  2281. spellfix1ResizeCursor(pCur, iLimit);
  2282. zMatchThis = sqlite3_value_text(argv[0]);
  2283. if( zMatchThis==0 ) return SQLITE_OK;
  2284. if( p->pConfig3 ){
  2285. x.pLang = editDist3FindLang(p->pConfig3, iLang);
  2286. pMatchStr3 = editDist3FromStringNew(x.pLang, (const char*)zMatchThis, -1);
  2287. if( pMatchStr3==0 ){
  2288. x.rc = SQLITE_NOMEM;
  2289. goto filter_exit;
  2290. }
  2291. }else{
  2292. x.pLang = 0;
  2293. }
  2294. zPattern = (char*)transliterate(zMatchThis, sqlite3_value_bytes(argv[0]));
  2295. sqlite3_free(pCur->zPattern);
  2296. pCur->zPattern = zPattern;
  2297. if( zPattern==0 ){
  2298. x.rc = SQLITE_NOMEM;
  2299. goto filter_exit;
  2300. }
  2301. nPattern = (int)strlen(zPattern);
  2302. if( zPattern[nPattern-1]=='*' ) nPattern--;
  2303. zSql = sqlite3_mprintf(
  2304. "SELECT id, word, rank, k1"
  2305. " FROM \"%w\".\"%w_vocab\""
  2306. " WHERE langid=%d AND k2>=?1 AND k2<?2",
  2307. p->zDbName, p->zTableName, iLang
  2308. );
  2309. if( zSql==0 ){
  2310. x.rc = SQLITE_NOMEM;
  2311. pStmt = 0;
  2312. goto filter_exit;
  2313. }
  2314. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  2315. sqlite3_free(zSql);
  2316. pCur->iLang = iLang;
  2317. x.pCur = pCur;
  2318. x.pStmt = pStmt;
  2319. x.zPattern = zPattern;
  2320. x.nPattern = nPattern;
  2321. x.pMatchStr3 = pMatchStr3;
  2322. x.iLang = iLang;
  2323. x.rc = rc;
  2324. x.pConfig3 = p->pConfig3;
  2325. if( x.rc==SQLITE_OK ){
  2326. spellfix1RunQuery(&x, zPattern, nPattern);
  2327. }
  2328. if( pCur->a ){
  2329. qsort(pCur->a, pCur->nRow, sizeof(pCur->a[0]), spellfix1RowCompare);
  2330. pCur->iTop = iLimit;
  2331. pCur->iScope = iScope;
  2332. }else{
  2333. x.rc = SQLITE_NOMEM;
  2334. }
  2335. filter_exit:
  2336. sqlite3_finalize(pStmt);
  2337. editDist3FromStringDelete(pMatchStr3);
  2338. return x.rc;
  2339. }
  2340. /*
  2341. ** This version of xFilter handles a full-table scan case
  2342. */
  2343. static int spellfix1FilterForFullScan(
  2344. spellfix1_cursor *pCur,
  2345. int idxNum,
  2346. int argc,
  2347. sqlite3_value **argv
  2348. ){
  2349. int rc;
  2350. char *zSql;
  2351. spellfix1_vtab *pVTab = pCur->pVTab;
  2352. spellfix1ResetCursor(pCur);
  2353. zSql = sqlite3_mprintf(
  2354. "SELECT word, rank, NULL, langid, id FROM \"%w\".\"%w_vocab\"",
  2355. pVTab->zDbName, pVTab->zTableName);
  2356. if( zSql==0 ) return SQLITE_NOMEM;
  2357. rc = sqlite3_prepare_v2(pVTab->db, zSql, -1, &pCur->pFullScan, 0);
  2358. sqlite3_free(zSql);
  2359. pCur->nRow = pCur->iRow = 0;
  2360. if( rc==SQLITE_OK ){
  2361. rc = sqlite3_step(pCur->pFullScan);
  2362. if( rc==SQLITE_ROW ){ pCur->iRow = -1; rc = SQLITE_OK; }
  2363. if( rc==SQLITE_DONE ){ rc = SQLITE_OK; }
  2364. }else{
  2365. pCur->iRow = 0;
  2366. }
  2367. return rc;
  2368. }
  2369. /*
  2370. ** Called to "rewind" a cursor back to the beginning so that
  2371. ** it starts its output over again. Always called at least once
  2372. ** prior to any spellfix1Column, spellfix1Rowid, or spellfix1Eof call.
  2373. */
  2374. static int spellfix1Filter(
  2375. sqlite3_vtab_cursor *cur,
  2376. int idxNum, const char *idxStr,
  2377. int argc, sqlite3_value **argv
  2378. ){
  2379. spellfix1_cursor *pCur = (spellfix1_cursor *)cur;
  2380. int rc;
  2381. if( idxNum & 1 ){
  2382. rc = spellfix1FilterForMatch(pCur, idxNum, argc, argv);
  2383. }else{
  2384. rc = spellfix1FilterForFullScan(pCur, idxNum, argc, argv);
  2385. }
  2386. return rc;
  2387. }
  2388. /*
  2389. ** Advance a cursor to its next row of output
  2390. */
  2391. static int spellfix1Next(sqlite3_vtab_cursor *cur){
  2392. spellfix1_cursor *pCur = (spellfix1_cursor *)cur;
  2393. int rc = SQLITE_OK;
  2394. if( pCur->iRow < pCur->nRow ){
  2395. if( pCur->pFullScan ){
  2396. rc = sqlite3_step(pCur->pFullScan);
  2397. if( rc!=SQLITE_ROW ) pCur->iRow = pCur->nRow;
  2398. if( rc==SQLITE_ROW || rc==SQLITE_DONE ) rc = SQLITE_OK;
  2399. }else{
  2400. pCur->iRow++;
  2401. }
  2402. }
  2403. return rc;
  2404. }
  2405. /*
  2406. ** Return TRUE if we are at the end-of-file
  2407. */
  2408. static int spellfix1Eof(sqlite3_vtab_cursor *cur){
  2409. spellfix1_cursor *pCur = (spellfix1_cursor *)cur;
  2410. return pCur->iRow>=pCur->nRow;
  2411. }
  2412. /*
  2413. ** Return columns from the current row.
  2414. */
  2415. static int spellfix1Column(
  2416. sqlite3_vtab_cursor *cur,
  2417. sqlite3_context *ctx,
  2418. int i
  2419. ){
  2420. spellfix1_cursor *pCur = (spellfix1_cursor*)cur;
  2421. if( pCur->pFullScan ){
  2422. if( i<=SPELLFIX_COL_LANGID ){
  2423. sqlite3_result_value(ctx, sqlite3_column_value(pCur->pFullScan, i));
  2424. }else{
  2425. sqlite3_result_null(ctx);
  2426. }
  2427. return SQLITE_OK;
  2428. }
  2429. switch( i ){
  2430. case SPELLFIX_COL_WORD: {
  2431. sqlite3_result_text(ctx, pCur->a[pCur->iRow].zWord, -1, SQLITE_STATIC);
  2432. break;
  2433. }
  2434. case SPELLFIX_COL_RANK: {
  2435. sqlite3_result_int(ctx, pCur->a[pCur->iRow].iRank);
  2436. break;
  2437. }
  2438. case SPELLFIX_COL_DISTANCE: {
  2439. sqlite3_result_int(ctx, pCur->a[pCur->iRow].iDistance);
  2440. break;
  2441. }
  2442. case SPELLFIX_COL_LANGID: {
  2443. sqlite3_result_int(ctx, pCur->iLang);
  2444. break;
  2445. }
  2446. case SPELLFIX_COL_SCORE: {
  2447. sqlite3_result_int(ctx, pCur->a[pCur->iRow].iScore);
  2448. break;
  2449. }
  2450. case SPELLFIX_COL_MATCHLEN: {
  2451. int iMatchlen = pCur->a[pCur->iRow].iMatchlen;
  2452. if( iMatchlen<0 ){
  2453. int nPattern = (int)strlen(pCur->zPattern);
  2454. char *zWord = pCur->a[pCur->iRow].zWord;
  2455. int nWord = (int)strlen(zWord);
  2456. if( nPattern>0 && pCur->zPattern[nPattern-1]=='*' ){
  2457. char *zTranslit;
  2458. int res;
  2459. zTranslit = (char *)transliterate((unsigned char *)zWord, nWord);
  2460. if( !zTranslit ) return SQLITE_NOMEM;
  2461. res = editdist1(pCur->zPattern, zTranslit, &iMatchlen);
  2462. sqlite3_free(zTranslit);
  2463. if( res<0 ) return SQLITE_NOMEM;
  2464. iMatchlen = translen_to_charlen(zWord, nWord, iMatchlen);
  2465. }else{
  2466. iMatchlen = utf8Charlen(zWord, nWord);
  2467. }
  2468. }
  2469. sqlite3_result_int(ctx, iMatchlen);
  2470. break;
  2471. }
  2472. case SPELLFIX_COL_PHONEHASH: {
  2473. sqlite3_result_text(ctx, pCur->a[pCur->iRow].zHash, -1, SQLITE_STATIC);
  2474. break;
  2475. }
  2476. case SPELLFIX_COL_TOP: {
  2477. sqlite3_result_int(ctx, pCur->iTop);
  2478. break;
  2479. }
  2480. case SPELLFIX_COL_SCOPE: {
  2481. sqlite3_result_int(ctx, pCur->iScope);
  2482. break;
  2483. }
  2484. case SPELLFIX_COL_SRCHCNT: {
  2485. sqlite3_result_int(ctx, pCur->nSearch);
  2486. break;
  2487. }
  2488. default: {
  2489. sqlite3_result_null(ctx);
  2490. break;
  2491. }
  2492. }
  2493. return SQLITE_OK;
  2494. }
  2495. /*
  2496. ** The rowid.
  2497. */
  2498. static int spellfix1Rowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  2499. spellfix1_cursor *pCur = (spellfix1_cursor*)cur;
  2500. if( pCur->pFullScan ){
  2501. *pRowid = sqlite3_column_int64(pCur->pFullScan, 4);
  2502. }else{
  2503. *pRowid = pCur->a[pCur->iRow].iRowid;
  2504. }
  2505. return SQLITE_OK;
  2506. }
  2507. /*
  2508. ** The xUpdate() method.
  2509. */
  2510. static int spellfix1Update(
  2511. sqlite3_vtab *pVTab,
  2512. int argc,
  2513. sqlite3_value **argv,
  2514. sqlite_int64 *pRowid
  2515. ){
  2516. int rc = SQLITE_OK;
  2517. sqlite3_int64 rowid, newRowid;
  2518. spellfix1_vtab *p = (spellfix1_vtab*)pVTab;
  2519. sqlite3 *db = p->db;
  2520. if( argc==1 ){
  2521. /* A delete operation on the rowid given by argv[0] */
  2522. rowid = *pRowid = sqlite3_value_int64(argv[0]);
  2523. spellfix1DbExec(&rc, db, "DELETE FROM \"%w\".\"%w_vocab\" "
  2524. " WHERE id=%lld",
  2525. p->zDbName, p->zTableName, rowid);
  2526. }else{
  2527. const unsigned char *zWord = sqlite3_value_text(argv[SPELLFIX_COL_WORD+2]);
  2528. int nWord = sqlite3_value_bytes(argv[SPELLFIX_COL_WORD+2]);
  2529. int iLang = sqlite3_value_int(argv[SPELLFIX_COL_LANGID+2]);
  2530. int iRank = sqlite3_value_int(argv[SPELLFIX_COL_RANK+2]);
  2531. const unsigned char *zSoundslike =
  2532. sqlite3_value_text(argv[SPELLFIX_COL_SOUNDSLIKE+2]);
  2533. int nSoundslike = sqlite3_value_bytes(argv[SPELLFIX_COL_SOUNDSLIKE+2]);
  2534. char *zK1, *zK2;
  2535. int i;
  2536. char c;
  2537. if( zWord==0 ){
  2538. /* Inserts of the form: INSERT INTO table(command) VALUES('xyzzy');
  2539. ** cause zWord to be NULL, so we look at the "command" column to see
  2540. ** what special actions to take */
  2541. const char *zCmd =
  2542. (const char*)sqlite3_value_text(argv[SPELLFIX_COL_COMMAND+2]);
  2543. if( zCmd==0 ){
  2544. pVTab->zErrMsg = sqlite3_mprintf("%s.word may not be NULL",
  2545. p->zTableName);
  2546. return SQLITE_CONSTRAINT_NOTNULL;
  2547. }
  2548. if( strcmp(zCmd,"reset")==0 ){
  2549. /* Reset the edit cost table (if there is one). */
  2550. editDist3ConfigDelete(p->pConfig3);
  2551. p->pConfig3 = 0;
  2552. return SQLITE_OK;
  2553. }
  2554. if( strncmp(zCmd,"edit_cost_table=",16)==0 ){
  2555. editDist3ConfigDelete(p->pConfig3);
  2556. p->pConfig3 = 0;
  2557. sqlite3_free(p->zCostTable);
  2558. p->zCostTable = spellfix1Dequote(zCmd+16);
  2559. if( p->zCostTable==0 ) return SQLITE_NOMEM;
  2560. if( p->zCostTable[0]==0 || sqlite3_stricmp(p->zCostTable,"null")==0 ){
  2561. sqlite3_free(p->zCostTable);
  2562. p->zCostTable = 0;
  2563. }
  2564. return SQLITE_OK;
  2565. }
  2566. pVTab->zErrMsg = sqlite3_mprintf("unknown value for %s.command: \"%w\"",
  2567. p->zTableName, zCmd);
  2568. return SQLITE_ERROR;
  2569. }
  2570. if( iRank<1 ) iRank = 1;
  2571. if( zSoundslike ){
  2572. zK1 = (char*)transliterate(zSoundslike, nSoundslike);
  2573. }else{
  2574. zK1 = (char*)transliterate(zWord, nWord);
  2575. }
  2576. if( zK1==0 ) return SQLITE_NOMEM;
  2577. for(i=0; (c = zK1[i])!=0; i++){
  2578. if( c>='A' && c<='Z' ) zK1[i] += 'a' - 'A';
  2579. }
  2580. zK2 = (char*)phoneticHash((const unsigned char*)zK1, i);
  2581. if( zK2==0 ){
  2582. sqlite3_free(zK1);
  2583. return SQLITE_NOMEM;
  2584. }
  2585. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  2586. spellfix1DbExec(&rc, db,
  2587. "INSERT INTO \"%w\".\"%w_vocab\"(rank,langid,word,k1,k2) "
  2588. "VALUES(%d,%d,%Q,%Q,%Q)",
  2589. p->zDbName, p->zTableName,
  2590. iRank, iLang, zWord, zK1, zK2
  2591. );
  2592. *pRowid = sqlite3_last_insert_rowid(db);
  2593. }else{
  2594. rowid = sqlite3_value_int64(argv[0]);
  2595. newRowid = *pRowid = sqlite3_value_int64(argv[1]);
  2596. spellfix1DbExec(&rc, db,
  2597. "UPDATE \"%w\".\"%w_vocab\" SET id=%lld, rank=%d, langid=%d,"
  2598. " word=%Q, k1=%Q, k2=%Q WHERE id=%lld",
  2599. p->zDbName, p->zTableName, newRowid, iRank, iLang,
  2600. zWord, zK1, zK2, rowid
  2601. );
  2602. }
  2603. sqlite3_free(zK1);
  2604. sqlite3_free(zK2);
  2605. }
  2606. return rc;
  2607. }
  2608. /*
  2609. ** Rename the spellfix1 table.
  2610. */
  2611. static int spellfix1Rename(sqlite3_vtab *pVTab, const char *zNew){
  2612. spellfix1_vtab *p = (spellfix1_vtab*)pVTab;
  2613. sqlite3 *db = p->db;
  2614. int rc = SQLITE_OK;
  2615. char *zNewName = sqlite3_mprintf("%s", zNew);
  2616. if( zNewName==0 ){
  2617. return SQLITE_NOMEM;
  2618. }
  2619. spellfix1DbExec(&rc, db,
  2620. "ALTER TABLE \"%w\".\"%w_vocab\" RENAME TO \"%w_vocab\"",
  2621. p->zDbName, p->zTableName, zNewName
  2622. );
  2623. if( rc==SQLITE_OK ){
  2624. sqlite3_free(p->zTableName);
  2625. p->zTableName = zNewName;
  2626. }else{
  2627. sqlite3_free(zNewName);
  2628. }
  2629. return rc;
  2630. }
  2631. /*
  2632. ** A virtual table module that provides fuzzy search.
  2633. */
  2634. static sqlite3_module spellfix1Module = {
  2635. 0, /* iVersion */
  2636. spellfix1Create, /* xCreate - handle CREATE VIRTUAL TABLE */
  2637. spellfix1Connect, /* xConnect - reconnected to an existing table */
  2638. spellfix1BestIndex, /* xBestIndex - figure out how to do a query */
  2639. spellfix1Disconnect, /* xDisconnect - close a connection */
  2640. spellfix1Destroy, /* xDestroy - handle DROP TABLE */
  2641. spellfix1Open, /* xOpen - open a cursor */
  2642. spellfix1Close, /* xClose - close a cursor */
  2643. spellfix1Filter, /* xFilter - configure scan constraints */
  2644. spellfix1Next, /* xNext - advance a cursor */
  2645. spellfix1Eof, /* xEof - check for end of scan */
  2646. spellfix1Column, /* xColumn - read data */
  2647. spellfix1Rowid, /* xRowid - read data */
  2648. spellfix1Update, /* xUpdate */
  2649. 0, /* xBegin */
  2650. 0, /* xSync */
  2651. 0, /* xCommit */
  2652. 0, /* xRollback */
  2653. 0, /* xFindMethod */
  2654. spellfix1Rename, /* xRename */
  2655. };
  2656. /*
  2657. ** Register the various functions and the virtual table.
  2658. */
  2659. static int spellfix1Register(sqlite3 *db){
  2660. int rc = SQLITE_OK;
  2661. int i;
  2662. rc = sqlite3_create_function(db, "spellfix1_translit", 1, SQLITE_UTF8, 0,
  2663. transliterateSqlFunc, 0, 0);
  2664. if( rc==SQLITE_OK ){
  2665. rc = sqlite3_create_function(db, "spellfix1_editdist", 2, SQLITE_UTF8, 0,
  2666. editdistSqlFunc, 0, 0);
  2667. }
  2668. if( rc==SQLITE_OK ){
  2669. rc = sqlite3_create_function(db, "spellfix1_phonehash", 1, SQLITE_UTF8, 0,
  2670. phoneticHashSqlFunc, 0, 0);
  2671. }
  2672. if( rc==SQLITE_OK ){
  2673. rc = sqlite3_create_function(db, "spellfix1_scriptcode", 1, SQLITE_UTF8, 0,
  2674. scriptCodeSqlFunc, 0, 0);
  2675. }
  2676. if( rc==SQLITE_OK ){
  2677. rc = sqlite3_create_module(db, "spellfix1", &spellfix1Module, 0);
  2678. }
  2679. if( rc==SQLITE_OK ){
  2680. rc = editDist3Install(db);
  2681. }
  2682. /* Verify sanity of the translit[] table */
  2683. for(i=0; i<sizeof(translit)/sizeof(translit[0])-1; i++){
  2684. assert( translit[i].cFrom<translit[i+1].cFrom );
  2685. }
  2686. return rc;
  2687. }
  2688. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  2689. /*
  2690. ** Extension load function.
  2691. */
  2692. #ifdef _WIN32
  2693. __declspec(dllexport)
  2694. #endif
  2695. int sqlite3_spellfix_init(
  2696. sqlite3 *db,
  2697. char **pzErrMsg,
  2698. const sqlite3_api_routines *pApi
  2699. ){
  2700. SQLITE_EXTENSION_INIT2(pApi);
  2701. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2702. return spellfix1Register(db);
  2703. #endif
  2704. return SQLITE_OK;
  2705. }