interplane.Get Omega
Read in your language

sqlite

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

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / fts5 / fts5_main.c

3909 lines · 121391 bytes Raw Blame History
1/*
2** 2014 Jun 09
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 is an SQLite module implementing full-text search.
14*/
15
16
17#include "fts5Int.h"
18
19/*
20** This variable is set to false when running tests for which the on disk
21** structures should not be corrupt. Otherwise, true. If it is false, extra
22** assert() conditions in the fts5 code are activated - conditions that are
23** only true if it is guaranteed that the fts5 database is not corrupt.
24*/
25#ifdef SQLITE_DEBUG
26int sqlite3_fts5_may_be_corrupt = 1;
27#endif
28
29
30typedef struct Fts5Auxdata Fts5Auxdata;
31typedef struct Fts5Auxiliary Fts5Auxiliary;
32typedef struct Fts5Cursor Fts5Cursor;
33typedef struct Fts5FullTable Fts5FullTable;
34typedef struct Fts5Sorter Fts5Sorter;
35typedef struct Fts5TokenizerModule Fts5TokenizerModule;
36
37/*
38** NOTES ON TRANSACTIONS:
39**
40** SQLite invokes the following virtual table methods as transactions are
41** opened and closed by the user:
42**
43** xBegin(): Start of a new transaction.
44** xSync(): Initial part of two-phase commit.
45** xCommit(): Final part of two-phase commit.
46** xRollback(): Rollback the transaction.
47**
48** Anything that is required as part of a commit that may fail is performed
49** in the xSync() callback. Current versions of SQLite ignore any errors
50** returned by xCommit().
51**
52** And as sub-transactions are opened/closed:
53**
54** xSavepoint(int S): Open savepoint S.
55** xRelease(int S): Commit and close savepoint S.
56** xRollbackTo(int S): Rollback to start of savepoint S.
57**
58** During a write-transaction the fts5_index.c module may cache some data
59** in-memory. It is flushed to disk whenever xSync(), xRelease() or
60** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
61** is called.
62**
63** Additionally, if SQLITE_DEBUG is defined, an instance of the following
64** structure is used to record the current transaction state. This information
65** is not required, but it is used in the assert() statements executed by
66** function fts5CheckTransactionState() (see below).
67*/
68struct Fts5TransactionState {
69 int eState; /* 0==closed, 1==open, 2==synced */
70 int iSavepoint; /* Number of open savepoints (0 -> none) */
71};
72
73/*
74** A single object of this type is allocated when the FTS5 module is
75** registered with a database handle. It is used to store pointers to
76** all registered FTS5 extensions - tokenizers and auxiliary functions.
77*/
78struct Fts5Global {
79 fts5_api api; /* User visible part of object (see fts5.h) */
80 sqlite3 *db; /* Associated database connection */
81 i64 iNextId; /* Used to allocate unique cursor ids */
82 Fts5Auxiliary *pAux; /* First in list of all aux. functions */
83 Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
84 Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
85 Fts5Cursor *pCsr; /* First in list of all open cursors */
86 u32 aLocaleHdr[4];
87};
88
89/*
90** Size of header on fts5_locale() values. And macro to access a buffer
91** containing a copy of the header from an Fts5Config pointer.
92*/
93#define FTS5_LOCALE_HDR_SIZE ((int)sizeof( ((Fts5Global*)0)->aLocaleHdr ))
94#define FTS5_LOCALE_HDR(pConfig) ((const u8*)(pConfig->pGlobal->aLocaleHdr))
95
96#define FTS5_INSTTOKEN_SUBTYPE 73
97
98/*
99** Each auxiliary function registered with the FTS5 module is represented
100** by an object of the following type. All such objects are stored as part
101** of the Fts5Global.pAux list.
102*/
103struct Fts5Auxiliary {
104 Fts5Global *pGlobal; /* Global context for this function */
105 char *zFunc; /* Function name (nul-terminated) */
106 void *pUserData; /* User-data pointer */
107 fts5_extension_function xFunc; /* Callback function */
108 void (*xDestroy)(void*); /* Destructor function */
109 Fts5Auxiliary *pNext; /* Next registered auxiliary function */
110};
111
112/*
113** Each tokenizer module registered with the FTS5 module is represented
114** by an object of the following type. All such objects are stored as part
115** of the Fts5Global.pTok list.
116**
117** bV2Native:
118** True if the tokenizer was registered using xCreateTokenizer_v2(), false
119** for xCreateTokenizer(). If this variable is true, then x2 is populated
120** with the routines as supplied by the caller and x1 contains synthesized
121** wrapper routines. In this case the user-data pointer passed to
122** x1.xCreate should be a pointer to the Fts5TokenizerModule structure,
123** not a copy of pUserData.
124**
125** Of course, if bV2Native is false, then x1 contains the real routines and
126** x2 the synthesized ones. In this case a pointer to the Fts5TokenizerModule
127** object should be passed to x2.xCreate.
128**
129** The synthesized wrapper routines are necessary for xFindTokenizer(_v2)
130** calls.
131*/
132struct Fts5TokenizerModule {
133 char *zName; /* Name of tokenizer */
134 void *pUserData; /* User pointer passed to xCreate() */
135 int bV2Native; /* True if v2 native tokenizer */
136 fts5_tokenizer x1; /* Tokenizer functions */
137 fts5_tokenizer_v2 x2; /* V2 tokenizer functions */
138 void (*xDestroy)(void*); /* Destructor function */
139 Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
140};
141
142struct Fts5FullTable {
143 Fts5Table p; /* Public class members from fts5Int.h */
144 Fts5Storage *pStorage; /* Document store */
145 Fts5Global *pGlobal; /* Global (connection wide) data */
146 Fts5Cursor *pSortCsr; /* Sort data from this cursor */
147 int iSavepoint; /* Successful xSavepoint()+1 */
148
149#ifdef SQLITE_DEBUG
150 struct Fts5TransactionState ts;
151#endif
152};
153
154struct Fts5MatchPhrase {
155 Fts5Buffer *pPoslist; /* Pointer to current poslist */
156 int nTerm; /* Size of phrase in terms */
157};
158
159/*
160** pStmt:
161** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
162**
163** aIdx[]:
164** There is one entry in the aIdx[] array for each phrase in the query,
165** the value of which is the offset within aPoslist[] following the last
166** byte of the position list for the corresponding phrase.
167*/
168struct Fts5Sorter {
169 sqlite3_stmt *pStmt;
170 i64 iRowid; /* Current rowid */
171 const u8 *aPoslist; /* Position lists for current row */
172 int nIdx; /* Number of entries in aIdx[] */
173 int aIdx[FLEXARRAY]; /* Offsets into aPoslist for current row */
174};
175
176/* Size (int bytes) of an Fts5Sorter object with N indexes */
177#define SZ_FTS5SORTER(N) (offsetof(Fts5Sorter,nIdx)+((N+2)/2)*sizeof(i64))
178
179/*
180** Virtual-table cursor object.
181**
182** iSpecial:
183** If this is a 'special' query (refer to function fts5SpecialMatch()),
184** then this variable contains the result of the query.
185**
186** iFirstRowid, iLastRowid:
187** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
188** cursor iterates in ascending order of rowids, iFirstRowid is the lower
189** limit of rowids to return, and iLastRowid the upper. In other words, the
190** WHERE clause in the user's query might have been:
191**
192** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
193**
194** If the cursor iterates in descending order of rowid, iFirstRowid
195** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
196** the lower.
197*/
198struct Fts5Cursor {
199 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
200 Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
201 int *aColumnSize; /* Values for xColumnSize() */
202 i64 iCsrId; /* Cursor id */
203
204 /* Zero from this point onwards on cursor reset */
205 int ePlan; /* FTS5_PLAN_XXX value */
206 int bDesc; /* True for "ORDER BY rowid DESC" queries */
207 i64 iFirstRowid; /* Return no rowids earlier than this */
208 i64 iLastRowid; /* Return no rowids later than this */
209 sqlite3_stmt *pStmt; /* Statement used to read %_content */
210 Fts5Expr *pExpr; /* Expression for MATCH queries */
211 Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
212 int csrflags; /* Mask of cursor flags (see below) */
213 i64 iSpecial; /* Result of special query */
214
215 /* "rank" function. Populated on demand from vtab.xColumn(). */
216 char *zRank; /* Custom rank function */
217 char *zRankArgs; /* Custom rank function args */
218 Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
219 int nRankArg; /* Number of trailing arguments for rank() */
220 sqlite3_value **apRankArg; /* Array of trailing arguments */
221 sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
222
223 /* Auxiliary data storage */
224 Fts5Auxiliary *pAux; /* Currently executing extension function */
225 Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
226
227 /* Cache used by auxiliary API functions xInst() and xInstCount() */
228 Fts5PoslistReader *aInstIter; /* One for each phrase */
229 int nInstAlloc; /* Size of aInst[] array (entries / 3) */
230 int nInstCount; /* Number of phrase instances */
231 int *aInst; /* 3 integers per phrase instance */
232};
233
234/*
235** Bits that make up the "idxNum" parameter passed indirectly by
236** xBestIndex() to xFilter().
237*/
238#define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
239#define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
240#define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
241#define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
242#define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
243
244#define FTS5_BI_ORDER_RANK 0x0020
245#define FTS5_BI_ORDER_ROWID 0x0040
246#define FTS5_BI_ORDER_DESC 0x0080
247
248/*
249** Values for Fts5Cursor.csrflags
250*/
251#define FTS5CSR_EOF 0x01
252#define FTS5CSR_REQUIRE_CONTENT 0x02
253#define FTS5CSR_REQUIRE_DOCSIZE 0x04
254#define FTS5CSR_REQUIRE_INST 0x08
255#define FTS5CSR_FREE_ZRANK 0x10
256#define FTS5CSR_REQUIRE_RESEEK 0x20
257#define FTS5CSR_REQUIRE_POSLIST 0x40
258
259#define BitFlagAllTest(x,y) (((x) & (y))==(y))
260#define BitFlagTest(x,y) (((x) & (y))!=0)
261
262
263/*
264** Macros to Set(), Clear() and Test() cursor flags.
265*/
266#define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
267#define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
268#define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
269
270struct Fts5Auxdata {
271 Fts5Auxiliary *pAux; /* Extension to which this belongs */
272 void *pPtr; /* Pointer value */
273 void(*xDelete)(void*); /* Destructor */
274 Fts5Auxdata *pNext; /* Next object in linked list */
275};
276
277#ifdef SQLITE_DEBUG
278#define FTS5_BEGIN 1
279#define FTS5_SYNC 2
280#define FTS5_COMMIT 3
281#define FTS5_ROLLBACK 4
282#define FTS5_SAVEPOINT 5
283#define FTS5_RELEASE 6
284#define FTS5_ROLLBACKTO 7
285static void fts5CheckTransactionState(Fts5FullTable *p, int op, int iSavepoint){
286 switch( op ){
287 case FTS5_BEGIN:
288 assert( p->ts.eState==0 );
289 p->ts.eState = 1;
290 p->ts.iSavepoint = -1;
291 break;
292
293 case FTS5_SYNC:
294 assert( p->ts.eState==1 || p->ts.eState==2 );
295 p->ts.eState = 2;
296 break;
297
298 case FTS5_COMMIT:
299 assert( p->ts.eState==2 );
300 p->ts.eState = 0;
301 break;
302
303 case FTS5_ROLLBACK:
304 assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
305 p->ts.eState = 0;
306 break;
307
308 case FTS5_SAVEPOINT:
309 assert( p->ts.eState>=1 );
310 assert( iSavepoint>=0 );
311 assert( iSavepoint>=p->ts.iSavepoint );
312 p->ts.iSavepoint = iSavepoint;
313 break;
314
315 case FTS5_RELEASE:
316 assert( p->ts.eState>=1 );
317 assert( iSavepoint>=0 );
318 assert( iSavepoint<=p->ts.iSavepoint );
319 p->ts.iSavepoint = iSavepoint-1;
320 break;
321
322 case FTS5_ROLLBACKTO:
323 assert( p->ts.eState>=1 );
324 assert( iSavepoint>=-1 );
325 /* The following assert() can fail if another vtab strikes an error
326 ** within an xSavepoint() call then SQLite calls xRollbackTo() - without
327 ** having called xSavepoint() on this vtab. */
328 /* assert( iSavepoint<=p->ts.iSavepoint ); */
329 p->ts.iSavepoint = iSavepoint;
330 break;
331 }
332}
333#else
334# define fts5CheckTransactionState(x,y,z)
335#endif
336
337/*
338** Return true if pTab is a contentless table. If parameter bIncludeUnindexed
339** is true, this includes contentless tables that store UNINDEXED columns
340** only.
341*/
342static int fts5IsContentless(Fts5FullTable *pTab, int bIncludeUnindexed){
343 int eContent = pTab->p.pConfig->eContent;
344 return (
345 eContent==FTS5_CONTENT_NONE
346 || (bIncludeUnindexed && eContent==FTS5_CONTENT_UNINDEXED)
347 );
348}
349
350/*
351** Delete a virtual table handle allocated by fts5InitVtab().
352*/
353static void fts5FreeVtab(Fts5FullTable *pTab){
354 if( pTab ){
355 sqlite3Fts5IndexClose(pTab->p.pIndex);
356 sqlite3Fts5StorageClose(pTab->pStorage);
357 sqlite3Fts5ConfigFree(pTab->p.pConfig);
358 sqlite3_free(pTab);
359 }
360}
361
362/*
363** The xDisconnect() virtual table method.
364*/
365static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
366 fts5FreeVtab((Fts5FullTable*)pVtab);
367 return SQLITE_OK;
368}
369
370/*
371** The xDestroy() virtual table method.
372*/
373static int fts5DestroyMethod(sqlite3_vtab *pVtab){
374 Fts5Table *pTab = (Fts5Table*)pVtab;
375 int rc = sqlite3Fts5DropAll(pTab->pConfig);
376 if( rc==SQLITE_OK ){
377 fts5FreeVtab((Fts5FullTable*)pVtab);
378 }
379 return rc;
380}
381
382/*
383** This function is the implementation of both the xConnect and xCreate
384** methods of the FTS3 virtual table.
385**
386** The argv[] array contains the following:
387**
388** argv[0] -> module name ("fts5")
389** argv[1] -> database name
390** argv[2] -> table name
391** argv[...] -> "column name" and other module argument fields.
392*/
393static int fts5InitVtab(
394 int bCreate, /* True for xCreate, false for xConnect */
395 sqlite3 *db, /* The SQLite database connection */
396 void *pAux, /* Hash table containing tokenizers */
397 int argc, /* Number of elements in argv array */
398 const char * const *argv, /* xCreate/xConnect argument array */
399 sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
400 char **pzErr /* Write any error message here */
401){
402 Fts5Global *pGlobal = (Fts5Global*)pAux;
403 const char **azConfig = (const char**)argv;
404 int rc = SQLITE_OK; /* Return code */
405 Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
406 Fts5FullTable *pTab = 0; /* New virtual table object */
407
408 /* Allocate the new vtab object and parse the configuration */
409 pTab = (Fts5FullTable*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5FullTable));
410 if( rc==SQLITE_OK ){
411 rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
412 assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
413 }
414 if( rc==SQLITE_OK ){
415 pConfig->pzErrmsg = pzErr;
416 pTab->p.pConfig = pConfig;
417 pTab->pGlobal = pGlobal;
418 if( bCreate || sqlite3Fts5TokenizerPreload(&pConfig->t) ){
419 rc = sqlite3Fts5LoadTokenizer(pConfig);
420 }
421 }
422
423 /* Open the index sub-system */
424 if( rc==SQLITE_OK ){
425 rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->p.pIndex, pzErr);
426 }
427
428 /* Open the storage sub-system */
429 if( rc==SQLITE_OK ){
430 rc = sqlite3Fts5StorageOpen(
431 pConfig, pTab->p.pIndex, bCreate, &pTab->pStorage, pzErr
432 );
433 }
434
435 /* Call sqlite3_declare_vtab() */
436 if( rc==SQLITE_OK ){
437 rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
438 }
439
440 /* Load the initial configuration */
441 if( rc==SQLITE_OK ){
442 rc = sqlite3Fts5ConfigLoad(pTab->p.pConfig, pTab->p.pConfig->iCookie-1);
443 }
444
445 if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
446 rc = sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, (int)1);
447 }
448 if( rc==SQLITE_OK ){
449 rc = sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
450 }
451
452 if( pConfig ) pConfig->pzErrmsg = 0;
453 if( rc!=SQLITE_OK ){
454 fts5FreeVtab(pTab);
455 pTab = 0;
456 }else if( bCreate ){
457 fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
458 }
459 *ppVTab = (sqlite3_vtab*)pTab;
460 return rc;
461}
462
463/*
464** The xConnect() and xCreate() methods for the virtual table. All the
465** work is done in function fts5InitVtab().
466*/
467static int fts5ConnectMethod(
468 sqlite3 *db, /* Database connection */
469 void *pAux, /* Pointer to tokenizer hash table */
470 int argc, /* Number of elements in argv array */
471 const char * const *argv, /* xCreate/xConnect argument array */
472 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
473 char **pzErr /* OUT: sqlite3_malloc'd error message */
474){
475 return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
476}
477static int fts5CreateMethod(
478 sqlite3 *db, /* Database connection */
479 void *pAux, /* Pointer to tokenizer hash table */
480 int argc, /* Number of elements in argv array */
481 const char * const *argv, /* xCreate/xConnect argument array */
482 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
483 char **pzErr /* OUT: sqlite3_malloc'd error message */
484){
485 return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
486}
487
488/*
489** The different query plans.
490*/
491#define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
492#define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
493#define FTS5_PLAN_SPECIAL 3 /* An internal query */
494#define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
495#define FTS5_PLAN_SCAN 5 /* No usable constraint */
496#define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
497
498/*
499** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
500** extension is currently being used by a version of SQLite too old to
501** support index-info flags. In that case this function is a no-op.
502*/
503static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
504#if SQLITE_VERSION_NUMBER>=3008012
505#ifndef SQLITE_CORE
506 if( sqlite3_libversion_number()>=3008012 )
507#endif
508 {
509 pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
510 }
511#endif
512}
513
514static void fts5SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
515#if SQLITE_VERSION_NUMBER>=3008002
516#ifndef SQLITE_CORE
517 if( sqlite3_libversion_number()>=3008002 )
518#endif
519 {
520 pIdxInfo->estimatedRows = MAX(1, nRow);
521 }
522#endif
523}
524
525static int fts5UsePatternMatch(
526 Fts5Config *pConfig,
527 struct sqlite3_index_constraint *p
528){
529 assert( FTS5_PATTERN_GLOB==SQLITE_INDEX_CONSTRAINT_GLOB );
530 assert( FTS5_PATTERN_LIKE==SQLITE_INDEX_CONSTRAINT_LIKE );
531 if( pConfig->t.ePattern==FTS5_PATTERN_GLOB && p->op==FTS5_PATTERN_GLOB ){
532 return 1;
533 }
534 if( pConfig->t.ePattern==FTS5_PATTERN_LIKE
535 && (p->op==FTS5_PATTERN_LIKE || p->op==FTS5_PATTERN_GLOB)
536 ){
537 return 1;
538 }
539 return 0;
540}
541
542/*
543** Implementation of the xBestIndex method for FTS5 tables. Within the
544** WHERE constraint, it searches for the following:
545**
546** 1. A MATCH constraint against the table column.
547** 2. A MATCH constraint against the "rank" column.
548** 3. A MATCH constraint against some other column.
549** 4. An == constraint against the rowid column.
550** 5. A < or <= constraint against the rowid column.
551** 6. A > or >= constraint against the rowid column.
552**
553** Within the ORDER BY, the following are supported:
554**
555** 5. ORDER BY rank [ASC|DESC]
556** 6. ORDER BY rowid [ASC|DESC]
557**
558** Information for the xFilter call is passed via both the idxNum and
559** idxStr variables. Specifically, idxNum is a bitmask of the following
560** flags used to encode the ORDER BY clause:
561**
562** FTS5_BI_ORDER_RANK
563** FTS5_BI_ORDER_ROWID
564** FTS5_BI_ORDER_DESC
565**
566** idxStr is used to encode data from the WHERE clause. For each argument
567** passed to the xFilter method, the following is appended to idxStr:
568**
569** Match against table column: "m"
570** Match against rank column: "r"
571** Match against other column: "M<column-number>"
572** LIKE against other column: "L<column-number>"
573** GLOB against other column: "G<column-number>"
574** Equality constraint against the rowid: "="
575** A < or <= against the rowid: "<"
576** A > or >= against the rowid: ">"
577**
578** This function ensures that there is at most one "r" or "=". And that if
579** there exists an "=" then there is no "<" or ">".
580**
581** If an unusable MATCH operator is present in the WHERE clause, then
582** SQLITE_CONSTRAINT is returned.
583**
584** Costs are assigned as follows:
585**
586** a) If a MATCH operator is present, the cost depends on the other
587** constraints also present. As follows:
588**
589** * No other constraints: cost=50000.0
590** * One rowid range constraint: cost=37500.0
591** * Both rowid range constraints: cost=30000.0
592** * An == rowid constraint: cost=25000.0
593**
594** b) Otherwise, if there is no MATCH:
595**
596** * No other constraints: cost=3000000.0
597** * One rowid range constraints: cost=2250000.0
598** * Both rowid range constraint: cost=750000.0
599** * An == rowid constraint: cost=25.0
600**
601** Costs are not modified by the ORDER BY clause.
602**
603** The ratios used in case (a) are based on informal results obtained from
604** the tool/fts5cost.tcl script. The "MATCH and ==" combination has the
605** cost set quite high because the query may be a prefix query. Unless
606** there is a prefix index, prefix queries with rowid constraints are much
607** more expensive than non-prefix queries with rowid constraints.
608**
609** The estimated rows returned is set to the cost/40. For simple queries,
610** experimental results show that cost/4 might be about right. But for
611** more complex queries that use multiple terms the number of rows might
612** be far fewer than this. So we compromise and use cost/40.
613*/
614static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
615 Fts5Table *pTab = (Fts5Table*)pVTab;
616 Fts5Config *pConfig = pTab->pConfig;
617 const int nCol = pConfig->nCol;
618 int idxFlags = 0; /* Parameter passed through to xFilter() */
619 int i;
620
621 char *idxStr;
622 int iIdxStr = 0;
623 int iCons = 0;
624
625 int bSeenEq = 0;
626 int bSeenGt = 0;
627 int bSeenLt = 0;
628 int nSeenMatch = 0;
629 int bSeenRank = 0;
630
631
632 assert( SQLITE_INDEX_CONSTRAINT_EQ<SQLITE_INDEX_CONSTRAINT_MATCH );
633 assert( SQLITE_INDEX_CONSTRAINT_GT<SQLITE_INDEX_CONSTRAINT_MATCH );
634 assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
635 assert( SQLITE_INDEX_CONSTRAINT_GE<SQLITE_INDEX_CONSTRAINT_MATCH );
636 assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
637
638 if( pConfig->bLock ){
639 pTab->base.zErrMsg = sqlite3_mprintf(
640 "recursively defined fts5 content table"
641 );
642 return SQLITE_ERROR;
643 }
644
645 idxStr = (char*)sqlite3_malloc64((i64)pInfo->nConstraint * 8 + 1);
646 if( idxStr==0 ) return SQLITE_NOMEM;
647 pInfo->idxStr = idxStr;
648 pInfo->needToFreeIdxStr = 1;
649
650 for(i=0; i<pInfo->nConstraint; i++){
651 struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
652 int iCol = p->iColumn;
653 if( p->op==SQLITE_INDEX_CONSTRAINT_MATCH
654 || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol>=nCol)
655 ){
656 /* A MATCH operator or equivalent */
657 if( p->usable==0 || iCol<0 ){
658 /* As there exists an unusable MATCH constraint this is an
659 ** unusable plan. Return SQLITE_CONSTRAINT. */
660 idxStr[iIdxStr] = 0;
661 return SQLITE_CONSTRAINT;
662 }else{
663 if( iCol==nCol+1 ){
664 if( bSeenRank ) continue;
665 idxStr[iIdxStr++] = 'r';
666 bSeenRank = 1;
667 }else{
668 nSeenMatch++;
669 idxStr[iIdxStr++] = 'M';
670 sqlite3_snprintf(6, &idxStr[iIdxStr], "%d", iCol);
671 iIdxStr += (int)strlen(&idxStr[iIdxStr]);
672 assert( idxStr[iIdxStr]=='\0' );
673 }
674 pInfo->aConstraintUsage[i].argvIndex = ++iCons;
675 pInfo->aConstraintUsage[i].omit = 1;
676 }
677 }else if( p->usable ){
678 if( iCol>=0 && iCol<nCol && fts5UsePatternMatch(pConfig, p)
679 && pConfig->abUnindexed[iCol]==0
680 ){
681 assert( p->op==FTS5_PATTERN_LIKE || p->op==FTS5_PATTERN_GLOB );
682 idxStr[iIdxStr++] = p->op==FTS5_PATTERN_LIKE ? 'L' : 'G';
683 sqlite3_snprintf(6, &idxStr[iIdxStr], "%d", iCol);
684 idxStr += strlen(&idxStr[iIdxStr]);
685 pInfo->aConstraintUsage[i].argvIndex = ++iCons;
686 assert( idxStr[iIdxStr]=='\0' );
687 nSeenMatch++;
688 }else if( bSeenEq==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol<0 ){
689 idxStr[iIdxStr++] = '=';
690 bSeenEq = 1;
691 pInfo->aConstraintUsage[i].argvIndex = ++iCons;
692 }
693 }
694 }
695
696 if( bSeenEq==0 ){
697 for(i=0; i<pInfo->nConstraint; i++){
698 struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
699 if( p->iColumn<0 && p->usable ){
700 int op = p->op;
701 if( op==SQLITE_INDEX_CONSTRAINT_LT || op==SQLITE_INDEX_CONSTRAINT_LE ){
702 if( bSeenLt ) continue;
703 idxStr[iIdxStr++] = '<';
704 pInfo->aConstraintUsage[i].argvIndex = ++iCons;
705 bSeenLt = 1;
706 }else
707 if( op==SQLITE_INDEX_CONSTRAINT_GT || op==SQLITE_INDEX_CONSTRAINT_GE ){
708 if( bSeenGt ) continue;
709 idxStr[iIdxStr++] = '>';
710 pInfo->aConstraintUsage[i].argvIndex = ++iCons;
711 bSeenGt = 1;
712 }
713 }
714 }
715 }
716 idxStr[iIdxStr] = '\0';
717
718 /* Set idxFlags flags for the ORDER BY clause
719 **
720 ** Note that tokendata=1 tables cannot currently handle "ORDER BY rowid DESC".
721 */
722 if( pInfo->nOrderBy==1 ){
723 int iSort = pInfo->aOrderBy[0].iColumn;
724 if( iSort==(pConfig->nCol+1) && nSeenMatch>0 ){
725 idxFlags |= FTS5_BI_ORDER_RANK;
726 }else if( iSort==-1 && (!pInfo->aOrderBy[0].desc || !pConfig->bTokendata) ){
727 idxFlags |= FTS5_BI_ORDER_ROWID;
728 }
729 if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
730 pInfo->orderByConsumed = 1;
731 if( pInfo->aOrderBy[0].desc ){
732 idxFlags |= FTS5_BI_ORDER_DESC;
733 }
734 }
735 }
736
737 /* Calculate the estimated cost based on the flags set in idxFlags. */
738 if( bSeenEq ){
739 pInfo->estimatedCost = nSeenMatch ? 25000.0 : 25.0;
740 fts5SetEstimatedRows(pInfo, 1);
741 fts5SetUniqueFlag(pInfo);
742 }else{
743 i64 nEstRows;
744 if( nSeenMatch ){
745 if( bSeenLt && bSeenGt ){
746 pInfo->estimatedCost = 50000.0;
747 }else if( bSeenLt || bSeenGt ){
748 pInfo->estimatedCost = 37500.0;
749 }else{
750 pInfo->estimatedCost = 50000.0;
751 }
752 nEstRows = (i64)(pInfo->estimatedCost / 40.0);
753 for(i=1; i<nSeenMatch; i++){
754 pInfo->estimatedCost *= 2.5;
755 nEstRows = nEstRows / 2;
756 }
757 }else{
758 if( bSeenLt && bSeenGt ){
759 pInfo->estimatedCost = 750000.0;
760 }else if( bSeenLt || bSeenGt ){
761 pInfo->estimatedCost = 2250000.0;
762 }else{
763 pInfo->estimatedCost = 3000000.0;
764 }
765 nEstRows = (i64)(pInfo->estimatedCost / 4.0);
766 }
767 fts5SetEstimatedRows(pInfo, nEstRows);
768 }
769
770 pInfo->idxNum = idxFlags;
771 return SQLITE_OK;
772}
773
774static int fts5NewTransaction(Fts5FullTable *pTab){
775 Fts5Cursor *pCsr;
776 for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
777 if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
778 }
779 return sqlite3Fts5StorageReset(pTab->pStorage);
780}
781
782/*
783** Implementation of xOpen method.
784*/
785static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
786 Fts5FullTable *pTab = (Fts5FullTable*)pVTab;
787 Fts5Config *pConfig = pTab->p.pConfig;
788 Fts5Cursor *pCsr = 0; /* New cursor object */
789 sqlite3_int64 nByte; /* Bytes of space to allocate */
790 int rc; /* Return code */
791
792 rc = fts5NewTransaction(pTab);
793 if( rc==SQLITE_OK ){
794 nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
795 pCsr = (Fts5Cursor*)sqlite3_malloc64(nByte);
796 if( pCsr ){
797 Fts5Global *pGlobal = pTab->pGlobal;
798 memset(pCsr, 0, (size_t)nByte);
799 pCsr->aColumnSize = (int*)&pCsr[1];
800 pCsr->pNext = pGlobal->pCsr;
801 pGlobal->pCsr = pCsr;
802 pCsr->iCsrId = ++pGlobal->iNextId;
803 }else{
804 rc = SQLITE_NOMEM;
805 }
806 }
807 *ppCsr = (sqlite3_vtab_cursor*)pCsr;
808 return rc;
809}
810
811static int fts5StmtType(Fts5Cursor *pCsr){
812 if( pCsr->ePlan==FTS5_PLAN_SCAN ){
813 return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
814 }
815 return FTS5_STMT_LOOKUP;
816}
817
818/*
819** This function is called after the cursor passed as the only argument
820** is moved to point at a different row. It clears all cached data
821** specific to the previous row stored by the cursor object.
822*/
823static void fts5CsrNewrow(Fts5Cursor *pCsr){
824 CsrFlagSet(pCsr,
825 FTS5CSR_REQUIRE_CONTENT
826 | FTS5CSR_REQUIRE_DOCSIZE
827 | FTS5CSR_REQUIRE_INST
828 | FTS5CSR_REQUIRE_POSLIST
829 );
830}
831
832static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
833 Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
834 Fts5Auxdata *pData;
835 Fts5Auxdata *pNext;
836
837 sqlite3_free(pCsr->aInstIter);
838 sqlite3_free(pCsr->aInst);
839 if( pCsr->pStmt ){
840 int eStmt = fts5StmtType(pCsr);
841 sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
842 }
843 if( pCsr->pSorter ){
844 Fts5Sorter *pSorter = pCsr->pSorter;
845 sqlite3_finalize(pSorter->pStmt);
846 sqlite3_free(pSorter);
847 }
848
849 if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
850 sqlite3Fts5ExprFree(pCsr->pExpr);
851 }
852
853 for(pData=pCsr->pAuxdata; pData; pData=pNext){
854 pNext = pData->pNext;
855 if( pData->xDelete ) pData->xDelete(pData->pPtr);
856 sqlite3_free(pData);
857 }
858
859 sqlite3_finalize(pCsr->pRankArgStmt);
860 sqlite3_free(pCsr->apRankArg);
861
862 if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
863 sqlite3_free(pCsr->zRank);
864 sqlite3_free(pCsr->zRankArgs);
865 }
866
867 sqlite3Fts5IndexCloseReader(pTab->p.pIndex);
868 memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
869}
870
871
872/*
873** Close the cursor. For additional information see the documentation
874** on the xClose method of the virtual table interface.
875*/
876static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
877 if( pCursor ){
878 Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
879 Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
880 Fts5Cursor **pp;
881
882 fts5FreeCursorComponents(pCsr);
883 /* Remove the cursor from the Fts5Global.pCsr list */
884 for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
885 *pp = pCsr->pNext;
886
887 sqlite3_free(pCsr);
888 }
889 return SQLITE_OK;
890}
891
892static int fts5SorterNext(Fts5Cursor *pCsr){
893 Fts5Sorter *pSorter = pCsr->pSorter;
894 int rc;
895
896 rc = sqlite3_step(pSorter->pStmt);
897 if( rc==SQLITE_DONE ){
898 rc = SQLITE_OK;
899 CsrFlagSet(pCsr, FTS5CSR_EOF|FTS5CSR_REQUIRE_CONTENT);
900 }else if( rc==SQLITE_ROW ){
901 const u8 *a;
902 const u8 *aBlob;
903 int nBlob;
904 int i;
905 int iOff = 0;
906 rc = SQLITE_OK;
907
908 pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
909 nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
910 aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
911
912 /* nBlob==0 in detail=none mode. */
913 if( nBlob>0 ){
914 for(i=0; i<(pSorter->nIdx-1); i++){
915 int iVal;
916 a += fts5GetVarint32(a, iVal);
917 iOff += iVal;
918 pSorter->aIdx[i] = iOff;
919 }
920 pSorter->aIdx[i] = &aBlob[nBlob] - a;
921 pSorter->aPoslist = a;
922 }
923
924 fts5CsrNewrow(pCsr);
925 }
926
927 return rc;
928}
929
930
931/*
932** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
933** open on table pTab.
934*/
935static void fts5TripCursors(Fts5FullTable *pTab){
936 Fts5Cursor *pCsr;
937 for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
938 if( pCsr->ePlan==FTS5_PLAN_MATCH
939 && pCsr->base.pVtab==(sqlite3_vtab*)pTab
940 ){
941 CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
942 }
943 }
944}
945
946/*
947** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
948** argument, close and reopen all Fts5IndexIter iterators that the cursor
949** is using. Then attempt to move the cursor to a rowid equal to or laster
950** (in the cursors sort order - ASC or DESC) than the current rowid.
951**
952** If the new rowid is not equal to the old, set output parameter *pbSkip
953** to 1 before returning. Otherwise, leave it unchanged.
954**
955** Return SQLITE_OK if successful or if no reseek was required, or an
956** error code if an error occurred.
957*/
958static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
959 int rc = SQLITE_OK;
960 assert( *pbSkip==0 );
961 if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
962 Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
963 int bDesc = pCsr->bDesc;
964 i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
965
966 rc = sqlite3Fts5ExprFirst(
967 pCsr->pExpr, pTab->p.pIndex, iRowid, pCsr->iLastRowid, bDesc
968 );
969 if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
970 *pbSkip = 1;
971 }
972
973 CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
974 fts5CsrNewrow(pCsr);
975 if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
976 CsrFlagSet(pCsr, FTS5CSR_EOF);
977 *pbSkip = 1;
978 }
979 }
980 return rc;
981}
982
983
984/*
985** Advance the cursor to the next row in the table that matches the
986** search criteria.
987**
988** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
989** even if we reach end-of-file. The fts5EofMethod() will be called
990** subsequently to determine whether or not an EOF was hit.
991*/
992static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
993 Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
994 int rc;
995
996 assert( (pCsr->ePlan<3)==
997 (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
998 );
999 assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
1000
1001 /* If this cursor uses FTS5_PLAN_MATCH and this is a tokendata=1 table,
1002 ** clear any token mappings accumulated at the fts5_index.c level. In
1003 ** other cases, specifically FTS5_PLAN_SOURCE and FTS5_PLAN_SORTED_MATCH,
1004 ** we need to retain the mappings for the entire query. */
1005 if( pCsr->ePlan==FTS5_PLAN_MATCH
1006 && ((Fts5Table*)pCursor->pVtab)->pConfig->bTokendata
1007 ){
1008 sqlite3Fts5ExprClearTokens(pCsr->pExpr);
1009 }
1010
1011 if( pCsr->ePlan<3 ){
1012 int bSkip = 0;
1013 if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
1014 rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
1015 CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
1016 fts5CsrNewrow(pCsr);
1017 }else{
1018 switch( pCsr->ePlan ){
1019 case FTS5_PLAN_SPECIAL: {
1020 CsrFlagSet(pCsr, FTS5CSR_EOF);
1021 rc = SQLITE_OK;
1022 break;
1023 }
1024
1025 case FTS5_PLAN_SORTED_MATCH: {
1026 rc = fts5SorterNext(pCsr);
1027 break;
1028 }
1029
1030 default: {
1031 Fts5Config *pConfig = ((Fts5Table*)pCursor->pVtab)->pConfig;
1032 pConfig->bLock++;
1033 rc = sqlite3_step(pCsr->pStmt);
1034 pConfig->bLock--;
1035 if( rc!=SQLITE_ROW ){
1036 CsrFlagSet(pCsr, FTS5CSR_EOF);
1037 rc = sqlite3_reset(pCsr->pStmt);
1038 if( rc!=SQLITE_OK ){
1039 pCursor->pVtab->zErrMsg = sqlite3_mprintf(
1040 "%s", sqlite3_errmsg(pConfig->db)
1041 );
1042 }
1043 }else{
1044 rc = SQLITE_OK;
1045 CsrFlagSet(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
1046 }
1047 break;
1048 }
1049 }
1050 }
1051
1052 return rc;
1053}
1054
1055
1056static int fts5PrepareStatement(
1057 sqlite3_stmt **ppStmt,
1058 Fts5Config *pConfig,
1059 const char *zFmt,
1060 ...
1061){
1062 sqlite3_stmt *pRet = 0;
1063 int rc;
1064 char *zSql;
1065 va_list ap;
1066
1067 va_start(ap, zFmt);
1068 zSql = sqlite3_vmprintf(zFmt, ap);
1069 if( zSql==0 ){
1070 rc = SQLITE_NOMEM;
1071 }else{
1072 rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
1073 SQLITE_PREPARE_PERSISTENT, &pRet, 0);
1074 if( rc!=SQLITE_OK ){
1075 sqlite3Fts5ConfigErrmsg(pConfig, "%s", sqlite3_errmsg(pConfig->db));
1076 }
1077 sqlite3_free(zSql);
1078 }
1079
1080 va_end(ap);
1081 *ppStmt = pRet;
1082 return rc;
1083}
1084
1085static int fts5CursorFirstSorted(
1086 Fts5FullTable *pTab,
1087 Fts5Cursor *pCsr,
1088 int bDesc
1089){
1090 Fts5Config *pConfig = pTab->p.pConfig;
1091 Fts5Sorter *pSorter;
1092 int nPhrase;
1093 sqlite3_int64 nByte;
1094 int rc;
1095 const char *zRank = pCsr->zRank;
1096 const char *zRankArgs = pCsr->zRankArgs;
1097
1098 nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
1099 nByte = SZ_FTS5SORTER(nPhrase);
1100 pSorter = (Fts5Sorter*)sqlite3_malloc64(nByte);
1101 if( pSorter==0 ) return SQLITE_NOMEM;
1102 memset(pSorter, 0, (size_t)nByte);
1103 pSorter->nIdx = nPhrase;
1104
1105 /* TODO: It would be better to have some system for reusing statement
1106 ** handles here, rather than preparing a new one for each query. But that
1107 ** is not possible as SQLite reference counts the virtual table objects.
1108 ** And since the statement required here reads from this very virtual
1109 ** table, saving it creates a circular reference.
1110 **
1111 ** If SQLite a built-in statement cache, this wouldn't be a problem. */
1112 rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
1113 "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(\"%w\"%s%s) %s",
1114 pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
1115 (zRankArgs ? ", " : ""),
1116 (zRankArgs ? zRankArgs : ""),
1117 bDesc ? "DESC" : "ASC"
1118 );
1119
1120 pCsr->pSorter = pSorter;
1121 if( rc==SQLITE_OK ){
1122 assert( pTab->pSortCsr==0 );
1123 pTab->pSortCsr = pCsr;
1124 rc = fts5SorterNext(pCsr);
1125 pTab->pSortCsr = 0;
1126 }
1127
1128 if( rc!=SQLITE_OK ){
1129 sqlite3_finalize(pSorter->pStmt);
1130 sqlite3_free(pSorter);
1131 pCsr->pSorter = 0;
1132 }
1133
1134 return rc;
1135}
1136
1137static int fts5CursorFirst(Fts5FullTable *pTab, Fts5Cursor *pCsr, int bDesc){
1138 int rc;
1139 Fts5Expr *pExpr = pCsr->pExpr;
1140 rc = sqlite3Fts5ExprFirst(
1141 pExpr, pTab->p.pIndex, pCsr->iFirstRowid, pCsr->iLastRowid, bDesc
1142 );
1143 if( sqlite3Fts5ExprEof(pExpr) ){
1144 CsrFlagSet(pCsr, FTS5CSR_EOF);
1145 }
1146 fts5CsrNewrow(pCsr);
1147 return rc;
1148}
1149
1150/*
1151** Process a "special" query. A special query is identified as one with a
1152** MATCH expression that begins with a '*' character. The remainder of
1153** the text passed to the MATCH operator are used as the special query
1154** parameters.
1155*/
1156static int fts5SpecialMatch(
1157 Fts5FullTable *pTab,
1158 Fts5Cursor *pCsr,
1159 const char *zQuery
1160){
1161 int rc = SQLITE_OK; /* Return code */
1162 const char *z = zQuery; /* Special query text */
1163 int n; /* Number of bytes in text at z */
1164
1165 while( z[0]==' ' ) z++;
1166 for(n=0; z[n] && z[n]!=' '; n++);
1167
1168 assert( pTab->p.base.zErrMsg==0 );
1169 pCsr->ePlan = FTS5_PLAN_SPECIAL;
1170
1171 if( n==5 && 0==sqlite3_strnicmp("reads", z, n) ){
1172 pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->p.pIndex);
1173 }
1174 else if( n==2 && 0==sqlite3_strnicmp("id", z, n) ){
1175 pCsr->iSpecial = pCsr->iCsrId;
1176 }
1177 else{
1178 /* An unrecognized directive. Return an error message. */
1179 pTab->p.base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
1180 rc = SQLITE_ERROR;
1181 }
1182
1183 return rc;
1184}
1185
1186/*
1187** Search for an auxiliary function named zName that can be used with table
1188** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
1189** structure. Otherwise, if no such function exists, return NULL.
1190*/
1191static Fts5Auxiliary *fts5FindAuxiliary(Fts5FullTable *pTab, const char *zName){
1192 Fts5Auxiliary *pAux;
1193
1194 for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
1195 if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
1196 }
1197
1198 /* No function of the specified name was found. Return 0. */
1199 return 0;
1200}
1201
1202
1203static int fts5FindRankFunction(Fts5Cursor *pCsr){
1204 Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
1205 Fts5Config *pConfig = pTab->p.pConfig;
1206 int rc = SQLITE_OK;
1207 Fts5Auxiliary *pAux = 0;
1208 const char *zRank = pCsr->zRank;
1209 const char *zRankArgs = pCsr->zRankArgs;
1210
1211 if( zRankArgs ){
1212 char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
1213 if( zSql ){
1214 sqlite3_stmt *pStmt = 0;
1215 rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
1216 SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_FROM_DDL, &pStmt, 0
1217 );
1218 sqlite3_free(zSql);
1219 assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
1220 if( rc==SQLITE_OK ){
1221 if( SQLITE_ROW==sqlite3_step(pStmt) ){
1222 sqlite3_int64 nByte;
1223 pCsr->nRankArg = sqlite3_column_count(pStmt);
1224 nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
1225 pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
1226 if( rc==SQLITE_OK ){
1227 int i;
1228 for(i=0; i<pCsr->nRankArg; i++){
1229 pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
1230 }
1231 }
1232 pCsr->pRankArgStmt = pStmt;
1233 }else{
1234 rc = sqlite3_finalize(pStmt);
1235 assert( rc!=SQLITE_OK );
1236 }
1237 }
1238 }
1239 }
1240
1241 if( rc==SQLITE_OK ){
1242 pAux = fts5FindAuxiliary(pTab, zRank);
1243 if( pAux==0 ){
1244 assert( pTab->p.base.zErrMsg==0 );
1245 pTab->p.base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
1246 rc = SQLITE_ERROR;
1247 }
1248 }
1249
1250 pCsr->pRank = pAux;
1251 return rc;
1252}
1253
1254
1255static int fts5CursorParseRank(
1256 Fts5Config *pConfig,
1257 Fts5Cursor *pCsr,
1258 sqlite3_value *pRank
1259){
1260 int rc = SQLITE_OK;
1261 if( pRank ){
1262 const char *z = (const char*)sqlite3_value_text(pRank);
1263 char *zRank = 0;
1264 char *zRankArgs = 0;
1265
1266 if( z==0 ){
1267 if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
1268 }else{
1269 rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
1270 }
1271 if( rc==SQLITE_OK ){
1272 pCsr->zRank = zRank;
1273 pCsr->zRankArgs = zRankArgs;
1274 CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
1275 }else if( rc==SQLITE_ERROR ){
1276 pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
1277 "parse error in rank function: %s", z
1278 );
1279 }
1280 }else{
1281 if( pConfig->zRank ){
1282 pCsr->zRank = (char*)pConfig->zRank;
1283 pCsr->zRankArgs = (char*)pConfig->zRankArgs;
1284 }else{
1285 pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
1286 pCsr->zRankArgs = 0;
1287 }
1288 }
1289 return rc;
1290}
1291
1292static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
1293 if( pVal ){
1294 int eType = sqlite3_value_numeric_type(pVal);
1295 if( eType==SQLITE_INTEGER ){
1296 return sqlite3_value_int64(pVal);
1297 }
1298 }
1299 return iDefault;
1300}
1301
1302/*
1303** Set the error message on the virtual table passed as the first argument.
1304*/
1305static void fts5SetVtabError(Fts5FullTable *p, const char *zFormat, ...){
1306 va_list ap; /* ... printf arguments */
1307 va_start(ap, zFormat);
1308 sqlite3_free(p->p.base.zErrMsg);
1309 p->p.base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
1310 va_end(ap);
1311}
1312
1313/*
1314** Arrange for subsequent calls to sqlite3Fts5Tokenize() to use the locale
1315** specified by pLocale/nLocale. The buffer indicated by pLocale must remain
1316** valid until after the final call to sqlite3Fts5Tokenize() that will use
1317** the locale.
1318*/
1319static void sqlite3Fts5SetLocale(
1320 Fts5Config *pConfig,
1321 const char *zLocale,
1322 int nLocale
1323){
1324 Fts5TokenizerConfig *pT = &pConfig->t;
1325 pT->pLocale = zLocale;
1326 pT->nLocale = nLocale;
1327}
1328
1329/*
1330** Clear any locale configured by an earlier call to sqlite3Fts5SetLocale().
1331*/
1332void sqlite3Fts5ClearLocale(Fts5Config *pConfig){
1333 sqlite3Fts5SetLocale(pConfig, 0, 0);
1334}
1335
1336/*
1337** Return true if the value passed as the only argument is an
1338** fts5_locale() value.
1339*/
1340int sqlite3Fts5IsLocaleValue(Fts5Config *pConfig, sqlite3_value *pVal){
1341 int ret = 0;
1342 if( sqlite3_value_type(pVal)==SQLITE_BLOB ){
1343 /* Call sqlite3_value_bytes() after sqlite3_value_blob() in this case.
1344 ** If the blob was created using zeroblob(), then sqlite3_value_blob()
1345 ** may call malloc(). If this malloc() fails, then the values returned
1346 ** by both value_blob() and value_bytes() will be 0. If value_bytes() were
1347 ** called first, then the NULL pointer returned by value_blob() might
1348 ** be dereferenced. */
1349 const u8 *pBlob = sqlite3_value_blob(pVal);
1350 int nBlob = sqlite3_value_bytes(pVal);
1351 if( nBlob>FTS5_LOCALE_HDR_SIZE
1352 && 0==memcmp(pBlob, FTS5_LOCALE_HDR(pConfig), FTS5_LOCALE_HDR_SIZE)
1353 ){
1354 ret = 1;
1355 }
1356 }
1357 return ret;
1358}
1359
1360/*
1361** Value pVal is guaranteed to be an fts5_locale() value, according to
1362** sqlite3Fts5IsLocaleValue(). This function extracts the text and locale
1363** from the value and returns them separately.
1364**
1365** If successful, SQLITE_OK is returned and (*ppText) and (*ppLoc) set
1366** to point to buffers containing the text and locale, as utf-8,
1367** respectively. In this case output parameters (*pnText) and (*pnLoc) are
1368** set to the sizes in bytes of these two buffers.
1369**
1370** Or, if an error occurs, then an SQLite error code is returned. The final
1371** value of the four output parameters is undefined in this case.
1372*/
1373int sqlite3Fts5DecodeLocaleValue(
1374 sqlite3_value *pVal,
1375 const char **ppText,
1376 int *pnText,
1377 const char **ppLoc,
1378 int *pnLoc
1379){
1380 const char *p = sqlite3_value_blob(pVal);
1381 int n = sqlite3_value_bytes(pVal);
1382 int nLoc = 0;
1383
1384 assert( sqlite3_value_type(pVal)==SQLITE_BLOB );
1385 assert( n>FTS5_LOCALE_HDR_SIZE );
1386
1387 for(nLoc=FTS5_LOCALE_HDR_SIZE; p[nLoc]; nLoc++){
1388 if( nLoc==(n-1) ){
1389 return SQLITE_MISMATCH;
1390 }
1391 }
1392 *ppLoc = &p[FTS5_LOCALE_HDR_SIZE];
1393 *pnLoc = nLoc - FTS5_LOCALE_HDR_SIZE;
1394
1395 *ppText = &p[nLoc+1];
1396 *pnText = n - nLoc - 1;
1397 return SQLITE_OK;
1398}
1399
1400/*
1401** Argument pVal is the text of a full-text search expression. It may or
1402** may not have been wrapped by fts5_locale(). This function extracts
1403** the text of the expression, and sets output variable (*pzText) to
1404** point to a nul-terminated buffer containing the expression.
1405**
1406** If pVal was an fts5_locale() value, then sqlite3Fts5SetLocale() is called
1407** to set the tokenizer to use the specified locale.
1408**
1409** If output variable (*pbFreeAndReset) is set to true, then the caller
1410** is required to (a) call sqlite3Fts5ClearLocale() to reset the tokenizer
1411** locale, and (b) call sqlite3_free() to free (*pzText).
1412*/
1413static int fts5ExtractExprText(
1414 Fts5Config *pConfig, /* Fts5 configuration */
1415 sqlite3_value *pVal, /* Value to extract expression text from */
1416 char **pzText, /* OUT: nul-terminated buffer of text */
1417 int *pbFreeAndReset /* OUT: Free (*pzText) and clear locale */
1418){
1419 int rc = SQLITE_OK;
1420
1421 if( sqlite3Fts5IsLocaleValue(pConfig, pVal) ){
1422 const char *pText = 0;
1423 int nText = 0;
1424 const char *pLoc = 0;
1425 int nLoc = 0;
1426 rc = sqlite3Fts5DecodeLocaleValue(pVal, &pText, &nText, &pLoc, &nLoc);
1427 *pzText = sqlite3Fts5Mprintf(&rc, "%.*s", nText, pText);
1428 if( rc==SQLITE_OK ){
1429 sqlite3Fts5SetLocale(pConfig, pLoc, nLoc);
1430 }
1431 *pbFreeAndReset = 1;
1432 }else{
1433 *pzText = (char*)sqlite3_value_text(pVal);
1434 *pbFreeAndReset = 0;
1435 }
1436
1437 return rc;
1438}
1439
1440
1441/*
1442** This is the xFilter interface for the virtual table. See
1443** the virtual table xFilter method documentation for additional
1444** information.
1445**
1446** There are three possible query strategies:
1447**
1448** 1. Full-text search using a MATCH operator.
1449** 2. A by-rowid lookup.
1450** 3. A full-table scan.
1451*/
1452static int fts5FilterMethod(
1453 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
1454 int idxNum, /* Strategy index */
1455 const char *idxStr, /* Unused */
1456 int nVal, /* Number of elements in apVal */
1457 sqlite3_value **apVal /* Arguments for the indexing scheme */
1458){
1459 Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
1460 Fts5Config *pConfig = pTab->p.pConfig;
1461 Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
1462 int rc = SQLITE_OK; /* Error code */
1463 int bDesc; /* True if ORDER BY [rank|rowid] DESC */
1464 int bOrderByRank; /* True if ORDER BY rank */
1465 sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
1466 sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
1467 sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
1468 sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
1469 int iCol; /* Column on LHS of MATCH operator */
1470 char **pzErrmsg = pConfig->pzErrmsg;
1471 int bPrefixInsttoken = pConfig->bPrefixInsttoken;
1472 int i;
1473 int iIdxStr = 0;
1474 Fts5Expr *pExpr = 0;
1475
1476 assert( pConfig->bLock==0 );
1477 if( pCsr->ePlan ){
1478 fts5FreeCursorComponents(pCsr);
1479 memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
1480 }
1481
1482 assert( pCsr->pStmt==0 );
1483 assert( pCsr->pExpr==0 );
1484 assert( pCsr->csrflags==0 );
1485 assert( pCsr->pRank==0 );
1486 assert( pCsr->zRank==0 );
1487 assert( pCsr->zRankArgs==0 );
1488 assert( pTab->pSortCsr==0 || nVal==0 );
1489
1490 assert( pzErrmsg==0 || pzErrmsg==&pTab->p.base.zErrMsg );
1491 pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
1492
1493 /* Decode the arguments passed through to this function. */
1494 for(i=0; i<nVal; i++){
1495 switch( idxStr[iIdxStr++] ){
1496 case 'r':
1497 pRank = apVal[i];
1498 break;
1499 case 'M': {
1500 char *zText = 0;
1501 int bFreeAndReset = 0;
1502 int bInternal = 0;
1503
1504 rc = fts5ExtractExprText(pConfig, apVal[i], &zText, &bFreeAndReset);
1505 if( rc!=SQLITE_OK ) goto filter_out;
1506 if( zText==0 ) zText = "";
1507 if( sqlite3_value_subtype(apVal[i])==FTS5_INSTTOKEN_SUBTYPE ){
1508 pConfig->bPrefixInsttoken = 1;
1509 }
1510
1511 iCol = 0;
1512 do{
1513 iCol = iCol*10 + (idxStr[iIdxStr]-'0');
1514 iIdxStr++;
1515 }while( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' );
1516
1517 if( zText[0]=='*' ){
1518 /* The user has issued a query of the form "MATCH '*...'". This
1519 ** indicates that the MATCH expression is not a full text query,
1520 ** but a request for an internal parameter. */
1521 rc = fts5SpecialMatch(pTab, pCsr, &zText[1]);
1522 bInternal = 1;
1523 }else{
1524 char **pzErr = &pTab->p.base.zErrMsg;
1525 rc = sqlite3Fts5ExprNew(pConfig, 0, iCol, zText, &pExpr, pzErr);
1526 if( rc==SQLITE_OK ){
1527 rc = sqlite3Fts5ExprAnd(&pCsr->pExpr, pExpr);
1528 pExpr = 0;
1529 }
1530 }
1531
1532 if( bFreeAndReset ){
1533 sqlite3_free(zText);
1534 sqlite3Fts5ClearLocale(pConfig);
1535 }
1536
1537 if( bInternal || rc!=SQLITE_OK ) goto filter_out;
1538
1539 break;
1540 }
1541 case 'L':
1542 case 'G': {
1543 int bGlob = (idxStr[iIdxStr-1]=='G');
1544 const char *zText = (const char*)sqlite3_value_text(apVal[i]);
1545 iCol = 0;
1546 do{
1547 iCol = iCol*10 + (idxStr[iIdxStr]-'0');
1548 iIdxStr++;
1549 }while( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' );
1550 if( zText ){
1551 rc = sqlite3Fts5ExprPattern(pConfig, bGlob, iCol, zText, &pExpr);
1552 }
1553 if( rc==SQLITE_OK ){
1554 rc = sqlite3Fts5ExprAnd(&pCsr->pExpr, pExpr);
1555 pExpr = 0;
1556 }
1557 if( rc!=SQLITE_OK ) goto filter_out;
1558 break;
1559 }
1560 case '=':
1561 pRowidEq = apVal[i];
1562 break;
1563 case '<':
1564 pRowidLe = apVal[i];
1565 break;
1566 default: assert( idxStr[iIdxStr-1]=='>' );
1567 pRowidGe = apVal[i];
1568 break;
1569 }
1570 }
1571 bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
1572 pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
1573
1574 /* Set the cursor upper and lower rowid limits. Only some strategies
1575 ** actually use them. This is ok, as the xBestIndex() method leaves the
1576 ** sqlite3_index_constraint.omit flag clear for range constraints
1577 ** on the rowid field. */
1578 if( pRowidEq ){
1579 pRowidLe = pRowidGe = pRowidEq;
1580 }
1581 if( bDesc ){
1582 pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
1583 pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
1584 }else{
1585 pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
1586 pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
1587 }
1588
1589 rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
1590 if( rc!=SQLITE_OK ) goto filter_out;
1591
1592 if( pTab->pSortCsr ){
1593 /* If pSortCsr is non-NULL, then this call is being made as part of
1594 ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
1595 ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
1596 ** return results to the user for this query. The current cursor
1597 ** (pCursor) is used to execute the query issued by function
1598 ** fts5CursorFirstSorted() above. */
1599 assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
1600 assert( nVal==0 && bOrderByRank==0 && bDesc==0 );
1601 assert( pCsr->iLastRowid==LARGEST_INT64 );
1602 assert( pCsr->iFirstRowid==SMALLEST_INT64 );
1603 if( pTab->pSortCsr->bDesc ){
1604 pCsr->iLastRowid = pTab->pSortCsr->iFirstRowid;
1605 pCsr->iFirstRowid = pTab->pSortCsr->iLastRowid;
1606 }else{
1607 pCsr->iLastRowid = pTab->pSortCsr->iLastRowid;
1608 pCsr->iFirstRowid = pTab->pSortCsr->iFirstRowid;
1609 }
1610 pCsr->ePlan = FTS5_PLAN_SOURCE;
1611 pCsr->pExpr = pTab->pSortCsr->pExpr;
1612 rc = fts5CursorFirst(pTab, pCsr, bDesc);
1613 }else if( pCsr->pExpr ){
1614 assert( rc==SQLITE_OK );
1615 rc = fts5CursorParseRank(pConfig, pCsr, pRank);
1616 if( rc==SQLITE_OK ){
1617 if( bOrderByRank ){
1618 pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
1619 rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
1620 }else{
1621 pCsr->ePlan = FTS5_PLAN_MATCH;
1622 rc = fts5CursorFirst(pTab, pCsr, bDesc);
1623 }
1624 }
1625 }else if( pConfig->zContent==0 ){
1626 fts5SetVtabError(pTab,"%s: table does not support scanning",pConfig->zName);
1627 rc = SQLITE_ERROR;
1628 }else{
1629 /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
1630 ** by rowid (ePlan==FTS5_PLAN_ROWID). */
1631 pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
1632 rc = sqlite3Fts5StorageStmt(
1633 pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->p.base.zErrMsg
1634 );
1635 if( rc==SQLITE_OK ){
1636 if( pRowidEq!=0 ){
1637 assert( pCsr->ePlan==FTS5_PLAN_ROWID );
1638 sqlite3_bind_value(pCsr->pStmt, 1, pRowidEq);
1639 }else{
1640 sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
1641 sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
1642 }
1643 rc = fts5NextMethod(pCursor);
1644 }
1645 }
1646
1647 filter_out:
1648 sqlite3Fts5ExprFree(pExpr);
1649 pConfig->pzErrmsg = pzErrmsg;
1650 pConfig->bPrefixInsttoken = bPrefixInsttoken;
1651 return rc;
1652}
1653
1654/*
1655** This is the xEof method of the virtual table. SQLite calls this
1656** routine to find out if it has reached the end of a result set.
1657*/
1658static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
1659 Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
1660 return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
1661}
1662
1663/*
1664** Return the rowid that the cursor currently points to.
1665*/
1666static i64 fts5CursorRowid(Fts5Cursor *pCsr){
1667 assert( pCsr->ePlan==FTS5_PLAN_MATCH
1668 || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
1669 || pCsr->ePlan==FTS5_PLAN_SOURCE
1670 || pCsr->ePlan==FTS5_PLAN_SCAN
1671 || pCsr->ePlan==FTS5_PLAN_ROWID
1672 );
1673 if( pCsr->pSorter ){
1674 return pCsr->pSorter->iRowid;
1675 }else if( pCsr->ePlan>=FTS5_PLAN_SCAN ){
1676 return sqlite3_column_int64(pCsr->pStmt, 0);
1677 }else{
1678 return sqlite3Fts5ExprRowid(pCsr->pExpr);
1679 }
1680}
1681
1682/*
1683** This is the xRowid method. The SQLite core calls this routine to
1684** retrieve the rowid for the current row of the result set. fts5
1685** exposes %_content.rowid as the rowid for the virtual table. The
1686** rowid should be written to *pRowid.
1687*/
1688static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
1689 Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
1690 int ePlan = pCsr->ePlan;
1691
1692 assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
1693 if( ePlan==FTS5_PLAN_SPECIAL ){
1694 *pRowid = 0;
1695 }else{
1696 *pRowid = fts5CursorRowid(pCsr);
1697 }
1698
1699 return SQLITE_OK;
1700}
1701
1702
1703/*
1704** If the cursor requires seeking (bSeekRequired flag is set), seek it.
1705** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
1706**
1707** If argument bErrormsg is true and an error occurs, an error message may
1708** be left in sqlite3_vtab.zErrMsg.
1709*/
1710static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
1711 int rc = SQLITE_OK;
1712
1713 /* If the cursor does not yet have a statement handle, obtain one now. */
1714 if( pCsr->pStmt==0 ){
1715 Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
1716 int eStmt = fts5StmtType(pCsr);
1717 rc = sqlite3Fts5StorageStmt(
1718 pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->p.base.zErrMsg:0)
1719 );
1720 assert( rc!=SQLITE_OK || pTab->p.base.zErrMsg==0 );
1721 assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
1722 }
1723
1724 if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
1725 Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
1726 assert( pCsr->pExpr );
1727 sqlite3_reset(pCsr->pStmt);
1728 sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
1729 pTab->pConfig->bLock++;
1730 rc = sqlite3_step(pCsr->pStmt);
1731 pTab->pConfig->bLock--;
1732 if( rc==SQLITE_ROW ){
1733 rc = SQLITE_OK;
1734 CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
1735 }else{
1736 rc = sqlite3_reset(pCsr->pStmt);
1737 if( rc==SQLITE_OK ){
1738 rc = FTS5_CORRUPT;
1739 fts5SetVtabError((Fts5FullTable*)pTab,
1740 "fts5: missing row %lld from content table %s",
1741 fts5CursorRowid(pCsr),
1742 pTab->pConfig->zContent
1743 );
1744 }else if( pTab->pConfig->pzErrmsg ){
1745 fts5SetVtabError((Fts5FullTable*)pTab,
1746 "%s", sqlite3_errmsg(pTab->pConfig->db)
1747 );
1748 }
1749 }
1750 }
1751 return rc;
1752}
1753
1754/*
1755** This function is called to handle an FTS INSERT command. In other words,
1756** an INSERT statement of the form:
1757**
1758** INSERT INTO fts(fts) VALUES($pCmd)
1759** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
1760**
1761** Argument pVal is the value assigned to column "fts" by the INSERT
1762** statement. This function returns SQLITE_OK if successful, or an SQLite
1763** error code if an error occurs.
1764**
1765** The commands implemented by this function are documented in the "Special
1766** INSERT Directives" section of the documentation. It should be updated if
1767** more commands are added to this function.
1768*/
1769static int fts5SpecialInsert(
1770 Fts5FullTable *pTab, /* Fts5 table object */
1771 const char *zCmd, /* Text inserted into table-name column */
1772 sqlite3_value *pVal /* Value inserted into rank column */
1773){
1774 Fts5Config *pConfig = pTab->p.pConfig;
1775 int rc = SQLITE_OK;
1776 int bError = 0;
1777 int bLoadConfig = 0;
1778
1779 if( 0==sqlite3_stricmp("delete-all", zCmd) ){
1780 if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
1781 fts5SetVtabError(pTab,
1782 "'delete-all' may only be used with a "
1783 "contentless or external content fts5 table"
1784 );
1785 rc = SQLITE_ERROR;
1786 }else{
1787 rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
1788 }
1789 bLoadConfig = 1;
1790 }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
1791 if( fts5IsContentless(pTab, 1) ){
1792 fts5SetVtabError(pTab,
1793 "'rebuild' may not be used with a contentless fts5 table"
1794 );
1795 rc = SQLITE_ERROR;
1796 }else{
1797 rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
1798 }
1799 bLoadConfig = 1;
1800 }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
1801 rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
1802 }else if( 0==sqlite3_stricmp("merge", zCmd) ){
1803 int nMerge = sqlite3_value_int(pVal);
1804 rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
1805 }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
1806 int iArg = sqlite3_value_int(pVal);
1807 rc = sqlite3Fts5StorageIntegrity(pTab->pStorage, iArg);
1808#ifdef SQLITE_DEBUG
1809 }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
1810 pConfig->bPrefixIndex = sqlite3_value_int(pVal);
1811#endif
1812 }else if( 0==sqlite3_stricmp("flush", zCmd) ){
1813 rc = sqlite3Fts5FlushToDisk(&pTab->p);
1814 }else{
1815 rc = sqlite3Fts5FlushToDisk(&pTab->p);
1816 if( rc==SQLITE_OK ){
1817 rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
1818 }
1819 if( rc==SQLITE_OK ){
1820 rc = sqlite3Fts5ConfigSetValue(pTab->p.pConfig, zCmd, pVal, &bError);
1821 }
1822 if( rc==SQLITE_OK ){
1823 if( bError ){
1824 rc = SQLITE_ERROR;
1825 }else{
1826 rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
1827 }
1828 }
1829 }
1830
1831 if( rc==SQLITE_OK && bLoadConfig ){
1832 pTab->p.pConfig->iCookie--;
1833 rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
1834 }
1835
1836 return rc;
1837}
1838
1839static int fts5SpecialDelete(
1840 Fts5FullTable *pTab,
1841 sqlite3_value **apVal
1842){
1843 int rc = SQLITE_OK;
1844 int eType1 = sqlite3_value_type(apVal[1]);
1845 if( eType1==SQLITE_INTEGER ){
1846 sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
1847 rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2], 0);
1848 }
1849 return rc;
1850}
1851
1852static void fts5StorageInsert(
1853 int *pRc,
1854 Fts5FullTable *pTab,
1855 sqlite3_value **apVal,
1856 i64 *piRowid
1857){
1858 int rc = *pRc;
1859 if( rc==SQLITE_OK ){
1860 rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, 0, apVal, piRowid);
1861 }
1862 if( rc==SQLITE_OK ){
1863 rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
1864 }
1865 *pRc = rc;
1866}
1867
1868/*
1869**
1870** This function is called when the user attempts an UPDATE on a contentless
1871** table. Parameter bRowidModified is true if the UPDATE statement modifies
1872** the rowid value. Parameter apVal[] contains the new values for each user
1873** defined column of the fts5 table. pConfig is the configuration object of the
1874** table being updated (guaranteed to be contentless). The contentless_delete=1
1875** and contentless_unindexed=1 options may or may not be set.
1876**
1877** This function returns SQLITE_OK if the UPDATE can go ahead, or an SQLite
1878** error code if it cannot. In this case an error message is also loaded into
1879** pConfig. Output parameter (*pbContent) is set to true if the caller should
1880** update the %_content table only - not the FTS index or any other shadow
1881** table. This occurs when an UPDATE modifies only UNINDEXED columns of the
1882** table.
1883**
1884** An UPDATE may proceed if:
1885**
1886** * The only columns modified are UNINDEXED columns, or
1887**
1888** * The contentless_delete=1 option was specified and all of the indexed
1889** columns (not a subset) have been modified.
1890*/
1891static int fts5ContentlessUpdate(
1892 Fts5Config *pConfig,
1893 sqlite3_value **apVal,
1894 int bRowidModified,
1895 int *pbContent
1896){
1897 int ii;
1898 int bSeenIndex = 0; /* Have seen modified indexed column */
1899 int bSeenIndexNC = 0; /* Have seen unmodified indexed column */
1900 int rc = SQLITE_OK;
1901
1902 for(ii=0; ii<pConfig->nCol; ii++){
1903 if( pConfig->abUnindexed[ii]==0 ){
1904 if( sqlite3_value_nochange(apVal[ii]) ){
1905 bSeenIndexNC++;
1906 }else{
1907 bSeenIndex++;
1908 }
1909 }
1910 }
1911
1912 if( bSeenIndex==0 && bRowidModified==0 ){
1913 *pbContent = 1;
1914 }else{
1915 if( bSeenIndexNC || pConfig->bContentlessDelete==0 ){
1916 rc = SQLITE_ERROR;
1917 sqlite3Fts5ConfigErrmsg(pConfig,
1918 (pConfig->bContentlessDelete ?
1919 "%s a subset of columns on fts5 contentless-delete table: %s" :
1920 "%s contentless fts5 table: %s")
1921 , "cannot UPDATE", pConfig->zName
1922 );
1923 }
1924 }
1925
1926 return rc;
1927}
1928
1929/*
1930** This function is the implementation of the xUpdate callback used by
1931** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
1932** inserted, updated or deleted.
1933**
1934** A delete specifies a single argument - the rowid of the row to remove.
1935**
1936** Update and insert operations pass:
1937**
1938** 1. The "old" rowid, or NULL.
1939** 2. The "new" rowid.
1940** 3. Values for each of the nCol matchable columns.
1941** 4. Values for the two hidden columns (<tablename> and "rank").
1942*/
1943static int fts5UpdateMethod(
1944 sqlite3_vtab *pVtab, /* Virtual table handle */
1945 int nArg, /* Size of argument array */
1946 sqlite3_value **apVal, /* Array of arguments */
1947 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
1948){
1949 Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
1950 Fts5Config *pConfig = pTab->p.pConfig;
1951 int eType0; /* value_type() of apVal[0] */
1952 int rc = SQLITE_OK; /* Return code */
1953
1954 /* A transaction must be open when this is called. */
1955 assert( pTab->ts.eState==1 || pTab->ts.eState==2 );
1956
1957 assert( pVtab->zErrMsg==0 );
1958 assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
1959 assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER
1960 || sqlite3_value_type(apVal[0])==SQLITE_NULL
1961 );
1962 assert( pTab->p.pConfig->pzErrmsg==0 );
1963 if( pConfig->pgsz==0 ){
1964 rc = sqlite3Fts5ConfigLoad(pTab->p.pConfig, pTab->p.pConfig->iCookie);
1965 if( rc!=SQLITE_OK ) return rc;
1966 }
1967
1968 pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
1969
1970 /* Put any active cursors into REQUIRE_SEEK state. */
1971 fts5TripCursors(pTab);
1972
1973 eType0 = sqlite3_value_type(apVal[0]);
1974 if( eType0==SQLITE_NULL
1975 && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
1976 ){
1977 /* A "special" INSERT op. These are handled separately. */
1978 const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
1979 if( pConfig->eContent!=FTS5_CONTENT_NORMAL
1980 && 0==sqlite3_stricmp("delete", z)
1981 ){
1982 if( pConfig->bContentlessDelete ){
1983 fts5SetVtabError(pTab,
1984 "'delete' may not be used with a contentless_delete=1 table"
1985 );
1986 rc = SQLITE_ERROR;
1987 }else{
1988 rc = fts5SpecialDelete(pTab, apVal);
1989 }
1990 }else{
1991 rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
1992 }
1993 }else{
1994 /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
1995 ** any conflict on the rowid value must be detected before any
1996 ** modifications are made to the database file. There are 4 cases:
1997 **
1998 ** 1) DELETE
1999 ** 2) UPDATE (rowid not modified)
2000 ** 3) UPDATE (rowid modified)
2001 ** 4) INSERT
2002 **
2003 ** Cases 3 and 4 may violate the rowid constraint.
2004 */
2005 int eConflict = SQLITE_ABORT;
2006 if( pConfig->eContent==FTS5_CONTENT_NORMAL || pConfig->bContentlessDelete ){
2007 eConflict = sqlite3_vtab_on_conflict(pConfig->db);
2008 }
2009
2010 assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
2011 assert( nArg!=1 || eType0==SQLITE_INTEGER );
2012
2013 /* DELETE */
2014 if( nArg==1 ){
2015 /* It is only possible to DELETE from a contentless table if the
2016 ** contentless_delete=1 flag is set. */
2017 if( fts5IsContentless(pTab, 1) && pConfig->bContentlessDelete==0 ){
2018 fts5SetVtabError(pTab,
2019 "cannot DELETE from contentless fts5 table: %s", pConfig->zName
2020 );
2021 rc = SQLITE_ERROR;
2022 }else{
2023 i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
2024 rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0, 0);
2025 }
2026 }
2027
2028 /* INSERT or UPDATE */
2029 else{
2030 int eType1 = sqlite3_value_numeric_type(apVal[1]);
2031
2032 /* It is an error to write an fts5_locale() value to a table without
2033 ** the locale=1 option. */
2034 if( pConfig->bLocale==0 ){
2035 int ii;
2036 for(ii=0; ii<pConfig->nCol; ii++){
2037 sqlite3_value *pVal = apVal[ii+2];
2038 if( sqlite3Fts5IsLocaleValue(pConfig, pVal) ){
2039 fts5SetVtabError(pTab, "fts5_locale() requires locale=1");
2040 rc = SQLITE_MISMATCH;
2041 goto update_out;
2042 }
2043 }
2044 }
2045
2046 if( eType0!=SQLITE_INTEGER ){
2047 /* An INSERT statement. If the conflict-mode is REPLACE, first remove
2048 ** the current entry (if any). */
2049 if( eConflict==SQLITE_REPLACE && eType1==SQLITE_INTEGER ){
2050 i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
2051 rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0, 0);
2052 }
2053 fts5StorageInsert(&rc, pTab, apVal, pRowid);
2054 }
2055
2056 /* UPDATE */
2057 else{
2058 Fts5Storage *pStorage = pTab->pStorage;
2059 i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
2060 i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
2061 int bContent = 0; /* Content only update */
2062
2063 /* If this is a contentless table (including contentless_unindexed=1
2064 ** tables), check if the UPDATE may proceed. */
2065 if( fts5IsContentless(pTab, 1) ){
2066 rc = fts5ContentlessUpdate(pConfig, &apVal[2], iOld!=iNew, &bContent);
2067 if( rc!=SQLITE_OK ) goto update_out;
2068 }
2069
2070 if( eType1!=SQLITE_INTEGER ){
2071 rc = SQLITE_MISMATCH;
2072 }else if( iOld!=iNew ){
2073 assert( bContent==0 );
2074 if( eConflict==SQLITE_REPLACE ){
2075 rc = sqlite3Fts5StorageDelete(pStorage, iOld, 0, 1);
2076 if( rc==SQLITE_OK ){
2077 rc = sqlite3Fts5StorageDelete(pStorage, iNew, 0, 0);
2078 }
2079 fts5StorageInsert(&rc, pTab, apVal, pRowid);
2080 }else{
2081 rc = sqlite3Fts5StorageFindDeleteRow(pStorage, iOld);
2082 if( rc==SQLITE_OK ){
2083 rc = sqlite3Fts5StorageContentInsert(pStorage, 0, apVal, pRowid);
2084 }
2085 if( rc==SQLITE_OK ){
2086 rc = sqlite3Fts5StorageDelete(pStorage, iOld, 0, 0);
2087 }
2088 if( rc==SQLITE_OK ){
2089 rc = sqlite3Fts5StorageIndexInsert(pStorage, apVal, *pRowid);
2090 }
2091 }
2092 }else if( bContent ){
2093 /* This occurs when an UPDATE on a contentless table affects *only*
2094 ** UNINDEXED columns. This is a no-op for contentless_unindexed=0
2095 ** tables, or a write to the %_content table only for =1 tables. */
2096 assert( fts5IsContentless(pTab, 1) );
2097 rc = sqlite3Fts5StorageFindDeleteRow(pStorage, iOld);
2098 if( rc==SQLITE_OK ){
2099 rc = sqlite3Fts5StorageContentInsert(pStorage, 1, apVal, pRowid);
2100 }
2101 }else{
2102 rc = sqlite3Fts5StorageDelete(pStorage, iOld, 0, 1);
2103 fts5StorageInsert(&rc, pTab, apVal, pRowid);
2104 }
2105 sqlite3Fts5StorageReleaseDeleteRow(pStorage);
2106 }
2107 }
2108 }
2109
2110 update_out:
2111 sqlite3Fts5IndexCloseReader(pTab->p.pIndex);
2112 pTab->p.pConfig->pzErrmsg = 0;
2113 return rc;
2114}
2115
2116/*
2117** Implementation of xSync() method.
2118*/
2119static int fts5SyncMethod(sqlite3_vtab *pVtab){
2120 int rc;
2121 Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
2122 fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
2123 pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
2124 rc = sqlite3Fts5FlushToDisk(&pTab->p);
2125 pTab->p.pConfig->pzErrmsg = 0;
2126 return rc;
2127}
2128
2129/*
2130** Implementation of xBegin() method.
2131*/
2132static int fts5BeginMethod(sqlite3_vtab *pVtab){
2133 int rc = fts5NewTransaction((Fts5FullTable*)pVtab);
2134 if( rc==SQLITE_OK ){
2135 fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_BEGIN, 0);
2136 }
2137 return rc;
2138}
2139
2140/*
2141** Implementation of xCommit() method. This is a no-op. The contents of
2142** the pending-terms hash-table have already been flushed into the database
2143** by fts5SyncMethod().
2144*/
2145static int fts5CommitMethod(sqlite3_vtab *pVtab){
2146 UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
2147 fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_COMMIT, 0);
2148 return SQLITE_OK;
2149}
2150
2151/*
2152** Implementation of xRollback(). Discard the contents of the pending-terms
2153** hash-table. Any changes made to the database are reverted by SQLite.
2154*/
2155static int fts5RollbackMethod(sqlite3_vtab *pVtab){
2156 int rc;
2157 Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
2158 fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
2159 fts5TripCursors(pTab);
2160 rc = sqlite3Fts5StorageRollback(pTab->pStorage);
2161 pTab->p.pConfig->pgsz = 0;
2162 return rc;
2163}
2164
2165static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
2166
2167static void *fts5ApiUserData(Fts5Context *pCtx){
2168 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2169 return pCsr->pAux->pUserData;
2170}
2171
2172static int fts5ApiColumnCount(Fts5Context *pCtx){
2173 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2174 return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
2175}
2176
2177static int fts5ApiColumnTotalSize(
2178 Fts5Context *pCtx,
2179 int iCol,
2180 sqlite3_int64 *pnToken
2181){
2182 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2183 Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
2184 return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
2185}
2186
2187static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
2188 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2189 Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
2190 return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
2191}
2192
2193/*
2194** Implementation of xTokenize_v2() API.
2195*/
2196static int fts5ApiTokenize_v2(
2197 Fts5Context *pCtx,
2198 const char *pText, int nText,
2199 const char *pLoc, int nLoc,
2200 void *pUserData,
2201 int (*xToken)(void*, int, const char*, int, int, int)
2202){
2203 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2204 Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
2205 int rc = SQLITE_OK;
2206
2207 sqlite3Fts5SetLocale(pTab->pConfig, pLoc, nLoc);
2208 rc = sqlite3Fts5Tokenize(pTab->pConfig,
2209 FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
2210 );
2211 sqlite3Fts5SetLocale(pTab->pConfig, 0, 0);
2212
2213 return rc;
2214}
2215
2216/*
2217** Implementation of xTokenize() API. This is just xTokenize_v2() with NULL/0
2218** passed as the locale.
2219*/
2220static int fts5ApiTokenize(
2221 Fts5Context *pCtx,
2222 const char *pText, int nText,
2223 void *pUserData,
2224 int (*xToken)(void*, int, const char*, int, int, int)
2225){
2226 return fts5ApiTokenize_v2(pCtx, pText, nText, 0, 0, pUserData, xToken);
2227}
2228
2229static int fts5ApiPhraseCount(Fts5Context *pCtx){
2230 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2231 return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
2232}
2233
2234static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
2235 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2236 return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
2237}
2238
2239/*
2240** Argument pStmt is an SQL statement of the type used by Fts5Cursor. This
2241** function extracts the text value of column iCol of the current row.
2242** Additionally, if there is an associated locale, it invokes
2243** sqlite3Fts5SetLocale() to configure the tokenizer. In all cases the caller
2244** should invoke sqlite3Fts5ClearLocale() to clear the locale at some point
2245** after this function returns.
2246**
2247** If successful, (*ppText) is set to point to a buffer containing the text
2248** value as utf-8 and SQLITE_OK returned. (*pnText) is set to the size of that
2249** buffer in bytes. It is not guaranteed to be nul-terminated. If an error
2250** occurs, an SQLite error code is returned. The final values of the two
2251** output parameters are undefined in this case.
2252*/
2253static int fts5TextFromStmt(
2254 Fts5Config *pConfig,
2255 sqlite3_stmt *pStmt,
2256 int iCol,
2257 const char **ppText,
2258 int *pnText
2259){
2260 sqlite3_value *pVal = sqlite3_column_value(pStmt, iCol+1);
2261 const char *pLoc = 0;
2262 int nLoc = 0;
2263 int rc = SQLITE_OK;
2264
2265 if( pConfig->bLocale
2266 && pConfig->eContent==FTS5_CONTENT_EXTERNAL
2267 && sqlite3Fts5IsLocaleValue(pConfig, pVal)
2268 ){
2269 rc = sqlite3Fts5DecodeLocaleValue(pVal, ppText, pnText, &pLoc, &nLoc);
2270 }else{
2271 *ppText = (const char*)sqlite3_value_text(pVal);
2272 *pnText = sqlite3_value_bytes(pVal);
2273 if( pConfig->bLocale && pConfig->eContent==FTS5_CONTENT_NORMAL ){
2274 pLoc = (const char*)sqlite3_column_text(pStmt, iCol+1+pConfig->nCol);
2275 nLoc = sqlite3_column_bytes(pStmt, iCol+1+pConfig->nCol);
2276 }
2277 }
2278 sqlite3Fts5SetLocale(pConfig, pLoc, nLoc);
2279 return rc;
2280}
2281
2282static int fts5ApiColumnText(
2283 Fts5Context *pCtx,
2284 int iCol,
2285 const char **pz,
2286 int *pn
2287){
2288 int rc = SQLITE_OK;
2289 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2290 Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
2291
2292 assert( pCsr->ePlan!=FTS5_PLAN_SPECIAL );
2293 if( iCol<0 || iCol>=pTab->pConfig->nCol ){
2294 rc = SQLITE_RANGE;
2295 }else if( fts5IsContentless((Fts5FullTable*)(pCsr->base.pVtab), 0) ){
2296 *pz = 0;
2297 *pn = 0;
2298 }else{
2299 rc = fts5SeekCursor(pCsr, 0);
2300 if( rc==SQLITE_OK ){
2301 rc = fts5TextFromStmt(pTab->pConfig, pCsr->pStmt, iCol, pz, pn);
2302 sqlite3Fts5ClearLocale(pTab->pConfig);
2303 }
2304 }
2305 return rc;
2306}
2307
2308/*
2309** This is called by various API functions - xInst, xPhraseFirst,
2310** xPhraseFirstColumn etc. - to obtain the position list for phrase iPhrase
2311** of the current row. This function works for both detail=full tables (in
2312** which case the position-list was read from the fts index) or for other
2313** detail= modes if the row content is available.
2314*/
2315static int fts5CsrPoslist(
2316 Fts5Cursor *pCsr, /* Fts5 cursor object */
2317 int iPhrase, /* Phrase to find position list for */
2318 const u8 **pa, /* OUT: Pointer to position list buffer */
2319 int *pn /* OUT: Size of (*pa) in bytes */
2320){
2321 Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
2322 int rc = SQLITE_OK;
2323 int bLive = (pCsr->pSorter==0);
2324
2325 if( iPhrase<0 || iPhrase>=sqlite3Fts5ExprPhraseCount(pCsr->pExpr) ){
2326 rc = SQLITE_RANGE;
2327 }else if( pConfig->eDetail!=FTS5_DETAIL_FULL
2328 && fts5IsContentless((Fts5FullTable*)pCsr->base.pVtab, 1)
2329 ){
2330 *pa = 0;
2331 *pn = 0;
2332 return SQLITE_OK;
2333 }else if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
2334 if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
2335 Fts5PoslistPopulator *aPopulator;
2336 int i;
2337
2338 aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
2339 if( aPopulator==0 ) rc = SQLITE_NOMEM;
2340 if( rc==SQLITE_OK ){
2341 rc = fts5SeekCursor(pCsr, 0);
2342 }
2343 for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
2344 if( pConfig->abUnindexed[i]==0 ){
2345 const char *z = 0;
2346 int n = 0;
2347 rc = fts5TextFromStmt(pConfig, pCsr->pStmt, i, &z, &n);
2348 if( rc==SQLITE_OK ){
2349 rc = sqlite3Fts5ExprPopulatePoslists(
2350 pConfig, pCsr->pExpr, aPopulator, i, z, n
2351 );
2352 }
2353 sqlite3Fts5ClearLocale(pConfig);
2354 }
2355 }
2356 sqlite3_free(aPopulator);
2357
2358 if( pCsr->pSorter ){
2359 sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
2360 }
2361 }
2362 CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
2363 }
2364
2365 if( rc==SQLITE_OK ){
2366 if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
2367 Fts5Sorter *pSorter = pCsr->pSorter;
2368 int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
2369 *pn = pSorter->aIdx[iPhrase] - i1;
2370 *pa = &pSorter->aPoslist[i1];
2371 }else{
2372 *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
2373 }
2374 }else{
2375 *pa = 0;
2376 *pn = 0;
2377 }
2378
2379 return rc;
2380}
2381
2382/*
2383** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
2384** correctly for the current view. Return SQLITE_OK if successful, or an
2385** SQLite error code otherwise.
2386*/
2387static int fts5CacheInstArray(Fts5Cursor *pCsr){
2388 int rc = SQLITE_OK;
2389 Fts5PoslistReader *aIter; /* One iterator for each phrase */
2390 int nIter; /* Number of iterators/phrases */
2391 int nCol = ((Fts5Table*)pCsr->base.pVtab)->pConfig->nCol;
2392
2393 nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
2394 if( pCsr->aInstIter==0 ){
2395 sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nIter;
2396 pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
2397 }
2398 aIter = pCsr->aInstIter;
2399
2400 if( aIter ){
2401 int nInst = 0; /* Number instances seen so far */
2402 int i;
2403
2404 /* Initialize all iterators */
2405 for(i=0; i<nIter && rc==SQLITE_OK; i++){
2406 const u8 *a;
2407 int n;
2408 rc = fts5CsrPoslist(pCsr, i, &a, &n);
2409 if( rc==SQLITE_OK ){
2410 sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
2411 }
2412 }
2413
2414 if( rc==SQLITE_OK ){
2415 while( 1 ){
2416 int *aInst;
2417 int iBest = -1;
2418 for(i=0; i<nIter; i++){
2419 if( (aIter[i].bEof==0)
2420 && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
2421 ){
2422 iBest = i;
2423 }
2424 }
2425 if( iBest<0 ) break;
2426
2427 nInst++;
2428 if( nInst>=pCsr->nInstAlloc ){
2429 int nNewSize = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
2430 aInst = (int*)sqlite3_realloc64(
2431 pCsr->aInst, nNewSize*sizeof(int)*3
2432 );
2433 if( aInst ){
2434 pCsr->aInst = aInst;
2435 pCsr->nInstAlloc = nNewSize;
2436 }else{
2437 nInst--;
2438 rc = SQLITE_NOMEM;
2439 break;
2440 }
2441 }
2442
2443 aInst = &pCsr->aInst[3 * (nInst-1)];
2444 aInst[0] = iBest;
2445 aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
2446 aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
2447 assert( aInst[1]>=0 );
2448 if( aInst[1]>=nCol ){
2449 rc = FTS5_CORRUPT;
2450 break;
2451 }
2452 sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
2453 }
2454 }
2455
2456 pCsr->nInstCount = nInst;
2457 CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
2458 }
2459 return rc;
2460}
2461
2462static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
2463 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2464 int rc = SQLITE_OK;
2465 if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
2466 || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
2467 *pnInst = pCsr->nInstCount;
2468 }
2469 return rc;
2470}
2471
2472static int fts5ApiInst(
2473 Fts5Context *pCtx,
2474 int iIdx,
2475 int *piPhrase,
2476 int *piCol,
2477 int *piOff
2478){
2479 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2480 int rc = SQLITE_OK;
2481 if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
2482 || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
2483 ){
2484 if( iIdx<0 || iIdx>=pCsr->nInstCount ){
2485 rc = SQLITE_RANGE;
2486 }else{
2487 *piPhrase = pCsr->aInst[iIdx*3];
2488 *piCol = pCsr->aInst[iIdx*3 + 1];
2489 *piOff = pCsr->aInst[iIdx*3 + 2];
2490 }
2491 }
2492 return rc;
2493}
2494
2495static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
2496 return fts5CursorRowid((Fts5Cursor*)pCtx);
2497}
2498
2499static int fts5ColumnSizeCb(
2500 void *pContext, /* Pointer to int */
2501 int tflags,
2502 const char *pUnused, /* Buffer containing token */
2503 int nUnused, /* Size of token in bytes */
2504 int iUnused1, /* Start offset of token */
2505 int iUnused2 /* End offset of token */
2506){
2507 int *pCnt = (int*)pContext;
2508 UNUSED_PARAM2(pUnused, nUnused);
2509 UNUSED_PARAM2(iUnused1, iUnused2);
2510 if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
2511 (*pCnt)++;
2512 }
2513 return SQLITE_OK;
2514}
2515
2516static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
2517 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2518 Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
2519 Fts5Config *pConfig = pTab->p.pConfig;
2520 int rc = SQLITE_OK;
2521
2522 if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
2523 if( pConfig->bColumnsize ){
2524 i64 iRowid = fts5CursorRowid(pCsr);
2525 rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
2526 }else if( !pConfig->zContent || pConfig->eContent==FTS5_CONTENT_UNINDEXED ){
2527 int i;
2528 for(i=0; i<pConfig->nCol; i++){
2529 if( pConfig->abUnindexed[i]==0 ){
2530 pCsr->aColumnSize[i] = -1;
2531 }
2532 }
2533 }else{
2534 int i;
2535 rc = fts5SeekCursor(pCsr, 0);
2536 for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
2537 if( pConfig->abUnindexed[i]==0 ){
2538 const char *z = 0;
2539 int n = 0;
2540 pCsr->aColumnSize[i] = 0;
2541 rc = fts5TextFromStmt(pConfig, pCsr->pStmt, i, &z, &n);
2542 if( rc==SQLITE_OK ){
2543 rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_AUX,
2544 z, n, (void*)&pCsr->aColumnSize[i], fts5ColumnSizeCb
2545 );
2546 }
2547 sqlite3Fts5ClearLocale(pConfig);
2548 }
2549 }
2550 }
2551 CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
2552 }
2553 if( iCol<0 ){
2554 int i;
2555 *pnToken = 0;
2556 for(i=0; i<pConfig->nCol; i++){
2557 *pnToken += pCsr->aColumnSize[i];
2558 }
2559 }else if( iCol<pConfig->nCol ){
2560 *pnToken = pCsr->aColumnSize[iCol];
2561 }else{
2562 *pnToken = 0;
2563 rc = SQLITE_RANGE;
2564 }
2565 return rc;
2566}
2567
2568/*
2569** Implementation of the xSetAuxdata() method.
2570*/
2571static int fts5ApiSetAuxdata(
2572 Fts5Context *pCtx, /* Fts5 context */
2573 void *pPtr, /* Pointer to save as auxdata */
2574 void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
2575){
2576 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2577 Fts5Auxdata *pData;
2578
2579 /* Search through the cursors list of Fts5Auxdata objects for one that
2580 ** corresponds to the currently executing auxiliary function. */
2581 for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
2582 if( pData->pAux==pCsr->pAux ) break;
2583 }
2584
2585 if( pData ){
2586 if( pData->xDelete ){
2587 pData->xDelete(pData->pPtr);
2588 }
2589 }else{
2590 int rc = SQLITE_OK;
2591 pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
2592 if( pData==0 ){
2593 if( xDelete ) xDelete(pPtr);
2594 return rc;
2595 }
2596 pData->pAux = pCsr->pAux;
2597 pData->pNext = pCsr->pAuxdata;
2598 pCsr->pAuxdata = pData;
2599 }
2600
2601 pData->xDelete = xDelete;
2602 pData->pPtr = pPtr;
2603 return SQLITE_OK;
2604}
2605
2606static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
2607 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2608 Fts5Auxdata *pData;
2609 void *pRet = 0;
2610
2611 for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
2612 if( pData->pAux==pCsr->pAux ) break;
2613 }
2614
2615 if( pData ){
2616 pRet = pData->pPtr;
2617 if( bClear ){
2618 pData->pPtr = 0;
2619 pData->xDelete = 0;
2620 }
2621 }
2622
2623 return pRet;
2624}
2625
2626static void fts5ApiPhraseNext(
2627 Fts5Context *pCtx,
2628 Fts5PhraseIter *pIter,
2629 int *piCol, int *piOff
2630){
2631 if( pIter->a>=pIter->b ){
2632 *piCol = -1;
2633 *piOff = -1;
2634 }else{
2635 int iVal;
2636 pIter->a += fts5GetVarint32(pIter->a, iVal);
2637 if( iVal==1 ){
2638 /* Avoid returning a (*piCol) value that is too large for the table,
2639 ** even if the position-list is corrupt. The caller might not be
2640 ** expecting it. */
2641 int nCol = ((Fts5Table*)(((Fts5Cursor*)pCtx)->base.pVtab))->pConfig->nCol;
2642 pIter->a += fts5GetVarint32(pIter->a, iVal);
2643 *piCol = (iVal>=nCol ? nCol-1 : iVal);
2644 *piOff = 0;
2645 pIter->a += fts5GetVarint32(pIter->a, iVal);
2646 }
2647 *piOff += (iVal-2);
2648 }
2649}
2650
2651static int fts5ApiPhraseFirst(
2652 Fts5Context *pCtx,
2653 int iPhrase,
2654 Fts5PhraseIter *pIter,
2655 int *piCol, int *piOff
2656){
2657 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2658 int n;
2659 int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
2660 if( rc==SQLITE_OK ){
2661 assert( pIter->a || n==0 );
2662 pIter->b = (pIter->a ? &pIter->a[n] : 0);
2663 *piCol = 0;
2664 *piOff = 0;
2665 fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
2666 }
2667 return rc;
2668}
2669
2670static void fts5ApiPhraseNextColumn(
2671 Fts5Context *pCtx,
2672 Fts5PhraseIter *pIter,
2673 int *piCol
2674){
2675 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2676 Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
2677
2678 if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
2679 if( pIter->a>=pIter->b ){
2680 *piCol = -1;
2681 }else{
2682 int iIncr;
2683 pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
2684 *piCol += (iIncr-2);
2685 }
2686 }else{
2687 while( 1 ){
2688 int dummy;
2689 if( pIter->a>=pIter->b ){
2690 *piCol = -1;
2691 return;
2692 }
2693 if( pIter->a[0]==0x01 ) break;
2694 pIter->a += fts5GetVarint32(pIter->a, dummy);
2695 }
2696 pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
2697 }
2698}
2699
2700static int fts5ApiPhraseFirstColumn(
2701 Fts5Context *pCtx,
2702 int iPhrase,
2703 Fts5PhraseIter *pIter,
2704 int *piCol
2705){
2706 int rc = SQLITE_OK;
2707 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2708 Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
2709
2710 if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
2711 Fts5Sorter *pSorter = pCsr->pSorter;
2712 if( iPhrase<0 || iPhrase>=sqlite3Fts5ExprPhraseCount(pCsr->pExpr) ){
2713 rc = SQLITE_RANGE;
2714 }else{
2715 int n;
2716 if( pSorter ){
2717 int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
2718 n = pSorter->aIdx[iPhrase] - i1;
2719 pIter->a = &pSorter->aPoslist[i1];
2720 }else{
2721 rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
2722 }
2723 if( rc==SQLITE_OK ){
2724 assert( pIter->a || n==0 );
2725 pIter->b = (pIter->a ? &pIter->a[n] : 0);
2726 *piCol = 0;
2727 fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
2728 }
2729 }
2730 }else{
2731 int n;
2732 rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
2733 if( rc==SQLITE_OK ){
2734 assert( pIter->a || n==0 );
2735 pIter->b = (pIter->a ? &pIter->a[n] : 0);
2736 if( n<=0 ){
2737 *piCol = -1;
2738 }else if( pIter->a[0]==0x01 ){
2739 pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
2740 }else{
2741 *piCol = 0;
2742 }
2743 }
2744 }
2745
2746 return rc;
2747}
2748
2749/*
2750** xQueryToken() API implemenetation.
2751*/
2752static int fts5ApiQueryToken(
2753 Fts5Context* pCtx,
2754 int iPhrase,
2755 int iToken,
2756 const char **ppOut,
2757 int *pnOut
2758){
2759 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2760 return sqlite3Fts5ExprQueryToken(pCsr->pExpr, iPhrase, iToken, ppOut, pnOut);
2761}
2762
2763/*
2764** xInstToken() API implemenetation.
2765*/
2766static int fts5ApiInstToken(
2767 Fts5Context *pCtx,
2768 int iIdx,
2769 int iToken,
2770 const char **ppOut, int *pnOut
2771){
2772 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2773 int rc = SQLITE_OK;
2774 if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
2775 || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
2776 ){
2777 if( iIdx<0 || iIdx>=pCsr->nInstCount ){
2778 rc = SQLITE_RANGE;
2779 }else{
2780 int iPhrase = pCsr->aInst[iIdx*3];
2781 int iCol = pCsr->aInst[iIdx*3 + 1];
2782 int iOff = pCsr->aInst[iIdx*3 + 2];
2783 i64 iRowid = fts5CursorRowid(pCsr);
2784 rc = sqlite3Fts5ExprInstToken(
2785 pCsr->pExpr, iRowid, iPhrase, iCol, iOff, iToken, ppOut, pnOut
2786 );
2787 }
2788 }
2789 return rc;
2790}
2791
2792
2793static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
2794 int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
2795);
2796
2797/*
2798** The xColumnLocale() API.
2799*/
2800static int fts5ApiColumnLocale(
2801 Fts5Context *pCtx,
2802 int iCol,
2803 const char **pzLocale,
2804 int *pnLocale
2805){
2806 int rc = SQLITE_OK;
2807 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2808 Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
2809
2810 *pzLocale = 0;
2811 *pnLocale = 0;
2812
2813 assert( pCsr->ePlan!=FTS5_PLAN_SPECIAL );
2814 if( iCol<0 || iCol>=pConfig->nCol ){
2815 rc = SQLITE_RANGE;
2816 }else if(
2817 pConfig->abUnindexed[iCol]==0
2818 && 0==fts5IsContentless((Fts5FullTable*)pCsr->base.pVtab, 1)
2819 && pConfig->bLocale
2820 ){
2821 rc = fts5SeekCursor(pCsr, 0);
2822 if( rc==SQLITE_OK ){
2823 const char *zDummy = 0;
2824 int nDummy = 0;
2825 rc = fts5TextFromStmt(pConfig, pCsr->pStmt, iCol, &zDummy, &nDummy);
2826 if( rc==SQLITE_OK ){
2827 *pzLocale = pConfig->t.pLocale;
2828 *pnLocale = pConfig->t.nLocale;
2829 }
2830 sqlite3Fts5ClearLocale(pConfig);
2831 }
2832 }
2833
2834 return rc;
2835}
2836
2837static const Fts5ExtensionApi sFts5Api = {
2838 4, /* iVersion */
2839 fts5ApiUserData,
2840 fts5ApiColumnCount,
2841 fts5ApiRowCount,
2842 fts5ApiColumnTotalSize,
2843 fts5ApiTokenize,
2844 fts5ApiPhraseCount,
2845 fts5ApiPhraseSize,
2846 fts5ApiInstCount,
2847 fts5ApiInst,
2848 fts5ApiRowid,
2849 fts5ApiColumnText,
2850 fts5ApiColumnSize,
2851 fts5ApiQueryPhrase,
2852 fts5ApiSetAuxdata,
2853 fts5ApiGetAuxdata,
2854 fts5ApiPhraseFirst,
2855 fts5ApiPhraseNext,
2856 fts5ApiPhraseFirstColumn,
2857 fts5ApiPhraseNextColumn,
2858 fts5ApiQueryToken,
2859 fts5ApiInstToken,
2860 fts5ApiColumnLocale,
2861 fts5ApiTokenize_v2
2862};
2863
2864/*
2865** Implementation of API function xQueryPhrase().
2866*/
2867static int fts5ApiQueryPhrase(
2868 Fts5Context *pCtx,
2869 int iPhrase,
2870 void *pUserData,
2871 int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
2872){
2873 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
2874 Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
2875 int rc;
2876 Fts5Cursor *pNew = 0;
2877
2878 rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
2879 if( rc==SQLITE_OK ){
2880 pNew->ePlan = FTS5_PLAN_MATCH;
2881 pNew->iFirstRowid = SMALLEST_INT64;
2882 pNew->iLastRowid = LARGEST_INT64;
2883 pNew->base.pVtab = (sqlite3_vtab*)pTab;
2884 rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
2885 }
2886
2887 if( rc==SQLITE_OK ){
2888 for(rc = fts5CursorFirst(pTab, pNew, 0);
2889 rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
2890 rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
2891 ){
2892 rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
2893 if( rc!=SQLITE_OK ){
2894 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
2895 break;
2896 }
2897 }
2898 }
2899
2900 fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
2901 return rc;
2902}
2903
2904static void fts5ApiInvoke(
2905 Fts5Auxiliary *pAux,
2906 Fts5Cursor *pCsr,
2907 sqlite3_context *context,
2908 int argc,
2909 sqlite3_value **argv
2910){
2911 assert( pCsr->pAux==0 );
2912 assert( pCsr->ePlan!=FTS5_PLAN_SPECIAL );
2913 pCsr->pAux = pAux;
2914 pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
2915 pCsr->pAux = 0;
2916}
2917
2918static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
2919 Fts5Cursor *pCsr;
2920 for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
2921 if( pCsr->iCsrId==iCsrId ) break;
2922 }
2923 return pCsr;
2924}
2925
2926/*
2927** Parameter zFmt is a printf() style formatting string. This function
2928** formats it using the trailing arguments and returns the result as
2929** an error message to the context passed as the first argument.
2930*/
2931static void fts5ResultError(sqlite3_context *pCtx, const char *zFmt, ...){
2932 char *zErr = 0;
2933 va_list ap;
2934 va_start(ap, zFmt);
2935 zErr = sqlite3_vmprintf(zFmt, ap);
2936 sqlite3_result_error(pCtx, zErr, -1);
2937 sqlite3_free(zErr);
2938 va_end(ap);
2939}
2940
2941static void fts5ApiCallback(
2942 sqlite3_context *context,
2943 int argc,
2944 sqlite3_value **argv
2945){
2946
2947 Fts5Auxiliary *pAux;
2948 Fts5Cursor *pCsr;
2949 i64 iCsrId;
2950
2951 assert( argc>=1 );
2952 pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
2953 iCsrId = sqlite3_value_int64(argv[0]);
2954
2955 pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
2956 if( pCsr==0 || (pCsr->ePlan==0 || pCsr->ePlan==FTS5_PLAN_SPECIAL) ){
2957 fts5ResultError(context, "no such cursor: %lld", iCsrId);
2958 }else{
2959 sqlite3_vtab *pTab = pCsr->base.pVtab;
2960 fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
2961 sqlite3_free(pTab->zErrMsg);
2962 pTab->zErrMsg = 0;
2963 }
2964}
2965
2966
2967/*
2968** Given cursor id iId, return a pointer to the corresponding Fts5Table
2969** object. Or NULL If the cursor id does not exist.
2970*/
2971Fts5Table *sqlite3Fts5TableFromCsrid(
2972 Fts5Global *pGlobal, /* FTS5 global context for db handle */
2973 i64 iCsrId /* Id of cursor to find */
2974){
2975 Fts5Cursor *pCsr;
2976 pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
2977 if( pCsr ){
2978 return (Fts5Table*)pCsr->base.pVtab;
2979 }
2980 return 0;
2981}
2982
2983/*
2984** Return a "position-list blob" corresponding to the current position of
2985** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
2986** the current position-list for each phrase in the query associated with
2987** cursor pCsr.
2988**
2989** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
2990** the number of phrases in the query. Following the varints are the
2991** concatenated position lists for each phrase, in order.
2992**
2993** The first varint (if it exists) contains the size of the position list
2994** for phrase 0. The second (same disclaimer) contains the size of position
2995** list 1. And so on. There is no size field for the final position list,
2996** as it can be derived from the total size of the blob.
2997*/
2998static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
2999 int i;
3000 int rc = SQLITE_OK;
3001 int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
3002 Fts5Buffer val;
3003
3004 memset(&val, 0, sizeof(Fts5Buffer));
3005 switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
3006 case FTS5_DETAIL_FULL:
3007
3008 /* Append the varints */
3009 for(i=0; i<(nPhrase-1); i++){
3010 const u8 *dummy;
3011 int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
3012 sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
3013 }
3014
3015 /* Append the position lists */
3016 for(i=0; i<nPhrase; i++){
3017 const u8 *pPoslist;
3018 int nPoslist;
3019 nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
3020 sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
3021 }
3022 break;
3023
3024 case FTS5_DETAIL_COLUMNS:
3025
3026 /* Append the varints */
3027 for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
3028 const u8 *dummy;
3029 int nByte;
3030 rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
3031 sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
3032 }
3033
3034 /* Append the position lists */
3035 for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
3036 const u8 *pPoslist;
3037 int nPoslist;
3038 rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
3039 sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
3040 }
3041 break;
3042
3043 default:
3044 break;
3045 }
3046
3047 sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
3048 return rc;
3049}
3050
3051/*
3052** This is the xColumn method, called by SQLite to request a value from
3053** the row that the supplied cursor currently points to.
3054*/
3055static int fts5ColumnMethod(
3056 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
3057 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
3058 int iCol /* Index of column to read value from */
3059){
3060 Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
3061 Fts5Config *pConfig = pTab->p.pConfig;
3062 Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
3063 int rc = SQLITE_OK;
3064
3065 assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
3066
3067 if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
3068 if( iCol==pConfig->nCol ){
3069 sqlite3_result_int64(pCtx, pCsr->iSpecial);
3070 }
3071 }else
3072
3073 if( iCol==pConfig->nCol ){
3074 /* User is requesting the value of the special column with the same name
3075 ** as the table. Return the cursor integer id number. This value is only
3076 ** useful in that it may be passed as the first argument to an FTS5
3077 ** auxiliary function. */
3078 sqlite3_result_int64(pCtx, pCsr->iCsrId);
3079 }else if( iCol==pConfig->nCol+1 ){
3080 /* The value of the "rank" column. */
3081
3082 if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
3083 fts5PoslistBlob(pCtx, pCsr);
3084 }else if(
3085 pCsr->ePlan==FTS5_PLAN_MATCH
3086 || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
3087 ){
3088 if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
3089 fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
3090 }
3091 }
3092 }else{
3093 if( !sqlite3_vtab_nochange(pCtx) && pConfig->eContent!=FTS5_CONTENT_NONE ){
3094 pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
3095 rc = fts5SeekCursor(pCsr, 1);
3096 if( rc==SQLITE_OK ){
3097 sqlite3_value *pVal = sqlite3_column_value(pCsr->pStmt, iCol+1);
3098 if( pConfig->bLocale
3099 && pConfig->eContent==FTS5_CONTENT_EXTERNAL
3100 && sqlite3Fts5IsLocaleValue(pConfig, pVal)
3101 ){
3102 const char *z = 0;
3103 int n = 0;
3104 rc = fts5TextFromStmt(pConfig, pCsr->pStmt, iCol, &z, &n);
3105 if( rc==SQLITE_OK ){
3106 sqlite3_result_text(pCtx, z, n, SQLITE_TRANSIENT);
3107 }
3108 sqlite3Fts5ClearLocale(pConfig);
3109 }else{
3110 sqlite3_result_value(pCtx, pVal);
3111 }
3112 }
3113
3114 pConfig->pzErrmsg = 0;
3115 }
3116 }
3117
3118 return rc;
3119}
3120
3121
3122/*
3123** This routine implements the xFindFunction method for the FTS3
3124** virtual table.
3125*/
3126static int fts5FindFunctionMethod(
3127 sqlite3_vtab *pVtab, /* Virtual table handle */
3128 int nUnused, /* Number of SQL function arguments */
3129 const char *zName, /* Name of SQL function */
3130 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
3131 void **ppArg /* OUT: User data for *pxFunc */
3132){
3133 Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
3134 Fts5Auxiliary *pAux;
3135
3136 UNUSED_PARAM(nUnused);
3137 pAux = fts5FindAuxiliary(pTab, zName);
3138 if( pAux ){
3139 *pxFunc = fts5ApiCallback;
3140 *ppArg = (void*)pAux;
3141 return 1;
3142 }
3143
3144 /* No function of the specified name was found. Return 0. */
3145 return 0;
3146}
3147
3148/*
3149** Implementation of FTS5 xRename method. Rename an fts5 table.
3150*/
3151static int fts5RenameMethod(
3152 sqlite3_vtab *pVtab, /* Virtual table handle */
3153 const char *zName /* New name of table */
3154){
3155 int rc;
3156 Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
3157 rc = sqlite3Fts5StorageRename(pTab->pStorage, zName);
3158 return rc;
3159}
3160
3161int sqlite3Fts5FlushToDisk(Fts5Table *pTab){
3162 fts5TripCursors((Fts5FullTable*)pTab);
3163 return sqlite3Fts5StorageSync(((Fts5FullTable*)pTab)->pStorage);
3164}
3165
3166/*
3167** The xSavepoint() method.
3168**
3169** Flush the contents of the pending-terms table to disk.
3170*/
3171static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
3172 Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
3173 int rc = SQLITE_OK;
3174
3175 fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
3176 rc = sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);
3177 if( rc==SQLITE_OK ){
3178 pTab->iSavepoint = iSavepoint+1;
3179 }
3180 return rc;
3181}
3182
3183/*
3184** The xRelease() method.
3185**
3186** This is a no-op.
3187*/
3188static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
3189 Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
3190 int rc = SQLITE_OK;
3191 fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
3192 if( (iSavepoint+1)<pTab->iSavepoint ){
3193 rc = sqlite3Fts5FlushToDisk(&pTab->p);
3194 if( rc==SQLITE_OK ){
3195 pTab->iSavepoint = iSavepoint;
3196 }
3197 }
3198 return rc;
3199}
3200
3201/*
3202** The xRollbackTo() method.
3203**
3204** Discard the contents of the pending terms table.
3205*/
3206static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
3207 Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
3208 int rc = SQLITE_OK;
3209 fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
3210 fts5TripCursors(pTab);
3211 if( (iSavepoint+1)<=pTab->iSavepoint ){
3212 pTab->p.pConfig->pgsz = 0;
3213 rc = sqlite3Fts5StorageRollback(pTab->pStorage);
3214 }
3215 return rc;
3216}
3217
3218/*
3219** Register a new auxiliary function with global context pGlobal.
3220*/
3221static int fts5CreateAux(
3222 fts5_api *pApi, /* Global context (one per db handle) */
3223 const char *zName, /* Name of new function */
3224 void *pUserData, /* User data for aux. function */
3225 fts5_extension_function xFunc, /* Aux. function implementation */
3226 void(*xDestroy)(void*) /* Destructor for pUserData */
3227){
3228 Fts5Global *pGlobal = (Fts5Global*)pApi;
3229 int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
3230 if( rc==SQLITE_OK ){
3231 Fts5Auxiliary *pAux;
3232 sqlite3_int64 nName; /* Size of zName in bytes, including \0 */
3233 sqlite3_int64 nByte; /* Bytes of space to allocate */
3234
3235 nName = strlen(zName) + 1;
3236 nByte = sizeof(Fts5Auxiliary) + nName;
3237 pAux = (Fts5Auxiliary*)sqlite3_malloc64(nByte);
3238 if( pAux ){
3239 memset(pAux, 0, (size_t)nByte);
3240 pAux->zFunc = (char*)&pAux[1];
3241 memcpy(pAux->zFunc, zName, nName);
3242 pAux->pGlobal = pGlobal;
3243 pAux->pUserData = pUserData;
3244 pAux->xFunc = xFunc;
3245 pAux->xDestroy = xDestroy;
3246 pAux->pNext = pGlobal->pAux;
3247 pGlobal->pAux = pAux;
3248 }else{
3249 rc = SQLITE_NOMEM;
3250 }
3251 }
3252
3253 return rc;
3254}
3255
3256/*
3257** This function is used by xCreateTokenizer_v2() and xCreateTokenizer().
3258** It allocates and partially populates a new Fts5TokenizerModule object.
3259** The new object is already linked into the Fts5Global context before
3260** returning.
3261**
3262** If successful, SQLITE_OK is returned and a pointer to the new
3263** Fts5TokenizerModule object returned via output parameter (*ppNew). All
3264** that is required is for the caller to fill in the methods in
3265** Fts5TokenizerModule.x1 and x2, and to set Fts5TokenizerModule.bV2Native
3266** as appropriate.
3267**
3268** If an error occurs, an SQLite error code is returned and the final value
3269** of (*ppNew) undefined.
3270*/
3271static int fts5NewTokenizerModule(
3272 Fts5Global *pGlobal, /* Global context (one per db handle) */
3273 const char *zName, /* Name of new function */
3274 void *pUserData, /* User data for aux. function */
3275 void(*xDestroy)(void*), /* Destructor for pUserData */
3276 Fts5TokenizerModule **ppNew
3277){
3278 int rc = SQLITE_OK;
3279 Fts5TokenizerModule *pNew;
3280 sqlite3_int64 nName; /* Size of zName and its \0 terminator */
3281 sqlite3_int64 nByte; /* Bytes of space to allocate */
3282
3283 nName = strlen(zName) + 1;
3284 nByte = sizeof(Fts5TokenizerModule) + nName;
3285 *ppNew = pNew = (Fts5TokenizerModule*)sqlite3Fts5MallocZero(&rc, nByte);
3286 if( pNew ){
3287 pNew->zName = (char*)&pNew[1];
3288 memcpy(pNew->zName, zName, nName);
3289 pNew->pUserData = pUserData;
3290 pNew->xDestroy = xDestroy;
3291 pNew->pNext = pGlobal->pTok;
3292 pGlobal->pTok = pNew;
3293 if( pNew->pNext==0 ){
3294 pGlobal->pDfltTok = pNew;
3295 }
3296 }
3297
3298 return rc;
3299}
3300
3301/*
3302** An instance of this type is used as the Fts5Tokenizer object for
3303** wrapper tokenizers - those that provide access to a v1 tokenizer via
3304** the fts5_tokenizer_v2 API, and those that provide access to a v2 tokenizer
3305** via the fts5_tokenizer API.
3306*/
3307typedef struct Fts5VtoVTokenizer Fts5VtoVTokenizer;
3308struct Fts5VtoVTokenizer {
3309 int bV2Native; /* True if v2 native tokenizer */
3310 fts5_tokenizer x1; /* Tokenizer functions */
3311 fts5_tokenizer_v2 x2; /* V2 tokenizer functions */
3312 Fts5Tokenizer *pReal;
3313};
3314
3315/*
3316** Create a wrapper tokenizer. The context argument pCtx points to the
3317** Fts5TokenizerModule object.
3318*/
3319static int fts5VtoVCreate(
3320 void *pCtx,
3321 const char **azArg,
3322 int nArg,
3323 Fts5Tokenizer **ppOut
3324){
3325 Fts5TokenizerModule *pMod = (Fts5TokenizerModule*)pCtx;
3326 Fts5VtoVTokenizer *pNew = 0;
3327 int rc = SQLITE_OK;
3328
3329 pNew = (Fts5VtoVTokenizer*)sqlite3Fts5MallocZero(&rc, sizeof(*pNew));
3330 if( rc==SQLITE_OK ){
3331 pNew->x1 = pMod->x1;
3332 pNew->x2 = pMod->x2;
3333 pNew->bV2Native = pMod->bV2Native;
3334 if( pMod->bV2Native ){
3335 rc = pMod->x2.xCreate(pMod->pUserData, azArg, nArg, &pNew->pReal);
3336 }else{
3337 rc = pMod->x1.xCreate(pMod->pUserData, azArg, nArg, &pNew->pReal);
3338 }
3339 if( rc!=SQLITE_OK ){
3340 sqlite3_free(pNew);
3341 pNew = 0;
3342 }
3343 }
3344
3345 *ppOut = (Fts5Tokenizer*)pNew;
3346 return rc;
3347}
3348
3349/*
3350** Delete an Fts5VtoVTokenizer wrapper tokenizer.
3351*/
3352static void fts5VtoVDelete(Fts5Tokenizer *pTok){
3353 Fts5VtoVTokenizer *p = (Fts5VtoVTokenizer*)pTok;
3354 if( p ){
3355 if( p->bV2Native ){
3356 p->x2.xDelete(p->pReal);
3357 }else{
3358 p->x1.xDelete(p->pReal);
3359 }
3360 sqlite3_free(p);
3361 }
3362}
3363
3364
3365/*
3366** xTokenizer method for a wrapper tokenizer that offers the v1 interface
3367** (no support for locales).
3368*/
3369static int fts5V1toV2Tokenize(
3370 Fts5Tokenizer *pTok,
3371 void *pCtx, int flags,
3372 const char *pText, int nText,
3373 int (*xToken)(void*, int, const char*, int, int, int)
3374){
3375 Fts5VtoVTokenizer *p = (Fts5VtoVTokenizer*)pTok;
3376 assert( p->bV2Native );
3377 return p->x2.xTokenize(p->pReal, pCtx, flags, pText, nText, 0, 0, xToken);
3378}
3379
3380/*
3381** xTokenizer method for a wrapper tokenizer that offers the v2 interface
3382** (with locale support).
3383*/
3384static int fts5V2toV1Tokenize(
3385 Fts5Tokenizer *pTok,
3386 void *pCtx, int flags,
3387 const char *pText, int nText,
3388 const char *pLocale, int nLocale,
3389 int (*xToken)(void*, int, const char*, int, int, int)
3390){
3391 Fts5VtoVTokenizer *p = (Fts5VtoVTokenizer*)pTok;
3392 assert( p->bV2Native==0 );
3393 UNUSED_PARAM2(pLocale,nLocale);
3394 return p->x1.xTokenize(p->pReal, pCtx, flags, pText, nText, xToken);
3395}
3396
3397/*
3398** Register a new tokenizer. This is the implementation of the
3399** fts5_api.xCreateTokenizer_v2() method.
3400*/
3401static int fts5CreateTokenizer_v2(
3402 fts5_api *pApi, /* Global context (one per db handle) */
3403 const char *zName, /* Name of new function */
3404 void *pUserData, /* User data for aux. function */
3405 fts5_tokenizer_v2 *pTokenizer, /* Tokenizer implementation */
3406 void(*xDestroy)(void*) /* Destructor for pUserData */
3407){
3408 Fts5Global *pGlobal = (Fts5Global*)pApi;
3409 int rc = SQLITE_OK;
3410
3411 if( pTokenizer->iVersion>2 ){
3412 rc = SQLITE_ERROR;
3413 }else{
3414 Fts5TokenizerModule *pNew = 0;
3415 rc = fts5NewTokenizerModule(pGlobal, zName, pUserData, xDestroy, &pNew);
3416 if( pNew ){
3417 pNew->x2 = *pTokenizer;
3418 pNew->bV2Native = 1;
3419 pNew->x1.xCreate = fts5VtoVCreate;
3420 pNew->x1.xTokenize = fts5V1toV2Tokenize;
3421 pNew->x1.xDelete = fts5VtoVDelete;
3422 }
3423 }
3424
3425 return rc;
3426}
3427
3428/*
3429** The fts5_api.xCreateTokenizer() method.
3430*/
3431static int fts5CreateTokenizer(
3432 fts5_api *pApi, /* Global context (one per db handle) */
3433 const char *zName, /* Name of new function */
3434 void *pUserData, /* User data for aux. function */
3435 fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
3436 void(*xDestroy)(void*) /* Destructor for pUserData */
3437){
3438 Fts5TokenizerModule *pNew = 0;
3439 int rc = SQLITE_OK;
3440
3441 rc = fts5NewTokenizerModule(
3442 (Fts5Global*)pApi, zName, pUserData, xDestroy, &pNew
3443 );
3444 if( pNew ){
3445 pNew->x1 = *pTokenizer;
3446 pNew->x2.xCreate = fts5VtoVCreate;
3447 pNew->x2.xTokenize = fts5V2toV1Tokenize;
3448 pNew->x2.xDelete = fts5VtoVDelete;
3449 }
3450 return rc;
3451}
3452
3453/*
3454** Search the global context passed as the first argument for a tokenizer
3455** module named zName. If found, return a pointer to the Fts5TokenizerModule
3456** object. Otherwise, return NULL.
3457*/
3458static Fts5TokenizerModule *fts5LocateTokenizer(
3459 Fts5Global *pGlobal, /* Global (one per db handle) object */
3460 const char *zName /* Name of tokenizer module to find */
3461){
3462 Fts5TokenizerModule *pMod = 0;
3463
3464 if( zName==0 ){
3465 pMod = pGlobal->pDfltTok;
3466 }else{
3467 for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
3468 if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
3469 }
3470 }
3471
3472 return pMod;
3473}
3474
3475/*
3476** Find a tokenizer. This is the implementation of the
3477** fts5_api.xFindTokenizer_v2() method.
3478*/
3479static int fts5FindTokenizer_v2(
3480 fts5_api *pApi, /* Global context (one per db handle) */
3481 const char *zName, /* Name of tokenizer */
3482 void **ppUserData,
3483 fts5_tokenizer_v2 **ppTokenizer /* Populate this object */
3484){
3485 int rc = SQLITE_OK;
3486 Fts5TokenizerModule *pMod;
3487
3488 pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
3489 if( pMod ){
3490 if( pMod->bV2Native ){
3491 *ppUserData = pMod->pUserData;
3492 }else{
3493 *ppUserData = (void*)pMod;
3494 }
3495 *ppTokenizer = &pMod->x2;
3496 }else{
3497 *ppTokenizer = 0;
3498 *ppUserData = 0;
3499 rc = SQLITE_ERROR;
3500 }
3501
3502 return rc;
3503}
3504
3505/*
3506** Find a tokenizer. This is the implementation of the
3507** fts5_api.xFindTokenizer() method.
3508*/
3509static int fts5FindTokenizer(
3510 fts5_api *pApi, /* Global context (one per db handle) */
3511 const char *zName, /* Name of new function */
3512 void **ppUserData,
3513 fts5_tokenizer *pTokenizer /* Populate this object */
3514){
3515 int rc = SQLITE_OK;
3516 Fts5TokenizerModule *pMod;
3517
3518 pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
3519 if( pMod ){
3520 if( pMod->bV2Native==0 ){
3521 *ppUserData = pMod->pUserData;
3522 }else{
3523 *ppUserData = (void*)pMod;
3524 }
3525 *pTokenizer = pMod->x1;
3526 }else{
3527 memset(pTokenizer, 0, sizeof(*pTokenizer));
3528 *ppUserData = 0;
3529 rc = SQLITE_ERROR;
3530 }
3531
3532 return rc;
3533}
3534
3535/*
3536** Attempt to instantiate the tokenizer.
3537*/
3538int sqlite3Fts5LoadTokenizer(Fts5Config *pConfig){
3539 const char **azArg = pConfig->t.azArg;
3540 const int nArg = pConfig->t.nArg;
3541 Fts5TokenizerModule *pMod = 0;
3542 int rc = SQLITE_OK;
3543
3544 pMod = fts5LocateTokenizer(pConfig->pGlobal, nArg==0 ? 0 : azArg[0]);
3545 if( pMod==0 ){
3546 assert( nArg>0 );
3547 rc = SQLITE_ERROR;
3548 sqlite3Fts5ConfigErrmsg(pConfig, "no such tokenizer: %s", azArg[0]);
3549 }else{
3550 int (*xCreate)(void*, const char**, int, Fts5Tokenizer**) = 0;
3551 if( pMod->bV2Native ){
3552 xCreate = pMod->x2.xCreate;
3553 pConfig->t.pApi2 = &pMod->x2;
3554 }else{
3555 pConfig->t.pApi1 = &pMod->x1;
3556 xCreate = pMod->x1.xCreate;
3557 }
3558
3559 rc = xCreate(pMod->pUserData,
3560 (azArg?&azArg[1]:0), (nArg?nArg-1:0), &pConfig->t.pTok
3561 );
3562
3563 if( rc!=SQLITE_OK ){
3564 if( rc!=SQLITE_NOMEM ){
3565 sqlite3Fts5ConfigErrmsg(pConfig, "error in tokenizer constructor");
3566 }
3567 }else if( pMod->bV2Native==0 ){
3568 pConfig->t.ePattern = sqlite3Fts5TokenizerPattern(
3569 pMod->x1.xCreate, pConfig->t.pTok
3570 );
3571 }
3572 }
3573
3574 if( rc!=SQLITE_OK ){
3575 pConfig->t.pApi1 = 0;
3576 pConfig->t.pApi2 = 0;
3577 pConfig->t.pTok = 0;
3578 }
3579
3580 return rc;
3581}
3582
3583
3584/*
3585** xDestroy callback passed to sqlite3_create_module(). This is invoked
3586** when the db handle is being closed. Free memory associated with
3587** tokenizers and aux functions registered with this db handle.
3588*/
3589static void fts5ModuleDestroy(void *pCtx){
3590 Fts5TokenizerModule *pTok, *pNextTok;
3591 Fts5Auxiliary *pAux, *pNextAux;
3592 Fts5Global *pGlobal = (Fts5Global*)pCtx;
3593
3594 for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
3595 pNextAux = pAux->pNext;
3596 if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
3597 sqlite3_free(pAux);
3598 }
3599
3600 for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
3601 pNextTok = pTok->pNext;
3602 if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
3603 sqlite3_free(pTok);
3604 }
3605
3606 sqlite3_free(pGlobal);
3607}
3608
3609/*
3610** Implementation of the fts5() function used by clients to obtain the
3611** API pointer.
3612*/
3613static void fts5Fts5Func(
3614 sqlite3_context *pCtx, /* Function call context */
3615 int nArg, /* Number of args */
3616 sqlite3_value **apArg /* Function arguments */
3617){
3618 Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
3619 fts5_api **ppApi;
3620 UNUSED_PARAM(nArg);
3621 assert( nArg==1 );
3622 ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], "fts5_api_ptr");
3623 if( ppApi ) *ppApi = &pGlobal->api;
3624}
3625
3626/*
3627** Implementation of fts5_source_id() function.
3628*/
3629static void fts5SourceIdFunc(
3630 sqlite3_context *pCtx, /* Function call context */
3631 int nArg, /* Number of args */
3632 sqlite3_value **apUnused /* Function arguments */
3633){
3634 assert( nArg==0 );
3635 UNUSED_PARAM2(nArg, apUnused);
3636 sqlite3_result_text(pCtx, "--FTS5-SOURCE-ID--", -1, SQLITE_TRANSIENT);
3637}
3638
3639/*
3640** Implementation of fts5_locale(LOCALE, TEXT) function.
3641**
3642** If parameter LOCALE is NULL, or a zero-length string, then a copy of
3643** TEXT is returned. Otherwise, both LOCALE and TEXT are interpreted as
3644** text, and the value returned is a blob consisting of:
3645**
3646** * The 4 bytes 0x00, 0xE0, 0xB2, 0xEb (FTS5_LOCALE_HEADER).
3647** * The LOCALE, as utf-8 text, followed by
3648** * 0x00, followed by
3649** * The TEXT, as utf-8 text.
3650**
3651** There is no final nul-terminator following the TEXT value.
3652*/
3653static void fts5LocaleFunc(
3654 sqlite3_context *pCtx, /* Function call context */
3655 int nArg, /* Number of args */
3656 sqlite3_value **apArg /* Function arguments */
3657){
3658 const char *zLocale = 0;
3659 i64 nLocale = 0;
3660 const char *zText = 0;
3661 i64 nText = 0;
3662
3663 assert( nArg==2 );
3664 UNUSED_PARAM(nArg);
3665
3666 zLocale = (const char*)sqlite3_value_text(apArg[0]);
3667 nLocale = sqlite3_value_bytes(apArg[0]);
3668
3669 zText = (const char*)sqlite3_value_text(apArg[1]);
3670 nText = sqlite3_value_bytes(apArg[1]);
3671
3672 if( zLocale==0 || zLocale[0]=='\0' ){
3673 sqlite3_result_text(pCtx, zText, nText, SQLITE_TRANSIENT);
3674 }else{
3675 Fts5Global *p = (Fts5Global*)sqlite3_user_data(pCtx);
3676 u8 *pBlob = 0;
3677 u8 *pCsr = 0;
3678 i64 nBlob = 0;
3679
3680 nBlob = FTS5_LOCALE_HDR_SIZE + nLocale + 1 + nText;
3681 pBlob = (u8*)sqlite3_malloc64(nBlob);
3682 if( pBlob==0 ){
3683 sqlite3_result_error_nomem(pCtx);
3684 return;
3685 }
3686
3687 pCsr = pBlob;
3688 memcpy(pCsr, (const u8*)p->aLocaleHdr, FTS5_LOCALE_HDR_SIZE);
3689 pCsr += FTS5_LOCALE_HDR_SIZE;
3690 memcpy(pCsr, zLocale, nLocale);
3691 pCsr += nLocale;
3692 (*pCsr++) = 0x00;
3693 if( zText ) memcpy(pCsr, zText, nText);
3694 assert( &pCsr[nText]==&pBlob[nBlob] );
3695
3696 sqlite3_result_blob(pCtx, pBlob, nBlob, sqlite3_free);
3697 }
3698}
3699
3700/*
3701** Implementation of fts5_insttoken() function.
3702*/
3703static void fts5InsttokenFunc(
3704 sqlite3_context *pCtx, /* Function call context */
3705 int nArg, /* Number of args */
3706 sqlite3_value **apArg /* Function arguments */
3707){
3708 assert( nArg==1 );
3709 (void)nArg;
3710 sqlite3_result_value(pCtx, apArg[0]);
3711 sqlite3_result_subtype(pCtx, FTS5_INSTTOKEN_SUBTYPE);
3712}
3713
3714/*
3715** Return true if zName is the extension on one of the shadow tables used
3716** by this module.
3717*/
3718static int fts5ShadowName(const char *zName){
3719 static const char *azName[] = {
3720 "config", "content", "data", "docsize", "idx"
3721 };
3722 unsigned int i;
3723 for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
3724 if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
3725 }
3726 return 0;
3727}
3728
3729/*
3730** Run an integrity check on the FTS5 data structures. Return a string
3731** if anything is found amiss. Return a NULL pointer if everything is
3732** OK.
3733*/
3734static int fts5IntegrityMethod(
3735 sqlite3_vtab *pVtab, /* the FTS5 virtual table to check */
3736 const char *zSchema, /* Name of schema in which this table lives */
3737 const char *zTabname, /* Name of the table itself */
3738 int isQuick, /* True if this is a quick-check */
3739 char **pzErr /* Write error message here */
3740){
3741 Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
3742 int rc;
3743
3744 assert( pzErr!=0 && *pzErr==0 );
3745 UNUSED_PARAM(isQuick);
3746 assert( pTab->p.pConfig->pzErrmsg==0 );
3747 pTab->p.pConfig->pzErrmsg = pzErr;
3748 rc = sqlite3Fts5StorageIntegrity(pTab->pStorage, 0);
3749 if( *pzErr==0 && rc!=SQLITE_OK ){
3750 if( (rc&0xff)==SQLITE_CORRUPT ){
3751 *pzErr = sqlite3_mprintf("malformed inverted index for FTS5 table %s.%s",
3752 zSchema, zTabname);
3753 rc = (*pzErr) ? SQLITE_OK : SQLITE_NOMEM;
3754 }else{
3755 *pzErr = sqlite3_mprintf("unable to validate the inverted index for"
3756 " FTS5 table %s.%s: %s",
3757 zSchema, zTabname, sqlite3_errstr(rc));
3758 }
3759 }else if( (rc&0xff)==SQLITE_CORRUPT ){
3760 rc = SQLITE_OK;
3761 }
3762 sqlite3Fts5IndexCloseReader(pTab->p.pIndex);
3763 pTab->p.pConfig->pzErrmsg = 0;
3764
3765 return rc;
3766}
3767
3768static int fts5Init(sqlite3 *db){
3769 static const sqlite3_module fts5Mod = {
3770 /* iVersion */ 4,
3771 /* xCreate */ fts5CreateMethod,
3772 /* xConnect */ fts5ConnectMethod,
3773 /* xBestIndex */ fts5BestIndexMethod,
3774 /* xDisconnect */ fts5DisconnectMethod,
3775 /* xDestroy */ fts5DestroyMethod,
3776 /* xOpen */ fts5OpenMethod,
3777 /* xClose */ fts5CloseMethod,
3778 /* xFilter */ fts5FilterMethod,
3779 /* xNext */ fts5NextMethod,
3780 /* xEof */ fts5EofMethod,
3781 /* xColumn */ fts5ColumnMethod,
3782 /* xRowid */ fts5RowidMethod,
3783 /* xUpdate */ fts5UpdateMethod,
3784 /* xBegin */ fts5BeginMethod,
3785 /* xSync */ fts5SyncMethod,
3786 /* xCommit */ fts5CommitMethod,
3787 /* xRollback */ fts5RollbackMethod,
3788 /* xFindFunction */ fts5FindFunctionMethod,
3789 /* xRename */ fts5RenameMethod,
3790 /* xSavepoint */ fts5SavepointMethod,
3791 /* xRelease */ fts5ReleaseMethod,
3792 /* xRollbackTo */ fts5RollbackToMethod,
3793 /* xShadowName */ fts5ShadowName,
3794 /* xIntegrity */ fts5IntegrityMethod
3795 };
3796
3797 int rc;
3798 Fts5Global *pGlobal = 0;
3799
3800 pGlobal = (Fts5Global*)sqlite3_malloc64(sizeof(Fts5Global));
3801 if( pGlobal==0 ){
3802 rc = SQLITE_NOMEM;
3803 }else{
3804 void *p = (void*)pGlobal;
3805 memset(pGlobal, 0, sizeof(Fts5Global));
3806 pGlobal->db = db;
3807 pGlobal->api.iVersion = 3;
3808 pGlobal->api.xCreateFunction = fts5CreateAux;
3809 pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
3810 pGlobal->api.xFindTokenizer = fts5FindTokenizer;
3811 pGlobal->api.xCreateTokenizer_v2 = fts5CreateTokenizer_v2;
3812 pGlobal->api.xFindTokenizer_v2 = fts5FindTokenizer_v2;
3813
3814 /* Initialize pGlobal->aLocaleHdr[] to a 128-bit pseudo-random vector.
3815 ** The constants below were generated randomly. */
3816 sqlite3_randomness(sizeof(pGlobal->aLocaleHdr), pGlobal->aLocaleHdr);
3817 pGlobal->aLocaleHdr[0] ^= 0xF924976D;
3818 pGlobal->aLocaleHdr[1] ^= 0x16596E13;
3819 pGlobal->aLocaleHdr[2] ^= 0x7C80BEAA;
3820 pGlobal->aLocaleHdr[3] ^= 0x9B03A67F;
3821 assert( sizeof(pGlobal->aLocaleHdr)==16 );
3822
3823 rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
3824 if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
3825 if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
3826 if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
3827 if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
3828 if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
3829 if( rc==SQLITE_OK ){
3830 rc = sqlite3_create_function(
3831 db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
3832 );
3833 }
3834 if( rc==SQLITE_OK ){
3835 rc = sqlite3_create_function(
3836 db, "fts5_source_id", 0,
3837 SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS,
3838 p, fts5SourceIdFunc, 0, 0
3839 );
3840 }
3841 if( rc==SQLITE_OK ){
3842 rc = sqlite3_create_function(
3843 db, "fts5_locale", 2,
3844 SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_RESULT_SUBTYPE|SQLITE_SUBTYPE,
3845 p, fts5LocaleFunc, 0, 0
3846 );
3847 }
3848 if( rc==SQLITE_OK ){
3849 rc = sqlite3_create_function(
3850 db, "fts5_insttoken", 1,
3851 SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_RESULT_SUBTYPE,
3852 p, fts5InsttokenFunc, 0, 0
3853 );
3854 }
3855 }
3856
3857 /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
3858 ** fts5_test_mi.c is compiled and linked into the executable. And call
3859 ** its entry point to enable the matchinfo() demo. */
3860#ifdef SQLITE_FTS5_ENABLE_TEST_MI
3861 if( rc==SQLITE_OK ){
3862 extern int sqlite3Fts5TestRegisterMatchinfoAPI(fts5_api*);
3863 rc = sqlite3Fts5TestRegisterMatchinfoAPI(&pGlobal->api);
3864 }
3865#endif
3866
3867 return rc;
3868}
3869
3870/*
3871** The following functions are used to register the module with SQLite. If
3872** this module is being built as part of the SQLite core (SQLITE_CORE is
3873** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
3874**
3875** Or, if this module is being built as a loadable extension,
3876** sqlite3Fts5Init() is omitted and the two standard entry points
3877** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
3878*/
3879#ifndef SQLITE_CORE
3880#ifdef _WIN32
3881__declspec(dllexport)
3882#endif
3883int sqlite3_fts_init(
3884 sqlite3 *db,
3885 char **pzErrMsg,
3886 const sqlite3_api_routines *pApi
3887){
3888 SQLITE_EXTENSION_INIT2(pApi);
3889 (void)pzErrMsg; /* Unused parameter */
3890 return fts5Init(db);
3891}
3892
3893#ifdef _WIN32
3894__declspec(dllexport)
3895#endif
3896int sqlite3_fts5_init(
3897 sqlite3 *db,
3898 char **pzErrMsg,
3899 const sqlite3_api_routines *pApi
3900){
3901 SQLITE_EXTENSION_INIT2(pApi);
3902 (void)pzErrMsg; /* Unused parameter */
3903 return fts5Init(db);
3904}
3905#else
3906int sqlite3Fts5Init(sqlite3 *db){
3907 return fts5Init(db);
3908}
3909#endif