fulltext.c 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511
  1. /* The author disclaims copyright to this source code.
  2. *
  3. * This is an SQLite module implementing full-text search.
  4. */
  5. #include <assert.h>
  6. #if !defined(__APPLE__)
  7. #include <malloc.h>
  8. #else
  9. #include <stdlib.h>
  10. #endif
  11. #include <stdio.h>
  12. #include <string.h>
  13. #include <ctype.h>
  14. #include "fulltext.h"
  15. #include "ft_hash.h"
  16. #include "tokenizer.h"
  17. #include "sqlite3.h"
  18. #include "sqlite3ext.h"
  19. SQLITE_EXTENSION_INIT1
  20. /* utility functions */
  21. /* We encode variable-length integers in little-endian order using seven bits
  22. * per byte as follows:
  23. **
  24. ** KEY:
  25. ** A = 0xxxxxxx 7 bits of data and one flag bit
  26. ** B = 1xxxxxxx 7 bits of data and one flag bit
  27. **
  28. ** 7 bits - A
  29. ** 14 bits - BA
  30. ** 21 bits - BBA
  31. ** and so on.
  32. */
  33. /* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
  34. #define VARINT_MAX 10
  35. /* Write a 64-bit variable-length integer to memory starting at p[0].
  36. * The length of data written will be between 1 and VARINT_MAX bytes.
  37. * The number of bytes written is returned. */
  38. static int putVarint(char *p, sqlite_int64 v){
  39. unsigned char *q = (unsigned char *) p;
  40. sqlite_uint64 vu = v;
  41. do{
  42. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  43. vu >>= 7;
  44. }while( vu!=0 );
  45. q[-1] &= 0x7f; /* turn off high bit in final byte */
  46. assert( q - (unsigned char *)p <= VARINT_MAX );
  47. return (int) (q - (unsigned char *)p);
  48. }
  49. /* Read a 64-bit variable-length integer from memory starting at p[0].
  50. * Return the number of bytes read, or 0 on error.
  51. * The value is stored in *v. */
  52. static int getVarint(const char *p, sqlite_int64 *v){
  53. const unsigned char *q = (const unsigned char *) p;
  54. sqlite_uint64 x = 0, y = 1;
  55. while( (*q & 0x80) == 0x80 ){
  56. x += y * (*q++ & 0x7f);
  57. y <<= 7;
  58. if( q - (unsigned char *)p >= VARINT_MAX ){ /* bad data */
  59. assert( 0 );
  60. return 0;
  61. }
  62. }
  63. x += y * (*q++);
  64. *v = (sqlite_int64) x;
  65. return (int) (q - (unsigned char *)p);
  66. }
  67. static int getVarint32(const char *p, int *pi){
  68. sqlite_int64 i;
  69. int ret = getVarint(p, &i);
  70. *pi = (int) i;
  71. assert( *pi==i );
  72. return ret;
  73. }
  74. /*** Document lists ***
  75. *
  76. * A document list holds a sorted list of varint-encoded document IDs.
  77. *
  78. * A doclist with type DL_POSITIONS_OFFSETS is stored like this:
  79. *
  80. * array {
  81. * varint docid;
  82. * array {
  83. * varint position; (delta from previous position plus 1, or 0 for end)
  84. * varint startOffset; (delta from previous startOffset)
  85. * varint endOffset; (delta from startOffset)
  86. * }
  87. * }
  88. *
  89. * Here, array { X } means zero or more occurrences of X, adjacent in memory.
  90. *
  91. * A doclist with type DL_POSITIONS is like the above, but holds only docids
  92. * and positions without offset information.
  93. *
  94. * A doclist with type DL_DOCIDS is like the above, but holds only docids
  95. * without positions or offset information.
  96. *
  97. * On disk, every document list has positions and offsets, so we don't bother
  98. * to serialize a doclist's type.
  99. *
  100. * We don't yet delta-encode document IDs; doing so will probably be a
  101. * modest win.
  102. *
  103. * NOTE(shess) I've thought of a slightly (1%) better offset encoding.
  104. * After the first offset, estimate the next offset by using the
  105. * current token position and the previous token position and offset,
  106. * offset to handle some variance. So the estimate would be
  107. * (iPosition*w->iStartOffset/w->iPosition-64), which is delta-encoded
  108. * as normal. Offsets more than 64 chars from the estimate are
  109. * encoded as the delta to the previous start offset + 128. An
  110. * additional tiny increment can be gained by using the end offset of
  111. * the previous token to make the estimate a tiny bit more precise.
  112. */
  113. typedef enum DocListType {
  114. DL_DOCIDS, /* docids only */
  115. DL_POSITIONS, /* docids + positions */
  116. DL_POSITIONS_OFFSETS /* docids + positions + offsets */
  117. } DocListType;
  118. typedef struct DocList {
  119. char *pData;
  120. int nData;
  121. DocListType iType;
  122. int iLastPos; /* the last position written */
  123. int iLastOffset; /* the last start offset written */
  124. } DocList;
  125. /* Initialize a new DocList to hold the given data. */
  126. static void docListInit(DocList *d, DocListType iType,
  127. const char *pData, int nData){
  128. d->nData = nData;
  129. if( nData>0 ){
  130. d->pData = malloc(nData);
  131. memcpy(d->pData, pData, nData);
  132. } else {
  133. d->pData = NULL;
  134. }
  135. d->iType = iType;
  136. d->iLastPos = 0;
  137. d->iLastOffset = 0;
  138. }
  139. /* Create a new dynamically-allocated DocList. */
  140. static DocList *docListNew(DocListType iType){
  141. DocList *d = (DocList *) malloc(sizeof(DocList));
  142. docListInit(d, iType, 0, 0);
  143. return d;
  144. }
  145. static void docListDestroy(DocList *d){
  146. free(d->pData);
  147. #ifndef NDEBUG
  148. memset(d, 0x55, sizeof(*d));
  149. #endif
  150. }
  151. static void docListDelete(DocList *d){
  152. docListDestroy(d);
  153. free(d);
  154. }
  155. static char *docListEnd(DocList *d){
  156. return d->pData + d->nData;
  157. }
  158. /* Append a varint to a DocList's data. */
  159. static void appendVarint(DocList *d, sqlite_int64 i){
  160. char c[VARINT_MAX];
  161. int n = putVarint(c, i);
  162. d->pData = realloc(d->pData, d->nData + n);
  163. memcpy(d->pData + d->nData, c, n);
  164. d->nData += n;
  165. }
  166. static void docListAddDocid(DocList *d, sqlite_int64 iDocid){
  167. appendVarint(d, iDocid);
  168. d->iLastPos = 0;
  169. }
  170. /* Add a position to the last position list in a doclist. */
  171. static void docListAddPos(DocList *d, int iPos){
  172. assert( d->iType>=DL_POSITIONS );
  173. appendVarint(d, iPos-d->iLastPos+1);
  174. d->iLastPos = iPos;
  175. }
  176. static void docListAddPosOffset(DocList *d, int iPos,
  177. int iStartOffset, int iEndOffset){
  178. assert( d->iType==DL_POSITIONS_OFFSETS );
  179. docListAddPos(d, iPos);
  180. appendVarint(d, iStartOffset-d->iLastOffset);
  181. d->iLastOffset = iStartOffset;
  182. appendVarint(d, iEndOffset-iStartOffset);
  183. }
  184. /* Terminate the last position list in the given doclist. */
  185. static void docListAddEndPos(DocList *d){
  186. appendVarint(d, 0);
  187. }
  188. typedef struct DocListReader {
  189. DocList *pDoclist;
  190. char *p;
  191. int iLastPos; /* the last position read */
  192. } DocListReader;
  193. static void readerInit(DocListReader *r, DocList *pDoclist){
  194. r->pDoclist = pDoclist;
  195. if( pDoclist!=NULL ){
  196. r->p = pDoclist->pData;
  197. }
  198. r->iLastPos = 0;
  199. }
  200. static int readerAtEnd(DocListReader *pReader){
  201. return pReader->p >= docListEnd(pReader->pDoclist);
  202. }
  203. /* Peek at the next docid without advancing the read pointer. */
  204. static sqlite_int64 peekDocid(DocListReader *pReader){
  205. sqlite_int64 ret;
  206. assert( !readerAtEnd(pReader) );
  207. getVarint(pReader->p, &ret);
  208. return ret;
  209. }
  210. /* Read the next docid. */
  211. static sqlite_int64 readDocid(DocListReader *pReader){
  212. sqlite_int64 ret;
  213. assert( !readerAtEnd(pReader) );
  214. pReader->p += getVarint(pReader->p, &ret);
  215. pReader->iLastPos = 0;
  216. return ret;
  217. }
  218. /* Read the next position from a position list.
  219. * Returns the position, or -1 at the end of the list. */
  220. static int readPosition(DocListReader *pReader){
  221. int i;
  222. int iType = pReader->pDoclist->iType;
  223. assert( iType>=DL_POSITIONS );
  224. assert( !readerAtEnd(pReader) );
  225. pReader->p += getVarint32(pReader->p, &i);
  226. if( i==0 ){
  227. pReader->iLastPos = -1;
  228. return -1;
  229. }
  230. pReader->iLastPos += ((int) i)-1;
  231. if( iType>=DL_POSITIONS_OFFSETS ){
  232. /* Skip over offsets, ignoring them for now. */
  233. int iStart, iEnd;
  234. pReader->p += getVarint32(pReader->p, &iStart);
  235. pReader->p += getVarint32(pReader->p, &iEnd);
  236. }
  237. return pReader->iLastPos;
  238. }
  239. /* Skip past the end of a position list. */
  240. static void skipPositionList(DocListReader *pReader){
  241. while( readPosition(pReader)!=-1 )
  242. ;
  243. }
  244. /* Skip over a docid, including its position list if the doclist has
  245. * positions. */
  246. static void skipDocument(DocListReader *pReader){
  247. readDocid(pReader);
  248. if( pReader->pDoclist->iType >= DL_POSITIONS ){
  249. skipPositionList(pReader);
  250. }
  251. }
  252. static sqlite_int64 firstDocid(DocList *d){
  253. DocListReader r;
  254. readerInit(&r, d);
  255. return readDocid(&r);
  256. }
  257. /* Doclist multi-tool. Pass pUpdate==NULL to delete the indicated docid;
  258. * otherwise pUpdate, which must contain only the single docid [iDocid], is
  259. * inserted (if not present) or updated (if already present). */
  260. static int docListUpdate(DocList *d, sqlite_int64 iDocid, DocList *pUpdate){
  261. int modified = 0;
  262. DocListReader reader;
  263. char *p;
  264. if( pUpdate!=NULL ){
  265. assert( d->iType==pUpdate->iType);
  266. assert( iDocid==firstDocid(pUpdate) );
  267. }
  268. readerInit(&reader, d);
  269. while( !readerAtEnd(&reader) && peekDocid(&reader)<iDocid ){
  270. skipDocument(&reader);
  271. }
  272. p = reader.p;
  273. /* Delete if there is a matching element. */
  274. if( !readerAtEnd(&reader) && iDocid==peekDocid(&reader) ){
  275. skipDocument(&reader);
  276. memmove(p, reader.p, docListEnd(d) - reader.p);
  277. d->nData -= (reader.p - p);
  278. modified = 1;
  279. }
  280. /* Insert if indicated. */
  281. if( pUpdate!=NULL ){
  282. int iDoclist = p-d->pData;
  283. docListAddEndPos(pUpdate);
  284. d->pData = realloc(d->pData, d->nData+pUpdate->nData);
  285. p = d->pData + iDoclist;
  286. memmove(p+pUpdate->nData, p, docListEnd(d) - p);
  287. memcpy(p, pUpdate->pData, pUpdate->nData);
  288. d->nData += pUpdate->nData;
  289. modified = 1;
  290. }
  291. return modified;
  292. }
  293. /* Split the second half of doclist d into a separate doclist d2. Returns 1
  294. * if successful, or 0 if d contains a single document and hence can't be
  295. * split. */
  296. static int docListSplit(DocList *d, DocList *d2){
  297. const char *pSplitPoint = d->pData + d->nData / 2;
  298. DocListReader reader;
  299. readerInit(&reader, d);
  300. while( reader.p<pSplitPoint ){
  301. skipDocument(&reader);
  302. }
  303. if( readerAtEnd(&reader) ) return 0;
  304. docListInit(d2, d->iType, reader.p, docListEnd(d) - reader.p);
  305. d->nData = reader.p - d->pData;
  306. d->pData = realloc(d->pData, d->nData);
  307. return 1;
  308. }
  309. /* A DocListMerge computes the AND of an in-memory DocList [in] and a chunked
  310. * on-disk doclist, resulting in another in-memory DocList [out]. [in]
  311. * and [out] may or may not store position information according to the
  312. * caller's wishes. The on-disk doclist always comes with positions.
  313. *
  314. * The caller must read each chunk of the on-disk doclist in succession and
  315. * pass it to mergeBlock().
  316. *
  317. * If [in] has positions, then the merge output contains only documents with
  318. * matching positions in the two input doclists. If [in] does not have
  319. * positions, then the merge output contains all documents common to the two
  320. * input doclists.
  321. *
  322. * If [in] is NULL, then the on-disk doclist is copied to [out] directly.
  323. *
  324. * A merge is performed using an integer [iOffset] provided by the caller.
  325. * [iOffset] is subtracted from each position in the on-disk doclist for the
  326. * purpose of position comparison; this is helpful in implementing phrase
  327. * searches.
  328. *
  329. * A DocListMerge is not yet able to propagate offsets through query
  330. * processing; we should add that capability soon.
  331. */
  332. typedef struct DocListMerge {
  333. DocListReader in;
  334. DocList *pOut;
  335. int iOffset;
  336. } DocListMerge;
  337. static void mergeInit(DocListMerge *m,
  338. DocList *pIn, int iOffset, DocList *pOut){
  339. readerInit(&m->in, pIn);
  340. m->pOut = pOut;
  341. m->iOffset = iOffset;
  342. /* can't handle offsets yet */
  343. assert( pIn==NULL || pIn->iType <= DL_POSITIONS );
  344. assert( pOut->iType <= DL_POSITIONS );
  345. }
  346. /* A helper function for mergeBlock(), below. Merge the position lists
  347. * pointed to by m->in and pBlockReader.
  348. * If the merge matches, write [iDocid] to m->pOut; if m->pOut
  349. * has positions then write all matching positions as well. */
  350. static void mergePosList(DocListMerge *m, sqlite_int64 iDocid,
  351. DocListReader *pBlockReader){
  352. int block_pos = readPosition(pBlockReader);
  353. int in_pos = readPosition(&m->in);
  354. int match = 0;
  355. while( block_pos!=-1 || in_pos!=-1 ){
  356. if( block_pos-m->iOffset==in_pos ){
  357. if( !match ){
  358. docListAddDocid(m->pOut, iDocid);
  359. match = 1;
  360. }
  361. if( m->pOut->iType >= DL_POSITIONS ){
  362. docListAddPos(m->pOut, in_pos);
  363. }
  364. block_pos = readPosition(pBlockReader);
  365. in_pos = readPosition(&m->in);
  366. } else if( in_pos==-1 || (block_pos!=-1 && block_pos-m->iOffset<in_pos) ){
  367. block_pos = readPosition(pBlockReader);
  368. } else {
  369. in_pos = readPosition(&m->in);
  370. }
  371. }
  372. if( m->pOut->iType >= DL_POSITIONS && match ){
  373. docListAddEndPos(m->pOut);
  374. }
  375. }
  376. /* Merge one block of an on-disk doclist into a DocListMerge. */
  377. static void mergeBlock(DocListMerge *m, DocList *pBlock){
  378. DocListReader blockReader;
  379. assert( pBlock->iType >= DL_POSITIONS );
  380. readerInit(&blockReader, pBlock);
  381. while( !readerAtEnd(&blockReader) ){
  382. sqlite_int64 iDocid = readDocid(&blockReader);
  383. if( m->in.pDoclist!=NULL ){
  384. while( 1 ){
  385. if( readerAtEnd(&m->in) ) return; /* nothing more to merge */
  386. if( peekDocid(&m->in)>=iDocid ) break;
  387. skipDocument(&m->in);
  388. }
  389. if( peekDocid(&m->in)>iDocid ){ /* [pIn] has no match with iDocid */
  390. skipPositionList(&blockReader); /* skip this docid in the block */
  391. continue;
  392. }
  393. readDocid(&m->in);
  394. }
  395. /* We have a document match. */
  396. if( m->in.pDoclist==NULL || m->in.pDoclist->iType < DL_POSITIONS ){
  397. /* We don't need to do a poslist merge. */
  398. docListAddDocid(m->pOut, iDocid);
  399. if( m->pOut->iType >= DL_POSITIONS ){
  400. /* Copy all positions to the output doclist. */
  401. while( 1 ){
  402. int pos = readPosition(&blockReader);
  403. if( pos==-1 ) break;
  404. docListAddPos(m->pOut, pos);
  405. }
  406. docListAddEndPos(m->pOut);
  407. } else skipPositionList(&blockReader);
  408. continue;
  409. }
  410. mergePosList(m, iDocid, &blockReader);
  411. }
  412. }
  413. static char *string_dup_n(const char *s, int n){
  414. char *str = malloc(n + 1);
  415. memcpy(str, s, n);
  416. str[n] = '\0';
  417. return str;
  418. }
  419. /* Duplicate a string; the caller must free() the returned string.
  420. * (We don't use strdup() since it's not part of the standard C library and
  421. * may not be available everywhere.) */
  422. static char *string_dup(const char *s){
  423. return string_dup_n(s, strlen(s));
  424. }
  425. /* Format a string, replacing each occurrence of the % character with
  426. * zName. This may be more convenient than sqlite_mprintf()
  427. * when one string is used repeatedly in a format string.
  428. * The caller must free() the returned string. */
  429. static char *string_format(const char *zFormat, const char *zName){
  430. const char *p;
  431. size_t len = 0;
  432. size_t nName = strlen(zName);
  433. char *result;
  434. char *r;
  435. /* first compute length needed */
  436. for(p = zFormat ; *p ; ++p){
  437. len += (*p=='%' ? nName : 1);
  438. }
  439. len += 1; /* for null terminator */
  440. r = result = malloc(len);
  441. for(p = zFormat; *p; ++p){
  442. if( *p=='%' ){
  443. memcpy(r, zName, nName);
  444. r += nName;
  445. } else {
  446. *r++ = *p;
  447. }
  448. }
  449. *r++ = '\0';
  450. assert( r == result + len );
  451. return result;
  452. }
  453. static int sql_exec(sqlite3 *db, const char *zName, const char *zFormat){
  454. char *zCommand = string_format(zFormat, zName);
  455. int rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
  456. free(zCommand);
  457. return rc;
  458. }
  459. static int sql_prepare(sqlite3 *db, const char *zName, sqlite3_stmt **ppStmt,
  460. const char *zFormat){
  461. char *zCommand = string_format(zFormat, zName);
  462. int rc = sqlite3_prepare(db, zCommand, -1, ppStmt, NULL);
  463. free(zCommand);
  464. return rc;
  465. }
  466. /* end utility functions */
  467. #define QUERY_GENERIC 0
  468. #define QUERY_FULLTEXT 1
  469. #define CHUNK_MAX 1024
  470. typedef enum fulltext_statement {
  471. CONTENT_INSERT_STMT,
  472. CONTENT_SELECT_STMT,
  473. CONTENT_DELETE_STMT,
  474. TERM_SELECT_STMT,
  475. TERM_CHUNK_SELECT_STMT,
  476. TERM_INSERT_STMT,
  477. TERM_UPDATE_STMT,
  478. TERM_DELETE_STMT,
  479. MAX_STMT /* Always at end! */
  480. } fulltext_statement;
  481. /* These must exactly match the enum above. */
  482. /* TODO(adam): Is there some risk that a statement (in particular,
  483. ** pTermSelectStmt) will be used in two cursors at once, e.g. if a
  484. ** query joins a virtual table to itself? If so perhaps we should
  485. ** move some of these to the cursor object.
  486. */
  487. static const char *fulltext_zStatement[MAX_STMT] = {
  488. /* CONTENT_INSERT */ "insert into %_content (rowid, content) values (?, ?)",
  489. /* CONTENT_SELECT */ "select content from %_content where rowid = ?",
  490. /* CONTENT_DELETE */ "delete from %_content where rowid = ?",
  491. /* TERM_SELECT */
  492. "select rowid, doclist from %_term where term = ? and first = ?",
  493. /* TERM_CHUNK_SELECT */
  494. "select max(first) from %_term where term = ? and first <= ?",
  495. /* TERM_INSERT */
  496. "insert into %_term (term, first, doclist) values (?, ?, ?)",
  497. /* TERM_UPDATE */ "update %_term set doclist = ? where rowid = ?",
  498. /* TERM_DELETE */ "delete from %_term where rowid = ?",
  499. };
  500. typedef struct fulltext_vtab {
  501. sqlite3_vtab base;
  502. sqlite3 *db;
  503. const char *zName; /* virtual table name */
  504. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  505. /* Precompiled statements which we keep as long as the table is
  506. ** open.
  507. */
  508. sqlite3_stmt *pFulltextStatements[MAX_STMT];
  509. } fulltext_vtab;
  510. typedef struct fulltext_cursor {
  511. sqlite3_vtab_cursor base;
  512. int iCursorType; /* QUERY_GENERIC or QUERY_FULLTEXT */
  513. sqlite3_stmt *pStmt;
  514. int eof;
  515. /* The following is used only when iCursorType == QUERY_FULLTEXT. */
  516. DocListReader result;
  517. } fulltext_cursor;
  518. static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){
  519. return (fulltext_vtab *) c->base.pVtab;
  520. }
  521. static sqlite3_module fulltextModule; /* forward declaration */
  522. /* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
  523. ** If the indicated statement has never been prepared, it is prepared
  524. ** and cached, otherwise the cached version is reset.
  525. */
  526. static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
  527. sqlite3_stmt **ppStmt){
  528. assert( iStmt<MAX_STMT );
  529. if( v->pFulltextStatements[iStmt]==NULL ){
  530. int rc = sql_prepare(v->db, v->zName, &v->pFulltextStatements[iStmt],
  531. fulltext_zStatement[iStmt]);
  532. if( rc!=SQLITE_OK ) return rc;
  533. } else {
  534. int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
  535. if( rc!=SQLITE_OK ) return rc;
  536. }
  537. *ppStmt = v->pFulltextStatements[iStmt];
  538. return SQLITE_OK;
  539. }
  540. /* Step the indicated statement, handling errors SQLITE_BUSY (by
  541. ** retrying) and SQLITE_SCHEMA (by re-preparing and transferring
  542. ** bindings to the new statement).
  543. ** TODO(adam): We should extend this function so that it can work with
  544. ** statements declared locally, not only globally cached statements.
  545. */
  546. static int sql_step_statement(fulltext_vtab *v, fulltext_statement iStmt,
  547. sqlite3_stmt **ppStmt){
  548. int rc;
  549. sqlite3_stmt *s = *ppStmt;
  550. assert( iStmt<MAX_STMT );
  551. assert( s==v->pFulltextStatements[iStmt] );
  552. while( (rc=sqlite3_step(s))!=SQLITE_DONE && rc!=SQLITE_ROW ){
  553. sqlite3_stmt *pNewStmt;
  554. if( rc==SQLITE_BUSY ) continue;
  555. if( rc!=SQLITE_ERROR ) return rc;
  556. rc = sqlite3_reset(s);
  557. if( rc!=SQLITE_SCHEMA ) return SQLITE_ERROR;
  558. v->pFulltextStatements[iStmt] = NULL; /* Still in s */
  559. rc = sql_get_statement(v, iStmt, &pNewStmt);
  560. if( rc!=SQLITE_OK ) goto err;
  561. *ppStmt = pNewStmt;
  562. rc = sqlite3_transfer_bindings(s, pNewStmt);
  563. if( rc!=SQLITE_OK ) goto err;
  564. rc = sqlite3_finalize(s);
  565. if( rc!=SQLITE_OK ) return rc;
  566. s = pNewStmt;
  567. }
  568. return rc;
  569. err:
  570. sqlite3_finalize(s);
  571. return rc;
  572. }
  573. /* Like sql_step_statement(), but convert SQLITE_DONE to SQLITE_OK.
  574. ** Useful for statements like UPDATE, where we expect no results.
  575. */
  576. static int sql_single_step_statement(fulltext_vtab *v,
  577. fulltext_statement iStmt,
  578. sqlite3_stmt **ppStmt){
  579. int rc = sql_step_statement(v, iStmt, ppStmt);
  580. return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
  581. }
  582. /* insert into %_content (rowid, content) values ([rowid], [zContent]) */
  583. static int content_insert(fulltext_vtab *v, sqlite3_value *rowid,
  584. const char *zContent, int nContent){
  585. sqlite3_stmt *s;
  586. int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
  587. if( rc!=SQLITE_OK ) return rc;
  588. rc = sqlite3_bind_value(s, 1, rowid);
  589. if( rc!=SQLITE_OK ) return rc;
  590. rc = sqlite3_bind_text(s, 2, zContent, nContent, SQLITE_STATIC);
  591. if( rc!=SQLITE_OK ) return rc;
  592. return sql_single_step_statement(v, CONTENT_INSERT_STMT, &s);
  593. }
  594. /* select content from %_content where rowid = [iRow]
  595. * The caller must delete the returned string. */
  596. static int content_select(fulltext_vtab *v, sqlite_int64 iRow,
  597. char **pzContent){
  598. sqlite3_stmt *s;
  599. int rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
  600. if( rc!=SQLITE_OK ) return rc;
  601. rc = sqlite3_bind_int64(s, 1, iRow);
  602. if( rc!=SQLITE_OK ) return rc;
  603. rc = sql_step_statement(v, CONTENT_SELECT_STMT, &s);
  604. if( rc!=SQLITE_ROW ) return rc;
  605. *pzContent = string_dup((const char *)sqlite3_column_text(s, 0));
  606. /* We expect only one row. We must execute another sqlite3_step()
  607. * to complete the iteration; otherwise the table will remain locked. */
  608. rc = sqlite3_step(s);
  609. if( rc==SQLITE_DONE ) return SQLITE_OK;
  610. free(*pzContent);
  611. return rc;
  612. }
  613. /* delete from %_content where rowid = [iRow ] */
  614. static int content_delete(fulltext_vtab *v, sqlite_int64 iRow){
  615. sqlite3_stmt *s;
  616. int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
  617. if( rc!=SQLITE_OK ) return rc;
  618. rc = sqlite3_bind_int64(s, 1, iRow);
  619. if( rc!=SQLITE_OK ) return rc;
  620. return sql_single_step_statement(v, CONTENT_DELETE_STMT, &s);
  621. }
  622. /* select rowid, doclist from %_term where term = [zTerm] and first = [iFirst]
  623. * If found, returns SQLITE_OK; the caller must free the returned doclist.
  624. * If no rows found, returns SQLITE_ERROR. */
  625. static int term_select(fulltext_vtab *v, const char *zTerm, int nTerm,
  626. sqlite_int64 iFirst,
  627. sqlite_int64 *rowid,
  628. DocList *out){
  629. sqlite3_stmt *s;
  630. int rc = sql_get_statement(v, TERM_SELECT_STMT, &s);
  631. if( rc!=SQLITE_OK ) return rc;
  632. rc = sqlite3_bind_text(s, 1, zTerm, nTerm, SQLITE_TRANSIENT);
  633. if( rc!=SQLITE_OK ) return rc;
  634. rc = sqlite3_bind_int64(s, 2, iFirst);
  635. if( rc!=SQLITE_OK ) return rc;
  636. rc = sql_step_statement(v, TERM_SELECT_STMT, &s);
  637. if( rc!=SQLITE_ROW ) return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
  638. *rowid = sqlite3_column_int64(s, 0);
  639. docListInit(out, DL_POSITIONS_OFFSETS,
  640. sqlite3_column_blob(s, 1), sqlite3_column_bytes(s, 1));
  641. /* We expect only one row. We must execute another sqlite3_step()
  642. * to complete the iteration; otherwise the table will remain locked. */
  643. rc = sqlite3_step(s);
  644. return rc==SQLITE_DONE ? SQLITE_OK : rc;
  645. }
  646. /* select max(first) from %_term where term = [zTerm] and first <= [iFirst]
  647. * If found, returns SQLITE_ROW and result in *piResult; if the query returns
  648. * NULL (meaning no row found) returns SQLITE_DONE.
  649. */
  650. static int term_chunk_select(fulltext_vtab *v, const char *zTerm, int nTerm,
  651. sqlite_int64 iFirst, sqlite_int64 *piResult){
  652. sqlite3_stmt *s;
  653. int rc = sql_get_statement(v, TERM_CHUNK_SELECT_STMT, &s);
  654. if( rc!=SQLITE_OK ) return rc;
  655. rc = sqlite3_bind_text(s, 1, zTerm, nTerm, SQLITE_STATIC);
  656. if( rc!=SQLITE_OK ) return rc;
  657. rc = sqlite3_bind_int64(s, 2, iFirst);
  658. if( rc!=SQLITE_OK ) return rc;
  659. rc = sql_step_statement(v, TERM_CHUNK_SELECT_STMT, &s);
  660. if( rc!=SQLITE_ROW ) return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
  661. switch( sqlite3_column_type(s, 0) ){
  662. case SQLITE_NULL:
  663. rc = SQLITE_DONE;
  664. break;
  665. case SQLITE_INTEGER:
  666. *piResult = sqlite3_column_int64(s, 0);
  667. break;
  668. default:
  669. return SQLITE_ERROR;
  670. }
  671. /* We expect only one row. We must execute another sqlite3_step()
  672. * to complete the iteration; otherwise the table will remain locked. */
  673. if( sqlite3_step(s) != SQLITE_DONE ) return SQLITE_ERROR;
  674. return rc;
  675. }
  676. /* insert into %_term (term, first, doclist)
  677. values ([zTerm], [iFirst], [doclist]) */
  678. static int term_insert(fulltext_vtab *v, const char *zTerm, int nTerm,
  679. sqlite_int64 iFirst, DocList *doclist){
  680. sqlite3_stmt *s;
  681. int rc = sql_get_statement(v, TERM_INSERT_STMT, &s);
  682. if( rc!=SQLITE_OK ) return rc;
  683. rc = sqlite3_bind_text(s, 1, zTerm, nTerm, SQLITE_STATIC);
  684. if( rc!=SQLITE_OK ) return rc;
  685. rc = sqlite3_bind_int64(s, 2, iFirst);
  686. if( rc!=SQLITE_OK ) return rc;
  687. rc = sqlite3_bind_blob(s, 3, doclist->pData, doclist->nData, SQLITE_STATIC);
  688. if( rc!=SQLITE_OK ) return rc;
  689. return sql_single_step_statement(v, TERM_INSERT_STMT, &s);
  690. }
  691. /* update %_term set doclist = [doclist] where rowid = [rowid] */
  692. static int term_update(fulltext_vtab *v, sqlite_int64 rowid,
  693. DocList *doclist){
  694. sqlite3_stmt *s;
  695. int rc = sql_get_statement(v, TERM_UPDATE_STMT, &s);
  696. if( rc!=SQLITE_OK ) return rc;
  697. rc = sqlite3_bind_blob(s, 1, doclist->pData, doclist->nData,
  698. SQLITE_STATIC);
  699. if( rc!=SQLITE_OK ) return rc;
  700. rc = sqlite3_bind_int64(s, 2, rowid);
  701. if( rc!=SQLITE_OK ) return rc;
  702. return sql_single_step_statement(v, TERM_UPDATE_STMT, &s);
  703. }
  704. static int term_delete(fulltext_vtab *v, sqlite_int64 rowid){
  705. sqlite3_stmt *s;
  706. int rc = sql_get_statement(v, TERM_DELETE_STMT, &s);
  707. if( rc!=SQLITE_OK ) return rc;
  708. rc = sqlite3_bind_int64(s, 1, rowid);
  709. if( rc!=SQLITE_OK ) return rc;
  710. return sql_single_step_statement(v, TERM_DELETE_STMT, &s);
  711. }
  712. static void fulltext_vtab_destroy(fulltext_vtab *v){
  713. int iStmt;
  714. for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
  715. if( v->pFulltextStatements[iStmt]!=NULL ){
  716. sqlite3_finalize(v->pFulltextStatements[iStmt]);
  717. v->pFulltextStatements[iStmt] = NULL;
  718. }
  719. }
  720. if( v->pTokenizer!=NULL ){
  721. v->pTokenizer->pModule->xDestroy(v->pTokenizer);
  722. v->pTokenizer = NULL;
  723. }
  724. free((void *) v->zName);
  725. free(v);
  726. }
  727. /* Current interface:
  728. ** argv[0] - module name
  729. ** argv[1] - database name
  730. ** argv[2] - table name
  731. ** argv[3] - tokenizer name (optional, a sensible default is provided)
  732. ** argv[4..] - passed to tokenizer (optional based on tokenizer)
  733. **/
  734. static int fulltextConnect(
  735. sqlite3 *db,
  736. void *pAux,
  737. int argc,
  738. const char * const *argv,
  739. sqlite3_vtab **ppVTab,
  740. char **pzErr
  741. ){
  742. int rc;
  743. fulltext_vtab *v;
  744. sqlite3_tokenizer_module *m = NULL;
  745. assert( argc>=3 );
  746. v = (fulltext_vtab *) malloc(sizeof(fulltext_vtab));
  747. /* sqlite will initialize v->base */
  748. v->db = db;
  749. v->zName = string_dup(argv[2]);
  750. v->pTokenizer = NULL;
  751. if( argc==3 ){
  752. get_simple_tokenizer_module(&m);
  753. } else {
  754. /* TODO(shess) For now, add new tokenizers as else if clauses. */
  755. if( !strcmp(argv[3], "simple") ){
  756. get_simple_tokenizer_module(&m);
  757. } else {
  758. assert( "unrecognized tokenizer"==NULL );
  759. }
  760. }
  761. /* TODO(shess) Since tokenization impacts the index, the parameters
  762. ** to the tokenizer need to be identical when a persistent virtual
  763. ** table is re-created. One solution would be a meta-table to track
  764. ** such information in the database. Then we could verify that the
  765. ** information is identical on subsequent creates.
  766. */
  767. /* TODO(shess) Why isn't argv already (const char **)? */
  768. rc = m->xCreate(argc-3, (const char **) (argv+3), &v->pTokenizer);
  769. if( rc!=SQLITE_OK ) return rc;
  770. v->pTokenizer->pModule = m;
  771. /* TODO: verify the existence of backing tables foo_content, foo_term */
  772. rc = sqlite3_declare_vtab(db, "create table x(content text)");
  773. if( rc!=SQLITE_OK ) return rc;
  774. memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));
  775. *ppVTab = &v->base;
  776. return SQLITE_OK;
  777. }
  778. static int fulltextCreate(
  779. sqlite3 *db,
  780. void *pAux,
  781. int argc,
  782. const char * const *argv,
  783. sqlite3_vtab **ppVTab,
  784. char **pzErr
  785. ){
  786. int rc;
  787. assert( argc>=3 );
  788. /* The %_content table holds the text of each full-text item, with
  789. ** the rowid used as the docid.
  790. **
  791. ** The %_term table maps each term to a document list blob
  792. ** containing elements sorted by ascending docid, each element
  793. ** encoded as:
  794. **
  795. ** docid varint-encoded
  796. ** token count varint-encoded
  797. ** "count" token elements (poslist):
  798. ** position varint-encoded as delta from previous position
  799. ** start offset varint-encoded as delta from previous start offset
  800. ** end offset varint-encoded as delta from start offset
  801. **
  802. ** Additionally, doclist blobs can be chunked into multiple rows,
  803. ** using "first" to order the blobs. "first" is simply the first
  804. ** docid in the blob.
  805. */
  806. /*
  807. ** NOTE(shess) That last sentence is incorrect in the face of
  808. ** deletion, which can leave a doclist that doesn't contain the
  809. ** first from that row. I _believe_ this does not matter to the
  810. ** operation of the system, but it might be reasonable to update
  811. ** appropriately in case this assumption becomes more important.
  812. */
  813. rc = sql_exec(db, argv[2],
  814. "create table %_content(content text);"
  815. "create table %_term(term text, first integer, doclist blob);"
  816. "create index %_index on %_term(term, first)");
  817. if( rc!=SQLITE_OK ) return rc;
  818. return fulltextConnect(db, pAux, argc, argv, ppVTab, pzErr);
  819. }
  820. /* Decide how to handle an SQL query.
  821. * At the moment, MATCH queries can include implicit boolean ANDs; we
  822. * haven't implemented phrase searches or OR yet. */
  823. static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  824. int i;
  825. for(i=0; i<pInfo->nConstraint; ++i){
  826. const struct sqlite3_index_constraint *pConstraint;
  827. pConstraint = &pInfo->aConstraint[i];
  828. if( pConstraint->iColumn==0 &&
  829. pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH &&
  830. pConstraint->usable ){ /* a full-text search */
  831. pInfo->aConstraintUsage[i].argvIndex = 1;
  832. pInfo->aConstraintUsage[i].omit = 1;
  833. pInfo->idxNum = QUERY_FULLTEXT;
  834. pInfo->estimatedCost = 1.0; /* an arbitrary value for now */
  835. return SQLITE_OK;
  836. }
  837. }
  838. pInfo->idxNum = QUERY_GENERIC;
  839. return SQLITE_OK;
  840. }
  841. static int fulltextDisconnect(sqlite3_vtab *pVTab){
  842. fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  843. return SQLITE_OK;
  844. }
  845. static int fulltextDestroy(sqlite3_vtab *pVTab){
  846. fulltext_vtab *v = (fulltext_vtab *)pVTab;
  847. int rc = sql_exec(v->db, v->zName,
  848. "drop table %_content; drop table %_term");
  849. if( rc!=SQLITE_OK ) return rc;
  850. fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  851. return SQLITE_OK;
  852. }
  853. static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  854. fulltext_cursor *c;
  855. c = (fulltext_cursor *) calloc(sizeof(fulltext_cursor), 1);
  856. /* sqlite will initialize c->base */
  857. *ppCursor = &c->base;
  858. return SQLITE_OK;
  859. }
  860. static int fulltextClose(sqlite3_vtab_cursor *pCursor){
  861. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  862. sqlite3_finalize(c->pStmt);
  863. if( c->result.pDoclist!=NULL ){
  864. docListDelete(c->result.pDoclist);
  865. }
  866. free(c);
  867. return SQLITE_OK;
  868. }
  869. static int fulltextNext(sqlite3_vtab_cursor *pCursor){
  870. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  871. sqlite_int64 iDocid;
  872. int rc;
  873. switch( c->iCursorType ){
  874. case QUERY_GENERIC:
  875. /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
  876. rc = sqlite3_step(c->pStmt);
  877. switch( rc ){
  878. case SQLITE_ROW:
  879. c->eof = 0;
  880. return SQLITE_OK;
  881. case SQLITE_DONE:
  882. c->eof = 1;
  883. return SQLITE_OK;
  884. default:
  885. c->eof = 1;
  886. return rc;
  887. }
  888. case QUERY_FULLTEXT:
  889. rc = sqlite3_reset(c->pStmt);
  890. if( rc!=SQLITE_OK ) return rc;
  891. if( readerAtEnd(&c->result)){
  892. c->eof = 1;
  893. return SQLITE_OK;
  894. }
  895. iDocid = readDocid(&c->result);
  896. rc = sqlite3_bind_int64(c->pStmt, 1, iDocid);
  897. if( rc!=SQLITE_OK ) return rc;
  898. /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
  899. rc = sqlite3_step(c->pStmt);
  900. if( rc==SQLITE_ROW ){ /* the case we expect */
  901. c->eof = 0;
  902. return SQLITE_OK;
  903. }
  904. /* an error occurred; abort */
  905. return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
  906. default:
  907. assert( 0 );
  908. return SQLITE_ERROR; /* not reached */
  909. }
  910. }
  911. static int term_select_doclist(fulltext_vtab *v, const char *pTerm, int nTerm,
  912. sqlite3_stmt **ppStmt){
  913. int rc;
  914. if( *ppStmt ){
  915. rc = sqlite3_reset(*ppStmt);
  916. } else {
  917. rc = sql_prepare(v->db, v->zName, ppStmt,
  918. "select doclist from %_term where term = ? order by first");
  919. }
  920. if( rc!=SQLITE_OK ) return rc;
  921. rc = sqlite3_bind_text(*ppStmt, 1, pTerm, nTerm, SQLITE_TRANSIENT);
  922. if( rc!=SQLITE_OK ) return rc;
  923. return sqlite3_step(*ppStmt); /* TODO(adamd): handle schema error */
  924. }
  925. /* Read the posting list for [zTerm]; AND it with the doclist [in] to
  926. * produce the doclist [out], using the given offset [iOffset] for phrase
  927. * matching.
  928. * (*pSelect) is used to hold an SQLite statement used inside this function;
  929. * the caller should initialize *pSelect to NULL before the first call.
  930. */
  931. static int query_merge(fulltext_vtab *v, sqlite3_stmt **pSelect,
  932. const char *zTerm,
  933. DocList *pIn, int iOffset, DocList *out){
  934. int rc;
  935. DocListMerge merge;
  936. if( pIn!=NULL && !pIn->nData ){
  937. /* If [pIn] is already empty, there's no point in reading the
  938. * posting list to AND it in; return immediately. */
  939. return SQLITE_OK;
  940. }
  941. rc = term_select_doclist(v, zTerm, -1, pSelect);
  942. if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;
  943. mergeInit(&merge, pIn, iOffset, out);
  944. while( rc==SQLITE_ROW ){
  945. DocList block;
  946. docListInit(&block, DL_POSITIONS_OFFSETS,
  947. sqlite3_column_blob(*pSelect, 0),
  948. sqlite3_column_bytes(*pSelect, 0));
  949. mergeBlock(&merge, &block);
  950. docListDestroy(&block);
  951. rc = sqlite3_step(*pSelect);
  952. if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  953. return rc;
  954. }
  955. }
  956. return SQLITE_OK;
  957. }
  958. typedef struct QueryTerm {
  959. int is_phrase; /* true if this term begins a new phrase */
  960. const char *zTerm;
  961. } QueryTerm;
  962. /* A parsed query.
  963. *
  964. * As an example, parsing the query ["four score" years "new nation"] will
  965. * yield a Query with 5 terms:
  966. * "four", is_phrase = 1
  967. * "score", is_phrase = 0
  968. * "years", is_phrase = 1
  969. * "new", is_phrase = 1
  970. * "nation", is_phrase = 0
  971. */
  972. typedef struct Query {
  973. int nTerms;
  974. QueryTerm *pTerm;
  975. } Query;
  976. static void query_add(Query *q, int is_phrase, const char *zTerm){
  977. QueryTerm *t;
  978. ++q->nTerms;
  979. q->pTerm = realloc(q->pTerm, q->nTerms * sizeof(q->pTerm[0]));
  980. t = &q->pTerm[q->nTerms - 1];
  981. t->is_phrase = is_phrase;
  982. t->zTerm = zTerm;
  983. }
  984. static void query_free(Query *q){
  985. int i;
  986. for(i = 0; i < q->nTerms; ++i){
  987. free((void *) q->pTerm[i].zTerm);
  988. }
  989. free(q->pTerm);
  990. }
  991. static int tokenize_segment(sqlite3_tokenizer *pTokenizer,
  992. const char *zQuery, int in_phrase,
  993. Query *pQuery){
  994. sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
  995. sqlite3_tokenizer_cursor *pCursor;
  996. int is_first = 1;
  997. int rc = pModule->xOpen(pTokenizer, zQuery, -1, &pCursor);
  998. if( rc!=SQLITE_OK ) return rc;
  999. pCursor->pTokenizer = pTokenizer;
  1000. while( 1 ){
  1001. const char *zToken;
  1002. int nToken, iStartOffset, iEndOffset, dummy_pos;
  1003. rc = pModule->xNext(pCursor,
  1004. &zToken, &nToken,
  1005. &iStartOffset, &iEndOffset,
  1006. &dummy_pos);
  1007. if( rc!=SQLITE_OK ) break;
  1008. query_add(pQuery, !in_phrase || is_first, string_dup_n(zToken, nToken));
  1009. is_first = 0;
  1010. }
  1011. return pModule->xClose(pCursor);
  1012. }
  1013. /* Parse a query string, yielding a Query object. */
  1014. static int parse_query(fulltext_vtab *v, const char *zQuery, Query *pQuery){
  1015. char *zQuery1 = string_dup(zQuery);
  1016. int in_phrase = 0;
  1017. char *s = zQuery1;
  1018. pQuery->nTerms = 0;
  1019. pQuery->pTerm = NULL;
  1020. while( *s ){
  1021. char *t = s;
  1022. while( *t ){
  1023. if( *t=='"' ){
  1024. *t++ = '\0';
  1025. break;
  1026. }
  1027. ++t;
  1028. }
  1029. if( *s ){
  1030. tokenize_segment(v->pTokenizer, s, in_phrase, pQuery);
  1031. }
  1032. s = t;
  1033. in_phrase = !in_phrase;
  1034. }
  1035. free(zQuery1);
  1036. return SQLITE_OK;
  1037. }
  1038. /* Perform a full-text query; return a list of documents in [pResult]. */
  1039. static int fulltext_query(fulltext_vtab *v, const char *zQuery,
  1040. DocList **pResult){
  1041. Query q;
  1042. int phrase_start = -1;
  1043. int i;
  1044. sqlite3_stmt *pSelect = NULL;
  1045. DocList *d = NULL;
  1046. int rc = parse_query(v, zQuery, &q);
  1047. if( rc!=SQLITE_OK ) return rc;
  1048. /* Merge terms. */
  1049. for(i = 0 ; i < q.nTerms ; ++i){
  1050. /* In each merge step, we need to generate positions whenever we're
  1051. * processing a phrase which hasn't ended yet. */
  1052. int need_positions = i<q.nTerms-1 && !q.pTerm[i+1].is_phrase;
  1053. DocList *next = docListNew(need_positions ? DL_POSITIONS : DL_DOCIDS);
  1054. if( q.pTerm[i].is_phrase ){
  1055. phrase_start = i;
  1056. }
  1057. rc = query_merge(v, &pSelect, q.pTerm[i].zTerm, d, i - phrase_start, next);
  1058. if( rc!=SQLITE_OK ) break;
  1059. if( d!=NULL ){
  1060. docListDelete(d);
  1061. }
  1062. d = next;
  1063. }
  1064. sqlite3_finalize(pSelect);
  1065. query_free(&q);
  1066. *pResult = d;
  1067. return rc;
  1068. }
  1069. static int fulltextFilter(sqlite3_vtab_cursor *pCursor,
  1070. int idxNum, const char *idxStr,
  1071. int argc, sqlite3_value **argv){
  1072. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  1073. fulltext_vtab *v = cursor_vtab(c);
  1074. int rc;
  1075. const char *zStatement;
  1076. c->iCursorType = idxNum;
  1077. switch( idxNum ){
  1078. case QUERY_GENERIC:
  1079. zStatement = "select rowid, content from %_content";
  1080. break;
  1081. case QUERY_FULLTEXT: /* full-text search */
  1082. {
  1083. const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
  1084. DocList *pResult;
  1085. assert( argc==1 );
  1086. rc = fulltext_query(v, zQuery, &pResult);
  1087. if( rc!=SQLITE_OK ) return rc;
  1088. readerInit(&c->result, pResult);
  1089. zStatement = "select rowid, content from %_content where rowid = ?";
  1090. break;
  1091. }
  1092. default:
  1093. assert( 0 );
  1094. }
  1095. rc = sql_prepare(v->db, v->zName, &c->pStmt, zStatement);
  1096. if( rc!=SQLITE_OK ) return rc;
  1097. return fulltextNext(pCursor);
  1098. }
  1099. static int fulltextEof(sqlite3_vtab_cursor *pCursor){
  1100. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  1101. return c->eof;
  1102. }
  1103. static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
  1104. sqlite3_context *pContext, int idxCol){
  1105. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  1106. const char *s;
  1107. assert( idxCol==0 );
  1108. s = (const char *) sqlite3_column_text(c->pStmt, 1);
  1109. sqlite3_result_text(pContext, s, -1, SQLITE_TRANSIENT);
  1110. return SQLITE_OK;
  1111. }
  1112. static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  1113. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  1114. *pRowid = sqlite3_column_int64(c->pStmt, 0);
  1115. return SQLITE_OK;
  1116. }
  1117. /* Build a hash table containing all terms in zText. */
  1118. static int build_terms(Hash *terms, sqlite3_tokenizer *pTokenizer,
  1119. const char *zText, sqlite_int64 iDocid){
  1120. sqlite3_tokenizer_cursor *pCursor;
  1121. const char *pToken;
  1122. int nTokenBytes;
  1123. int iStartOffset, iEndOffset, iPosition;
  1124. int rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
  1125. if( rc!=SQLITE_OK ) return rc;
  1126. pCursor->pTokenizer = pTokenizer;
  1127. HashInit(terms, HASH_STRING, 1);
  1128. while( SQLITE_OK==pTokenizer->pModule->xNext(pCursor,
  1129. &pToken, &nTokenBytes,
  1130. &iStartOffset, &iEndOffset,
  1131. &iPosition) ){
  1132. DocList *p;
  1133. /* Positions can't be negative; we use -1 as a terminator internally. */
  1134. if( iPosition<0 ) {
  1135. rc = SQLITE_ERROR;
  1136. goto err;
  1137. }
  1138. p = HashFind(terms, pToken, nTokenBytes);
  1139. if( p==NULL ){
  1140. p = docListNew(DL_POSITIONS_OFFSETS);
  1141. docListAddDocid(p, iDocid);
  1142. HashInsert(terms, pToken, nTokenBytes, p);
  1143. }
  1144. docListAddPosOffset(p, iPosition, iStartOffset, iEndOffset);
  1145. }
  1146. err:
  1147. /* TODO(shess) Check return? Should this be able to cause errors at
  1148. ** this point? Actually, same question about sqlite3_finalize(),
  1149. ** though one could argue that failure there means that the data is
  1150. ** not durable. *ponder*
  1151. */
  1152. pTokenizer->pModule->xClose(pCursor);
  1153. return rc;
  1154. }
  1155. /* Update the %_terms table to map the term [zTerm] to the given rowid. */
  1156. static int index_insert_term(fulltext_vtab *v, const char *zTerm, int nTerm,
  1157. sqlite_int64 iDocid, DocList *p){
  1158. sqlite_int64 iFirst;
  1159. sqlite_int64 iIndexRow;
  1160. DocList doclist;
  1161. int rc = term_chunk_select(v, zTerm, nTerm, iDocid, &iFirst);
  1162. if( rc==SQLITE_DONE ){
  1163. docListInit(&doclist, DL_POSITIONS_OFFSETS, 0, 0);
  1164. if( docListUpdate(&doclist, iDocid, p) ){
  1165. rc = term_insert(v, zTerm, nTerm, iDocid, &doclist);
  1166. docListDestroy(&doclist);
  1167. return rc;
  1168. }
  1169. return SQLITE_OK;
  1170. }
  1171. if( rc!=SQLITE_ROW ) return SQLITE_ERROR;
  1172. /* This word is in the index; add this document ID to its blob. */
  1173. rc = term_select(v, zTerm, nTerm, iFirst, &iIndexRow, &doclist);
  1174. if( rc!=SQLITE_OK ) return rc;
  1175. if( docListUpdate(&doclist, iDocid, p) ){
  1176. /* If the blob is too big, split it in half. */
  1177. if( doclist.nData>CHUNK_MAX ){
  1178. DocList half;
  1179. if( docListSplit(&doclist, &half) ){
  1180. rc = term_insert(v, zTerm, nTerm, firstDocid(&half), &half);
  1181. docListDestroy(&half);
  1182. if( rc!=SQLITE_OK ) goto err;
  1183. }
  1184. }
  1185. rc = term_update(v, iIndexRow, &doclist);
  1186. }
  1187. err:
  1188. docListDestroy(&doclist);
  1189. return rc;
  1190. }
  1191. /* Insert a row into the full-text index; set *piRowid to be the ID of the
  1192. * new row. */
  1193. static int index_insert(fulltext_vtab *v,
  1194. sqlite3_value *pRequestRowid, const char *zText,
  1195. sqlite_int64 *piRowid){
  1196. Hash terms; /* maps term string -> PosList */
  1197. HashElem *e;
  1198. int rc = content_insert(v, pRequestRowid, zText, -1);
  1199. if( rc!=SQLITE_OK ) return rc;
  1200. *piRowid = sqlite3_last_insert_rowid(v->db);
  1201. if( !zText ) return SQLITE_OK; /* nothing to index */
  1202. rc = build_terms(&terms, v->pTokenizer, zText, *piRowid);
  1203. if( rc!=SQLITE_OK ) return rc;
  1204. for(e=HashFirst(&terms); e; e=HashNext(e)){
  1205. DocList *p = HashData(e);
  1206. rc = index_insert_term(v, HashKey(e), HashKeysize(e), *piRowid, p);
  1207. if( rc!=SQLITE_OK ) break;
  1208. }
  1209. for(e=HashFirst(&terms); e; e=HashNext(e)){
  1210. DocList *p = HashData(e);
  1211. docListDelete(p);
  1212. }
  1213. HashClear(&terms);
  1214. return rc;
  1215. }
  1216. static int index_delete_term(fulltext_vtab *v, const char *zTerm, int nTerm,
  1217. sqlite_int64 iDocid){
  1218. sqlite_int64 iFirst;
  1219. sqlite_int64 iIndexRow;
  1220. DocList doclist;
  1221. int rc = term_chunk_select(v, zTerm, nTerm, iDocid, &iFirst);
  1222. if( rc!=SQLITE_ROW ) return SQLITE_ERROR;
  1223. rc = term_select(v, zTerm, nTerm, iFirst, &iIndexRow, &doclist);
  1224. if( rc!=SQLITE_OK ) return rc;
  1225. if( docListUpdate(&doclist, iDocid, NULL) ){
  1226. if( doclist.nData>0 ){
  1227. rc = term_update(v, iIndexRow, &doclist);
  1228. } else { /* empty posting list */
  1229. rc = term_delete(v, iIndexRow);
  1230. }
  1231. }
  1232. docListDestroy(&doclist);
  1233. return rc;
  1234. }
  1235. /* Delete a row from the full-text index. */
  1236. static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
  1237. char *zText;
  1238. Hash terms;
  1239. HashElem *e;
  1240. int rc = content_select(v, iRow, &zText);
  1241. if( rc!=SQLITE_OK ) return rc;
  1242. rc = build_terms(&terms, v->pTokenizer, zText, iRow);
  1243. free(zText);
  1244. if( rc!=SQLITE_OK ) return rc;
  1245. for(e=HashFirst(&terms); e; e=HashNext(e)){
  1246. rc = index_delete_term(v, HashKey(e), HashKeysize(e), iRow);
  1247. if( rc!=SQLITE_OK ) break;
  1248. }
  1249. for(e=HashFirst(&terms); e; e=HashNext(e)){
  1250. DocList *p = HashData(e);
  1251. docListDelete(p);
  1252. }
  1253. HashClear(&terms);
  1254. return content_delete(v, iRow);
  1255. }
  1256. static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
  1257. sqlite_int64 *pRowid){
  1258. fulltext_vtab *v = (fulltext_vtab *) pVtab;
  1259. if( nArg<2 ){
  1260. return index_delete(v, sqlite3_value_int64(ppArg[0]));
  1261. }
  1262. if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
  1263. return SQLITE_ERROR; /* an update; not yet supported */
  1264. }
  1265. assert( nArg==3 ); /* ppArg[1] = rowid, ppArg[2] = content */
  1266. return index_insert(v, ppArg[1],
  1267. (const char *)sqlite3_value_text(ppArg[2]), pRowid);
  1268. }
  1269. static sqlite3_module fulltextModule = {
  1270. 0,
  1271. fulltextCreate,
  1272. fulltextConnect,
  1273. fulltextBestIndex,
  1274. fulltextDisconnect,
  1275. fulltextDestroy,
  1276. fulltextOpen,
  1277. fulltextClose,
  1278. fulltextFilter,
  1279. fulltextNext,
  1280. fulltextEof,
  1281. fulltextColumn,
  1282. fulltextRowid,
  1283. fulltextUpdate
  1284. };
  1285. int fulltext_init(sqlite3 *db){
  1286. return sqlite3_create_module(db, "fulltext", &fulltextModule, 0);
  1287. }
  1288. #if !SQLITE_CORE
  1289. #ifdef _WIN32
  1290. __declspec(dllexport)
  1291. #endif
  1292. int sqlite3_fulltext_init(sqlite3 *db, char **pzErrMsg,
  1293. const sqlite3_api_routines *pApi){
  1294. SQLITE_EXTENSION_INIT2(pApi)
  1295. return fulltext_init(db);
  1296. }
  1297. #endif